From e77c638f89473dc1561c505b54d5ddaa360938f5 Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Tue, 8 Sep 2026 14:10:55 +0800 Subject: [PATCH] fix(agent): keep tool results stable across replay (#5695) * fix(agent): keep processed tool results stable across replay * fix(agent): preserve multimodal text and complete result references * docs: trim tool result persistence comments * fix(tools): allow complete reads of oversized text lines * fix: keep read_file interface unchanged in replay fix * refactor: pass one tool result reference path * refactor: keep tool result persistence text-only * fix: keep tool output references stable across workspace changes --- nanobot/agent/context_governance.py | 40 ++++- nanobot/agent/loop.py | 19 +- nanobot/utils/helpers.py | 50 +++--- tests/agent/test_loop_save_turn.py | 44 ++++- tests/agent/test_runner_persistence.py | 236 ++++++++++++++++++++++++- tests/test_truncate_text_shadowing.py | 11 +- 6 files changed, 333 insertions(+), 67 deletions(-) diff --git a/nanobot/agent/context_governance.py b/nanobot/agent/context_governance.py index 5b8a55198..d522da779 100644 --- a/nanobot/agent/context_governance.py +++ b/nanobot/agent/context_governance.py @@ -65,7 +65,7 @@ ProviderCompactionConsolidator = Callable[ ] SNIP_SAFETY_BUFFER = 1024 -# read_file is the recovery path for persisted results; exempting it prevents persist->read->persist loops. +# read_file has its own bound; exempt it to avoid persist->read->persist loops. TOOL_RESULT_OFFLOAD_EXEMPT_TOOLS = frozenset({"read_file"}) BACKFILL_CONTENT = "[Tool result unavailable — call was interrupted or lost]" PLACEHOLDER_TEXTS = frozenset({ @@ -701,24 +701,48 @@ class ContextGovernor: result = ensure_nonempty_tool_result(tool_name, result) if tool_name in TOOL_RESULT_OFFLOAD_EXEMPT_TOOLS: return result - try: + + def persist_text(text: str, call_id: str) -> str: content = maybe_persist_tool_result( config.workspace, config.session_key, - tool_call_id, - result, + call_id, + text, max_chars=config.max_tool_result_chars, ) + # Persisted references must retain their complete paths. + return truncate_text(content, config.max_tool_result_chars) if config.workspace is None else content + + original_result: object = result + try: + if isinstance(result, str): + return persist_text(result, tool_call_id) + if isinstance(result, list): + result = cast(list[object], result) + blocks: list[dict[str, Any]] = [] + for raw_block in result: + if not isinstance(raw_block, dict): + return result + block = cast(dict[str, Any], raw_block) + if not isinstance(block.get("type"), str): + return result + if block["type"] == "text" and not isinstance(block.get("text"), str): + return result + blocks.append(block) + # Image redaction must not change how neighboring text is normalized. + return [ + {**block, "text": persist_text(block["text"], f"{tool_call_id}_text_{index}")} + if block["type"] == "text" else block + for index, block in enumerate(blocks) + ] except Exception: logger.exception( "Tool result persist failed for {} in {}; using raw result", tool_call_id, config.session_key or "default", ) - content = result - if isinstance(content, str) and len(content) > config.max_tool_result_chars: - return truncate_text(content, config.max_tool_result_chars) - return content + return truncate_text(result, config.max_tool_result_chars) if isinstance(result, str) else original_result + return result @staticmethod def strip_placeholder_assistant_messages( diff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.py index 588da69be..515edd959 100644 --- a/nanobot/agent/loop.py +++ b/nanobot/agent/loop.py @@ -106,7 +106,6 @@ from nanobot.triggers.local_turns import LocalTriggerTurnCoordinator from nanobot.utils.cancellation import task_is_cancelling from nanobot.utils.document import reference_non_image_attachments from nanobot.utils.helpers import image_placeholder_text -from nanobot.utils.helpers import truncate_text as truncate_text_fn from nanobot.utils.llm_runtime import LLMRuntime from nanobot.utils.progress_events import output_events from nanobot.utils.runtime import ( @@ -2103,8 +2102,6 @@ class AgentLoop: def _sanitize_persisted_blocks( self, content: list[object], - *, - should_truncate_text: bool = False, ) -> list[object]: """Strip volatile multimodal payloads before writing session history.""" filtered: list[object] = [] @@ -2125,16 +2122,6 @@ class AgentLoop: ) continue - if block_data.get("type") == "text" and isinstance( - block_data.get("text"), - str, - ): - text = cast(str, block_data["text"]) - if should_truncate_text and len(text) > self.max_tool_result_chars: - text = truncate_text_fn(text, self.max_tool_result_chars) - filtered.append({**block_data, "text": text}) - continue - filtered.append(block_data) return filtered @@ -2251,12 +2238,10 @@ class AgentLoop: ) continue fulfilled_tool_call_ids.add(tool_call_id_str) - if isinstance(content, str) and len(content) > self.max_tool_result_chars: - entry["content"] = truncate_text_fn(content, self.max_tool_result_chars) - elif isinstance(content, list): + # Preserve model-visible text for replay; redact only inline images. + if isinstance(content, list): filtered = self._sanitize_persisted_blocks( cast(list[object], content), - should_truncate_text=True, ) if not filtered: # Preserve the tool_call/result pair after block filtering. diff --git a/nanobot/utils/helpers.py b/nanobot/utils/helpers.py index 1e4ac3e74..f964437d4 100644 --- a/nanobot/utils/helpers.py +++ b/nanobot/utils/helpers.py @@ -503,20 +503,24 @@ def stringify_text_blocks(content: list[object]) -> str | None: def _render_tool_result_reference( - filepath: Path, + reference_path: str, *, original_size: int, preview: str, truncated_preview: bool, + max_chars: int | None = None, ) -> str: result = ( f"[tool output persisted]\n" - f"Full output saved to: {filepath}\n" + f"Full output saved to workspace path: {reference_path}\n" f"Original size: {original_size} chars\n" f"Preview:\n{preview}" ) if truncated_preview: - result += "\n...\n(Read the saved file if you need the full output.)" + result += "\n...\nPreview is also truncated." + result += "\nResult truncated. Read the saved file if you need the complete output." + if max_chars and len(result) > max_chars: + result = f"[truncated: {reference_path}]" return result @@ -570,48 +574,34 @@ def maybe_persist_tool_result( workspace: Path | None, session_key: str | None, tool_call_id: str, - content: Any, + content: str, *, max_chars: int, -) -> Any: - """Persist oversized tool output and replace it with a stable reference string.""" - if workspace is None or max_chars <= 0: - return content +) -> str: + """Offload oversized text. - text_payload: str | None = None - suffix = "txt" - if isinstance(content, str): - text_payload = content - elif isinstance(content, list): - text_payload = stringify_text_blocks(cast(list[object], content)) - if text_payload is None: - return cast(Any, content) - suffix = "json" - else: + Complete references may exceed the per-block ``max_chars`` budget. + """ + if workspace is None or max_chars <= 0 or len(content) <= max_chars: return content - if len(text_payload) <= max_chars: - return cast(Any, content) - root = ensure_dir(workspace / _TOOL_RESULTS_DIR) bucket = ensure_dir(root / safe_filename(session_key or "default")) try: _cleanup_tool_result_buckets(root, bucket) except Exception: logger.exception("Failed to clean stale tool result buckets in {}", root) - path = bucket / f"{safe_filename(tool_call_id)}.{suffix}" + path = bucket / f"{safe_filename(tool_call_id)}.txt" if not path.exists(): - if suffix == "json" and isinstance(content, list): - _write_text_atomic(path, json.dumps(content, ensure_ascii=False, indent=2)) - else: - _write_text_atomic(path, text_payload) + _write_text_atomic(path, content) - preview = text_payload[:_TOOL_RESULT_PREVIEW_CHARS] + preview = content[:_TOOL_RESULT_PREVIEW_CHARS] return _render_tool_result_reference( - path, - original_size=len(text_payload), + str(path.resolve()), + original_size=len(content), preview=preview, - truncated_preview=len(text_payload) > _TOOL_RESULT_PREVIEW_CHARS, + truncated_preview=len(content) > _TOOL_RESULT_PREVIEW_CHARS, + max_chars=max_chars, ) diff --git a/tests/agent/test_loop_save_turn.py b/tests/agent/test_loop_save_turn.py index 34bfaafaf..862d6a1d6 100644 --- a/tests/agent/test_loop_save_turn.py +++ b/tests/agent/test_loop_save_turn.py @@ -638,6 +638,46 @@ def test_save_turn_keeps_image_placeholder_without_meta() -> None: ] +def test_save_turn_redacts_tool_image_without_truncating_text() -> None: + loop = _mk_loop() + session = Session(key="test:tool-image") + text = "start-" + ("x" * 20_000) + "-end" + + loop._save_turn( + session, + [ + { + "role": "assistant", + "content": "", + "tool_calls": [{ + "id": "call_image", + "type": "function", + "function": {"name": "read_file", "arguments": "{}"}, + }], + }, + { + "role": "tool", + "tool_call_id": "call_image", + "name": "read_file", + "content": [ + { + "type": "image_url", + "image_url": {"url": "data:image/png;base64,abc"}, + "_meta": {"path": "media/photo.png"}, + }, + {"type": "text", "text": text}, + ], + }, + ], + skip=0, + ) + + assert session.messages[1]["content"] == [ + {"type": "text", "text": "[image: media/photo.png]"}, + {"type": "text", "text": text}, + ] + + def test_save_turn_persists_runtime_context_and_public_view_hides_it() -> None: loop = _mk_loop() session = Session(key="test:suffix-strip") @@ -710,10 +750,10 @@ def test_save_turn_keeps_string_when_only_runtime_context() -> None: assert public_history_message(session.messages[0])["content"] == "" -def test_save_turn_keeps_tool_results_under_16k() -> None: +def test_save_turn_keeps_full_processed_tool_result() -> None: loop = _mk_loop() session = Session(key="test:tool-result") - content = "x" * 12_000 + content = "start-" + ("x" * 20_000) + "-end" loop._save_turn( session, diff --git a/tests/agent/test_runner_persistence.py b/tests/agent/test_runner_persistence.py index 1b7aa6ae8..1d87d3b27 100644 --- a/tests/agent/test_runner_persistence.py +++ b/tests/agent/test_runner_persistence.py @@ -6,14 +6,33 @@ import os import time from unittest.mock import AsyncMock, MagicMock, patch +import pytest + from agent.runner_helpers import make_run_spec from nanobot.config.schema import AgentDefaults from nanobot.providers.base import LLMResponse, LLMUsage, ToolCallRequest _MAX_TOOL_RESULT_CHARS = AgentDefaults().max_tool_result_chars + +@pytest.mark.parametrize("invalid_block", [42, ["nested"], {}, {"type": "text", "text": 42}]) +def test_unrecognized_result_list_is_not_partially_offloaded(tmp_path, invalid_block): + from nanobot.agent.context_governance import ContextGovernanceConfig, ContextGovernor + from nanobot.agent.tools.registry import ToolRegistry + + result = [{"type": "text", "text": "x" * 20_000}, invalid_block] + config = ContextGovernanceConfig( + provider=MagicMock(), model="test", tools=ToolRegistry(), workspace=tmp_path, + session_key="invalid", max_tool_result_chars=2048, + ) + assert ContextGovernor.normalize_tool_result(config, "call", "custom", result) is result + assert list(tmp_path.iterdir()) == [] + + async def test_runner_persists_large_tool_results_for_follow_up_calls(tmp_path): + from nanobot.agent.loop import AgentLoop from nanobot.agent.runner import AgentRunner + from nanobot.session.manager import Session provider = MagicMock() captured_second_call: list[dict] = [] @@ -48,9 +67,52 @@ async def test_runner_persists_large_tool_results_for_follow_up_calls(tmp_path): assert result.final_content == "done" tool_message = next(msg for msg in captured_second_call if msg.get("role") == "tool") + assert len(tool_message["content"]) <= 2048 assert "[tool output persisted]" in tool_message["content"] + assert "Result truncated. Read the saved file" in tool_message["content"] assert "tool-results" in tool_message["content"] - assert (tmp_path / ".nanobot" / "tool-results" / "test_runner" / "call_big.txt").exists() + persisted_path = tmp_path / ".nanobot" / "tool-results" / "test_runner" / "call_big.txt" + assert persisted_path.read_text(encoding="utf-8") == "x" * 20_000 + + from nanobot.agent.tools.filesystem import ReadFileTool + + readback = await ReadFileTool(workspace=tmp_path).execute( + path=".nanobot/tool-results/test_runner/call_big.txt" + ) + assert "x" * 20_000 in readback + + loop = AgentLoop.__new__(AgentLoop) + loop.max_tool_result_chars = 2048 + session = Session(key="test:runner") + loop._save_turn(session, result.messages, skip=1) + persisted_tool = next(message for message in session.messages if message.get("role") == "tool") + assert persisted_tool["content"] == tool_message["content"] + + replay_provider = MagicMock() + replay_provider.chat_with_retry = AsyncMock( + return_value=LLMResponse(content="replayed", tool_calls=[], usage=None) + ) + replay_tools = MagicMock() + replay_tools.get_definitions.return_value = [] + replay_result = await AgentRunner().run(make_run_spec(replay_provider, + initial_messages=[ + *session.get_history(), + {"role": "user", "content": "continue"}, + ], + tools=replay_tools, + model="test-model", + max_iterations=1, + workspace=tmp_path, + session_key="test:runner", + max_tool_result_chars=2048, + )) + replay_tool = next( + message + for message in replay_provider.chat_with_retry.await_args.kwargs["messages"] + if message.get("role") == "tool" + ) + assert replay_result.final_content == "replayed" + assert replay_tool["content"] == tool_message["content"] def test_persist_tool_result_prunes_old_session_buckets(tmp_path): @@ -76,7 +138,8 @@ def test_persist_tool_result_prunes_old_session_buckets(tmp_path): max_chars=64, ) - assert "[tool output persisted]" in persisted + assert "truncated" in persisted + assert ".nanobot" in persisted assert not old_bucket.exists() assert recent_bucket.exists() assert (root / "current_session" / "call_big.txt").exists() @@ -120,7 +183,8 @@ def test_persist_tool_result_logs_cleanup_failures(monkeypatch, tmp_path): max_chars=64, ) - assert "[tool output persisted]" in persisted + assert "truncated" in persisted + assert ".nanobot" in persisted assert warnings and "Failed to clean stale tool result buckets" in warnings[0] @@ -170,6 +234,80 @@ async def test_read_file_result_is_not_offloaded(tmp_path): assert not any(offload_dir.rglob("call_rf.txt")) if offload_dir.exists() else True +async def test_processed_tool_result_is_stable_for_persistence_and_replay(tmp_path): + """The content sent after a tool call must survive the session round trip unchanged.""" + from nanobot.agent.loop import AgentLoop + from nanobot.agent.runner import AgentRunner + from nanobot.session.manager import Session + + raw_result = "start-" + ("x" * 20_000) + "-end-marker" + first_provider = MagicMock() + first_tools = MagicMock() + first_tools.get_definitions.return_value = [] + first_tools.execute = AsyncMock(return_value=raw_result) + + first_provider.chat_with_retry = AsyncMock(side_effect=[ + LLMResponse( + content="working", + tool_calls=[ToolCallRequest( + id="call_replay", + name="read_file", + arguments={"path": "large.txt"}, + )], + usage=None, + ), + LLMResponse(content="done", tool_calls=[], usage=None), + ]) + result = await AgentRunner().run(make_run_spec(first_provider, + initial_messages=[{"role": "user", "content": "read large file"}], + tools=first_tools, + model="test-model", + max_iterations=2, + workspace=tmp_path, + session_key="test:replay", + max_tool_result_chars=2048, + )) + request_tool = next( + message for message in first_provider.chat_with_retry.await_args_list[1].kwargs["messages"] + if message.get("role") == "tool" + ) + + loop = AgentLoop.__new__(AgentLoop) + loop.max_tool_result_chars = 2048 + session = Session(key="test:replay") + loop._save_turn(session, result.messages, skip=1) + persisted_tool = next(message for message in session.messages if message.get("role") == "tool") + + assert request_tool["content"] == raw_result + assert persisted_tool["content"] == request_tool["content"] + + replay_provider = MagicMock() + replay_provider.chat_with_retry = AsyncMock( + return_value=LLMResponse(content="replayed", tool_calls=[], usage=None) + ) + replay_tools = MagicMock() + replay_tools.get_definitions.return_value = [] + replay_result = await AgentRunner().run(make_run_spec(replay_provider, + initial_messages=[ + *session.get_history(), + {"role": "user", "content": "continue"}, + ], + tools=replay_tools, + model="test-model", + max_iterations=1, + workspace=tmp_path, + session_key="test:replay", + max_tool_result_chars=2048, + )) + replay_request_tool = next( + message for message in replay_provider.chat_with_retry.await_args.kwargs["messages"] + if message.get("role") == "tool" + ) + + assert replay_result.final_content == "replayed" + assert replay_request_tool["content"] == request_tool["content"] + + async def test_runner_keeps_going_when_tool_result_persistence_fails(): from nanobot.agent.runner import AgentRunner @@ -209,3 +347,95 @@ async def test_runner_keeps_going_when_tool_result_persistence_fails(): assert result.final_content == "done" tool_message = next(msg for msg in captured_second_call if msg.get("role") == "tool") assert tool_message["content"] == "tool result" + + +async def test_mixed_tool_text_survives_model_save_replay(tmp_path): + from nanobot.agent.context_governance import ContextGovernanceConfig, ContextGovernor + from nanobot.agent.loop import AgentLoop + from nanobot.agent.tools.filesystem import ReadFileTool + from nanobot.agent.tools.registry import ToolRegistry + from nanobot.session.manager import Session + + tools = ToolRegistry() + reader = ReadFileTool(workspace=tmp_path, allowed_dir=tmp_path) + tools.register(reader) + config = ContextGovernanceConfig( + provider=MagicMock(), model="test", tools=tools, workspace=tmp_path, + session_key="mixed", max_tool_result_chars=2048, + ) + raw = "start-" + "x" * 20_000 + "-end" + image = {"type": "image_url", "image_url": {"url": "data:image/png;base64,aGVsbG8="}} + messages = [ + {"role": "assistant", "content": "", "tool_calls": [{ + "id": "mixed", "type": "function", + "function": {"name": "custom_image_tool", "arguments": "{}"}, + }]}, + {"role": "tool", "name": "custom_image_tool", "tool_call_id": "mixed", + "content": [{"type": "text", "text": raw}, image]}, + ] + governor = ContextGovernor() + live = governor.prepare_messages_for_model(config, messages) + reference = live[-1]["content"][0]["text"] + assert len(reference) <= 2048 + assert live[-1]["content"][1] == image + loop = AgentLoop.__new__(AgentLoop) + session = Session(key="mixed") + loop._save_turn(session, live, skip=0) + replay = governor.prepare_messages_for_model(config, session.get_history()) + assert replay[-1]["content"][0]["text"] == reference + assert "data:image" not in str(replay[-1]["content"]) + readback = await reader.execute(path=".nanobot/tool-results/mixed/mixed_text_0.txt") + assert raw in readback + assert messages[-1]["content"][0]["text"] == raw + + +async def test_tiny_budget_keeps_complete_readable_reference(tmp_path): + from nanobot.agent.context_governance import ContextGovernanceConfig, ContextGovernor + from nanobot.agent.tools.filesystem import ReadFileTool + from nanobot.agent.tools.registry import ToolRegistry + + tools = ToolRegistry() + reader = ReadFileTool(workspace=tmp_path, allowed_dir=tmp_path) + tools.register(reader) + session_key = "review-session-0123456789-0123456789" + call_id = "call_012345678901234567890123456789" + config = ContextGovernanceConfig( + provider=MagicMock(), model="test", tools=tools, workspace=tmp_path, + session_key=session_key, max_tool_result_chars=64, + ) + raw = "y" * 20_000 + reference = ContextGovernor.normalize_tool_result(config, call_id, "exec", raw) + assert reference.startswith("[truncated: ") and reference.endswith("]") + path = reference.removeprefix("[truncated: ").removesuffix("]") + assert raw in await reader.execute(path=path) + assert ContextGovernor.normalize_tool_result(config, call_id, "exec", reference) == reference + assert (tmp_path / path).read_text(encoding="utf-8") == raw + + +async def test_result_reference_survives_workspace_switch_without_bypassing_restriction(tmp_path): + import re + + from nanobot.agent.tools.filesystem import ReadFileTool + from nanobot.security.workspace_access import ( + bind_workspace_scope, + build_workspace_scope, + reset_workspace_scope, + ) + from nanobot.utils.helpers import maybe_persist_tool_result + + first = tmp_path / "first" + second = tmp_path / "second" + first.mkdir() + second.mkdir() + raw = "x" * 20_000 + reference = maybe_persist_tool_result(first, "session", "call", raw, max_chars=2048) + match = re.search(r"workspace path: (.+)", reference) + assert match is not None + reader = ReadFileTool(workspace=first) + for mode, expected in [("full", raw), ("restricted", "Error")]: + token = bind_workspace_scope(build_workspace_scope(second, mode)) + try: + result = await reader.execute(path=match[1], force=True) + assert expected in result + finally: + reset_workspace_scope(token) diff --git a/tests/test_truncate_text_shadowing.py b/tests/test_truncate_text_shadowing.py index 1415b9a42..deabaf80f 100644 --- a/tests/test_truncate_text_shadowing.py +++ b/tests/test_truncate_text_shadowing.py @@ -1,15 +1,12 @@ from types import SimpleNamespace -def test_sanitize_persisted_blocks_truncates_text() -> None: +def test_sanitize_persisted_blocks_preserves_tool_text() -> None: from nanobot.agent.loop import AgentLoop - dummy = SimpleNamespace(max_tool_result_chars=5) + dummy = SimpleNamespace() content = [{"type": "text", "text": "0123456789"}] - out = AgentLoop._sanitize_persisted_blocks(dummy, content, should_truncate_text=True) - assert isinstance(out, list) - assert out and out[0]["type"] == "text" - assert isinstance(out[0]["text"], str) - assert out[0]["text"] != content[0]["text"] + out = AgentLoop._sanitize_persisted_blocks(dummy, content) + assert out == content