From 519d0a44fc84a255ed0585bf101cd4f901970140 Mon Sep 17 00:00:00 2001 From: su1feng <2286923612@qq.com> Date: Wed, 15 Jul 2026 19:16:38 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=94=AF=E6=8C=81=E5=A4=9A=E8=BD=AE?= =?UTF-8?q?=E5=B7=A5=E5=85=B7=E7=BB=93=E6=9E=9C=E5=9B=9E=E5=A1=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Agent 将受治理工具结果按 tool_call_id 回填模型上下文,并增加轮次、工具、令牌和时间预算的 fail-closed 收口与审计。 --- ...33\345\272\246\347\234\213\346\235\277.md" | 1 + ...23\346\236\234\345\233\236\345\241\253.md" | 33 +++ src/fulcrum/adapters/assistant/agent.py | 206 ++++++++++++++++-- tests/test_assistant_agent.py | 133 +++++++++++ 4 files changed, 357 insertions(+), 16 deletions(-) create mode 100644 "docs/plan/16-Agent\345\267\245\345\205\267\347\273\223\346\236\234\345\233\236\345\241\253.md" diff --git "a/docs/plan/03-\350\277\233\345\272\246\347\234\213\346\235\277.md" "b/docs/plan/03-\350\277\233\345\272\246\347\234\213\346\235\277.md" index 01aca7e..49501e6 100644 --- "a/docs/plan/03-\350\277\233\345\272\246\347\234\213\346\235\277.md" +++ "b/docs/plan/03-\350\277\233\345\272\246\347\234\213\346\235\277.md" @@ -200,3 +200,4 @@ | v1.64 | 2026-07-07 | **审计读热路径修 M14(评审报告):三条轮询路由消 N+1 冗余全量读 + sqlite 阻塞卸载线程**:`/overview/stats`、`/audit`、`/events` 此前每次请求对每个会话各自 `verify_chain`(每次=该会话全量重读+JSON 反序列化+重算整链)再叠 `all_events()`,且 `SqliteAuditSink` 的同步 sqlite 直接跑在事件循环上——前端轮询看板=每次 N+1 趟全量读并卡住全部并发请求(认证后 DoS 面)。两刀:①**sink 卸载**——`append/events/verify_chain/locate_break` 内部同步读写经 `asyncio.to_thread` 进工作线程,事件循环不再被审计 I/O 卡住(审计写在每次判定的 await 路径上,受益面=全部请求);②**路由消冗余**——三路由改单遍取全量(经 to_thread)、按会话分组后就地 `locate_break` 校验;`/audit` 每会话从两读(events+verify_chain 内部重读)降一读。**实测(20 会话)每请求 sqlite 连接数:/overview 21→1、/events 22→1、/audit 41→21(减半)**。**防篡改语义红线(设计取舍,回归锁死)**:**故意不缓存校验结果**——校验的意义正是发现落库后被篡改的留痕,缓存布尔值会把事后篡改掩盖到进程重启;哈希仍逐事件全量重算(新鲜度不降级),只消重复 I/O。评审建议的「聚合走 SQL」不在本 PR(需动响应聚合口径,收益小于以上两刀,如实排后)。`assistant/operations` 同模式但非轮询路径且属维护者活跃区,不越界。+3 HTTP 级回归(篡改库内事件→三路由**下一次请求立即**反映未校验;完好路径响应口径不变)。全门绿:ruff/format/pyright 0、import-linter 3 KEPT、pytest 859→862。基于 origin/dev 独立提(fork→上游 FPSZ/Fulcrum:dev),版本号撞栈由审核者重编号 | | v1.65 | 2026-07-07 | **前端处置元数据抽单一真源(评审报告 M29)**:Disposition 的「类型 + 展示顺序 + 徽标色调」此前在 events/gateway/audit/policies/tools/supply/eval **七处各写一份**,且已实际漂移——events 的 sanitize 色调独为 `info`,其余六页与总览硬编码均为 `med`(正是复制粘贴的后果)。新增 `console/src/lib/disposition.ts` 单一真源:`Disposition` 类型(与后端 core.domain.Disposition 值域一致,supply 的 `Rating` 别名同源)、`DISPOSITION_ORDER`、`DISPOSITION_TONE`、宽入口 `dispositionTone()`(未收窄字符串用,未知值回退 neutral,口径同 eval 页旧 `?? 'neutral'`)。七页删本地拷贝改导入;5 处类型定义(events/audit/gateway/policies/tools)与 supply `Rating` 改"import + re-export"保持既有导入面零波及。**唯一行为变化(有意)**:events 页 sanitize 徽标色 `info`→`med`,归一到全站既成口径(六页+总览一致)。**刻意不归一**:各页处置**文案**(i18n)按语境措辞是设计而非重复(gateway「转人工审核」/supply「需复核」/events「待审批」/其余「审批」),留在各页命名空间。前端门绿:tsc 0、vite build 通过;全仓 `type Disposition` 定义与 tone 映射各仅剩 lib 一处(grep 验证)。13 文件改 + 1 新增,纯前端零后端。基于 origin/dev 独立提(fork→上游 FPSZ/Fulcrum:dev),版本号撞栈由审核者重编号 | | v1.66 | 2026-07-07 | **助手流式对话可中止 + 错误不再覆盖已流出内容(评审报告 M25)**:此前 `assistant-page` 的流式发送①无 AbortController——网络挂起时该轮 `streaming` 永真、busy 锁死输入,只能刷新页面;②catch 里 `text` 被**整体替换**为错误文案——流到一半断线,已流出的回答全部丢失。三处修:①`sendChatStream` 加可选 `signal` 参数透传 fetch(连接与 reader.read() 均以 AbortError 解除);②页面按会话维护 `AbortController` Map(键=会话 id,切会话互不干扰;**组件卸载不中止**——后台续写模块 store 是既有有意设计,保留),catch 区分「用户主动停止」(已有内容原样保留,一字未出标「已停止生成」)与「真错误」(**错误文案追加在已流出内容之后**,绝不整体替换);③Composer 发送键在流式期间变为可点的「停止」(Square 图标,GPT/Kimi 惯例)——网络挂起也能一键解除 busy。i18n 补 `assistant.composer.stop`/`assistant.turn.stopped` 中英两 key(MessageKey 由 zh 词典派生,编译期锁定)。前端门绿:tsc 0、vite build 通过。**诚实边界**:未本地配真模型跑流式端到端,中止语义依赖标准 fetch AbortController 行为(连接中断/读取拒绝为平台保证);5 文件纯前端。基于 origin/dev 独立提(fork→上游 FPSZ/Fulcrum:dev),版本号撞栈由审核者重编号 | +| v1.75 | 2026-07-15 | **多轮工具结果回填(PR #120)**:保留 `tool_call_id` 并记录轮次、工具、令牌与时间预算;异常路径采用 fail-closed 处置并补充审计证据。 | diff --git "a/docs/plan/16-Agent\345\267\245\345\205\267\347\273\223\346\236\234\345\233\236\345\241\253.md" "b/docs/plan/16-Agent\345\267\245\345\205\267\347\273\223\346\236\234\345\233\236\345\241\253.md" new file mode 100644 index 0000000..10bf8f0 --- /dev/null +++ "b/docs/plan/16-Agent\345\267\245\345\205\267\347\273\223\346\236\234\345\233\236\345\241\253.md" @@ -0,0 +1,33 @@ +# 15 · 多轮 Agent 工具结果回填 + +> 本文回答:AI 操作助手如何把受治理工具结果以 `tool_call_id` 回填模型,继续下一轮规划,并在预算、异常和超时时安全收口。 +> 状态:定稿 v1 + +## 范围 + +已实现的最小闭环位于 `src/fulcrum/adapters/assistant/agent.py`: + +- 模型返回 `tool_calls` 后,助手先按既有 RBAC、读写分流和工具返回闸门执行或处置;每一条结果都以 `role: tool`、原始 `tool_call_id`、工具名和受处置内容追加到规范消息序列。 +- 下一模型轮收到完整的 `assistant.tool_calls` 与对应 `tool` 消息,因此只能依据受治理结果继续规划。写类工具仍仅生成提案,确认、审批和撤销链路不变。 +- 单次会话默认限制为 8 个模型规划轮、8 次工具调用、12,000 个估算上下文令牌和 60 秒墙钟时间。令牌值由规范消息序列化字符数按保守规则估算,原因是当前三种模型传输协议没有统一 usage 返回。 +- 预算耗尽、模型或工具超时、模型或工具异常、越权工具调用都会停止后续模型/工具调用;出口闸门异常则拦截未审答复。所有这些路径均在既有 `ASSISTANT_CHAT` hash-chain 审计中记录终止原因、轮数、工具调用数和估算令牌数。 + +## 非范围与限制 + +- 本期不改变单轮成功路径,也不改变高危写操作的人审、策略和审批要求。 +- 预算不等同于上游账单 token;后续若所有模型协议均返回可靠 usage,可替换为精确计量。 +- 流式路径在最终出口闸门判定前仍可能已发送文本增量;最终 `done` 事件仍以出口闸门处置结果为准。这是现有流式协议的限制,不在本优先级修改范围。 + +## 验证 + +定向测试使用 fake model/client 和无害内存工具,不访问外部服务,覆盖: + +- 原始 `tool_call_id` 回填后触发下一轮规划。 +- 令牌预算耗尽时模型不被调用且会话审计收口。 +- 模型超时、受治理工具或出口闸门异常时停止后续规划或拦截答复,并留审计证据。 + +## 修订记录 + +| 版本 | 日期 | 变更 | +| --- | --- | --- | +| v1 | 2026-07-15 | 实现优先级 6 最小闭环:工具结果回填、多轮预算与 fail-closed 审计。 | diff --git a/src/fulcrum/adapters/assistant/agent.py b/src/fulcrum/adapters/assistant/agent.py index 8fe9aaa..1992b32 100644 --- a/src/fulcrum/adapters/assistant/agent.py +++ b/src/fulcrum/adapters/assistant/agent.py @@ -14,7 +14,10 @@ from __future__ import annotations -from collections.abc import AsyncIterator +import asyncio +import json +import time +from collections.abc import AsyncIterator, Callable from dataclasses import dataclass, field from typing import Any @@ -144,6 +147,10 @@ class AssistantRunResult: proposed_actions: list[AssistantProposedAction] = field(default_factory=list) approval_requests: list[AssistantApprovalRequest] = field(default_factory=list) steps: list[AssistantStep] = field(default_factory=list) + termination_reason: str = "" # 预算/异常导致的 fail-closed 收口原因 + model_rounds: int = 0 + tool_calls: int = 0 + estimated_tokens: int = 0 @dataclass(slots=True) @@ -154,11 +161,25 @@ class _ToolOutcome: step: AssistantStep ui: AssistantUiDirective | None = None proposal: AssistantProposedAction | None = None + terminal: bool = False # 异常/越权后停止后续规划,避免失败后继续扩权尝试 _MAX_FEED = 6000 # 单个工具回填给模型的最大字符数(防长列表撑爆上下文) +def _estimate_tokens(messages: list[dict]) -> int: + """零依赖的上下文令牌上界估算。 + + 模型协议未统一返回 usage,按规范消息序列化后的字符数除以 2 估算,宁可偏保守地提前 + 收口,也不在预算未知时继续把工具结果灌入下一轮规划。 + """ + try: + chars = len(json.dumps(messages, ensure_ascii=False, default=str)) + except (TypeError, ValueError): + chars = len(str(messages)) + return max(1, (chars + 1) // 2) + + def _read_feed(res: OperationResult) -> str: """把读类结果组装成回填模型的文本:摘要 + **结构化数据(JSON)**。 @@ -255,19 +276,59 @@ def __init__( model_turn: ModelTurn, *, max_steps: int = 8, + max_tool_calls: int | None = None, + max_session_tokens: int = 12_000, + max_session_seconds: float = 60.0, token_signer: ActionTokenSigner | None = None, stream_turn: StreamTurn | None = None, conversation: ConversationStore | None = None, summarizer: Summarizer | None = None, + clock: Callable[[], float] = time.monotonic, ) -> None: + if max_steps < 1 or (max_tool_calls is not None and max_tool_calls < 1): + raise ValueError("Agent 轮数与工具调用上限必须为正数") + if max_session_tokens < 1 or max_session_seconds <= 0: + raise ValueError("Agent 令牌与时间预算必须为正数") self._pipeline = pipeline self._services = services self._turn = model_turn self._max_steps = max_steps + self._max_tool_calls = max_tool_calls if max_tool_calls is not None else max_steps + self._max_session_tokens = max_session_tokens + self._max_session_seconds = max_session_seconds self._signer = token_signer self._stream = stream_turn self._conversation = conversation self._summarizer = summarizer + self._clock = clock + + def _budget_reason( + self, messages: list[dict], started: float, tool_calls: int + ) -> tuple[str, int]: + """在调用模型或工具前检查预算;超额一律停止后续规划。""" + estimated_tokens = _estimate_tokens(messages) + if self._clock() - started >= self._max_session_seconds: + return "time_limit", estimated_tokens + if estimated_tokens > self._max_session_tokens: + return "token_limit", estimated_tokens + if tool_calls >= self._max_tool_calls: + return "tool_call_limit", estimated_tokens + return "", estimated_tokens + + @staticmethod + def _termination_reply(reason: str) -> str: + messages = { + "round_limit": "已达到本次会话的规划轮数上限,已安全停止后续工具调用。", + "tool_call_limit": "已达到本次会话的工具调用上限,已安全停止后续工具调用。", + "token_limit": "上下文已达到本次会话的令牌预算,已安全停止后续规划。", + "time_limit": "本次会话已达到时间上限,已安全停止后续规划。", + "model_timeout": "模型规划超时,已安全停止后续工具调用。", + "model_error": "模型规划异常,已安全停止后续工具调用。", + "tool_timeout": "受治理工具执行超时,已安全停止后续规划。", + "tool_error": "受治理工具执行异常,已安全停止后续规划。", + "output_gate_error": "出口安全策略异常,已拦截本次答复。", + } + return messages.get(reason, "本次会话已安全停止后续规划。") def _initial_messages( self, intent: str, session_id: str, *, progressive: bool = False @@ -374,18 +435,49 @@ async def run(self, intent: str, principal: Any, session_id: str) -> AssistantRu messages = self._initial_messages(intent, session_id, progressive=progressive) final: str | None = None + started = self._clock() + tool_calls = 0 for _step in range(self._max_steps): + reason, result.estimated_tokens = self._budget_reason(messages, started, tool_calls) + if reason: + result.termination_reason = reason + break specs = self._specs_for_turn(tools, loaded) if progressive else all_specs - reply = await self._turn(messages, specs) + remaining = self._max_session_seconds - (self._clock() - started) + try: + reply = await asyncio.wait_for(self._turn(messages, specs), timeout=remaining) + except TimeoutError: + result.termination_reason = "model_timeout" + break + except Exception: # noqa: BLE001 -- 不可信模型异常必须 fail-closed + result.termination_reason = "model_error" + break + result.model_rounds += 1 if not reply.tool_calls: final = reply.content break messages.append(_assistant_msg(reply)) for tc in reply.tool_calls: + reason, result.estimated_tokens = self._budget_reason(messages, started, tool_calls) + if reason: + result.termination_reason = reason + break + tool_calls += 1 if progressive and tc.name == _SEARCH_TOOL_NAME: o = self._handle_search(tc, principal, tools, loaded) else: - o = await self._execute_tool(tc, by_name.get(tc.name), principal, session_id) + remaining = self._max_session_seconds - (self._clock() - started) + try: + o = await asyncio.wait_for( + self._execute_tool(tc, by_name.get(tc.name), principal, session_id), + timeout=remaining, + ) + except TimeoutError: + result.termination_reason = "tool_timeout" + break + except Exception: # noqa: BLE001 -- 工具/闸门异常不得继续规划 + result.termination_reason = "tool_error" + break result.steps.append(o.step) if o.ui is not None: result.ui_directives.append(o.ui) @@ -399,12 +491,27 @@ async def run(self, intent: str, principal: Any, session_id: str) -> AssistantRu "content": o.feed, } ) + if o.terminal: + result.termination_reason = "tool_error" + break + if result.termination_reason: + break if final is None: - final = "我已尽力检索(达到单轮步数上限)。请缩小范围或分步再问。" + result.termination_reason = result.termination_reason or "round_limit" + final = self._termination_reply(result.termination_reason) final = final or "(已完成上述操作。)" + result.tool_calls = tool_calls + result.estimated_tokens = _estimate_tokens(messages) - out = await self._pipeline.screen_output(session_id, final) + try: + out = await self._pipeline.screen_output(session_id, final) + except Exception: # noqa: BLE001 -- 出口闸门不可用时不得回传未审答复 + result.termination_reason = result.termination_reason or "output_gate_error" + result.reply = self._termination_reply("output_gate_error") + result.compressed = await self._persist(session_id, messages, result.reply) + await self._audit(session_id, principal, intent, result, gate) + return result if out.decision == Disposition.APPROVE: # 回复需人工复核:不直接回传内容,当面问操作员是否发起审批申请。 result.approval_requests.append(self._approval_request("output", out, final)) @@ -479,25 +586,58 @@ async def run_stream(self, intent: str, principal: Any, session_id: str) -> Asyn messages = self._initial_messages(intent, session_id, progressive=progressive) final: str | None = None + started = self._clock() + tool_calls = 0 for _step in range(self._max_steps): + reason, result.estimated_tokens = self._budget_reason(messages, started, tool_calls) + if reason: + result.termination_reason = reason + break specs = self._specs_for_turn(tools, loaded) if progressive else all_specs reply: ModelReply | None = None - async for chunk in stream(messages, specs): - if chunk.delta: - yield {"type": "delta", "text": chunk.delta} - elif chunk.final is not None: - reply = chunk.final + remaining = self._max_session_seconds - (self._clock() - started) + try: + async with asyncio.timeout(remaining): + async for chunk in stream(messages, specs): + if chunk.delta: + yield {"type": "delta", "text": chunk.delta} + elif chunk.final is not None: + reply = chunk.final + except TimeoutError: + result.termination_reason = "model_timeout" + break + except Exception: # noqa: BLE001 -- 流式模型异常不得继续调用工具 + result.termination_reason = "model_error" + break + result.model_rounds += 1 if reply is None: + result.termination_reason = "model_error" break if not reply.tool_calls: final = reply.content break messages.append(_assistant_msg(reply)) for tc in reply.tool_calls: + reason, result.estimated_tokens = self._budget_reason(messages, started, tool_calls) + if reason: + result.termination_reason = reason + break + tool_calls += 1 if progressive and tc.name == _SEARCH_TOOL_NAME: o = self._handle_search(tc, principal, tools, loaded) else: - o = await self._execute_tool(tc, by_name.get(tc.name), principal, session_id) + remaining = self._max_session_seconds - (self._clock() - started) + try: + o = await asyncio.wait_for( + self._execute_tool(tc, by_name.get(tc.name), principal, session_id), + timeout=remaining, + ) + except TimeoutError: + result.termination_reason = "tool_timeout" + break + except Exception: # noqa: BLE001 -- 工具/闸门异常不得继续规划 + result.termination_reason = "tool_error" + break result.steps.append(o.step) yield _step_event(o.step) if o.ui is not None: @@ -514,11 +654,33 @@ async def run_stream(self, intent: str, principal: Any, session_id: str) -> Asyn "content": o.feed, } ) + if o.terminal: + result.termination_reason = "tool_error" + break + if result.termination_reason: + break if final is None: - final = "我已尽力检索(达到单轮步数上限)。请缩小范围或分步再问。" + result.termination_reason = result.termination_reason or "round_limit" + final = self._termination_reply(result.termination_reason) final = final or "(已完成上述操作。)" - out = await self._pipeline.screen_output(session_id, final) + result.tool_calls = tool_calls + result.estimated_tokens = _estimate_tokens(messages) + try: + out = await self._pipeline.screen_output(session_id, final) + except Exception: # noqa: BLE001 -- 出口闸门不可用时不得回传未审答复 + result.termination_reason = result.termination_reason or "output_gate_error" + result.reply = self._termination_reply("output_gate_error") + result.compressed = await self._persist(session_id, messages, result.reply) + await self._audit(session_id, principal, intent, result, gate) + yield { + "type": "done", + "session_id": session_id, + "blocked": False, + "reply": result.reply, + "compressed": result.compressed, + } + return if out.decision == Disposition.APPROVE: req = self._approval_request("output", out, final) result.approval_requests.append(req) @@ -554,6 +716,7 @@ async def _execute_tool( return _ToolOutcome( feed="该工具不存在或你的角色无权调用,已拒绝。", step=AssistantStep(tc.name, "?", tc.name, False, "工具不可用或越权,已拒绝"), + terminal=True, ) if tool.kind == "ui": @@ -598,10 +761,17 @@ async def _execute_tool( assert tool.handler is not None try: res = await tool.handler(tc.arguments, principal, self._services) - except Exception as exc: # noqa: BLE001 —— 单个工具失败不拖垮整轮,记痕迹后跳过 + except Exception as exc: # noqa: BLE001 -- 异常结果不能驱动下一轮规划 return _ToolOutcome( - feed=f"执行「{tool.label}」时出错,已跳过。", - step=AssistantStep(tool.name, "read", tool.label, False, f"执行异常:{exc}"), + feed=f"执行「{tool.label}」时出错,已安全停止后续规划。", + step=AssistantStep( + tool.name, + "read", + tool.label, + False, + f"执行异常:{type(exc).__name__}", + ), + terminal=True, ) feed = _read_feed(res) @@ -651,6 +821,10 @@ async def _audit( "ui_directives": len(result.ui_directives), "proposed_actions": len(result.proposed_actions), "read_steps": sum(1 for s in result.steps if s.kind == "read"), + "termination_reason": result.termination_reason or "completed", + "model_rounds": result.model_rounds, + "tool_calls": result.tool_calls, + "estimated_tokens": result.estimated_tokens, }, ) ) diff --git a/tests/test_assistant_agent.py b/tests/test_assistant_agent.py index f334ac2..ed18d22 100644 --- a/tests/test_assistant_agent.py +++ b/tests/test_assistant_agent.py @@ -89,6 +89,139 @@ def test_read_orchestration_runs_and_audits(tmp_path: Path) -> None: assert any(e.event_type.value == "assistant_chat" for e in events) +def test_tool_result_is_refilled_with_original_tool_call_id(tmp_path: Path) -> None: + """下一轮规划必须看到与 assistant tool_calls 成对的 tool_call_id。""" + pipeline = _pipeline(tmp_path) + seen: list[list[dict]] = [] + + async def turn(messages: list[dict], _tools: list[dict]) -> ModelReply: + seen.append(list(messages)) + if len(seen) == 1: + return ModelReply( + tool_calls=[ToolCallReq(id="call-42", name="get_overview_stats", arguments={})] + ) + tool_result = messages[-1] + assert tool_result["role"] == "tool" + assert tool_result["tool_call_id"] == "call-42" + assert tool_result["name"] == "get_overview_stats" + return ModelReply(content="已基于工具结果完成下一轮规划。") + + agent = AssistantAgent(pipeline, _services(tmp_path, pipeline), turn) + res = asyncio.run(agent.run("查看总览", _principal(ALL_PERMISSION_KEYS), "s-tool-result")) + assert res.reply == "已基于工具结果完成下一轮规划。" + assert res.model_rounds == 2 and res.tool_calls == 1 + + +def test_budget_exhaustion_is_audited_and_stops_before_model(tmp_path: Path) -> None: + """令牌预算不足时不请求模型,且以 ASSISTANT_CHAT 留下收口证据。""" + pipeline = _pipeline(tmp_path) + calls = 0 + + async def turn(_messages: list[dict], _tools: list[dict]) -> ModelReply: + nonlocal calls + calls += 1 + return ModelReply(content="不应调用") + + agent = AssistantAgent(pipeline, _services(tmp_path, pipeline), turn, max_session_tokens=1) + res = asyncio.run(agent.run("查看总览", _principal(ALL_PERMISSION_KEYS), "s-token-limit")) + assert calls == 0 and res.termination_reason == "token_limit" + event = asyncio.run(pipeline.audit.events("s-token-limit"))[-1] + assert event.evidence["termination_reason"] == "token_limit" + + +def test_round_limit_stops_followup_planning_and_is_audited(tmp_path: Path) -> None: + pipeline = _pipeline(tmp_path) + agent = AssistantAgent( + pipeline, + _services(tmp_path, pipeline), + _scripted( + ModelReply( + tool_calls=[ToolCallReq(id="only-round", name="get_overview_stats", arguments={})] + ), + ModelReply(content="不应开始第二轮。"), + ), + max_steps=1, + ) + res = asyncio.run(agent.run("查看总览", _principal(ALL_PERMISSION_KEYS), "s-round-limit")) + assert res.termination_reason == "round_limit" + assert res.model_rounds == 1 and res.tool_calls == 1 + event = asyncio.run(pipeline.audit.events("s-round-limit"))[-1] + assert event.evidence["termination_reason"] == "round_limit" + + +def test_model_timeout_is_audited_and_fails_closed(tmp_path: Path) -> None: + pipeline = _pipeline(tmp_path) + + async def slow_turn(_messages: list[dict], _tools: list[dict]) -> ModelReply: + await asyncio.sleep(0.05) + return ModelReply(content="不应返回") + + agent = AssistantAgent( + pipeline, _services(tmp_path, pipeline), slow_turn, max_session_seconds=0.001 + ) + res = asyncio.run(agent.run("查看总览", _principal(ALL_PERMISSION_KEYS), "s-model-timeout")) + assert res.termination_reason in {"time_limit", "model_timeout"} + assert "安全停止" in res.reply + event = asyncio.run(pipeline.audit.events("s-model-timeout"))[-1] + assert event.evidence["termination_reason"] == res.termination_reason + + +def test_tool_exception_is_audited_and_stops_followup_planning(tmp_path: Path) -> None: + pipeline = _pipeline(tmp_path) + + async def broken(_args: dict, _principal: object, _services: object) -> OperationResult: + raise RuntimeError("fake tool failure") + + operation_registry.register( + AssistantTool( + name="broken_read", + kind="read", + label="故障读取", + description="测试用:抛出无害异常", + requires=("overview.view",), + handler=broken, + ) + ) + try: + agent = AssistantAgent( + pipeline, + _services(tmp_path, pipeline), + _scripted( + ModelReply( + tool_calls=[ToolCallReq(id="broken-1", name="broken_read", arguments={})] + ), + ModelReply(content="不应继续规划。"), + ), + ) + res = asyncio.run( + agent.run("读取测试数据", _principal(ALL_PERMISSION_KEYS), "s-tool-error") + ) + assert res.termination_reason == "tool_error" + assert res.model_rounds == 1 and res.tool_calls == 1 + assert res.steps[-1].ok is False and "RuntimeError" in res.steps[-1].detail + event = asyncio.run(pipeline.audit.events("s-tool-error"))[-1] + assert event.evidence["termination_reason"] == "tool_error" + finally: + operation_registry._ops.pop("broken_read", None) + + +def test_output_gate_exception_is_audited_and_does_not_leak_reply(tmp_path: Path) -> None: + pipeline = _pipeline(tmp_path) + + async def broken_output(_session_id: str, _text: str): + raise RuntimeError("fake output gate failure") + + pipeline.screen_output = broken_output # type: ignore[method-assign] + agent = AssistantAgent( + pipeline, _services(tmp_path, pipeline), _scripted(ModelReply(content="模型原始答复")) + ) + res = asyncio.run(agent.run("查看总览", _principal(ALL_PERMISSION_KEYS), "s-output-error")) + assert res.termination_reason == "output_gate_error" + assert "模型原始答复" not in res.reply and "已拦截" in res.reply + event = asyncio.run(pipeline.audit.events("s-output-error"))[-1] + assert event.evidence["termination_reason"] == "output_gate_error" + + def test_malicious_intent_blocked_before_model(tmp_path: Path) -> None: pipeline = _pipeline(tmp_path) # 若入口没拦住,脚本会驱动一次工具调用 → steps 非空;用它反证模型未被调用。