The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): end the turn as interrupted when the iteration summary is cancelled
kshitijk4poor578bcd2349a0
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 1c666ed44b5..72e962c62bb 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -2372,7 +2372,7 @@ def handle_max_iterations(agent, messages: list, api_call_count: int) -> str:# Shared constant so compaction recognizers can identify this runtime nudge by its stable# content after SessionDB projection strips metadata flags.from agent.context_compressor import MAX_ITERATIONS_SUMMARY_REQUEST- append_message(messages, {"role": "user", "content": MAX_ITERATIONS_SUMMARY_REQUEST})+ nudge = append_message(messages, {"role": "user", "content": MAX_ITERATIONS_SUMMARY_REQUEST})try:api_messages = _iteration_summary_api_messages(agent, messages)@@ -2393,6 +2393,13 @@ def handle_max_iterations(agent, messages: list, api_call_count: int) -> str:final_response = textbreak+ except InterruptedError:+ # Cancellation is not a summary failure: drop the unanswered nudge and let the+ # finalizer end the turn as interrupted so the pending message is requeued.+ summary_call_outcome = "cancelled"+ if messages and messages[-1] is nudge:+ messages.pop()+ raiseexcept Exception as e:logger.warning("Failed to get summary response: %s", e)from agent.turn_failure_copy import site_copydiff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.pyindex 53c78050b43..5c98a3961ea 100644--- a/agent/turn_finalizer.py+++ b/agent/turn_finalizer.py@@ -8,11 +8,13 @@ from __future__ import annotationsimport loggingimport os+import timefrom contextlib import suppressfrom typing import Any, Callable, List, Optional, Tuplefrom agent.codex_responses_adapter import _summarize_user_message_for_logfrom agent.delegation_context import is_dispatcher_owned_worker_context+from agent.interrupt_control import interrupt_issuerfrom agent.turn_failure_copy import exit_reason_failure, stamp_failurefrom agent.context_compressor import _DB_PERSISTED_MARKERfrom agent.message_content import flatten_message_text@@ -122,9 +124,9 @@ def _guarded_cleanup(label: str, fn: Callable[[], Any], errors: List[str], loggedef _resolve_budget_fallback(agent, *, final_response, api_call_count, interrupted, failed, messages, _turn_exit_reason,_pending_verification_response, _pending_verification_response_previewed, logger,-) -> Tuple[Any, Any, bool]:+) -> Tuple[Any, Any, bool, Any]:"""Iteration-budget exhaustion. Returns ``(final_response, _turn_exit_reason,- preserved_verification_fallback)``."""+ preserved_verification_fallback, interrupted)``."""budget_exhausted = (api_call_count >= agent.max_iterations or agent.iteration_budget.remaining <= 0)@@ -154,7 +156,20 @@ def _resolve_budget_fallback(f"\n⚠️ Iteration budget exhausted ({api_call_count}/{agent.max_iterations}) ""— requesting summary...", diagnostic=True,)- final_response = agent._handle_max_iterations(messages, api_call_count)+ _summary_start = time.time()+ try:+ final_response = agent._handle_max_iterations(messages, api_call_count)+ except InterruptedError:+ # Same surfacing as an interrupted loop API call (handle_api_interrupt):+ # the turn is interrupted, so the pending interrupt message is returned+ # for requeue instead of being cleared behind a fallback summary.+ from agent.conversation_loop import INTERRUPT_WAITING_FOR_MODEL_PREFIX+ interrupted = True+ _issuer = interrupt_issuer(agent)+ _turn_exit_reason = (+ f"interrupted_during_api_call({_issuer})" if _issuer else "interrupted_during_api_call"+ )+ final_response = f"{INTERRUPT_WAITING_FOR_MODEL_PREFIX}{time.time() - _summary_start:.1f}s elapsed)."# A kanban worker must record a terminal outcome whether or not a fallback path# was eligible, so the dispatcher learns the worker could not complete. Only the@@ -178,7 +193,7 @@ def _resolve_budget_fallback(# closed it — the CAS invariant in ``_end_run`` (``WHERE ended_at IS NULL``) guarantees idempotence.if _kanban_task:_record_kanban_budget_exhausted(_kanban_task, api_call_count, agent.max_iterations, logger)- return final_response, _turn_exit_reason, preserved_verification_fallback+ return final_response, _turn_exit_reason, preserved_verification_fallback, interrupteddef _rollback_interrupted_preflight_display(agent, interrupted) -> None:@@ -503,7 +518,7 @@ def finalize_turn("""Run the post-loop finalization and return the turn ``result`` dict."""from agent.conversation_loop import logger- final_response, _turn_exit_reason, preserved_verification_fallback = _resolve_budget_fallback(+ final_response, _turn_exit_reason, preserved_verification_fallback, interrupted = _resolve_budget_fallback(agent, final_response=final_response, api_call_count=api_call_count,interrupted=interrupted, failed=failed, messages=messages,_turn_exit_reason=_turn_exit_reason,diff --git a/tests/agent/test_run_agent.py b/tests/agent/test_run_agent.pyindex febf261870c..00c16454b60 100644--- a/tests/agent/test_run_agent.py+++ b/tests/agent/test_run_agent.py@@ -2486,9 +2486,13 @@ class TestHandleMaxIterations:monkeypatch.setattr(agent, "_get_transport", lambda: transport)monkeypatch.setattr(agent, "_anthropic_messages_create", blocked)+ raised = []+def summarize():try:agent._handle_max_iterations([{"role": "user", "content": "work"}], 1)+ except InterruptedError as exc:+ raised.append(exc)finally:finished.set()@@ -2499,11 +2503,64 @@ class TestHandleMaxIterations:agent.interrupt()assert finished.wait(4), "summary ignored interrupt while provider was blocked"assert aborted == [request_client]+ assert len(raised) == 1, "summary cancellation must propagate, not become a fallback"agent.client.close.assert_not_called()finally:release.set()worker.join(12)+ def test_interrupted_summary_ends_turn_interrupted_and_keeps_pending_message(self, agent, monkeypatch):+ from agent.context_compressor import MAX_ITERATIONS_SUMMARY_REQUEST+ from agent.conversation_loop import INTERRUPT_WAITING_FOR_MODEL_PREFIX++ agent._cached_system_prompt = "You are helpful."+ agent._use_prompt_caching = False+ agent.compression_enabled = False+ agent.save_trajectories = False+ agent.max_iterations = 1+ tool_resp = _mock_response(+ content="", finish_reason="tool_calls",+ tool_calls=[_mock_tool_call(name="web_search", arguments="{}", call_id="c1")],+ )+ release = threading.Event()+ calls = []++ def provider(*args, **kwargs):+ calls.append(kwargs)+ if len(calls) == 1:+ return tool_resp+ # The summary request: a new user message arrives while it is in flight.+ agent.interrupt("follow-up message")+ release.wait(10)+ raise OSError("fixture request stopped")++ request_client = MagicMock()+ request_client.chat.completions.create.side_effect = provider+ agent.client.chat.completions.create.side_effect = provider+ monkeypatch.setattr(agent, "_create_request_openai_client", lambda **kw: request_client)+ monkeypatch.setattr(agent, "_abort_request_openai_client", lambda *a, **kw: release.set())+ monkeypatch.setattr(agent, "_close_request_openai_client", lambda *a, **kw: None)++ try:+ with (+ patch("model_tools.handle_function_call", return_value="ok"),+ patch.object(agent, "_persist_session"),+ patch.object(agent, "_save_trajectory"),+ patch.object(agent, "_cleanup_task_resources"),+ ):+ result = agent.run_conversation("do the work")+ finally:+ release.set()++ assert len(calls) == 2, "summary request never reached the provider fixture"+ assert result["interrupted"] is True+ assert result["completed"] is False+ assert result["interrupt_message"] == "follow-up message"+ assert result["turn_exit_reason"].startswith("interrupted_during_api_call")+ assert result["final_response"].startswith(INTERRUPT_WAITING_FOR_MODEL_PREFIX)+ assert "couldn't produce a summary" not in result["final_response"]+ assert all(m.get("content") != MAX_ITERATIONS_SUMMARY_REQUEST for m in result["messages"])+def test_summary_notice_uses_safe_print(self, agent):agent._print_fn = lambda *_args, **_kwargs: (_ for _ in ()).throw(ValueError("closed"))agent.client.chat.completions.create.return_value = _mock_response(content="Summary")