The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent): tidy the interrupt-placeholder fold-ups
kshitijk4poorc8634c7b644f
diff --git a/agent/message_sanitization.py b/agent/message_sanitization.pyindex 200f492395f..2cfdf80fad9 100644--- a/agent/message_sanitization.py+++ b/agent/message_sanitization.py@@ -310,7 +310,7 @@ def close_interrupted_tool_sequence(messages: list, final_response: Any = None)"role": "assistant","content": "","display_kind": "hidden",- "api_content": stripped or _INTERRUPTED_PLACEHOLDER,+ "api_content": _INTERRUPTED_PLACEHOLDER,})else:append_message(messages, {"role": "assistant", "content": stripped})diff --git a/agent/tool_executor.py b/agent/tool_executor.pyindex e2945d9ec44..d70a158d66f 100644--- a/agent/tool_executor.py+++ b/agent/tool_executor.py@@ -1507,8 +1507,9 @@ def _unfinished_tool_result(agent, ref: _ToolCallRef, *, timed_out: bool, timeououtcome = dict(duration_ms=int((timeout_s or 0.0) * 1000), status="timeout", error_type="tool_timeout", error_message=function_result)tool_duration, effect_disposition = float(timeout_s or 0.0), "unknown"elif agent._interrupt_requested:- function_result = f"[Tool execution cancelled — {ref.name} was skipped. {interrupt_skip_wording(agent)}]"- outcome = dict(status="cancelled", error_type="keyboard_interrupt", error_message=f"Tool execution cancelled. {interrupt_skip_wording(agent)}")+ why = interrupt_skip_wording(agent)+ function_result = f"[Tool execution cancelled — {ref.name} was skipped. {why}]"+ outcome = dict(status="cancelled", error_type="keyboard_interrupt", error_message=f"Tool execution cancelled. {why}")tool_duration, effect_disposition = 0.0, Noneelse:function_result = f"Error executing tool '{ref.name}': thread did not return a result"diff --git a/agent/turn_iteration_prep.py b/agent/turn_iteration_prep.pyindex cc313d54208..b821efd7254 100644--- a/agent/turn_iteration_prep.py+++ b/agent/turn_iteration_prep.py@@ -110,15 +110,44 @@ class IterationPrep:current_turn_user_idx: Any+# Retire hidden interrupt placeholders whose text the model echoes on replay+# (#81841 for the scaffold, #132949 for the placeholder). A hidden row still+# reaches the provider as assistant content; a natural-language phrase in that+# position is reproduced verbatim. The row is never dropped: removal can form+# ``tool -> user`` (#48879) or ``user -> user``, which repair then merges —+# losing the second row's checkpoint ``api_content``. Neutralise a copy instead.+def _neutralise_replay_echo_ghosts(seq: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], int]:+ """(new list, neutralised); never mutates ``seq`` or its row dicts."""+ from agent.agent_runtime_helpers import (+ _INTERRUPTED_PLACEHOLDER,+ _LEGACY_INTERRUPTED_PLACEHOLDER,+ )+ from agent.conversation_loop import _INTERRUPT_SCAFFOLD_MARKER+ # Retire only spellings that predate the #132949 wording change: the scaffold+ # (#81841) and the old placeholder, both reproduced verbatim. The current+ # placeholder is the post-fix value — it stays (this is also what+ # neutralisation rewrites to, so the rewrite does not retrigger the filter).+ hazards = {_INTERRUPT_SCAFFOLD_MARKER, _LEGACY_INTERRUPTED_PLACEHOLDER}+ neutralised = 0+ out: List[Dict[str, Any]] = []+ for m in seq:+ if (+ m.get("display_kind") == "hidden" and m.get("role") == "assistant"+ and any(isinstance(m.get(k), str) and m[k].strip() in hazards for k in ("content", "api_content"))+ ):+ m = {**m, "content": "", "api_content": _INTERRUPTED_PLACEHOLDER}+ neutralised += 1+ out.append(m)+ return (out if neutralised else seq), neutralised++def prepare_iteration(agent: Any, *, messages: Any, api_call_count: Any, user_message: Any = None, current_turn_user_idx: Any = None,) -> IterationPrep:"""Prepare ``messages`` for this iteration in the original order. Every mutation here iscache-safe by construction: steer text is appended as a new (not yet persisted) user row, the ghost-row- filter only drops hidden scaffold placeholders, and repair runs BEFORE the request build."""- from agent.conversation_loop import (- _INTERRUPT_SCAFFOLD_MARKER, _maybe_inject_run_budget_wrapup- )+ filter neutralises copies of hidden interrupt placeholders, and repair runs BEFORE the request build."""+ from agent.conversation_loop import _maybe_inject_run_budget_wrapup# nous.anthropic_wire=auto: a wire switch decided from the previous response lands here,# before this iteration's request is built and with nothing in flight.@@ -180,35 +209,6 @@ def prepare_iteration(agent.session_id or "-",)- # Retire hidden interrupt placeholders whose text the model echoes on replay- # (#81841 for the scaffold, #132949 for the placeholder). A hidden row still- # reaches the provider as assistant content; a natural-language phrase in that- # position is reproduced verbatim. The row is never dropped: removal can form- # ``tool -> user`` (#48879) or ``user -> user``, which repair then merges —- # losing the second row's checkpoint ``api_content``. Neutralise a copy instead.- def _neutralise_replay_echo_ghosts(seq: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], int]:- """(new list, neutralised); never mutates ``seq`` or its row dicts."""- from agent.agent_runtime_helpers import (- _INTERRUPTED_PLACEHOLDER,- _LEGACY_INTERRUPTED_PLACEHOLDER,- )- # Retire only spellings that predate the #132949 wording change: the scaffold- # (#81841) and the old placeholder, both reproduced verbatim. The current- # placeholder is the post-fix value — it stays (this is also what- # neutralisation rewrites to, so the rewrite does not retrigger the filter).- hazards = {_INTERRUPT_SCAFFOLD_MARKER, _LEGACY_INTERRUPTED_PLACEHOLDER}- neutralised = 0- out: List[Dict[str, Any]] = []- for m in seq:- if (- m.get("display_kind") == "hidden" and m.get("role") == "assistant"- and any(isinstance(m.get(k), str) and m[k].strip() in hazards for k in ("content", "api_content"))- ):- m = {**m, "content": "", "api_content": _INTERRUPTED_PLACEHOLDER}- neutralised += 1- out.append(m)- return (out if neutralised else seq), neutralised-messages, _echo_neutralised = _neutralise_replay_echo_ghosts(messages)if _echo_neutralised:request_logger.info(diff --git a/tests/agent/test_turn_finalizer_interrupt_alternation.py b/tests/agent/test_turn_finalizer_interrupt_alternation.pyindex 3ff097f7ea1..e19818e33d2 100644--- a/tests/agent/test_turn_finalizer_interrupt_alternation.py+++ b/tests/agent/test_turn_finalizer_interrupt_alternation.py@@ -16,6 +16,7 @@ an empty-content assistant turn. The synthetic row is hidden from the user"""+from agent.agent_runtime_helpers import _INTERRUPTED_PLACEHOLDERfrom agent.turn_finalizer import finalize_turn@@ -159,7 +160,7 @@ def test_interrupt_after_tool_closes_sequence_with_placeholder():# hidden; placeholder lives in api_content (LLM sees it via sidecar).assert messages[-1]["content"] == ""assert messages[-1]["display_kind"] == "hidden"- assert messages[-1]["api_content"].strip()+ assert messages[-1]["api_content"] == _INTERRUPTED_PLACEHOLDER# The persisted snapshot is alternation-safe: appending a new user# message would follow an assistant, not an orphan tool.