feat: add runtime capability probing

这个提交存在于:
YokiiroBW 2026-07-24 21:34:04 +08:00
父节点 809a1ed3bb
当前提交 e66be2a993
共有 6 个文件被更改,包括 227 次插入 和 0 次删除

查看文件

@ -34,6 +34,14 @@ class MemoryCompanionBridge:
def __init__(self, plugin: Any):
self._plugin = plugin
def probe_runtime_capabilities(self) -> dict[str, Any]:
capabilities = getattr(self._plugin, "runtime_capabilities", None)
if capabilities is None:
return {"compatibility_level": "unknown", "capabilities": {}}
getter = getattr(capabilities, "to_dict", None)
result = getter() if callable(getter) else capabilities
return result if isinstance(result, dict) else {"compatibility_level": "unknown", "capabilities": {}}
async def record_event(
self,
*,

查看文件

@ -310,6 +310,23 @@ class MemoryCompanionCommandHandler:
)
return "用法:/mcomp preset status|apply light|standard|companion"
def runtime(self) -> str:
capabilities = getattr(self.service, "runtime_capabilities", None)
if capabilities is None:
return "运行时能力探测不可用。"
payload = capabilities.to_dict()
lines = [
f"AstrBot 运行时:{payload.get('astrbot_version', 'unknown')}",
f"兼容级别:{payload.get('compatibility_level', 'unknown')}",
f"API 世代:{payload.get('api_generation', 'unknown')}",
]
missing = payload.get("missing_required") or []
if missing:
lines.append("缺少必需能力:" + ", ".join(str(item) for item in missing))
for warning in payload.get("warnings") or []:
lines.append("提示:" + str(warning))
return "\n".join(lines)
async def ops_migration(self, action: str = "preview", source: str = "") -> str:
action = clean_text(action, 40).lower() or "preview"
source_path = Path(source).expanduser() if source.strip() else self.service.data_dir.parent / "astrbot_plugin_memory_companion"

127
core/runtime_compat.py 普通文件
查看文件

@ -0,0 +1,127 @@
from __future__ import annotations
import importlib
import importlib.metadata
from dataclasses import asdict, dataclass, field
from typing import Any
_REQUIRED_CAPABILITIES = (
"star_register",
"data_dir",
"event_hooks",
"provider_request",
"message_components",
)
_OPTIONAL_IMPORTS = {
"star_register": ("astrbot.api.star", "register"),
"data_dir": ("astrbot.api.star", "StarTools"),
"event_hooks": ("astrbot.api.event", "filter"),
"provider_request": ("astrbot.api.provider", "ProviderRequest"),
}
@dataclass(frozen=True)
class RuntimeCapabilities:
plugin_name: str
plugin_version: str
astrbot_version: str = "unknown"
api_generation: str = "unknown"
compatibility_level: str = "unsupported"
capabilities: dict[str, bool] = field(default_factory=dict)
missing_required: tuple[str, ...] = ()
warnings: tuple[str, ...] = ()
def to_dict(self) -> dict[str, Any]:
result = asdict(self)
result["missing_required"] = list(self.missing_required)
result["warnings"] = list(self.warnings)
return result
def _version_from_module() -> str:
for module_name in ("astrbot", "astrbot.core"):
try:
module = importlib.import_module(module_name)
except Exception:
continue
for attr_name in ("__version__", "VERSION", "version"):
value = getattr(module, attr_name, "")
if value:
return str(value)
for distribution_name in ("astrbot", "AstrBot"):
try:
return importlib.metadata.version(distribution_name)
except importlib.metadata.PackageNotFoundError:
continue
except Exception:
break
return "unknown"
def _probe_import(module_name: str, attribute_name: str) -> bool:
try:
module = importlib.import_module(module_name)
return hasattr(module, attribute_name)
except Exception:
return False
def _probe_filter_capabilities() -> dict[str, bool]:
try:
module = importlib.import_module("astrbot.api.event")
event_filter = getattr(module, "filter", None)
except Exception:
event_filter = None
return {
"llm_request_hook": callable(getattr(event_filter, "on_llm_request", None)),
"llm_response_hook": callable(getattr(event_filter, "on_llm_response", None)),
"event_message_type": callable(getattr(event_filter, "event_message_type", None)),
"command_group": callable(getattr(event_filter, "command_group", None)),
}
def probe_runtime_capabilities(
*,
context: Any = None,
event: Any = None,
plugin_name: str = "",
plugin_version: str = "",
) -> RuntimeCapabilities:
capabilities = {name: _probe_import(*target) for name, target in _OPTIONAL_IMPORTS.items()}
capabilities.update(_probe_filter_capabilities())
capabilities["message_components"] = _probe_import("astrbot.api.message_components", "Plain") or _probe_import(
"astrbot.core.message.components", "Plain"
)
capabilities["web_api"] = callable(getattr(context, "register_web_api", None))
capabilities["platform_manager"] = getattr(context, "platform_manager", None) is not None
capabilities["event_unified_msg_origin"] = bool(event is not None and hasattr(event, "unified_msg_origin"))
capabilities["event_send"] = any(
callable(getattr(event, name, None)) for name in ("send", "send_message", "plain_result")
)
capabilities["event_stop"] = callable(getattr(event, "stop_event", None))
missing_required = tuple(name for name in _REQUIRED_CAPABILITIES if not capabilities.get(name, False))
warnings: list[str] = []
if not capabilities.get("web_api"):
warnings.append("当前上下文没有 register_web_api,管理页面/扩展 API 需要降级或关闭")
if not capabilities.get("platform_manager"):
warnings.append("当前上下文没有 platform_manager,平台实例选择将依赖事件或配置")
if not capabilities.get("event_unified_msg_origin"):
warnings.append("启动探测阶段没有事件对象,消息 scope 需在收到事件后再次确认")
if missing_required:
level = "unsupported"
elif len(warnings) > 1:
level = "degraded"
else:
level = "full"
version = _version_from_module()
api_generation = "4.x" if version.startswith("4.") else "unknown"
return RuntimeCapabilities(
plugin_name=plugin_name,
plugin_version=plugin_version,
astrbot_version=version,
api_generation=api_generation,
compatibility_level=level,
capabilities=capabilities,
missing_required=missing_required,
warnings=tuple(warnings),
)

查看文件

@ -132,3 +132,23 @@
- 修复或规避:增加 `core/ops_migration.py`,只允许管理员显式执行 preview/run;SQLite 使用只读校验与 backup,成功后写迁移标记。
- 预防规则:先预览和备份,再执行迁移;目标非空、格式损坏或已有标记时必须拒绝。
- 验证证据:`tests/test_ops_migration.py` 5 项 unittest 通过,`compileall` 通过。
## 2026-07-24 — 运行时能力与平台能力不能混成一层
- 阶段:Q2 运行时兼容层
- 类型:API契约 / 兼容性
- 现象:已有 `platform_compat.py` 能判断 OneBot、QQ 官方等平台动作,但无法说明当前 AstrBot 是否提供对应 Hook、ProviderRequest 或消息组件。
- 根因:平台能力和宿主运行时 API 是两种不同维度;只判断平台会把版本/API 缺失误判成平台不支持。
- 修复或规避:新增 `runtime_compat.py`,启动时只做导入和对象形状探测,返回 full/degraded/unsupported;平台能力继续由 `platform_compat.py` 负责。
- 预防规则:新增 AstrBot API 调用前先进入运行时兼容层;不得用未认证管理 API 作为能力探测依据。
- 验证证据:运行时兼容单元测试 2 项通过,插件 compileall 通过。
## 2026-07-24 — 运维版模块名必须进入跨插件发现列表
- 阶段:Q2 插件联动适配
- 类型:API契约 / 集成
- 现象:Memory Archivist 只寻找普通版 MemoryCompanion 模块名,运维版插件虽然已安装,仍会被判定为记忆源不可用。
- 根因:普通版和运维版按设计使用不同插件身份,跨插件发现不能只保留旧包名。
- 修复或规避:Memory Archivist 的公开适配器加入 `astrbot_plugin_memory_companion_ops.main` 和 `data.plugins.astrbot_plugin_memory_companion_ops.main`,并读取 Bridge 的运行时能力快照。
- 预防规则:插件分支改名时必须同步检查模块发现、Bridge、页面、备份和适配器候选列表。
- 验证证据:适配器和测试 `py_compile` 通过;最小能力探测返回 archive 与 runtime 两组状态。

17
main.py
查看文件

@ -14,6 +14,7 @@ from .core.bridge import MemoryCompanionBridge
from .core.commands import MemoryCompanionCommandHandler
from .core.models import json_dumps
from .core.service import MemoryCompanionService
from .core.runtime_compat import probe_runtime_capabilities
from .plugin_identity import PLUGIN_DISPLAY_NAME, PLUGIN_NAME, PLUGIN_REPO, PLUGIN_VERSION
_ACTIVE_BRIDGE: MemoryCompanionBridge | None = None
@ -45,12 +46,23 @@ class MemoryCompanionPlugin(Star):
super().__init__(context)
self.context = context
data_dir = _prepare_data_dir()
self.runtime_capabilities = probe_runtime_capabilities(
context=context, plugin_name=PLUGIN_NAME, plugin_version=PLUGIN_VERSION
)
if self.runtime_capabilities.compatibility_level != "full":
logger.warning(
"[MemoryCompanionOps] AstrBot 运行时兼容级别=%s missing=%s warnings=%s",
self.runtime_capabilities.compatibility_level,
self.runtime_capabilities.missing_required,
self.runtime_capabilities.warnings,
)
self.service = MemoryCompanionService(
context=context,
config=config or {},
plugin_root=Path(__file__).resolve().parent,
data_dir=data_dir,
)
self.service.runtime_capabilities = self.runtime_capabilities
self.memory_companion = MemoryCompanionBridge(self.service)
self.commands = MemoryCompanionCommandHandler(self.service, PLUGIN_VERSION)
self.page_api = None
@ -291,6 +303,11 @@ class MemoryCompanionPlugin(Star):
yield event.plain_result(await self.commands.portable_data(action, path))
@permission_type(PermissionType.ADMIN)
@permission_type(PermissionType.ADMIN)
@mcomp.command("runtime", priority=10)
async def cmd_mcomp_runtime(self, event: AstrMessageEvent) -> AsyncGenerator[MessageEventResult, None]:
yield event.plain_result(self.commands.runtime())
@mcomp.command("ops_migration", priority=10)
async def cmd_mcomp_ops_migration(
self, event: AstrMessageEvent, action: str = "preview", source: str = ""

查看文件

@ -0,0 +1,38 @@
from __future__ import annotations
import unittest
from core.runtime_compat import probe_runtime_capabilities
class RuntimeCompatTests(unittest.TestCase):
def test_probe_is_safe_without_astrbot_runtime(self) -> None:
result = probe_runtime_capabilities(
context=type("Context", (), {})(),
plugin_name="astrbot_plugin_memory_companion_ops",
plugin_version="1.6.2-ops.1",
)
payload = result.to_dict()
self.assertEqual("astrbot_plugin_memory_companion_ops", payload["plugin_name"])
self.assertIn(payload["compatibility_level"], {"unsupported", "degraded", "full"})
self.assertIsInstance(payload["capabilities"], dict)
self.assertIsInstance(payload["warnings"], list)
def test_event_capabilities_are_detected_without_calling_event(self) -> None:
event = type(
"Event",
(),
{
"unified_msg_origin": "qq:private:1",
"send": lambda self, *args, **kwargs: None,
"stop_event": lambda self: None,
},
)()
result = probe_runtime_capabilities(event=event)
self.assertTrue(result.capabilities["event_unified_msg_origin"])
self.assertTrue(result.capabilities["event_send"])
self.assertTrue(result.capabilities["event_stop"])
if __name__ == "__main__":
unittest.main()