Files
agent-safe-middleware/middleware/runtime.py
T
starrrLight b331927773 feat(LLM): 增加可扩展模型插件能力
新增顶层 LLM 注册配置、插件授权列表和 guard 类型适配器。\n模型由独立 Python 进程加载,通过受限 IPC 为 Lua 提供 host.llm.list、host.llm.call 和可调用接口。\n增加 Qwen3Guard 结果解析、流式审核示例、可选依赖、Docker 构建文件和协议测试。
2026-10-11 17:39:03 +08:00

336 lines
13 KiB
Python

import asyncio
import json
import logging
import multiprocessing
import time
from datetime import UTC, datetime
from pathlib import Path
from uuid import uuid4
from .config import Settings
from .errors import LimitExceeded, Overloaded, PluginFailure, PolicyBlocked
from .llm import LLMRegistry
from .network import NetworkBroker
from .worker import json_bytes, worker_main
logger = logging.getLogger("middleware.audit")
ADAPTER_ID = "__protocol_adapter__"
class Session:
def __init__(self, manager, request_id=None):
self.manager = manager
self.context = {"request_id": request_id or str(uuid4())}
self.started = time.monotonic()
self.closed = False
self.dead = False
self.initialized = []
context = multiprocessing.get_context("spawn")
self.connection, child = context.Pipe(duplex=True)
limits = manager.settings.limits.model_dump()
limits["ipc_bytes"] = manager.ipc_bytes
self.process = context.Process(target=worker_main, args=(child, limits), daemon=True)
try:
self.process.start()
except Exception:
self.connection.close()
raise PluginFailure() from None
finally:
child.close()
async def kill(self):
self.dead = True
self.connection.close()
if self.process.is_alive():
self.process.terminate()
await asyncio.to_thread(self.process.join, 1)
if self.process.is_alive():
self.process.kill()
await asyncio.to_thread(self.process.join, 1)
async def rpc(self, command: dict):
if self.dead:
raise PluginFailure()
plugin = command["plugin"]
started = time.perf_counter()
action = "failure"
completed = False
try:
async with asyncio.timeout(self.manager.settings.limits.hook_timeout_seconds):
message = json_bytes(command)
if len(message) > self.manager.ipc_bytes:
raise LimitExceeded()
await asyncio.to_thread(self.connection.send_bytes, message)
callbacks = 0
while True:
raw = await asyncio.to_thread(
self.connection.recv_bytes,
self.manager.ipc_bytes,
)
result = json.loads(raw)
if result.get("type") == "callback":
callbacks += 1
if callbacks > self.manager.settings.limits.max_host_calls_per_hook:
raise LimitExceeded()
if result.get("plugin") != plugin:
raise PluginFailure()
reply = {"type": "callback_result"}
try:
if result["kind"] == "http":
config = self.manager.plugins_by_id.get(plugin)
if config is None:
raise PluginFailure()
reply["value"] = await self.manager.broker.request(
config.network,
result["value"],
self.manager.settings.limits.max_request_bytes,
)
elif result["kind"] == "log":
reply["value"] = None
logger.info(
"plugin_log request=%s plugin=%s",
self.context["request_id"],
plugin,
)
elif result["kind"] == "llm":
payload = result["value"]
if (
not isinstance(payload, dict)
or set(payload) != {"model", "request"}
or not isinstance(payload["model"], str)
or not isinstance(payload["request"], dict)
):
raise PluginFailure()
reply["value"] = await self.manager.llm.call(
plugin, payload["model"], payload["request"]
)
else:
raise PluginFailure()
except Exception:
reply["error"] = "CapabilityFailed"
await asyncio.to_thread(self.connection.send_bytes, json_bytes(reply))
elif result.get("type") == "result":
completed = True
if result.get("error"):
raise PluginFailure()
value = result.get("value")
action = value.get("action", "pass") if isinstance(value, dict) else "pass"
# Only allow fixed log tokens, never caller-supplied action strings.
action = (
action if action in {"pass", "replace", "hold", "block"} else "invalid"
)
return value
else:
raise PluginFailure()
except asyncio.CancelledError:
await self.kill()
raise
except Exception:
if not completed:
await self.kill()
raise PluginFailure() from None
finally:
logger.info(
"plugin_hook request=%s plugin=%s hook=%s action=%s duration_ms=%d",
self.context["request_id"],
plugin,
command.get("hook", "load"),
action,
int((time.perf_counter() - started) * 1000),
)
async def initialize(self, adapter_only=False):
for plugin_id, source in self.manager.sources.items():
if adapter_only and plugin_id != ADAPTER_ID:
continue
await self.rpc(
{
"op": "load",
"plugin": plugin_id,
"source": source,
"llm": self.manager.llm.describe_for(plugin_id),
}
)
self.initialized.append(plugin_id)
config = self.manager.plugins_by_id.get(plugin_id)
result = await self.invoke(plugin_id, "init", config.config if config else {})
if result is not None:
raise PluginFailure()
async def invoke(self, plugin_id, hook, value=None):
return await self.rpc(
{
"op": "invoke",
"plugin": plugin_id,
"hook": hook,
"context": {**self.context, "plugin_id": plugin_id},
"value": value,
}
)
async def apply(self, hook, value, start=0):
values = [value]
for plugin in self.manager.plugins[start:]:
output = []
for item in values:
result = await self.invoke(plugin.id, hook, item)
output.extend(self.decision(result, item, hook))
if hook == "on_event":
self.check_events_size(output)
values = output
if hook == "on_event":
output = []
for item in values:
result = await self.invoke(ADAPTER_ID, hook, item)
output.extend(self.decision(result, item, hook))
self.check_events_size(output)
values = output
return values
def check_events_size(self, events):
if len(json_bytes(events)) > self.manager.settings.limits.max_plugin_buffer_bytes:
raise LimitExceeded()
def decision(self, result, original, hook):
if result is None:
return [original] if hook != "on_end" else []
if not isinstance(result, dict) or set(result) - {"action", "value", "events", "reason"}:
raise PluginFailure()
action = result.get("action")
if action == "block":
raise PolicyBlocked()
if action == "pass":
if "value" in result or "events" in result:
raise PluginFailure()
return [original] if hook != "on_end" else []
if action == "hold" and hook == "on_event":
if "value" in result or "events" in result:
raise PluginFailure()
return []
if action == "replace":
if hook in {"on_event", "on_end"}:
if (
"events" not in result
or "value" in result
or not isinstance(result["events"], list)
):
raise PluginFailure()
output = result["events"]
if len(json_bytes(output)) > self.manager.settings.limits.max_plugin_buffer_bytes:
raise LimitExceeded()
return output
if "value" not in result or "events" in result or not isinstance(result["value"], dict):
raise PluginFailure()
return [result["value"]]
raise PluginFailure()
async def end(self):
output = []
for index, plugin in enumerate(self.manager.plugins):
result = await self.invoke(plugin.id, "on_end")
for event in self.decision(result, None, "on_end"):
output.extend(await self.apply("on_event", event, start=index + 1))
if len(json_bytes(output)) > self.manager.settings.limits.max_plugin_buffer_bytes:
raise LimitExceeded()
# The protocol adapter defers the success terminal event until every end hook passes.
result = await self.invoke(ADAPTER_ID, "on_end")
output.extend(self.decision(result, None, "on_end"))
self.check_events_size(output)
return output
async def aclose(self):
if self.closed:
return
self.closed = True
try:
if not self.dead:
for plugin_id in reversed(self.initialized):
try:
await self.invoke(plugin_id, "close")
except Exception:
continue
finally:
await self.kill()
self.manager.sessions.discard(self)
class PluginManager:
def __init__(self, settings: Settings):
self.settings = settings
self.plugins = [plugin for plugin in settings.plugins if plugin.enabled]
self.plugins_by_id = {plugin.id: plugin for plugin in self.plugins}
self.sources = {
plugin.id: plugin.file.read_text(encoding="utf-8") for plugin in self.plugins
}
if ADAPTER_ID in self.plugins_by_id:
raise ValueError("reserved plugin ID")
self.sources[ADAPTER_ID] = (
Path(__file__)
.with_name("lua")
.joinpath("agent_protocol.lua")
.read_text(encoding="utf-8")
)
limits = settings.limits
self.ipc_bytes = (
4
* max(
limits.max_request_bytes,
limits.max_response_bytes,
limits.max_plugin_buffer_bytes,
limits.max_sse_frame_bytes,
*(p.network.max_response_bytes for p in self.plugins),
)
+ 65536
)
self.broker = NetworkBroker()
self.llm = LLMRegistry(settings)
self.llm_started = False
self.sessions = set()
self.stopping = False
async def start(self):
if not self.llm_started:
await self.llm.start()
self.llm_started = True
async def open(self, request_id=None, adapter_only=False):
if self.stopping or len(self.sessions) >= self.settings.limits.max_sessions:
raise Overloaded()
await self.start()
session = Session(self, request_id)
self.sessions.add(session)
try:
await session.initialize(adapter_only)
return session
except BaseException:
await session.aclose()
raise
async def validate(self):
session = await self.open()
await session.aclose()
async def error_event(self, request_id, last_event, error_type):
# Failed/timed-out business runtimes never render their own errors.
session = await self.open(request_id, adapter_only=True)
try:
result = await session.invoke(
ADAPTER_ID,
"on_error",
{
"last_event": last_event,
"error_type": error_type,
"timestamp": datetime.now(UTC).isoformat(),
},
)
if not isinstance(result, dict):
raise PluginFailure()
return result
finally:
await session.aclose()
async def shutdown(self):
self.stopping = True
await asyncio.gather(*(s.aclose() for s in list(self.sessions)), return_exceptions=True)
await self.llm.stop()