The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): let the exit owner close the tool tail scaffolding uncovers
kshitijk4poor53156ea7256c
diff --git a/agent/session_persistence.py b/agent/session_persistence.pyindex 7bbc2f168b1..c882fc0dd8f 100644--- a/agent/session_persistence.py+++ b/agent/session_persistence.py@@ -352,12 +352,11 @@ class SessionPersistenceMixin:list used by the API call (#48677 is thus closed for every persist caller, not just this one)."""from agent.agent_runtime_helpers import note_turn_persisted- from agent.message_sanitization import close_interrupted_tool_sequencewith _persist_lock(self):- # Scaffolding is only on the tail when the turn leaves mid-recovery; close the tool tail it- # uncovers so the next user turn does not land as ``tool → user``.- if self._drop_trailing_empty_response_scaffolding(messages):- close_interrupted_tool_sequence(messages)+ # Only the scaffolding goes here. Closing a tool tail this uncovers is the exit+ # owner's job (``_close_transcript_tail``, ``abort_turn_on_interrupt``,+ # ``handle_api_interrupt``): only it knows the reason to record.+ self._drop_trailing_empty_response_scaffolding(messages)self._session_messages = messagesself._flush_messages_to_session_db(messages, conversation_history)# Drain async token-accounting deltas at every persist point; cheap no-op when nothing queued.diff --git a/agent/turn_api_call.py b/agent/turn_api_call.pyindex eea1a42c897..1cec074c6f6 100644--- a/agent/turn_api_call.py+++ b/agent/turn_api_call.py@@ -17,6 +17,7 @@ from typing import Any, Dict, Optionalfrom agent.error_classifier import FailoverReasonfrom agent.agent_runtime_helpers import _INTERRUPTED_PLACEHOLDERfrom agent.message_metadata import append_message+from agent.message_sanitization import close_interrupted_tool_sequencefrom agent.repetition_guard import REPETITION_LOOP_INTERRUPTED, is_runaway_repetitionfrom agent.turn_failure_copy import site_copy, stamp_failure@@ -187,6 +188,10 @@ def handle_api_interrupt(api_elapsed = time.time() - api_start_timeagent._vprint(f"{agent.log_prefix}⚡ Interrupted during API call.", force=True)interrupted = True+ # A Stop during the empty-response nudge request leaves the synthetic assistant+nudge+ # pair after an executed tool result; strip it so the row appended below (or the close)+ # follows the tool row, and this exit owner records its own reason.+ agent._drop_trailing_empty_response_scaffolding(messages)_partial = agent._strip_think_blocks(getattr(agent, "_current_streamed_assistant_text", "") or "").strip()@@ -204,6 +209,7 @@ def handle_api_interrupt(final_response = _partialelse:final_response = f"{INTERRUPT_WAITING_FOR_MODEL_PREFIX}{api_elapsed:.1f}s elapsed)."+ close_interrupted_tool_sequence(messages, final_response)agent._persist_session(messages, conversation_history)return ApiInterruptVerdict("break", thinking_spinner, interrupted, final_response)diff --git a/tests/agent/test_empty_response_recovery_persistence.py b/tests/agent/test_empty_response_recovery_persistence.pyindex a7ac663f816..4eb6da44e80 100644--- a/tests/agent/test_empty_response_recovery_persistence.py+++ b/tests/agent/test_empty_response_recovery_persistence.py@@ -53,8 +53,8 @@ def _agent_with_stubbed_persistence():def test_persist_session_strips_trailing_empty_recovery_scaffolding():"""Only the flagged scaffolding goes. The assistant(tool_calls) + tool pair- already ran and was saved before execution, so it stays; the tool tail it- leaves is closed so the next user message never lands as ``tool → user``.+ already ran and was saved before execution, so it stays. The persist layer does+ not author a closing row: the exit owner closes the tool tail with its reason."""agent = _agent_with_stubbed_persistence()messages = [@@ -83,7 +83,7 @@ def test_persist_session_strips_trailing_empty_recovery_scaffolding():AIAgent._persist_session(agent, messages, conversation_history=[])- assert [m["role"] for m in messages] == ["user", "assistant", "tool", "assistant"]+ assert [m["role"] for m in messages] == ["user", "assistant", "tool"]assert messages[1]["tool_calls"][0]["id"] == messages[2]["tool_call_id"]assert agent.flushed_session_db_messages[-1] == messagesassert all(not msg.get("_empty_recovery_synthetic") for msg in messages)