The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent): move interrupt placeholders into agent_runtime_helpers_placeholders to keep files under the size cap
kshitijk4poor2bbb37b97330
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex b85f4a0f2e9..dfe0044e21c 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -2678,21 +2678,6 @@ def repair_tool_call(agent, tool_name: str) -> str | None:return matches[0] if matches else None-# Placeholder for an empty non-final message the provider would reject. Kept identical to the stub-# placeholder in chat_completion_helpers so healed transcripts read consistently.-#-# Wording matters: this text is substituted into an assistant row's ``content`` on the wire copy-# (``fill_empty_non_final_wire_payload``, ``repair_empty_non_final_messages``, and the projection in-# ``run_conversation``), so the model reads it as something IT said. A short natural-language phrase-# in that position gets echoed verbatim — a clean ``finish_reason=stop`` turn answering an ordinary-# instruction with just the placeholder (#132949, and #81841 for the same hazard on the scaffold).-# Keep it a structural label the model has no conversational reason to reproduce, never prose.-_INTERRUPTED_PLACEHOLDER = "[interrupt: no assistant output for this turn]"--# The spelling shipped before #132949. Models reproduce it verbatim, so rows already carrying it-# stay poisoned after the wording change; the replay filters reference this name to retire them.-_LEGACY_INTERRUPTED_PLACEHOLDER = "[response interrupted]"-# Escalate repeated heals once per session window, then stay quiet. Default threshold; tunable via# ``agent.sanitizer_heal_escalation_threshold`` (<= 0 disables).# Repeated heals of the same poisoned transcript used to WARNING on every send (#96870).@@ -2749,6 +2734,7 @@ def fill_empty_non_final_wire_payload(msg: Dict[str, Any], *, is_final: bool) ->return Falseif _msg_has_payload(msg):return False+ from agent.agent_runtime_helpers_placeholders import _INTERRUPTED_PLACEHOLDERmsg["content"] = _INTERRUPTED_PLACEHOLDERreturn True@@ -2851,6 +2837,7 @@ def repair_empty_non_final_messages(messages: List[Dict[str, Any]]) -> List[Dictdeletion) keeps role alternation and tool-call pairing intact. The final message is untouched."""if not messages or len(messages) < 2:return messages+ from agent.agent_runtime_helpers_placeholders import _INTERRUPTED_PLACEHOLDERrepaired: List[Dict[str, Any]] = []healed = 0last_idx = len(messages) - 1diff --git a/agent/agent_runtime_helpers_placeholders.py b/agent/agent_runtime_helpers_placeholders.pynew file mode 100644index 00000000000..f3c5f375eed--- /dev/null+++ b/agent/agent_runtime_helpers_placeholders.py@@ -0,0 +1,20 @@+"""Interrupt placeholder wording substituted into empty non-final wire rows.++Split out of ``agent/agent_runtime_helpers.py`` (code-health size ratchet); a leaf module with no+imports so every reader (runtime helpers, turn prep, the conversation loop) can import it directly.+"""++# Placeholder for an empty non-final message the provider would reject. Kept identical to the stub+# placeholder in chat_completion_helpers so healed transcripts read consistently.+#+# Wording matters: this text is substituted into an assistant row's ``content`` on the wire copy+# (``fill_empty_non_final_wire_payload``, ``repair_empty_non_final_messages``, and the projection in+# ``run_conversation``), so the model reads it as something IT said. A short natural-language phrase+# in that position gets echoed verbatim — a clean ``finish_reason=stop`` turn answering an ordinary+# instruction with just the placeholder (#132949, and #81841 for the same hazard on the scaffold).+# Keep it a structural label the model has no conversational reason to reproduce, never prose.+_INTERRUPTED_PLACEHOLDER = "[interrupt: no assistant output for this turn]"++# The spelling shipped before #132949. Models reproduce it verbatim, so rows already carrying it+# stay poisoned after the wording change; the replay filters reference this name to retire them.+_LEGACY_INTERRUPTED_PLACEHOLDER = "[response interrupted]"diff --git a/agent/conversation_loop.py b/agent/conversation_loop.pyindex 5e48e3c9e55..8ef5968014f 100644--- a/agent/conversation_loop.py+++ b/agent/conversation_loop.py@@ -349,7 +349,7 @@ def _apply_active_turn_redirect(agent: Any, messages: List[Dict[str, Any]], text# Hidden row, but a non-empty neutral api_content so the pre-call sanitizer# does not re-heal it every call (#88955). Never _INTERRUPT_SCAFFOLD_MARKER:# as assistant text the model echoes it (#81841).- from agent.agent_runtime_helpers import _INTERRUPTED_PLACEHOLDER+ from agent.agent_runtime_helpers_placeholders import _INTERRUPTED_PLACEHOLDERplaceholder["api_content"] = _INTERRUPTED_PLACEHOLDERappend_message(messages, placeholder)# Transcript shows the user's own words; the provider replays the scaffolded form.diff --git a/agent/message_sanitization.py b/agent/message_sanitization.pyindex 2cfdf80fad9..d4d6edbb41e 100644--- a/agent/message_sanitization.py+++ b/agent/message_sanitization.py@@ -302,7 +302,7 @@ def close_interrupted_tool_sequence(messages: list, final_response: Any = None)return Falsetext = final_response if isinstance(final_response, str) else ""from agent.message_metadata import append_message- from agent.agent_runtime_helpers import _INTERRUPTED_PLACEHOLDER+ from agent.agent_runtime_helpers_placeholders import _INTERRUPTED_PLACEHOLDERstripped = text.strip()if not stripped or stripped == _INTERRUPTED_PLACEHOLDER:diff --git a/agent/turn_api_call.py b/agent/turn_api_call.pyindex 04c0a27d9cc..87d1cfe82d1 100644--- a/agent/turn_api_call.py+++ b/agent/turn_api_call.py@@ -15,7 +15,7 @@ import timefrom typing import Any, Dict, Optionalfrom agent.error_classifier import FailoverReason-from agent.agent_runtime_helpers import _INTERRUPTED_PLACEHOLDER+from agent.agent_runtime_helpers_placeholders import _INTERRUPTED_PLACEHOLDERfrom agent.message_metadata import append_messagefrom agent.repetition_guard import REPETITION_LOOP_INTERRUPTED, is_runaway_repetitionfrom agent.turn_failure_copy import site_copy, stamp_failurediff --git a/agent/turn_iteration_prep.py b/agent/turn_iteration_prep.pyindex b821efd7254..ec58f39a76f 100644--- a/agent/turn_iteration_prep.py+++ b/agent/turn_iteration_prep.py@@ -118,7 +118,7 @@ class IterationPrep:# 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 (+ from agent.agent_runtime_helpers_placeholders import (_INTERRUPTED_PLACEHOLDER,_LEGACY_INTERRUPTED_PLACEHOLDER,)diff --git a/tests/agent/test_partial_stream_finish_reason.py b/tests/agent/test_partial_stream_finish_reason.pyindex 0add0d956ed..89a5822dde4 100644--- a/tests/agent/test_partial_stream_finish_reason.py+++ b/tests/agent/test_partial_stream_finish_reason.py@@ -807,7 +807,7 @@ class TestSendTimeEmptyAssistantPad:and not m.get("tool_calls")),None,)- from agent.agent_runtime_helpers import _INTERRUPTED_PLACEHOLDER+ from agent.agent_runtime_helpers_placeholders import _INTERRUPTED_PLACEHOLDERassert stub is not None and stub["content"] == _INTERRUPTED_PLACEHOLDERdef test_tool_call_turn_not_padded_on_send(self, loop_agent):@@ -896,10 +896,8 @@ class TestSendTimePadMultimodalSafety:"""Unit-shape check against the REAL owner: multimodal list content(the exact AttributeError shape) passes through untouched; a textlessstr turn is repaired; tool-call turns are exempt."""- from agent.agent_runtime_helpers import (- _INTERRUPTED_PLACEHOLDER,- repair_empty_non_final_messages,- )+ from agent.agent_runtime_helpers import repair_empty_non_final_messages+ from agent.agent_runtime_helpers_placeholders import _INTERRUPTED_PLACEHOLDERapi_messages = [{"role": "assistant", "content": [{"type": "text", "text": "hi"}]},{"role": "assistant", "content": ""},diff --git a/tests/agent/test_run_agent.py b/tests/agent/test_run_agent.pyindex be9697b62e1..92cce19b863 100644--- a/tests/agent/test_run_agent.py+++ b/tests/agent/test_run_agent.py@@ -1592,43 +1592,6 @@ class TestExecuteToolCalls:assert metadata["tool_call_id"] == "mem-1"assert messages[-1]["tool_call_id"] == "mem-1"- def test_keyboard_interrupt_emits_cancelled_post_tool_hook(self, agent, monkeypatch):- tc = _mock_tool_call(name="web_search", arguments='{"q":"test"}', call_id="c1")- mock_msg = _mock_assistant_msg(content="", tool_calls=[tc])- messages = []- hook_calls = []- agent.session_id = "session-1"- agent._current_turn_id = "turn-1"- agent._current_api_request_id = "api-1"-- def _capture_hook(hook_name, **kwargs):- hook_calls.append((hook_name, kwargs))- return []-- monkeypatch.setattr("hermes_cli.lifecycle.invoke_hook", _capture_hook)- monkeypatch.setattr("hermes_cli.lifecycle.has_hook", lambda name: True)-- with (- patch("model_tools.handle_function_call", side_effect=KeyboardInterrupt),- patch("run_agent._set_interrupt"),- patch("agent.interrupt_control._set_interrupt"),- pytest.raises(KeyboardInterrupt),- ):- agent._execute_tool_calls_sequential(mock_msg, messages, "task-1")-- post_calls = [kwargs for name, kwargs in hook_calls if name == "post_tool_call"]- assert len(post_calls) == 1- assert post_calls[0]["tool_name"] == "web_search"- assert post_calls[0]["tool_call_id"] == "c1"- assert post_calls[0]["session_id"] == "session-1"- assert post_calls[0]["turn_id"] == "turn-1"- assert post_calls[0]["api_request_id"] == "api-1"- assert post_calls[0]["status"] == "cancelled"- assert post_calls[0]["error_type"] == "keyboard_interrupt"- assert json.loads(post_calls[0]["result"])["status"] == "cancelled"- # The hook sees the user-interrupt attribution, not the generic "Turn interrupted".- assert post_calls[0]["error_message"] == "Tool execution cancelled. User interrupt"-def test_interrupt_skips_remaining(self, agent, monkeypatch):tc1 = _mock_tool_call(name="web_search", arguments="{}", call_id="c1")tc2 = _mock_tool_call(name="web_search", arguments="{}", call_id="c2")diff --git a/tests/agent/test_run_agent_interrupt_hook.py b/tests/agent/test_run_agent_interrupt_hook.pynew file mode 100644index 00000000000..ad59a661c85--- /dev/null+++ b/tests/agent/test_run_agent_interrupt_hook.py@@ -0,0 +1,55 @@+"""Sequential tool execution: Ctrl-C emits a cancelled ``post_tool_call`` hook.++Split out of ``tests/agent/test_run_agent.py`` (code-health size ratchet); shares its fixtures.+"""++import json+from unittest.mock import patch++import pytest++from tests.agent import test_run_agent as _base+from tests.agent.test_run_agent import _mock_assistant_msg, _mock_tool_call++# Reuse the facade's fixtures by name (an import would shadow-redefine ``agent`` — F811).+agent = _base.agent+_mock_plugin_discovery = _base._mock_plugin_discovery+++class TestExecuteToolCallsInterruptHook:+ def test_keyboard_interrupt_emits_cancelled_post_tool_hook(self, agent, monkeypatch):+ tc = _mock_tool_call(name="web_search", arguments='{"q":"test"}', call_id="c1")+ mock_msg = _mock_assistant_msg(content="", tool_calls=[tc])+ messages = []+ hook_calls = []+ agent.session_id = "session-1"+ agent._current_turn_id = "turn-1"+ agent._current_api_request_id = "api-1"++ def _capture_hook(hook_name, **kwargs):+ hook_calls.append((hook_name, kwargs))+ return []++ monkeypatch.setattr("hermes_cli.lifecycle.invoke_hook", _capture_hook)+ monkeypatch.setattr("hermes_cli.lifecycle.has_hook", lambda name: True)++ with (+ patch("model_tools.handle_function_call", side_effect=KeyboardInterrupt),+ patch("run_agent._set_interrupt"),+ patch("agent.interrupt_control._set_interrupt"),+ pytest.raises(KeyboardInterrupt),+ ):+ agent._execute_tool_calls_sequential(mock_msg, messages, "task-1")++ post_calls = [kwargs for name, kwargs in hook_calls if name == "post_tool_call"]+ assert len(post_calls) == 1+ assert post_calls[0]["tool_name"] == "web_search"+ assert post_calls[0]["tool_call_id"] == "c1"+ assert post_calls[0]["session_id"] == "session-1"+ assert post_calls[0]["turn_id"] == "turn-1"+ assert post_calls[0]["api_request_id"] == "api-1"+ assert post_calls[0]["status"] == "cancelled"+ assert post_calls[0]["error_type"] == "keyboard_interrupt"+ assert json.loads(post_calls[0]["result"])["status"] == "cancelled"+ # The hook sees the user-interrupt attribution, not the generic "Turn interrupted".+ assert post_calls[0]["error_message"] == "Tool execution cancelled. User interrupt"diff --git a/tests/agent/test_sanitiser_escalation.py b/tests/agent/test_sanitiser_escalation.pyindex 65d31923c5e..d673e3d2e8d 100644--- a/tests/agent/test_sanitiser_escalation.py+++ b/tests/agent/test_sanitiser_escalation.py@@ -14,7 +14,6 @@ import loggingimport pytestfrom agent.agent_runtime_helpers import (- _INTERRUPTED_PLACEHOLDER,_empty_heal_log_state,_empty_heal_pending_notice,_empty_heal_user_notified,@@ -23,6 +22,7 @@ from agent.agent_runtime_helpers import (get_sanitizer_heal_stats,repair_empty_non_final_messages,)+from agent.agent_runtime_helpers_placeholders import _INTERRUPTED_PLACEHOLDERfrom hermes_logging import clear_session_context, set_session_contextdiff --git a/tests/agent/test_steer.py b/tests/agent/test_steer.pyindex 84a8f6e3370..c98c024be99 100644--- a/tests/agent/test_steer.py+++ b/tests/agent/test_steer.py@@ -11,7 +11,7 @@ import threadingimport pytest-from agent.agent_runtime_helpers import _INTERRUPTED_PLACEHOLDER+from agent.agent_runtime_helpers_placeholders import _INTERRUPTED_PLACEHOLDERfrom agent.prompt_builder import STEER_MARKER_OPEN, format_steer_markerfrom run_agent import AIAgentfrom tools.registry import registrydiff --git a/tests/agent/test_turn_api_call_interrupt.py b/tests/agent/test_turn_api_call_interrupt.pyindex e1a9baeda2e..764c9611579 100644--- a/tests/agent/test_turn_api_call_interrupt.py+++ b/tests/agent/test_turn_api_call_interrupt.py@@ -6,7 +6,7 @@ from __future__ import annotationsimport threadingimport time-from agent.agent_runtime_helpers import _INTERRUPTED_PLACEHOLDER+from agent.agent_runtime_helpers_placeholders import _INTERRUPTED_PLACEHOLDERfrom agent.repetition_guard import REPETITION_LOOP_INTERRUPTEDfrom agent.turn_api_call import handle_api_interruptfrom agent.turn_retry_state import TurnRetryStatediff --git a/tests/agent/test_turn_finalizer_interrupt_alternation.py b/tests/agent/test_turn_finalizer_interrupt_alternation.pyindex e19818e33d2..cd9c30b5d14 100644--- a/tests/agent/test_turn_finalizer_interrupt_alternation.py+++ b/tests/agent/test_turn_finalizer_interrupt_alternation.py@@ -16,7 +16,7 @@ an empty-content assistant turn. The synthetic row is hidden from the user"""-from agent.agent_runtime_helpers import _INTERRUPTED_PLACEHOLDER+from agent.agent_runtime_helpers_placeholders import _INTERRUPTED_PLACEHOLDERfrom agent.turn_finalizer import finalize_turn