The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat: identical re-calls enter context as reference stubs, not duplicate payloads
Teknium761990b7800b
diff --git a/agent/tool_executor.py b/agent/tool_executor.pyindex 2eb69c61249..4a828477c36 100644--- a/agent/tool_executor.py+++ b/agent/tool_executor.py@@ -48,12 +48,31 @@ from tools.thread_context import propagate_context_to_threadfrom tools.tool_result_storage import (maybe_persist_tool_result,enforce_turn_budget,+ extract_persisted_path,)from tools.budget_config import BudgetConfig, DEFAULT_BUDGET, budget_for_context_windowlogger = logging.getLogger(__name__)+def _record_persisted_path_for_stub(agent, tool_call_id: str, function_result) -> None:+ """Tell the stall guards where a persisted result's full content lives.++ When a large result is spilled to disk (<persisted-output> preview), a+ later result-reference stub pointing at that first occurrence must carry+ the spillover file path so the reference can't dangle. Best-effort: never+ lets bookkeeping break tool execution.+ """+ try:+ if not isinstance(function_result, str):+ return+ path = extract_persisted_path(function_result)+ if path:+ agent._tool_guardrails.record_persisted_result(tool_call_id, path)+ except Exception as exc:+ logger.debug("persisted-path record for result stub failed: %s", exc)++def _ensure_file_checkpoint(agent,function_name: str,@@ -1733,6 +1752,7 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effefunction_args,function_result,failed=is_error,+ tool_call_id=getattr(tc, "id", "") or "",)if is_error:@@ -1767,6 +1787,7 @@ def execute_tool_calls_concurrent(agent, assistant_message, messages: list, effeenv=get_active_env(effective_task_id),config=_tool_budget,) if not _is_multimodal_tool_result(function_result) else function_result+ _record_persisted_path_for_stub(agent, tc.id, function_result)subdir_hints = agent._subdirectory_hints.check_tool_call(name, args)if subdir_hints:@@ -2572,6 +2593,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effefunction_args,function_result,failed=_is_error_result,+ tool_call_id=getattr(tool_call, "id", "") or "",)result_preview = function_result if agent.verbose_logging else (function_result[:200] if len(function_result) > 200 else function_result@@ -2610,6 +2632,7 @@ def execute_tool_calls_sequential(agent, assistant_message, messages: list, effeenv=get_active_env(effective_task_id),config=_tool_budget,) if not _is_multimodal_tool_result(function_result) else function_result+ _record_persisted_path_for_stub(agent, tool_call.id, function_result)# Discover subdirectory context files from tool argumentssubdir_hints = agent._subdirectory_hints.check_tool_call(function_name, function_args)diff --git a/agent/tool_guardrails.py b/agent/tool_guardrails.pyindex b319046335f..e4afbbba822 100644--- a/agent/tool_guardrails.py+++ b/agent/tool_guardrails.py@@ -85,6 +85,19 @@ _STALL_GUARD_REPEATABLE_SUFFIXES = (# catching the observed re-issue loops (3x/4x identical calls in eval traces).STALL_GUARD_IDENTICAL_CALL_THRESHOLD = 3+# Result-reference stubbing (agent.stall_guards): from the 2nd consecutive+# identical call whose FRESH result is byte-identical to the previous one,+# the duplicate payload is replaced in context by a short reference stub.+# Results under this size aren't worth stubbing (the stub itself plus the+# lost locality outweigh the savings), and error results are never stubbed+# (the model must see every fresh error verbatim).+IDENTICAL_RESULT_STUB_MIN_CHARS = 512++# How much of the canonical args JSON the stub carries so the model still+# knows WHAT the referenced call was even if context compression later+# evicts the referenced result (cheap dangling-reference mitigation).+_RESULT_STUB_ARGS_PREVIEW_CHARS = 120+def is_stall_guard_repeatable(tool_name: str) -> bool:"""Whether a tool is exempt from the identical-call loop notice."""@@ -206,6 +219,21 @@ class LoopCapConfig:)+@dataclass(frozen=True)+class IdenticalCallObservation:+ """Outcome of observing one completed tool call for the stall guards.++ ``notice`` is the identical-call loop-breaker notice (appended after the+ result). ``stub`` is the result-reference replacement for a byte-identical+ duplicate result (replaces the result content). Both may be set on the+ same call (3rd+ identical call): the stub replaces the payload and the+ notice is appended after it.+ """++ notice: str | None = None+ stub: str | None = None++@dataclass(frozen=True)class ToolCallSignature:"""Stable, non-reversible identity for a tool name plus canonical args."""@@ -320,9 +348,21 @@ class ToolCallGuardrailController:# results were also identical. Any different call — or a different# result — resets the streak, so legitimate re-reads after edits and# varied polling are never flagged. Per-turn, like everything else here.+ # NOTE: open PR #85352 (patrykkopycinski) tracks no-progress loops+ # ACROSS turns via a detection window — a different mechanism from+ # this per-turn consecutive streak. Coordinate future work there.self._identical_streak_sig: ToolCallSignature | None = Noneself._identical_streak_result_hash: str = ""self._identical_streak_count: int = 0+ # tool_call_id of the FIRST call in the current streak, so a+ # result-reference stub can point at the message that carries the+ # full payload.+ self._identical_streak_first_call_id: str = ""+ # tool_call_id -> spillover file path for results that were persisted+ # out of context (persisted-output preview). Lets a reference stub+ # carry the file path so the reference can't dangle when the first+ # occurrence entered context as a preview.+ self._persisted_result_paths: dict[str, str] = {}# Per-turn runaway-loop cap counters. Reset every turn (this method# runs at the start of each run_conversation), so the caps bound a# single agent loop rather than accumulating across the session.@@ -493,44 +533,129 @@ class ToolCallGuardrailController:) -> str | None:"""Track consecutive identical calls; return a loop-breaker notice or None.- Fires the compact notice when the SAME tool is called with identical- canonical arguments AND returns an identical result for the- ``STALL_GUARD_IDENTICAL_CALL_THRESHOLD``-th (and every subsequent)- consecutive time within the turn. Purely observational — never blocks- the call. Allowlisted pollers (``is_stall_guard_repeatable``) are- exempt, and any intervening different call or changed result resets- the streak. Callers append the returned notice to the tool RESULT at- construction time, which is cache-safe: tool results are append-only- and never mutate already-sent context.+ Back-compat wrapper around :meth:`observe_call` for callers that only+ care about the loop-breaker notice."""- if is_stall_guard_repeatable(tool_name):- # Don't let a poller streak carry over into the next tool either.- self._identical_streak_sig = None- self._identical_streak_count = 0- return None+ return self.observe_call(tool_name, args, result).notice+ def observe_call(+ self,+ tool_name: str,+ args: Mapping[str, Any] | None,+ result: str | None,+ *,+ tool_call_id: str = "",+ failed: bool = False,+ ) -> "IdenticalCallObservation":+ """Track consecutive identical calls; return notice + dedupe stub info.++ Two independent outputs from the same consecutive-streak tracker:++ - ``notice``: the compact loop-breaker notice, fired when the SAME+ tool is called with identical canonical arguments AND returns an+ identical result for the ``STALL_GUARD_IDENTICAL_CALL_THRESHOLD``-th+ (and every subsequent) consecutive time within the turn. Purely+ observational — never blocks the call. Allowlisted pollers+ (``is_stall_guard_repeatable``) are exempt from the NOTICE.+ - ``stub``: a short reference replacement for the CURRENT result,+ produced from the 2nd consecutive identical call whose fresh result+ is byte-identical to the previous one. The tool still executed —+ only the context representation is deduplicated, so polling+ semantics are preserved (a changed result flows through whole and+ resets the streak). Pollers are NOT exempt from stubbing: for a+ poller, an identical result means nothing changed, which is exactly+ when the stub saves the most context and loses nothing. Results+ under ``IDENTICAL_RESULT_STUB_MIN_CHARS`` and failed/error results+ are never stubbed, and only plain-string results are considered.++ Any intervening different call or changed result resets the streak.+ Callers substitute/append at tool RESULT construction time, which is+ cache-safe: tool results are append-only and never mutate+ already-sent context.+ """+ is_plain_str = isinstance(result, str)signature = ToolCallSignature.from_call(tool_name, _coerce_args(args))- result_hash = _result_hash(result)+ result_hash = _result_hash(result) if is_plain_str else ""+if (- self._identical_streak_sig == signature+ is_plain_str+ and self._identical_streak_sig == signatureand self._identical_streak_result_hash == result_hash):self._identical_streak_count += 1else:- self._identical_streak_sig = signature+ # New streak (or non-string result, which never forms a streak —+ # multimodal content lists pass through untouched).+ self._identical_streak_sig = signature if is_plain_str else Noneself._identical_streak_result_hash = result_hash- self._identical_streak_count = 1+ self._identical_streak_count = 1 if is_plain_str else 0+ self._identical_streak_first_call_id = tool_call_id or ""count = self._identical_streak_count- if count < STALL_GUARD_IDENTICAL_CALL_THRESHOLD:- return None- ordinal = f"{count}{'th' if 11 <= count % 100 <= 13 else {1: 'st', 2: 'nd', 3: 'rd'}.get(count % 10, 'th')}"- return (- f"[hermes note: this is the {ordinal} consecutive identical call to "- f"{tool_name} with identical arguments returning the same result. "- "Do not repeat it — change arguments, use a different tool, or "- "proceed with what you have.]"++ notice = None+ if (+ not is_stall_guard_repeatable(tool_name)+ and count >= STALL_GUARD_IDENTICAL_CALL_THRESHOLD+ ):+ ordinal = f"{count}{'th' if 11 <= count % 100 <= 13 else {1: 'st', 2: 'nd', 3: 'rd'}.get(count % 10, 'th')}"+ notice = (+ f"[hermes note: this is the {ordinal} consecutive identical call to "+ f"{tool_name} with identical arguments returning the same result. "+ "Do not repeat it — change arguments, use a different tool, or "+ "proceed with what you have.]"+ )++ stub = None+ if (+ is_plain_str+ and count >= 2+ and not failed+ and len(result) >= IDENTICAL_RESULT_STUB_MIN_CHARS+ ):+ stub = self._build_result_reference_stub(tool_name, args)++ return IdenticalCallObservation(notice=notice, stub=stub)++ def record_persisted_result(self, tool_call_id: str, file_path: str) -> None:+ """Remember the spillover path a persisted result was saved to.++ When the first occurrence of a result entered context as a+ persisted-output preview, a later reference stub must carry the+ spillover file path so the reference can't dangle.+ """+ if tool_call_id and file_path:+ self._persisted_result_paths[tool_call_id] = file_path++ def _build_result_reference_stub(+ self, tool_name: str, args: Mapping[str, Any] | None+ ) -> str:+ """Build the reference stub replacing a byte-identical duplicate result.++ Carries the tool name + a canonical-args preview so that even if+ context compression later evicts the referenced result, the model+ still knows WHAT the call was (cheap dangling-reference mitigation).+ """+ try:+ args_preview = canonical_tool_args(_coerce_args(args))+ except TypeError:+ args_preview = "{}"+ if len(args_preview) > _RESULT_STUB_ARGS_PREVIEW_CHARS:+ args_preview = args_preview[:_RESULT_STUB_ARGS_PREVIEW_CHARS] + "…"+ first_id = self._identical_streak_first_call_id+ ref = f" (tool_call_id {first_id})" if first_id else ""+ stub = (+ f"[hermes note: this result is byte-identical to the {tool_name} "+ f"result earlier this turn{ref}. Refer to that result; it has not "+ f"changed. Args: {args_preview}]")+ spill_path = self._persisted_result_paths.get(first_id) if first_id else None+ if spill_path:+ stub += (+ f"\n[The referenced result was persisted to: {spill_path} — "+ "page through it with read_file if you need the full content.]"+ )+ return stubdef _check_loop_cap(self,diff --git a/run_agent.py b/run_agent.pyindex ac06aafaf1d..a54bc9cf8f9 100644--- a/run_agent.py+++ b/run_agent.py@@ -8239,6 +8239,7 @@ class AIAgent:function_result: str,*,failed: bool,+ tool_call_id: str = "",) -> str:decision = self._tool_guardrails.after_call(tool_name,@@ -8246,20 +8247,36 @@ class AIAgent:function_result,failed=failed,)- # Identical-call loop breaker (agent.stall_guards): notice-only, no+ # Identical-call stall guards (agent.stall_guards): notice-only, no# blocking. Observed on the RAW result (before the loop-warning suffix# below, whose embedded count changes per call and would defeat- # result-identity matching). Appended here — at result construction,+ # result-identity matching). Applied here — at result construction,# before the tool message is built — so it is cache-safe (tool results# are append-only; nothing already sent to the provider is mutated).stall_notice = None+ result_stub = Noneif self._stall_guards_enabled():try:- stall_notice = self._tool_guardrails.observe_identical_call(- tool_name, function_args, function_result,+ observation = self._tool_guardrails.observe_call(+ tool_name,+ function_args,+ function_result if isinstance(function_result, str) else None,+ tool_call_id=tool_call_id,+ failed=failed,)+ stall_notice = observation.notice+ result_stub = observation.stubexcept Exception as exc:logger.debug("stall-guard identical-call observation failed: %s", exc)+ # Result-reference stubbing: a 2nd+ consecutive identical call whose+ # FRESH result is byte-identical enters context as a short reference+ # stub instead of the duplicate payload. The tool still executed —+ # this is not a cache; a changed result flows through whole. Only+ # plain-string results are stubbed (multimodal content lists pass+ # through untouched), and the current message keeps its role and+ # tool_call_id — only the content is replaced.+ if result_stub and isinstance(function_result, str):+ function_result = result_stubif decision.action in {"warn", "halt"}:function_result = append_toolguard_guidance(function_result, decision)if decision.should_halt:diff --git a/tests/agent/test_stall_guards.py b/tests/agent/test_stall_guards.pyindex 33267362c0b..4ff12fe56e3 100644--- a/tests/agent/test_stall_guards.py+++ b/tests/agent/test_stall_guards.py@@ -17,6 +17,7 @@ These assert behavior contracts, not message snapshots.from agent.agent_runtime_helpers import trailing_continue_intentfrom agent.tool_guardrails import (+ IDENTICAL_RESULT_STUB_MIN_CHARS,STALL_GUARD_IDENTICAL_CALL_THRESHOLD,STALL_GUARD_REPEATABLE_TOOLS,ToolCallGuardrailController,@@ -142,8 +143,10 @@ def _fake_agent(stall_guards=True):lambda decision: AIAgent._set_tool_guardrail_halt(agent, decision))agent._append = (- lambda name, args, result: AIAgent._append_guardrail_observation(- agent, name, args, result, failed=False+ lambda name, args, result, failed=False, tool_call_id="": (+ AIAgent._append_guardrail_observation(+ agent, name, args, result, failed=failed, tool_call_id=tool_call_id+ )))return agent@@ -181,6 +184,170 @@ def test_notice_streak_keys_on_raw_result_not_annotated_result():assert "hermes note" in outs[2]+# ── result-reference stubbing (byte-identical duplicate results) ──────────+++_BIG = "x" * IDENTICAL_RESULT_STUB_MIN_CHARS # exactly at the stub threshold+++def test_stub_on_second_identical_call_first_full():+ agent = _fake_agent()+ args = {"query": "hermes"}+ r1 = agent._append("web_search", args, _BIG, tool_call_id="call_1")+ r2 = agent._append("web_search", args, _BIG, tool_call_id="call_2")+ assert r1 == _BIG # first occurrence always enters context whole+ assert r2 != _BIG+ assert "byte-identical" in r2+ assert "web_search" in r2+ assert "call_1" in r2 # references the FIRST occurrence in the streak+ assert len(r2) < len(_BIG)+++def test_no_stub_when_fresh_result_differs():+ agent = _fake_agent()+ args = {"query": "hermes"}+ agent._append("web_search", args, _BIG, tool_call_id="call_1")+ changed = "y" + _BIG+ r2 = agent._append("web_search", args, changed, tool_call_id="call_2")+ assert r2 == changed # changed result flows through whole+++def test_changed_result_resets_streak_then_stub_references_new_first():+ agent = _fake_agent()+ args = {"id": "job"}+ agent._append("web_search", args, _BIG, tool_call_id="a")+ changed = _BIG + "done"+ r2 = agent._append("web_search", args, changed, tool_call_id="b")+ assert r2 == changed+ r3 = agent._append("web_search", args, changed, tool_call_id="c")+ assert "byte-identical" in r3+ assert "tool_call_id b" in r3 # new streak's first occurrence, not 'a'+++def test_no_stub_below_min_chars():+ agent = _fake_agent()+ small = "x" * (IDENTICAL_RESULT_STUB_MIN_CHARS - 1)+ args = {"query": "hermes"}+ agent._append("web_search", args, small, tool_call_id="c1")+ r2 = agent._append("web_search", args, small, tool_call_id="c2")+ assert "byte-identical" not in r2+ assert r2.startswith(small) # full payload kept (pre-existing warning suffix allowed)+++def test_no_stub_for_error_results():+ agent = _fake_agent()+ err = "Error executing tool: " + _BIG+ args = {"command": "boom"}+ agent._append("terminal", args, err, failed=True, tool_call_id="c1")+ r2 = agent._append("terminal", args, err, failed=True, tool_call_id="c2")+ assert "byte-identical" not in r2+ assert r2.startswith(err) # models must see fresh errors whole+++def test_pollers_get_stub_but_never_loop_notice():+ agent = _fake_agent()+ args = {"id": "job1"}+ results = [+ agent._append("bfl_flux3_get_result", args, _BIG, tool_call_id=f"c{i}")+ for i in range(4)+ ]+ assert results[0] == _BIG+ for r in results[1:]:+ assert "byte-identical" in r # stubbed: unchanged poll saves context+ assert "consecutive identical call" not in r # notice stays exempt+++def test_third_identical_call_gets_stub_plus_loop_notice():+ agent = _fake_agent()+ args = {"query": "hermes"}+ agent._append("web_search", args, _BIG, tool_call_id="c1")+ agent._append("web_search", args, _BIG, tool_call_id="c2")+ r3 = agent._append("web_search", args, _BIG, tool_call_id="c3")+ assert "byte-identical" in r3 # stub replaces the payload+ assert "3rd consecutive identical call" in r3 # notice appended after it+ assert r3.index("byte-identical") < r3.index("3rd consecutive")+++def test_stub_carries_spillover_path_when_first_result_persisted():+ agent = _fake_agent()+ args = {"query": "big"}+ agent._tool_guardrails.record_persisted_result(+ "c1", "/home/u/.hermes/cache/spillover/c1.txt"+ )+ agent._append("web_search", args, _BIG, tool_call_id="c1")+ r2 = agent._append("web_search", args, _BIG, tool_call_id="c2")+ assert "/home/u/.hermes/cache/spillover/c1.txt" in r2+++def test_stub_includes_args_summary_for_compression_safety():+ agent = _fake_agent()+ args = {"query": "hermes result stubbing", "limit": 5}+ agent._append("web_search", args, _BIG, tool_call_id="c1")+ r2 = agent._append("web_search", args, _BIG, tool_call_id="c2")+ # Canonical-args preview so the model knows WHAT the call was even if+ # the referenced message is later evicted by compression.+ assert "hermes result stubbing" in r2+++def test_stub_args_summary_truncated_to_120_chars():+ c = ToolCallGuardrailController()+ args = {"query": "q" * 500}+ assert c.observe_call("web_search", args, _BIG, tool_call_id="c1").stub is None+ stub = c.observe_call("web_search", args, _BIG, tool_call_id="c2").stub+ assert stub is not None+ args_part = stub.split("Args: ", 1)[1]+ assert len(args_part) < 200 # ~120-char preview + ellipsis + closer+++def test_config_off_disables_stub():+ agent = _fake_agent(stall_guards=False)+ args = {"query": "hermes"}+ agent._append("web_search", args, _BIG, tool_call_id="c1")+ r2 = agent._append("web_search", args, _BIG, tool_call_id="c2")+ assert "byte-identical" not in r2+ assert r2.startswith(_BIG)+++def test_streak_reset_by_different_call_means_next_identical_is_full():+ agent = _fake_agent()+ args = {"query": "hermes"}+ agent._append("web_search", args, _BIG, tool_call_id="c1")+ agent._append("read_file", {"path": "/a"}, "other", tool_call_id="c2")+ r3 = agent._append("web_search", args, _BIG, tool_call_id="c3")+ assert "byte-identical" not in r3+ assert r3.startswith(_BIG) # fresh streak — first occurrence full again+++def test_multimodal_content_never_stubbed_and_breaks_streak():+ c = ToolCallGuardrailController()+ args = {"path": "/img.png"}+ assert c.observe_call("vision", args, _BIG, tool_call_id="c1").stub is None+ # Non-string (multimodal) results never form or extend a streak.+ obs = c.observe_call("vision", args, None, tool_call_id="c2")+ assert obs.stub is None+ assert c.observe_call("vision", args, _BIG, tool_call_id="c3").stub is None+++def test_observe_identical_call_backcompat_notice_still_fires():+ c = ToolCallGuardrailController()+ for _ in range(STALL_GUARD_IDENTICAL_CALL_THRESHOLD - 1):+ assert c.observe_identical_call("web_search", {"q": 1}, "r") is None+ assert c.observe_identical_call("web_search", {"q": 1}, "r") is not None+++def test_extract_persisted_path_round_trip():+ # The stub's spillover reference is parsed from the <persisted-output>+ # block that maybe_persist_tool_result builds — assert the round trip.+ from tools.tool_result_storage import (+ _build_persisted_message,+ extract_persisted_path,+ )++ block = _build_persisted_message("preview", True, 50_000, "/tmp/spill/x.txt")+ assert extract_persisted_path(block) == "/tmp/spill/x.txt"+ assert extract_persisted_path("plain result") is None++# ── said-continue-but-stopped detector ─────────────────────────────────────diff --git a/tools/tool_result_storage.py b/tools/tool_result_storage.pyindex ff731a5b8fe..1fc3085677a 100644--- a/tools/tool_result_storage.py+++ b/tools/tool_result_storage.py@@ -295,6 +295,22 @@ def _build_persisted_message(return msg+_PERSISTED_PATH_RE = re.compile(r"^Full output saved to: (.+)$", re.MULTILINE)+++def extract_persisted_path(content: str) -> str | None:+ """Return the file path from a <persisted-output> replacement block.++ Used by the result-reference stubbing guard (agent/tool_guardrails.py) so+ a stub referencing a persisted first occurrence can carry the spillover+ path instead of dangling. Returns None for non-persisted content.+ """+ if not isinstance(content, str) or PERSISTED_OUTPUT_TAG not in content:+ return None+ match = _PERSISTED_PATH_RE.search(content)+ return match.group(1).strip() if match else None++def maybe_persist_tool_result(content: str,tool_name: str,diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 28d58bd9119..68b3adf19c6 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -1752,6 +1752,8 @@ agent:stall_guards: false```+The same gate also enables **result-reference stubbing**: when a re-issued identical tool call returns a byte-identical fresh result, the duplicate payload enters context as a short reference stub pointing at the earlier result (tool name, `tool_call_id`, an args summary, and — if the first result was persisted to disk — its spillover path) instead of repeating the full output. The tool still executes every time, so polling semantics are preserved: a changed result always flows through whole. Results under 512 characters, error results, and multimodal results are never stubbed, and pollers *are* stubbed (an unchanged poll is exactly the case where the duplicate payload carries no information).+## TTS Configuration```yaml