炸 service 层

This commit is contained in:
DrSmoothl
2026-03-14 00:13:35 +08:00
parent 898fab6de9
commit 43c5b34623
13 changed files with 1408 additions and 1736 deletions

View File

@@ -0,0 +1,9 @@
from .components import RuntimeComponentCapabilityMixin
from .core import RuntimeCoreCapabilityMixin
from .data import RuntimeDataCapabilityMixin
__all__ = [
"RuntimeComponentCapabilityMixin",
"RuntimeCoreCapabilityMixin",
"RuntimeDataCapabilityMixin",
]

View File

@@ -0,0 +1,194 @@
from typing import Any, Dict, List, Optional
from src.common.logger import get_logger
logger = get_logger("plugin_runtime.integration")
class RuntimeComponentCapabilityMixin:
async def _cap_component_get_all_plugins(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
result: Dict[str, Any] = {}
for sv in self.supervisors:
for pid, reg in sv._registered_plugins.items():
if pid in result:
logger.error(f"检测到重复插件 ID {pid}component.get_all_plugins 结果已拒绝聚合")
return {"success": False, "error": f"检测到重复插件 ID: {pid}"}
comps = sv.component_registry.get_components_by_plugin(pid, enabled_only=False)
components_list = [
{
"name": component.name,
"full_name": component.full_name,
"type": component.component_type,
"enabled": component.enabled,
"metadata": component.metadata,
}
for component in comps
]
result[pid] = {
"name": pid,
"version": reg.plugin_version,
"description": "",
"author": "",
"enabled": True,
"components": components_list,
}
return {"success": True, "plugins": result}
async def _cap_component_get_plugin_info(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
plugin_name: str = args.get("plugin_name", plugin_id)
try:
sv = self._get_supervisor_for_plugin(plugin_name)
except RuntimeError as exc:
return {"success": False, "error": str(exc)}
if sv is not None and (reg := sv._registered_plugins.get(plugin_name)) is not None:
return {
"success": True,
"plugin": {
"name": plugin_name,
"version": reg.plugin_version,
"description": "",
"author": "",
"enabled": True,
},
}
return {"success": False, "error": f"未找到插件: {plugin_name}"}
async def _cap_component_list_loaded_plugins(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
plugins: List[str] = []
for sv in self.supervisors:
plugins.extend(sv._registered_plugins.keys())
return {"success": True, "plugins": plugins}
async def _cap_component_list_registered_plugins(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
plugins: List[str] = []
for sv in self.supervisors:
plugins.extend(sv._registered_plugins.keys())
return {"success": True, "plugins": plugins}
def _resolve_component_toggle_target(self, name: str, component_type: str) -> tuple[Optional[Any], Optional[str]]:
short_name_matches: List[Any] = []
for sv in self.supervisors:
comp = sv.component_registry.get_component(name)
if comp is not None and comp.component_type == component_type:
return comp, None
short_name_matches.extend(
candidate
for candidate in sv.component_registry.get_components_by_type(component_type, enabled_only=False)
if candidate.name == name
)
if len(short_name_matches) == 1:
return short_name_matches[0], None
if len(short_name_matches) > 1:
return None, f"组件名不唯一: {name} ({component_type}),请使用完整名 plugin_id.component_name"
return None, f"未找到组件: {name} ({component_type})"
async def _cap_component_enable(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
name: str = args.get("name", "")
component_type: str = args.get("component_type", "")
scope: str = args.get("scope", "global")
stream_id: str = args.get("stream_id", "")
if not name or not component_type:
return {"success": False, "error": "缺少必要参数 name 或 component_type"}
if scope != "global" or stream_id:
return {"success": False, "error": "当前仅支持全局组件启用,不支持 scope/stream_id 定位"}
comp, error = self._resolve_component_toggle_target(name, component_type)
if comp is None:
return {"success": False, "error": error or f"未找到组件: {name} ({component_type})"}
comp.enabled = True
return {"success": True}
async def _cap_component_disable(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
name: str = args.get("name", "")
component_type: str = args.get("component_type", "")
scope: str = args.get("scope", "global")
stream_id: str = args.get("stream_id", "")
if not name or not component_type:
return {"success": False, "error": "缺少必要参数 name 或 component_type"}
if scope != "global" or stream_id:
return {"success": False, "error": "当前仅支持全局组件禁用,不支持 scope/stream_id 定位"}
comp, error = self._resolve_component_toggle_target(name, component_type)
if comp is None:
return {"success": False, "error": error or f"未找到组件: {name} ({component_type})"}
comp.enabled = False
return {"success": True}
async def _cap_component_load_plugin(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
plugin_name: str = args.get("plugin_name", "")
if not plugin_name:
return {"success": False, "error": "缺少必要参数 plugin_name"}
import os
if duplicate_plugin_ids := self._find_duplicate_plugin_ids(list(self._iter_plugin_dirs())):
details = "; ".join(
f"{conflict_plugin_id}: {', '.join(paths)}"
for conflict_plugin_id, paths in sorted(duplicate_plugin_ids.items())
)
return {"success": False, "error": f"检测到重复插件 ID拒绝热重载: {details}"}
try:
registered_supervisor = self._get_supervisor_for_plugin(plugin_name)
except RuntimeError as exc:
return {"success": False, "error": str(exc)}
if registered_supervisor is not None:
try:
reloaded = await registered_supervisor.reload_plugins(reason=f"load {plugin_name}")
if reloaded:
return {"success": True, "count": 1}
return {"success": False, "error": f"插件 {plugin_name} 热重载失败,已回滚"}
except Exception as e:
logger.error(f"[cap.component.load_plugin] 热重载失败: {e}")
return {"success": False, "error": str(e)}
for sv in self.supervisors:
for pdir in sv._plugin_dirs:
if os.path.isdir(os.path.join(pdir, plugin_name)):
try:
reloaded = await sv.reload_plugins(reason=f"load {plugin_name}")
if reloaded:
return {"success": True, "count": 1}
return {"success": False, "error": f"插件 {plugin_name} 热重载失败,已回滚"}
except Exception as e:
logger.error(f"[cap.component.load_plugin] 热重载失败: {e}")
return {"success": False, "error": str(e)}
return {"success": False, "error": f"未找到插件: {plugin_name}"}
async def _cap_component_unload_plugin(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
return {"success": False, "error": "新运行时不支持单独卸载插件,请使用 reload"}
async def _cap_component_reload_plugin(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
plugin_name: str = args.get("plugin_name", "")
if not plugin_name:
return {"success": False, "error": "缺少必要参数 plugin_name"}
if duplicate_plugin_ids := self._find_duplicate_plugin_ids(list(self._iter_plugin_dirs())):
details = "; ".join(
f"{conflict_plugin_id}: {', '.join(paths)}"
for conflict_plugin_id, paths in sorted(duplicate_plugin_ids.items())
)
return {"success": False, "error": f"检测到重复插件 ID拒绝热重载: {details}"}
try:
sv = self._get_supervisor_for_plugin(plugin_name)
except RuntimeError as exc:
return {"success": False, "error": str(exc)}
if sv is not None:
try:
reloaded = await sv.reload_plugins(reason=f"reload {plugin_name}")
if reloaded:
return {"success": True}
return {"success": False, "error": f"插件 {plugin_name} 热重载失败,已回滚"}
except Exception as e:
logger.error(f"[cap.component.reload_plugin] 热重载失败: {e}")
return {"success": False, "error": str(e)}
return {"success": False, "error": f"未找到插件: {plugin_name}"}

View File

@@ -0,0 +1,283 @@
from typing import Any, Dict
from src.common.logger import get_logger
logger = get_logger("plugin_runtime.integration")
class RuntimeCoreCapabilityMixin:
async def _cap_send_text(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import send_service as send_api
text: str = args.get("text", "")
stream_id: str = args.get("stream_id", "")
if not text or not stream_id:
return {"success": False, "error": "缺少必要参数 text 或 stream_id"}
try:
result = await send_api.text_to_stream(
text=text,
stream_id=stream_id,
typing=args.get("typing", False),
set_reply=args.get("set_reply", False),
storage_message=args.get("storage_message", True),
)
return {"success": result}
except Exception as e:
logger.error(f"[cap.send.text] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_send_emoji(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import send_service as send_api
emoji_base64: str = args.get("emoji_base64", "")
stream_id: str = args.get("stream_id", "")
if not emoji_base64 or not stream_id:
return {"success": False, "error": "缺少必要参数 emoji_base64 或 stream_id"}
try:
result = await send_api.emoji_to_stream(
emoji_base64=emoji_base64,
stream_id=stream_id,
storage_message=args.get("storage_message", True),
)
return {"success": result}
except Exception as e:
logger.error(f"[cap.send.emoji] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_send_image(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import send_service as send_api
image_base64: str = args.get("image_base64", "")
stream_id: str = args.get("stream_id", "")
if not image_base64 or not stream_id:
return {"success": False, "error": "缺少必要参数 image_base64 或 stream_id"}
try:
result = await send_api.image_to_stream(
image_base64=image_base64,
stream_id=stream_id,
storage_message=args.get("storage_message", True),
)
return {"success": result}
except Exception as e:
logger.error(f"[cap.send.image] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_send_command(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import send_service as send_api
command = args.get("command", "")
stream_id: str = args.get("stream_id", "")
if not command or not stream_id:
return {"success": False, "error": "缺少必要参数 command 或 stream_id"}
try:
result = await send_api.command_to_stream(
command=command,
stream_id=stream_id,
storage_message=args.get("storage_message", True),
display_message=args.get("display_message", ""),
)
return {"success": result}
except Exception as e:
logger.error(f"[cap.send.command] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_send_custom(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import send_service as send_api
message_type: str = args.get("message_type", "") or args.get("custom_type", "")
content = args.get("content")
if content is None:
content = args.get("data", "")
stream_id: str = args.get("stream_id", "")
if not message_type or not stream_id:
return {"success": False, "error": "缺少必要参数 message_type 或 stream_id"}
try:
result = await send_api.custom_to_stream(
message_type=message_type,
content=content,
stream_id=stream_id,
display_message=args.get("display_message", ""),
typing=args.get("typing", False),
storage_message=args.get("storage_message", True),
)
return {"success": result}
except Exception as e:
logger.error(f"[cap.send.custom] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_send_forward(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import send_service as send_api
messages = args.get("messages", [])
stream_id: str = args.get("stream_id", "")
if not messages or not stream_id:
return {"success": False, "error": "缺少必要参数 messages 或 stream_id"}
try:
result = await send_api.forward_to_stream(messages=messages, stream_id=stream_id)
return {"success": result}
except Exception as e:
logger.error(f"[cap.send.forward] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_send_hybrid(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import send_service as send_api
segments = args.get("segments", [])
stream_id: str = args.get("stream_id", "")
if not segments or not stream_id:
return {"success": False, "error": "缺少必要参数 segments 或 stream_id"}
try:
result = await send_api.hybrid_to_stream(segments=segments, stream_id=stream_id)
return {"success": result}
except Exception as e:
logger.error(f"[cap.send.hybrid] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_llm_generate(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import llm_service as llm_api
prompt: str = args.get("prompt", "")
if not prompt:
return {"success": False, "error": "缺少必要参数 prompt"}
model_name: str = args.get("model", "") or args.get("model_name", "")
temperature = args.get("temperature")
max_tokens = args.get("max_tokens")
try:
models = llm_api.get_available_models()
if model_name and model_name in models:
model_config = models[model_name]
else:
if not models:
return {"success": False, "error": "没有可用的模型配置"}
model_config = next(iter(models.values()))
success, response, reasoning, used_model = await llm_api.generate_with_model(
prompt=prompt,
model_config=model_config,
request_type=f"plugin.{plugin_id}",
temperature=temperature,
max_tokens=max_tokens,
)
return {
"success": success,
"response": response,
"reasoning": reasoning,
"model_name": used_model,
}
except Exception as e:
logger.error(f"[cap.llm.generate] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_llm_generate_with_tools(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import llm_service as llm_api
prompt: str = args.get("prompt", "")
if not prompt:
return {"success": False, "error": "缺少必要参数 prompt"}
model_name: str = args.get("model", "") or args.get("model_name", "")
tool_options = args.get("tools") or args.get("tool_options")
temperature = args.get("temperature")
max_tokens = args.get("max_tokens")
try:
models = llm_api.get_available_models()
if model_name and model_name in models:
model_config = models[model_name]
else:
if not models:
return {"success": False, "error": "没有可用的模型配置"}
model_config = next(iter(models.values()))
success, response, reasoning, used_model, tool_calls = await llm_api.generate_with_model_with_tools(
prompt=prompt,
model_config=model_config,
tool_options=tool_options,
request_type=f"plugin.{plugin_id}",
temperature=temperature,
max_tokens=max_tokens,
)
serialized_tool_calls = None
if tool_calls:
serialized_tool_calls = [
{"id": tc.id, "function": {"name": tc.function.name, "arguments": tc.function.arguments}}
for tc in tool_calls
if hasattr(tc, "function")
]
return {
"success": success,
"response": response,
"reasoning": reasoning,
"model_name": used_model,
"tool_calls": serialized_tool_calls,
}
except Exception as e:
logger.error(f"[cap.llm.generate_with_tools] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_llm_get_available_models(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import llm_service as llm_api
try:
models = llm_api.get_available_models()
return {"success": True, "models": list(models.keys())}
except Exception as e:
logger.error(f"[cap.llm.get_available_models] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_config_get(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import config_service as config_api
key: str = args.get("key", "")
default = args.get("default")
if not key:
return {"success": False, "value": None, "error": "缺少必要参数 key"}
try:
value = config_api.get_global_config(key, default)
return {"success": True, "value": value}
except Exception as e:
return {"success": False, "value": None, "error": str(e)}
async def _cap_config_get_plugin(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.core.component_registry import component_registry as core_registry
plugin_name: str = args.get("plugin_name", plugin_id)
key: str = args.get("key", "")
default = args.get("default")
try:
config = core_registry.get_plugin_config(plugin_name)
if config is None:
return {"success": False, "value": default, "error": f"未找到插件 {plugin_name} 的配置"}
if key:
from src.services import config_service as config_api
value = config_api.get_plugin_config(config, key, default)
return {"success": True, "value": value}
return {"success": True, "value": config}
except Exception as e:
return {"success": False, "value": default, "error": str(e)}
async def _cap_config_get_all(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.core.component_registry import component_registry as core_registry
plugin_name: str = args.get("plugin_name", plugin_id)
try:
config = core_registry.get_plugin_config(plugin_name)
if config is None:
return {"success": True, "value": {}}
return {"success": True, "value": config}
except Exception as e:
return {"success": False, "value": {}, "error": str(e)}

View File

@@ -0,0 +1,582 @@
from typing import Any, Dict, List, Optional
from src.chat.message_receive.chat_manager import BotChatSession, chat_manager
from src.common.logger import get_logger
logger = get_logger("plugin_runtime.integration")
class RuntimeDataCapabilityMixin:
async def _cap_database_query(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import database_service as database_api
model_name: str = args.get("model_name", "")
if not model_name:
return {"success": False, "error": "缺少必要参数 model_name"}
try:
import src.common.database.database_model as db_models
model_class = getattr(db_models, model_name, None)
if model_class is None:
return {"success": False, "error": f"未找到数据模型: {model_name}"}
query_type = args.get("query_type", "get")
if query_type == "get":
result = await database_api.db_get(
model_class=model_class,
filters=args.get("filters"),
limit=args.get("limit"),
order_by=args.get("order_by"),
single_result=args.get("single_result", False),
)
elif query_type == "create":
if not (data := args.get("data")):
return {"success": False, "error": "create 需要 data"}
result = await database_api.db_save(model_class=model_class, data=data)
elif query_type == "update":
if not (data := args.get("data")):
return {"success": False, "error": "update 需要 data"}
result = await database_api.db_update(
model_class=model_class,
data=data,
filters=args.get("filters"),
)
elif query_type == "delete":
result = await database_api.db_delete(model_class=model_class, filters=args.get("filters"))
elif query_type == "count":
result = await database_api.db_count(model_class=model_class, filters=args.get("filters"))
else:
return {"success": False, "error": f"不支持的 query_type: {query_type}"}
return {"success": True, "result": result}
except Exception as e:
logger.error(f"[cap.database.query] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_database_save(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import database_service as database_api
model_name: str = args.get("model_name", "")
data: Optional[Dict[str, Any]] = args.get("data")
if not model_name or not data:
return {"success": False, "error": "缺少必要参数 model_name 或 data"}
try:
import src.common.database.database_model as db_models
model_class = getattr(db_models, model_name, None)
if model_class is None:
return {"success": False, "error": f"未找到数据模型: {model_name}"}
result = await database_api.db_save(
model_class=model_class,
data=data,
key_field=args.get("key_field"),
key_value=args.get("key_value"),
)
return {"success": True, "result": result}
except Exception as e:
logger.error(f"[cap.database.save] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_database_get(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import database_service as database_api
model_name: str = args.get("model_name", "")
if not model_name:
return {"success": False, "error": "缺少必要参数 model_name"}
try:
import src.common.database.database_model as db_models
model_class = getattr(db_models, model_name, None)
if model_class is None:
return {"success": False, "error": f"未找到数据模型: {model_name}"}
result = await database_api.db_get(
model_class=model_class,
filters=args.get("filters"),
limit=args.get("limit"),
order_by=args.get("order_by"),
single_result=args.get("single_result", False),
)
return {"success": True, "result": result}
except Exception as e:
logger.error(f"[cap.database.get] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_database_delete(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import database_service as database_api
model_name: str = args.get("model_name", "")
filters = args.get("filters", {})
if not model_name:
return {"success": False, "error": "缺少必要参数 model_name"}
if not filters:
return {"success": False, "error": "缺少必要参数 filters不允许无条件删除"}
try:
import src.common.database.database_model as db_models
model_class = getattr(db_models, model_name, None)
if model_class is None:
return {"success": False, "error": f"未找到数据模型: {model_name}"}
result = await database_api.db_delete(model_class=model_class, filters=filters)
return {"success": True, "result": result}
except Exception as e:
logger.error(f"[cap.database.delete] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_database_count(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import database_service as database_api
model_name: str = args.get("model_name", "")
if not model_name:
return {"success": False, "error": "缺少必要参数 model_name"}
try:
import src.common.database.database_model as db_models
model_class = getattr(db_models, model_name, None)
if model_class is None:
return {"success": False, "error": f"未找到数据模型: {model_name}"}
result = await database_api.db_count(model_class=model_class, filters=args.get("filters"))
return {"success": True, "count": result}
except Exception as e:
logger.error(f"[cap.database.count] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
def _list_sessions(self, platform: str, is_group_session: Optional[bool] = None) -> List[BotChatSession]:
return [
session
for session in chat_manager.sessions.values()
if (platform == "all_platforms" or session.platform == platform)
and (is_group_session is None or session.is_group_session == is_group_session)
]
@staticmethod
def _serialize_stream(stream: BotChatSession) -> Dict[str, Any]:
return {
"session_id": stream.session_id,
"platform": stream.platform,
"user_id": stream.user_id,
"group_id": stream.group_id,
"is_group_session": stream.is_group_session,
}
async def _cap_chat_get_all_streams(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
platform: str = args.get("platform", "qq")
try:
streams = self._list_sessions(platform=platform)
return {"success": True, "streams": [self._serialize_stream(item) for item in streams]}
except Exception as e:
logger.error(f"[cap.chat.get_all_streams] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_chat_get_group_streams(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
platform: str = args.get("platform", "qq")
try:
streams = self._list_sessions(platform=platform, is_group_session=True)
return {"success": True, "streams": [self._serialize_stream(item) for item in streams]}
except Exception as e:
logger.error(f"[cap.chat.get_group_streams] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_chat_get_private_streams(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
platform: str = args.get("platform", "qq")
try:
streams = self._list_sessions(platform=platform, is_group_session=False)
return {"success": True, "streams": [self._serialize_stream(item) for item in streams]}
except Exception as e:
logger.error(f"[cap.chat.get_private_streams] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_chat_get_stream_by_group_id(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
group_id: str = args.get("group_id", "")
if not group_id:
return {"success": False, "error": "缺少必要参数 group_id"}
platform: str = args.get("platform", "qq")
try:
stream = next(
(
item
for item in self._list_sessions(platform=platform, is_group_session=True)
if str(item.group_id) == str(group_id)
),
None,
)
return {"success": True, "stream": None if stream is None else self._serialize_stream(stream)}
except Exception as e:
logger.error(f"[cap.chat.get_stream_by_group_id] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_chat_get_stream_by_user_id(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
user_id: str = args.get("user_id", "")
if not user_id:
return {"success": False, "error": "缺少必要参数 user_id"}
platform: str = args.get("platform", "qq")
try:
stream = next(
(
item
for item in self._list_sessions(platform=platform, is_group_session=False)
if str(item.user_id) == str(user_id)
),
None,
)
return {"success": True, "stream": None if stream is None else self._serialize_stream(stream)}
except Exception as e:
logger.error(f"[cap.chat.get_stream_by_user_id] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
@staticmethod
def _serialize_messages(messages: list) -> List[Dict[str, Any]]:
result: List[Dict[str, Any]] = []
for msg in messages:
if hasattr(msg, "model_dump"):
result.append(msg.model_dump())
elif hasattr(msg, "__dict__"):
result.append(dict(msg.__dict__))
else:
result.append(str(msg))
return result
async def _cap_message_get_by_time(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import message_service as message_api
try:
messages = message_api.get_messages_by_time(
start_time=float(args.get("start_time", 0.0)),
end_time=float(args.get("end_time", 0.0)),
limit=args.get("limit", 0),
limit_mode=args.get("limit_mode", "latest"),
filter_mai=args.get("filter_mai", False),
)
return {"success": True, "messages": self._serialize_messages(messages)}
except Exception as e:
logger.error(f"[cap.message.get_by_time] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_message_get_by_time_in_chat(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import message_service as message_api
chat_id: str = args.get("chat_id", "")
if not chat_id:
return {"success": False, "error": "缺少必要参数 chat_id"}
try:
messages = message_api.get_messages_by_time_in_chat(
chat_id=chat_id,
start_time=float(args.get("start_time", 0.0)),
end_time=float(args.get("end_time", 0.0)),
limit=args.get("limit", 0),
limit_mode=args.get("limit_mode", "latest"),
filter_mai=args.get("filter_mai", False),
filter_command=args.get("filter_command", False),
)
return {"success": True, "messages": self._serialize_messages(messages)}
except Exception as e:
logger.error(f"[cap.message.get_by_time_in_chat] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_message_get_recent(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import message_service as message_api
chat_id: str = args.get("chat_id", "")
if not chat_id:
return {"success": False, "error": "缺少必要参数 chat_id"}
try:
messages = message_api.get_recent_messages(
chat_id=chat_id,
hours=float(args.get("hours", 24.0)),
limit=args.get("limit", 100),
limit_mode=args.get("limit_mode", "latest"),
filter_mai=args.get("filter_mai", False),
)
return {"success": True, "messages": self._serialize_messages(messages)}
except Exception as e:
logger.error(f"[cap.message.get_recent] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_message_count_new(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import message_service as message_api
chat_id: str = args.get("chat_id", "")
if not chat_id:
return {"success": False, "error": "缺少必要参数 chat_id"}
try:
since = args.get("since")
start_time = float(since) if since is not None else float(args.get("start_time", 0.0))
count = message_api.count_new_messages(
chat_id=chat_id,
start_time=start_time,
end_time=args.get("end_time"),
)
return {"success": True, "count": count}
except Exception as e:
logger.error(f"[cap.message.count_new] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_message_build_readable(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import message_service as message_api
try:
messages = args.get("messages")
if messages is None:
if not (chat_id := args.get("chat_id", "")):
return {"success": False, "error": "缺少必要参数: messages 或 chat_id"}
messages = message_api.get_messages_by_time_in_chat(
chat_id=chat_id,
start_time=float(args.get("start_time", 0.0)),
end_time=float(args.get("end_time", 0.0)),
limit=args.get("limit", 0),
)
readable = message_api.build_readable_messages_to_str(
messages=messages,
replace_bot_name=args.get("replace_bot_name", True),
timestamp_mode=args.get("timestamp_mode", "relative"),
truncate=args.get("truncate", False),
)
return {"success": True, "text": readable}
except Exception as e:
logger.error(f"[cap.message.build_readable] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_person_get_id(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.person_info.person_info import Person
platform: str = args.get("platform", "")
user_id = args.get("user_id", "")
if not platform or not user_id:
return {"success": False, "error": "缺少必要参数 platform 或 user_id"}
try:
pid = Person(platform=platform, user_id=str(user_id)).person_id
return {"success": True, "person_id": pid}
except Exception as e:
logger.error(f"[cap.person.get_id] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_person_get_value(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.person_info.person_info import Person
person_id: str = args.get("person_id", "")
field_name: str = args.get("field_name", "")
if not person_id or not field_name:
return {"success": False, "error": "缺少必要参数 person_id 或 field_name"}
try:
person = Person(person_id=person_id)
value = getattr(person, field_name)
if value is None:
value = args.get("default")
return {"success": True, "value": value}
except Exception as e:
logger.error(f"[cap.person.get_value] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_person_get_id_by_name(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.person_info.person_info import Person
person_name: str = args.get("person_name", "")
if not person_name:
return {"success": False, "error": "缺少必要参数 person_name"}
try:
pid = Person(person_name=person_name).person_id
return {"success": True, "person_id": pid}
except Exception as e:
logger.error(f"[cap.person.get_id_by_name] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_emoji_get_by_description(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import emoji_service as emoji_api
description: str = args.get("description", "")
if not description:
return {"success": False, "error": "缺少必要参数 description"}
try:
result = await emoji_api.get_by_description(description=description)
if result is None:
return {"success": True, "emoji": None}
emoji_base64, emoji_desc, matched_emotion = result
return {
"success": True,
"emoji": {
"base64": emoji_base64,
"description": emoji_desc,
"emotion": matched_emotion,
},
}
except Exception as e:
logger.error(f"[cap.emoji.get_by_description] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_emoji_get_random(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import emoji_service as emoji_api
count: int = args.get("count", 1)
try:
results = await emoji_api.get_random(count=count)
emojis = [{"base64": b64, "description": desc, "emotion": emo} for b64, desc, emo in results]
return {"success": True, "emojis": emojis}
except Exception as e:
logger.error(f"[cap.emoji.get_random] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_emoji_get_count(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import emoji_service as emoji_api
try:
return {"success": True, "count": emoji_api.get_count()}
except Exception as e:
logger.error(f"[cap.emoji.get_count] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_emoji_get_emotions(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import emoji_service as emoji_api
try:
return {"success": True, "emotions": emoji_api.get_emotions()}
except Exception as e:
logger.error(f"[cap.emoji.get_emotions] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_emoji_get_all(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import emoji_service as emoji_api
try:
results = await emoji_api.get_all()
emojis = [{"base64": b64, "description": desc, "emotion": emo} for b64, desc, emo in results] if results else []
return {"success": True, "emojis": emojis}
except Exception as e:
logger.error(f"[cap.emoji.get_all] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_emoji_get_info(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import emoji_service as emoji_api
try:
return {"success": True, "info": emoji_api.get_info()}
except Exception as e:
logger.error(f"[cap.emoji.get_info] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_emoji_register(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import emoji_service as emoji_api
emoji_base64: str = args.get("emoji_base64", "")
if not emoji_base64:
return {"success": False, "error": "缺少必要参数 emoji_base64"}
try:
return await emoji_api.register_emoji(emoji_base64)
except Exception as e:
logger.error(f"[cap.emoji.register] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_emoji_delete(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.services import emoji_service as emoji_api
emoji_hash: str = args.get("emoji_hash", "")
if not emoji_hash:
return {"success": False, "error": "缺少必要参数 emoji_hash"}
try:
return await emoji_api.delete_emoji(emoji_hash)
except Exception as e:
logger.error(f"[cap.emoji.delete] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
@staticmethod
def _get_frequency_adjust_value(chat_id: str) -> float:
from src.chat.heart_flow.heartflow_manager import heartflow_manager
heartflow_chat = heartflow_manager.heartflow_chat_list.get(chat_id)
return 1.0 if heartflow_chat is None else heartflow_chat._talk_frequency_adjust
async def _cap_frequency_get_current_talk_value(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.common.utils.utils_config import ChatConfigUtils
chat_id: str = args.get("chat_id", "")
if not chat_id:
return {"success": False, "error": "缺少必要参数 chat_id"}
try:
value = self._get_frequency_adjust_value(chat_id) * ChatConfigUtils.get_talk_value(chat_id)
return {"success": True, "value": value}
except Exception as e:
logger.error(f"[cap.frequency.get_current_talk_value] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_frequency_set_adjust(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.chat.heart_flow.heartflow_manager import heartflow_manager
chat_id: str = args.get("chat_id", "")
value = args.get("value")
if not chat_id or value is None:
return {"success": False, "error": "缺少必要参数 chat_id 或 value"}
try:
heartflow_manager.adjust_talk_frequency(chat_id, float(value))
return {"success": True}
except Exception as e:
logger.error(f"[cap.frequency.set_adjust] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_frequency_get_adjust(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
chat_id: str = args.get("chat_id", "")
if not chat_id:
return {"success": False, "error": "缺少必要参数 chat_id"}
try:
value = self._get_frequency_adjust_value(chat_id)
return {"success": True, "value": value}
except Exception as e:
logger.error(f"[cap.frequency.get_adjust] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_tool_get_definitions(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
from src.core.component_registry import component_registry as core_registry
try:
tools = core_registry.get_llm_available_tools()
return {
"success": True,
"tools": [{"name": name, "definition": info.get_llm_definition()} for name, info in tools.items()],
}
except Exception as e:
logger.error(f"[cap.tool.get_definitions] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}
async def _cap_knowledge_search(self, plugin_id: str, capability: str, args: Dict[str, Any]) -> Any:
query: str = args.get("query", "")
if not query:
return {"success": False, "error": "缺少必要参数 query"}
limit = args.get("limit", 5)
try:
limit_value = max(1, int(limit))
except (TypeError, ValueError):
limit_value = 5
try:
from src.chat.knowledge import qa_manager
if qa_manager is None:
return {"success": True, "content": "LPMM知识库已禁用"}
knowledge_info = await qa_manager.get_knowledge(query, limit=limit_value)
content = f"你知道这些知识: {knowledge_info}" if knowledge_info else f"你不太了解有关{query}的知识"
return {"success": True, "content": content}
except Exception as e:
logger.error(f"[cap.knowledge.search] 执行失败: {e}", exc_info=True)
return {"success": False, "error": str(e)}

View File

@@ -0,0 +1,80 @@
from typing import TYPE_CHECKING
from src.common.logger import get_logger
from src.plugin_runtime.host.supervisor import PluginSupervisor
if TYPE_CHECKING:
from src.plugin_runtime.integration import PluginRuntimeManager
logger = get_logger("plugin_runtime.integration")
def register_capability_impls(manager: "PluginRuntimeManager", supervisor: PluginSupervisor) -> None:
"""向指定 Supervisor 注册主程序提供的能力实现。"""
cap_service = supervisor.capability_service
cap_service.register_capability("send.text", manager._cap_send_text)
cap_service.register_capability("send.emoji", manager._cap_send_emoji)
cap_service.register_capability("send.image", manager._cap_send_image)
cap_service.register_capability("send.command", manager._cap_send_command)
cap_service.register_capability("send.custom", manager._cap_send_custom)
cap_service.register_capability("send.forward", manager._cap_send_forward)
cap_service.register_capability("send.hybrid", manager._cap_send_hybrid)
cap_service.register_capability("llm.generate", manager._cap_llm_generate)
cap_service.register_capability("llm.generate_with_tools", manager._cap_llm_generate_with_tools)
cap_service.register_capability("llm.get_available_models", manager._cap_llm_get_available_models)
cap_service.register_capability("config.get", manager._cap_config_get)
cap_service.register_capability("config.get_plugin", manager._cap_config_get_plugin)
cap_service.register_capability("config.get_all", manager._cap_config_get_all)
cap_service.register_capability("database.query", manager._cap_database_query)
cap_service.register_capability("database.save", manager._cap_database_save)
cap_service.register_capability("database.get", manager._cap_database_get)
cap_service.register_capability("database.delete", manager._cap_database_delete)
cap_service.register_capability("database.count", manager._cap_database_count)
cap_service.register_capability("chat.get_all_streams", manager._cap_chat_get_all_streams)
cap_service.register_capability("chat.get_group_streams", manager._cap_chat_get_group_streams)
cap_service.register_capability("chat.get_private_streams", manager._cap_chat_get_private_streams)
cap_service.register_capability("chat.get_stream_by_group_id", manager._cap_chat_get_stream_by_group_id)
cap_service.register_capability("chat.get_stream_by_user_id", manager._cap_chat_get_stream_by_user_id)
cap_service.register_capability("message.get_by_time", manager._cap_message_get_by_time)
cap_service.register_capability("message.get_by_time_in_chat", manager._cap_message_get_by_time_in_chat)
cap_service.register_capability("message.get_recent", manager._cap_message_get_recent)
cap_service.register_capability("message.count_new", manager._cap_message_count_new)
cap_service.register_capability("message.build_readable", manager._cap_message_build_readable)
cap_service.register_capability("person.get_id", manager._cap_person_get_id)
cap_service.register_capability("person.get_value", manager._cap_person_get_value)
cap_service.register_capability("person.get_id_by_name", manager._cap_person_get_id_by_name)
cap_service.register_capability("emoji.get_by_description", manager._cap_emoji_get_by_description)
cap_service.register_capability("emoji.get_random", manager._cap_emoji_get_random)
cap_service.register_capability("emoji.get_count", manager._cap_emoji_get_count)
cap_service.register_capability("emoji.get_emotions", manager._cap_emoji_get_emotions)
cap_service.register_capability("emoji.get_all", manager._cap_emoji_get_all)
cap_service.register_capability("emoji.get_info", manager._cap_emoji_get_info)
cap_service.register_capability("emoji.register", manager._cap_emoji_register)
cap_service.register_capability("emoji.delete", manager._cap_emoji_delete)
cap_service.register_capability("frequency.get_current_talk_value", manager._cap_frequency_get_current_talk_value)
cap_service.register_capability("frequency.set_adjust", manager._cap_frequency_set_adjust)
cap_service.register_capability("frequency.get_adjust", manager._cap_frequency_get_adjust)
cap_service.register_capability("tool.get_definitions", manager._cap_tool_get_definitions)
cap_service.register_capability("component.get_all_plugins", manager._cap_component_get_all_plugins)
cap_service.register_capability("component.get_plugin_info", manager._cap_component_get_plugin_info)
cap_service.register_capability("component.list_loaded_plugins", manager._cap_component_list_loaded_plugins)
cap_service.register_capability("component.list_registered_plugins", manager._cap_component_list_registered_plugins)
cap_service.register_capability("component.enable", manager._cap_component_enable)
cap_service.register_capability("component.disable", manager._cap_component_disable)
cap_service.register_capability("component.load_plugin", manager._cap_component_load_plugin)
cap_service.register_capability("component.unload_plugin", manager._cap_component_unload_plugin)
cap_service.register_capability("component.reload_plugin", manager._cap_component_reload_plugin)
cap_service.register_capability("knowledge.search", manager._cap_knowledge_search)
logger.debug("已注册全部主程序能力实现")

File diff suppressed because it is too large Load Diff