diff --git a/src/bub/core/agent.py b/src/bub/core/agent.py index d45e55a1..32ee39cf 100644 --- a/src/bub/core/agent.py +++ b/src/bub/core/agent.py @@ -8,7 +8,6 @@ from contextlib import AsyncExitStack, aclosing, asynccontextmanager from dataclasses import asdict, replace from datetime import UTC, datetime -from json import JSONDecodeError from typing import Any, TypeVar import republic @@ -49,6 +48,9 @@ MAX_AUTO_HANDOFF_RETRIES = 1 +INVALID_ARGUMENTS_EXCERPT = 500 +"""Characters kept from each end of undecodable tool call arguments in the error the model sees.""" + FIRST_CHUNK_KINDS = frozenset({"text", "reasoning"}) """Stream events that carry a token the model emitted, marking where decode starts. @@ -413,48 +415,57 @@ async def run_once( ) tool_calls = response.tool_calls - if tool_calls: - tool_map = {tool_item.name: tool_item for tool_item in tools} - if any(tool_call.name not in tool_map for tool_call in tool_calls): - tool_map = {tool_item.name: tool_item for tool_item in await self.prepare_tools(tape, None)} | tool_map - serialized_tool_calls = [asdict(tool_call) for tool_call in tool_calls] - tool_invocations = [_tool_invocation(tool_call, tool_map) for tool_call in tool_calls] - yield StreamEvent("tool_call", {"tool_calls": serialized_tool_calls}) - turn_state["_runtime_tool_names"] = tuple(tool_map) - context = ToolContext( - tape=tape, run_id=run_id, state=turn_state, events=self.events, step_messages=new_messages - ) - execution = await ToolExecutor(events=self.events, max_concurrency=self.max_tool_concurrency).execute_many( - tool_invocations, - context=context, - call_ids=[call.id for call in tool_calls], - ) - tool_results = execution.tool_results - else: - serialized_tool_calls, tool_results = [], None - assistant_fields = { - key: value - for key, value in { - "reasoning": response.reasoning, - "provider_data": [ - asdict(part) for part in response.message.parts if isinstance(part, republic.ProviderData) - ], - }.items() - if value + serialized_tool_calls: list[dict[str, Any]] = [] + tool_results: list[Any] | None = None + finished: dict[str, Any] = { + "run_id": run_id, + "model": request.model, + "system_prompt": system_prompt, + "new_messages": new_messages, + "usage": state.usage, + "provider": provider, + "finish_reason": response.finish_reason, + "assistant_fields": { + key: value + for key, value in { + "reasoning": response.reasoning, + "provider_data": [ + asdict(part) for part in response.message.parts if isinstance(part, republic.ProviderData) + ], + }.items() + if value + }, } + if tool_calls: + try: + tool_map, resolved = await self._resolve_tool_calls(tape, tools, response) + # Undecodable arguments are recorded as ``{}`` so the call can be sent back to any provider. + serialized_tool_calls = [ + asdict(tool_call) | ({} if valid else {"arguments": "{}"}) + for tool_call, (_, _, valid) in zip(tool_calls, resolved, strict=True) + ] + yield StreamEvent("tool_call", {"tool_calls": serialized_tool_calls}) + turn_state["_runtime_tool_names"] = tuple(tool_map) + context = ToolContext( + tape=tape, run_id=run_id, state=turn_state, events=self.events, step_messages=new_messages + ) + executor = ToolExecutor(events=self.events, max_concurrency=self.max_tool_concurrency) + execution = await executor.execute_many( + [(tool_obj, arguments) for tool_obj, arguments, _ in resolved], + context=context, + call_ids=[call.id for call in tool_calls], + ) + tool_results = execution.tool_results + except Exception as exc: + await self._record_failed_step(tape, exc, text, serialized_tool_calls, finished) + raise await self._emit( ChatFinished, tape, - run_id=run_id, - model=request.model, - system_prompt=system_prompt, - new_messages=new_messages, response_text=(text or None) if tool_calls else text, tool_calls=serialized_tool_calls, tool_results=tool_results, - usage=state.usage, - provider=provider, - assistant_fields=assistant_fields, + **finished, ) if tool_calls: yield StreamEvent("tool_result", {"tool_results": tool_results}) @@ -462,6 +473,50 @@ async def run_once( else: yield StreamEvent("final", {"ok": True, "text": text}) + async def _record_failed_step( + self, + tape: Tape, + exc: Exception, + text: str, + tool_calls: list[dict[str, Any]], + finished: dict[str, Any], + ) -> None: + """Record a step that failed after the model answered, with its usage; ``exc`` stays the step's error.""" + error = exc if isinstance(exc, BubError) else BubError(ErrorKind.UNKNOWN, f"{exc!s}") + # Every recorded call needs a result for the tape to replay, but which calls ran is not known. + unknown = BubError( + ErrorKind.UNKNOWN, + "The outcome of this call is unknown: the step failed before tool results were recorded " + f"({error.message}). The tool may or may not have run.", + ) + try: + await self._emit( + ChatFinished, + tape, + response_text=text or None, + tool_calls=tool_calls, + tool_results=[unknown] * len(tool_calls) if tool_calls else None, + error=error, + **finished, + ) + except Exception: + logger.exception("chat.record.error tape={}", tape.name) + + async def _resolve_tool_calls( + self, tape: Tape, tools: list[Tool], response: republic.Response + ) -> tuple[dict[str, Tool], list[tuple[Tool, dict[str, Any], bool]]]: + """Resolve a response's tool calls against the run's tools, and the agent's current ones if needed.""" + tool_map = {tool_item.name: tool_item for tool_item in tools} + calls = response.tool_calls + if any(tool_call.name not in tool_map for tool_call in calls): + tool_map = {tool_item.name: tool_item for tool_item in await self.prepare_tools(tape, None)} | tool_map + # A response that stopped at the output token limit was cut off inside its last call. + truncated = response.finish_reason == "length" + return tool_map, [ + _tool_invocation(call, tool_map, truncated=truncated and index == len(calls) - 1) + for index, call in enumerate(calls) + ] + def _model_client(self, model: Model | None) -> ModelClient: if model is None: model = self.model @@ -832,28 +887,62 @@ async def _stream_events( }) -def _tool_invocation(tool_call: republic.ToolCall, tool_map: dict[str, Tool]) -> tuple[Tool, dict[str, Any]]: - """Resolve a model tool call to (runtime tool, arguments). +def _tool_invocation( + tool_call: republic.ToolCall, tool_map: dict[str, Tool], *, truncated: bool = False +) -> tuple[Tool, dict[str, Any], bool]: + """Resolve a model tool call to (runtime tool, arguments, whether its arguments decoded). - An unknown tool name is not treated as a fatal error: it is surfaced as a - placeholder ``Tool`` so the invocation flows through ``ToolExecutor`` and - ``ToolCallStarted`` handlers can recover it into a guidance - ``tool_result`` instead of interrupting the turn. If no hook replaces the - call, the placeholder raises a clear tool error rather than succeeding with - an empty result. + Neither an unknown tool name nor undecodable arguments is treated as a fatal error: + each is surfaced as a placeholder ``Tool`` that raises, so the invocation flows + through ``ToolExecutor`` and comes back to the model as a failed ``tool_result`` it + can correct, instead of interrupting the turn. ``ToolCallStarted`` handlers may + recover an unknown tool into guidance; if none replaces the call, the placeholder + raises a clear tool error rather than succeeding with an empty result. + + ``truncated`` says the response stopped at the output token limit inside this call. """ tool_name = tool_call.name try: - arguments = tool_call.args - except JSONDecodeError as exc: - raise BubError(ErrorKind.INVALID_INPUT, "Expected a function tool call with JSON object arguments.") from exc - if not isinstance(arguments, dict): - raise BubError(ErrorKind.INVALID_INPUT, "Expected a function tool call with JSON object arguments.") + arguments = _decode_arguments(tool_call, truncated) + except BubError as exc: + return Tool.failing(tool_name, exc), {}, False tool_obj = tool_map.get(tool_name) if tool_obj is None: - - def raise_unknown_tool(**_: Any) -> None: - raise BubError(ErrorKind.TOOL, f"Unknown tool name: {tool_name}.") - - return Tool(name=tool_name, handler=raise_unknown_tool), arguments - return tool_obj, arguments + unknown = BubError(ErrorKind.TOOL, f"Unknown tool name: {tool_name}.") + return Tool.failing(tool_name, unknown), arguments, True + return tool_obj, arguments, True + + +def _decode_arguments(tool_call: republic.ToolCall, truncated: bool) -> dict[str, Any]: + """Return a tool call's arguments, or raise the error the model should see when they cannot be used.""" + raw = tool_call.arguments + reason = None + # Arguments cut off before their first character arrive as an empty object. + if truncated and raw.strip() in {"", "{}"}: + reason = "they are empty" + else: + try: + arguments = tool_call.args + except (ValueError, RecursionError) as exc: + reason = f"they are not valid JSON ({exc})" + else: + if isinstance(arguments, dict): + return arguments + reason = "they are not a JSON object" + if truncated: + message = ( + f"The arguments of this '{tool_call.name}' call were cut off because the response reached the " + "output token limit (max_tokens), so the tool did not run. Call it again with shorter arguments, " + "for example by splitting long content across several calls." + ) + else: + message = ( + f"The arguments of this '{tool_call.name}' call could not be used because {reason}, so the tool " + "did not run. Call it again with a JSON object of arguments." + ) + if len(raw) > 2 * INVALID_ARGUMENTS_EXCERPT: + excerpt = f"{raw[:INVALID_ARGUMENTS_EXCERPT]}…{raw[-INVALID_ARGUMENTS_EXCERPT:]}" + else: + excerpt = raw + details = {"arguments": excerpt, "arguments_length": len(raw), "truncated": truncated} + raise BubError(ErrorKind.INVALID_INPUT, message, details=details) diff --git a/src/bub/core/events.py b/src/bub/core/events.py index 375e0e0e..722cb0d8 100644 --- a/src/bub/core/events.py +++ b/src/bub/core/events.py @@ -284,8 +284,8 @@ class ToolCallFinished(AgentEvent): class ChatFinished(TapeEvent): """One model step's exchange is complete and ready to be recorded. - Also emitted when the step fails before calling the model (``context_error``) or a - ``before_llm_call`` decision finishes it. + Also emitted when the step fails before calling the model (``context_error``), when it + fails after the model answered (``error``), or when a ``before_llm_call`` decision finishes it. """ run_id: str @@ -297,6 +297,8 @@ class ChatFinished(TapeEvent): tool_results: list[Any] | None = None usage: dict[str, Any] | None = None provider: str | None = None + finish_reason: str | None = None + """Why the model stopped, such as ``length`` when it reached the output token limit.""" assistant_fields: dict[str, Any] = field(default_factory=dict) error: BubError | None = None context_error: BubError | None = None diff --git a/src/bub/core/recorder.py b/src/bub/core/recorder.py index d2446841..c24e6aff 100644 --- a/src/bub/core/recorder.py +++ b/src/bub/core/recorder.py @@ -84,6 +84,7 @@ async def on_chat_finished(self, event: ChatFinished) -> None: provider=event.provider, model=event.model, usage=event.usage, + finish_reason=event.finish_reason, ) diff --git a/src/bub/core/tape.py b/src/bub/core/tape.py index 397fc3ba..a7795ae5 100644 --- a/src/bub/core/tape.py +++ b/src/bub/core/tape.py @@ -465,6 +465,7 @@ async def record_chat( # noqa: C901 provider: str | None = None, model: str | None = None, usage: dict[str, Any] | None = None, + finish_reason: str | None = None, assistant_fields: dict[str, Any] | None = None, ) -> None: tape_name = self.name @@ -496,6 +497,8 @@ async def record_chat( # noqa: C901 data["provider"] = provider if model: data["model"] = model + if finish_reason: + data["finish_reason"] = finish_reason await self.store.append(tape_name, TapeEntry.event("run", data, **meta)) @staticmethod diff --git a/src/bub/core/tools.py b/src/bub/core/tools.py index a9cf699e..5ba0ea40 100644 --- a/src/bub/core/tools.py +++ b/src/bub/core/tools.py @@ -224,6 +224,19 @@ def to_schema(self) -> dict[str, Any]: """Build a function tool schema for hooks and diagnostics.""" return {"name": self.name, "description": self.description, "parameters": self.parameters} + @classmethod + def failing(cls, name: str, error: BubError) -> Tool: + """Return a placeholder tool named ``name`` whose every call fails with ``error``. + + It stands in for a call that cannot run, so the call still flows through + ``ToolExecutor`` and ``error`` becomes its result. + """ + + def fail(**_: Any) -> None: + raise error + + return cls(name=name, handler=fail) + @classmethod def from_callable( cls, diff --git a/tests/test_core_agent_step.py b/tests/test_core_agent_step.py index f71dd6fe..635ebe9a 100644 --- a/tests/test_core_agent_step.py +++ b/tests/test_core_agent_step.py @@ -10,7 +10,9 @@ from republic.errors import APIStatusError, StreamIncompleteError from bub.builtin.settings import AgentSettings +from bub.core import Agent from bub.core.context import default_tape_context +from bub.core.events import ChatFinished, ToolCallStarted from bub.core.store import AsyncTapeStoreAdapter, FileTapeStore, InMemoryTapeStore from bub.core.tape import Tape, TapeContext, TapeEntry from bub.core.tools import Tool @@ -226,30 +228,162 @@ async def test_tool_result_without_its_call_in_context_is_still_sent( @pytest.mark.asyncio @pytest.mark.parametrize("arguments", ["[]", "null", "1", "not json"]) -async def test_invalid_tool_arguments_do_not_execute_the_handler( - tmp_path: Path, provider_service: ProviderService, arguments: str +async def test_invalid_tool_arguments_come_back_to_the_model_as_a_failed_result( + provider_service: ProviderService, arguments: str ) -> None: provider_service.reply( sse(tool_events([{"index": 0, "id": "call-1", "function": {"name": "inspect", "arguments": arguments}}])) ) + provider_service.reply(sse(chat_events("recovered"))) invoked = [] + store = InMemoryTapeStore() async with provider_service.client() as client: - runner = StepRunner(AgentSettings(client_args={"http_client": client, "api_format": "chat"})) - tape = Tape(AsyncTapeStoreAdapter(InMemoryTapeStore()), TapeContext(anchor=None)).scoped("invalid") - with pytest.raises(BubError) as exc: - _ = [ - event - async for event in runner.run( - tape=tape, - model="openai:test", - tools=[Tool(name="inspect", handler=lambda: invoked.append(True))], - system_prompt=None, - prompt=to_content("Inspect."), - ) - ] - assert exc.value.kind == ErrorKind.INVALID_INPUT + model = republic.get_model("openai:test", http_client=client, api_format="chat", api_key="test") + agent = Agent(store=store, tools=[Tool(name="inspect", handler=lambda: invoked.append(True))]) + async with agent.run(["Inspect."], model=model, tape="invalid") as stream: + events = [event async for event in stream] + assert not invoked - assert not await tape.store.fetch_all(tape.query().kinds("tool_result")) + assert events[-1].data == {"ok": True, "text": "recovered"} + [result] = next(event.data["tool_results"] for event in events if event.kind == "tool_result") + assert isinstance(result, BubError) + assert result.kind == ErrorKind.INVALID_INPUT + assert result.details == {"arguments": arguments, "arguments_length": len(arguments), "truncated": False} + # The call is sent back with arguments any provider accepts, followed by the error. + assistant, tool = provider_service.body()["messages"][-2:] + assert assistant["tool_calls"][0]["function"] == {"name": "inspect", "arguments": "{}"} + assert "Call it again with a JSON object" in tool["content"] + + +@pytest.mark.asyncio +async def test_tool_arguments_cut_off_at_the_token_limit_say_so(provider_service: ProviderService) -> None: + cut_off = '{"command": "' + "x" * 2000 + call = {"index": 0, "id": "call-1", "function": {"name": "bash", "arguments": cut_off}} + provider_service.reply(sse([{"choices": [{"delta": {"tool_calls": [call]}, "finish_reason": "length"}]}, "[DONE]"])) + async with provider_service.client() as client: + runner = StepRunner(AgentSettings(client_args={"http_client": client, "api_format": "chat"})) + tape = Tape(AsyncTapeStoreAdapter(InMemoryTapeStore()), TapeContext(anchor=None)).scoped("cut-off") + events = [ + event + async for event in runner.run( + tape=tape, + model="openai:test", + tools=[Tool(name="bash", handler=lambda command: command)], + system_prompt=None, + prompt=to_content("Run it."), + ) + ] + + [result] = next(event.data["tool_results"] for event in events if event.kind == "tool_result") + assert "output token limit (max_tokens)" in result.message + assert result.details == { + "arguments": f"{cut_off[:500]}…{cut_off[-500:]}", + "arguments_length": len(cut_off), + "truncated": True, + } + [run] = [ + entry for entry in await tape.store.fetch_all(tape.query().kinds("event")) if entry.payload["name"] == "run" + ] + assert run.payload["data"]["finish_reason"] == "length" + + +@pytest.mark.asyncio +async def test_empty_arguments_at_the_token_limit_do_not_run_the_tool(provider_service: ProviderService) -> None: + calls = [ + {"index": 0, "id": "call-1", "function": {"name": "inspect", "arguments": "{}"}}, + {"index": 1, "id": "call-2", "function": {"name": "inspect", "arguments": ""}}, + ] + provider_service.reply(sse([{"choices": [{"delta": {"tool_calls": calls}, "finish_reason": "length"}]}, "[DONE]"])) + invoked = [] + async with provider_service.client() as client: + runner = StepRunner(AgentSettings(client_args={"http_client": client, "api_format": "chat"})) + tape = Tape(AsyncTapeStoreAdapter(InMemoryTapeStore()), TapeContext(anchor=None)).scoped("empty") + events = [ + event + async for event in runner.run( + tape=tape, + model="openai:test", + tools=[Tool(name="inspect", handler=lambda: invoked.append(True) or "ok")], + system_prompt=None, + prompt=to_content("Inspect."), + ) + ] + + # Only the last call can have been cut off. + complete, cut_off = next(event.data["tool_results"] for event in events if event.kind == "tool_result") + assert complete == "ok" + assert invoked == [True] + assert "output token limit (max_tokens)" in cut_off.message + + +@pytest.mark.asyncio +async def test_arguments_that_fail_to_decode_without_a_json_error_come_back_to_the_model( + provider_service: ProviderService, +) -> None: + # 5000 digits pass the JSON grammar but exceed Python's integer conversion limit. + arguments = '{"count": ' + "9" * 5000 + "}" + provider_service.reply( + sse(tool_events([{"index": 0, "id": "call-1", "function": {"name": "inspect", "arguments": arguments}}])) + ) + provider_service.reply(sse(chat_events("recovered"))) + async with provider_service.client() as client: + model = republic.get_model("openai:test", http_client=client, api_format="chat", api_key="test") + agent = Agent(tools=[Tool(name="inspect", handler=lambda count: count)]) + async with agent.run(["Inspect."], model=model, tape="digits") as stream: + events = [event async for event in stream] + + [result] = next(event.data["tool_results"] for event in events if event.kind == "tool_result") + assert result.kind == ErrorKind.INVALID_INPUT + assert events[-1].data == {"ok": True, "text": "recovered"} + + +@pytest.mark.asyncio +async def test_step_failing_after_the_model_answered_is_recorded_without_inventing_results( + provider_service: ProviderService, +) -> None: + provider_service.reply_chat( + "Checking.", + [ + {"id": "call-1", "name": "inspect", "arguments": "{}"}, + {"id": "call-2", "name": "delete", "arguments": "{}"}, + {"id": "call-3", "name": "inspect", "arguments": "not json"}, + ], + ) + store = InMemoryTapeStore() + + def broken_handler(event: ToolCallStarted) -> None: + if event.call.tool == "delete": + raise RuntimeError("handler broke") + + def broken_recorder(event: ChatFinished) -> None: + raise ValueError("recorder broke") + + async with provider_service.client() as client: + model = republic.get_model("openai:test", http_client=client, api_format="chat", api_key="test") + agent = Agent( + store=store, + tools=[Tool(name="inspect", handler=lambda: "ok"), Tool(name="delete", handler=lambda: "deleted")], + ) + agent.events.on(ToolCallStarted, broken_handler) + agent.events.on(ChatFinished, broken_recorder) + # The step's own error is raised, not one from recording it. + with pytest.raises(RuntimeError, match="handler broke"): + async with agent.run(["Inspect."], model=model, tape="failed") as stream: + _ = [event async for event in stream] + + entries = {entry.kind: entry.payload for entry in store.read("failed") or [] if entry.kind != "event"} + assert entries["message"] == {"role": "user", "content": "Inspect."} + assert [call["arguments"] for call in entries["tool_call"]["calls"]] == ["{}", "{}", "{}"] + # The call that succeeded is not recorded as failed with the other call's error. + ran, broke, invalid = entries["tool_result"]["results"] + assert ran == broke == invalid + assert ran["message"].startswith("The outcome of this call is unknown") + assert "handler broke" in ran["message"] + assert entries["error"] == {"kind": "unknown", "message": "handler broke"} + [run] = [entry.payload["data"] for entry in store.read("failed") or [] if entry.payload.get("name") == "run"] + assert run["status"] == "error" + assert run["finish_reason"] == "tool_calls" + assert run["usage"]["output_tokens"] == 2 @pytest.mark.asyncio diff --git a/website/src/content/docs/docs/reference/python-api.mdx b/website/src/content/docs/docs/reference/python-api.mdx index 8f6004a5..b2b7da04 100644 --- a/website/src/content/docs/docs/reference/python-api.mdx +++ b/website/src/content/docs/docs/reference/python-api.mdx @@ -237,6 +237,9 @@ class Tool: def render(self, result: Any) -> str: ... def to_schema(self) -> dict[str, Any]: ... + @classmethod + def failing(cls, name: str, error: BubError) -> Tool: ... + @classmethod def from_callable( cls, @@ -738,6 +741,7 @@ class ChatFinished(TapeEvent): tool_results: list[Any] | None = None usage: dict[str, Any] | None = None provider: str | None = None + finish_reason: str | None = None assistant_fields: dict[str, Any] = field(default_factory=dict) error: BubError | None = None context_error: BubError | None = None @@ -756,7 +760,7 @@ class ChatFinished(TapeEvent): | `LLMCallFinished` | After success or an ordinary provider failure | `request` and the aggregated `result` (`LLMCallResult`) | | `ToolCallStarted` | Before a local tool runs | Replace `call`; set `decision` (`proceed` / `deny` / `replace`) | | `ToolCallFinished` | Tool success, failure, denial, or replacement | `call` and `result` (assign `event.result.result` to change the model-facing result) | -| `ChatFinished` | When a Step's exchange is ready to be recorded | `new_messages`, `response_text`, `tool_calls`, `tool_results`, `usage`, `error` | +| `ChatFinished` | When a Step's exchange is ready to be recorded | `new_messages`, `response_text`, `tool_calls`, `tool_results`, `usage`, `finish_reason`, `error` | | `CommandFinished` | A direct command succeeds or fails | `line`, `name`, `status`, `elapsed_ms`, `output` | - `RunFinished` fires when the stream closes; a Run closed before iterating ends as `cancelled` with zero steps. `LLMCallFinished` and `ToolCallFinished` do not cover every cancellation path. diff --git a/website/src/content/docs/zh-cn/docs/reference/python-api.mdx b/website/src/content/docs/zh-cn/docs/reference/python-api.mdx index 9a42052a..89c7ded2 100644 --- a/website/src/content/docs/zh-cn/docs/reference/python-api.mdx +++ b/website/src/content/docs/zh-cn/docs/reference/python-api.mdx @@ -237,6 +237,9 @@ class Tool: def render(self, result: Any) -> str: ... def to_schema(self) -> dict[str, Any]: ... + @classmethod + def failing(cls, name: str, error: BubError) -> Tool: ... + @classmethod def from_callable( cls, @@ -738,6 +741,7 @@ class ChatFinished(TapeEvent): tool_results: list[Any] | None = None usage: dict[str, Any] | None = None provider: str | None = None + finish_reason: str | None = None assistant_fields: dict[str, Any] = field(default_factory=dict) error: BubError | None = None context_error: BubError | None = None @@ -756,7 +760,7 @@ class ChatFinished(TapeEvent): | `LLMCallFinished` | 模型调用成功或因普通异常失败后 | `request` 与汇总后的 `result` | | `ToolCallStarted` | 本地工具执行之前 | 替换 `call`;或设置 `decision`(`proceed` / `deny` / `replace`) | | `ToolCallFinished` | 工具成功、失败、被拒绝或被替代后 | `call` 与 `result`(可给 `event.result.result` 赋值以替换面向模型的结果) | -| `ChatFinished` | 当前 Step 的对话和工具往返准备写入 Tape 时 | `new_messages`、`response_text`、`tool_calls`、`tool_results`、`usage`、`error` | +| `ChatFinished` | 当前 Step 的对话和工具往返准备写入 Tape 时 | `new_messages`、`response_text`、`tool_calls`、`tool_results`、`usage`、`finish_reason`、`error` | | `CommandFinished` | 直接命令执行成功或失败时 | `line`、`name`、`status`、`elapsed_ms`、`output` | - `RunFinished` 在事件流关闭时发出;尚未迭代就关闭的 Run 以 `status="cancelled"`、`steps=0` 结束。`LLMCallFinished` 和 `ToolCallFinished` 不保证覆盖外部取消路径。