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
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-08 14:10:55 +08:00
1 parent 7aaff4f66b
commit e77c638f89
6 files changed
+333 -67

No files matched your search

+32 -8
View File
@@ -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(
+2 -17
View File
@@ -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.
+20 -30
View File
@@ -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,
)