The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): interrupt detection needs the executor's result shape; future-stamped confirmations expire
kshitijk4poorf296652a6629
diff --git a/agent/replay_cleanup.py b/agent/replay_cleanup.pyindex c0ef24122b2..ab00f4526a6 100644--- a/agent/replay_cleanup.py+++ b/agent/replay_cleanup.py@@ -6,8 +6,10 @@ re-issues the unanswered call → endless "thinking"/reboot loop. These pure helfrom __future__ import annotations+import jsonimport loggingimport math+import reimport timefrom typing import Any, Dict, List, Optional@@ -29,20 +31,32 @@ _DANGLING_NOTICES = ()-# Every executor renders an interrupt as a bracketed marker: "[Command interrupted]" (terminal-# backends, tools/environments/), "[Command interrupted - Modal ...]" (managed_modal.py) and-# "[execution interrupted ...]" (code_execution_tool.py).-_INTERRUPT_MARKERS = ("[command interrupted", "[execution interrupted")+# Every executor ends the killed run's ``output`` with a bracketed marker line: "[Command+# interrupted]" (tools/environments/, exit 130), "[Command interrupted - Modal ...]"+# (managed_modal.py, exit 130), "[execution interrupted ...]" (code_execution_tool.py, exit -1).+_INTERRUPT_MARKER_LINE = re.compile(r"^\[(?:command|execution) interrupted\b[^\n]*\]\s*$", re.IGNORECASE)def is_interrupted_tool_result(content: Any) -> bool:- """True only for an executor's interrupt marker. Nothing looser: this also runs on every- live request, where a substring heuristic rewrote an ordinary ``grep KeyboardInterrupt``- result mid-turn and broke the cached prefix."""+ """True only when the result has the executor's interrupt SHAPE: the marker is the last+ line of the output (JSON envelope with a non-zero exit code, or a bare text result). A+ marker quoted inside successful output — a grep hit, a doc example — is ordinary data;+ this runs on every live request, so a false positive rewrites real tool output."""if not isinstance(content, str):return False- lowered = content.lower()- return any(marker in lowered for marker in _INTERRUPT_MARKERS)+ output = content+ if content.lstrip().startswith("{"):+ try:+ envelope = json.loads(content)+ except ValueError:+ return False+ if not isinstance(envelope, dict) or envelope.get("exit_code") in (0, None):+ return False+ output = envelope.get("output")+ if not isinstance(output, str):+ return False+ last_line = output.rstrip().rsplit("\n", 1)[-1]+ return _INTERRUPT_MARKER_LINE.match(last_line) is not Nonedef _call_name(call: Dict[str, Any]) -> str:@@ -208,11 +222,12 @@ def strip_stale_dangerous_confirmations(if ts is None or not is_dangerous_confirmation(msg.get("content", "")):cleaned.append(msg)continue- # A present-but-corrupt stamp is treated as expired: the age is unknowable, and- # keeping the text (plus its api_content sidecar) would replay a live confirmation.+ # A present-but-untrustworthy stamp (corrupt, or issued in the future relative to+ # the admission clock) is treated as expired: its age is unknowable, and keeping the+ # text (plus its api_content sidecar) would replay a live confirmation.ts_f = coerce_epoch(ts, field="message timestamp")age = math.inf if ts_f is None else now - ts_f- if age <= expiry_seconds:+ if 0 <= age <= expiry_seconds:cleaned.append(msg)continuelogger.debug(diff --git a/tests/agent/test_replay_cleanup.py b/tests/agent/test_replay_cleanup.pyindex 6e3c4c5ad84..d14226730c3 100644--- a/tests/agent/test_replay_cleanup.py+++ b/tests/agent/test_replay_cleanup.py@@ -145,12 +145,15 @@ def test_send_wire_matches_replay_wire_after_db_round_trip(tmp_path):db.append_message("s1", role="user", content="confirm reboot", timestamp=now - 120)db.append_message("s1", role="assistant", content="", tool_calls=[{"id": "c1", "type": "function", "function": {"name": "read_file", "arguments": "{}"}}], timestamp=now - 119)- db.append_message("s1", role="tool", content="[execution interrupted — user stop]", tool_call_id="c1", tool_name="read_file", timestamp=now - 118)- # An ordinary result that merely mentions interrupts is NOT replay debris.- grep_hit = '{"output": "loop.py:12: except KeyboardInterrupt:\\n@@ -1,4 +1,5 @@", "exit_code": 0}'+ db.append_message("s1", role="tool", content='{"output": "[execution interrupted — user stop]", "exit_code": -1}', tool_call_id="c1", tool_name="read_file", timestamp=now - 118)+ # A successful result that merely QUOTES an interrupt marker is NOT replay debris.+ grep_hit = json.dumps({"output": "docs.txt:12: [execution interrupted — user stop]\nloop.py:4: [Command interrupted]", "exit_code": 0})+ doc_text = "how interrupts render:\n[Command interrupted]\n(the marker above is documentation)"db.append_message("s1", role="assistant", content="", tool_calls=[- {"id": "c2", "type": "function", "function": {"name": "search_files", "arguments": "{}"}}], timestamp=now - 110)+ {"id": "c2", "type": "function", "function": {"name": "search_files", "arguments": "{}"}},+ {"id": "c3", "type": "function", "function": {"name": "read_file", "arguments": "{}"}}], timestamp=now - 110)db.append_message("s1", role="tool", content=grep_hit, tool_call_id="c2", tool_name="search_files", timestamp=now - 109)+ db.append_message("s1", role="tool", content=doc_text, tool_call_id="c3", tool_name="read_file", timestamp=now - 108)persisted = db.get_messages_as_conversation("s1")db.close()assert persisted[0].get("api_content") == "hello [with memory]" and persisted[2].get("timestamp")@@ -165,14 +168,14 @@ def test_send_wire_matches_replay_wire_after_db_round_trip(tmp_path):assert live == frozenassert _wire(request) == _wire(replay + [{"role": "user", "content": "now"}])assert "[with memory]" in request[0]["content"] and "EXPIRED" in request[2]["content"]- assert [m["role"] for m in request] == ["user", "assistant", "user", "assistant", "tool", "user"]- assert request[4]["content"] == grep_hit+ assert [m["role"] for m in request] == ["user", "assistant", "user", "assistant", "tool", "tool", "user"]+ assert (request[4]["content"], request[5]["content"]) == (grep_hit, doc_text)# Rows this turn appended stay verbatim even when they look like replay debris.live += [{"role": "assistant", "content": "", "tool_calls": [- {"id": "c3", "type": "function", "function": {"name": "search_files", "arguments": "{}"}}]},- {"role": "tool", "tool_call_id": "c3", "content": "[Command interrupted]"},+ {"id": "c4", "type": "function", "function": {"name": "search_files", "arguments": "{}"}}]},+ {"role": "tool", "tool_call_id": "c4", "content": "[Command interrupted]"},]request2 = build_api_messages(_SendAgent(), live, current_turn_user_idx=len(persisted), ext_prefetch_cache="",@@ -212,7 +215,8 @@ def test_confirmation_expiry_uses_frozen_admission_clock_and_fails_closed(monkeyplugin_user_context="", moa_config=None, active_system_prompt="")[0]assert late[0]["content"] == "confirm reboot"- corrupt = [{"role": "user", "content": "confirm reboot", "timestamp": "nan", "api_content": "confirm reboot"}]- out = canonicalize_replay_history(corrupt, now=10_000.0)- assert "EXPIRED" in out[0]["content"] and "api_content" not in out[0]+ for untrusted in ("nan", 96_400.0, 4_000_000_000.0): # corrupt, or issued in the future+ row = [{"role": "user", "content": "confirm reboot", "timestamp": untrusted, "api_content": "confirm reboot"}]+ out = canonicalize_replay_history(row, now=10_000.0)+ assert "EXPIRED" in out[0]["content"] and "api_content" not in out[0], untrustedassert canonicalize_replay_history([{"role": "user", "content": "confirm reboot"}], now=1e9)[0]["content"] == "confirm reboot"