Files
agent-safe-middleware/middleware/runtime.py
T
Автомата Калашникова af7b2e28f3 请求侧改为直接拦截,宿主统一渲染 OpenAI 错误体
response_guard.lua:判定通过直接 pass,原始请求一字不改转发上游;不通过直接 block。删除 stub 替换逻辑,风险请求不再让上游白跑一次生成。

middleware/errors.py:PolicyBlocked 携带 code。middleware/runtime.py:block 的 reason 经白名单映射成 code,插件文本不进响应。middleware/proxy.py:PolicyBlocked 输出 OpenAI 错误体(400 content_policy_violation / 503 safety_review_unavailable),替换原来的 403 {error: PolicyBlocked}。

tools/verify_plugins.py:断言同步到新流程。
2026-11-27 17:52:52 +08:00

397 lines
16 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 .attachments import validate_multipart
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__"
# A plugin may only name a rejection from this closed set; anything else falls back to the
# default. This keeps plugin-supplied text out of the response body (see errors.PolicyBlocked).
BLOCK_CODES = frozenset({"content_policy_violation", "safety_review_unavailable"})
DEFAULT_BLOCK_CODE = "content_policy_violation"
def block_code(reason):
return reason if reason in BLOCK_CODES else DEFAULT_BLOCK_CODE
class Session:
def __init__(self, manager, request_id=None, plugins=None, attachments=None):
self.manager = manager
self.attachments = attachments
self.plugins = list(manager.plugins if plugins is None else plugins)
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"] == "files":
if self.attachments is None or plugin == ADAPTER_ID:
raise PluginFailure()
reply["value"] = self.attachments.read_text(result["value"])
elif result["kind"] == "log":
reply["value"] = None
payload = result["value"]
if not isinstance(payload, dict):
raise PluginFailure()
level = payload.get("level")
message = payload.get("message")
levels = {
"info": logging.INFO,
"warning": logging.WARNING,
"error": logging.ERROR,
}
if (
not isinstance(level, str)
or level not in levels
or not isinstance(message, str)
):
raise PluginFailure()
raw = message.encode("utf-8")
max_bytes = self.manager.settings.limits.max_plugin_buffer_bytes
truncated = len(raw) > max_bytes
message = raw[:max_bytes].decode("utf-8", errors="ignore")
logger.log(
levels[level],
"plugin_log request=%s plugin=%s truncated=%s message=%s",
self.context["request_id"],
plugin,
truncated,
json.dumps(message, ensure_ascii=False),
)
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):
plugin_ids = [] if adapter_only else [plugin.id for plugin in self.plugins]
plugin_ids.append(ADAPTER_ID)
for plugin_id in plugin_ids:
source = self.manager.sources[plugin_id]
config = self.manager.plugins_by_id.get(plugin_id)
await self.rpc(
{
"op": "load",
"plugin": plugin_id,
"source": source,
"llm": self.manager.llm.describe_for(plugin_id),
}
)
self.initialized.append(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.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_request" and self.attachments is not None:
for candidate in output:
# Validate every stage so later plugins never see forged file metadata.
validate_multipart(candidate, item)
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(block_code(result.get("reason")))
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.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:
try:
await self.kill()
finally:
try:
if self.attachments is not None:
await self.attachments.aclose()
finally:
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,
2 * limits.max_attachment_text_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, path=None, adapter_only=False, all_plugins=False, attachments=None
):
if self.stopping or len(self.sessions) >= self.settings.limits.max_sessions:
raise Overloaded()
if path is None and not adapter_only and not all_plugins:
raise ValueError("path is required when opening a plugin session")
await self.start()
plugins = self.plugins if all_plugins else self.plugins_for_path(path)
session = Session(self, request_id, plugins, attachments)
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(all_plugins=True)
await session.aclose()
def plugins_for_path(self, path):
return [
plugin for plugin in self.plugins if plugin.match is None or plugin.match.matches(path)
]
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()