The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent,gateway): report interrupted and unfinished turns truthfully
teknium10a6c7b7fa3e1
diff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.pyindex 65dda75a7bd..a98aa461b32 100644--- a/agent/turn_finalizer.py+++ b/agent/turn_finalizer.py@@ -462,9 +462,12 @@ def finalize_turn(if _exit_failure is not None and _exit_failure.fails_turn:failed = True+ # Sibling producers (``turn_recovery``, ``codex_runtime``) return ``completed=False`` for an+ # interrupted turn; the gateway stream gate and the API run status rely on that contract.completed = (final_response is not Noneand not failed+ and not interruptedand (api_call_count < agent.max_iterations or str(_turn_exit_reason).startswith("text_response(")))diff --git a/gateway/platforms/api_server.py b/gateway/platforms/api_server.pyindex 33f76cd7847..d764e972d0d 100644--- a/gateway/platforms/api_server.py+++ b/gateway/platforms/api_server.py@@ -3193,24 +3193,18 @@ class APIServerAdapter(OpenAICompatRoutesMixin, BasePlatformAdapter):effective_session_id = result.get("session_id", session_id) if is_dict else session_idturn_messages = self._turn_transcript_messages(history, user_message, result) if is_dict else []effective_runtime = self._effective_turn_runtime(runtime_request, result, usage)+ # Terminal status and flags come from the result (interrupted -> cancelled,+ # unfinished -> failed); a late steer rides along as ``pending_steer`` for replay.+ status, fields = _api_runs.terminal_run_status(result if is_dict else {})await queue.put(_event_payload("assistant.completed", {"session_id": effective_session_id, "message_id": message_id,- "content": final_response, "completed": True,- "partial": bool(result.get("partial")) if is_dict else False,- "interrupted": False, "runtime": effective_runtime}))- # A steer accepted after the final reply lands in result["pending_steer"]; surface- # it so clients can replay it rather than lose it.- pending_steer = result.get("pending_steer") if is_dict else None- completed_payload = {- "session_id": effective_session_id, "message_id": message_id, "completed": True,- "messages": turn_messages, "usage": usage, "runtime": effective_runtime}- if pending_steer:- completed_payload["pending_steer"] = pending_steer- await queue.put(_event_payload("run.completed", completed_payload))+ "content": final_response, **fields, "runtime": effective_runtime}))+ await queue.put(_event_payload(f"run.{status}", {+ "session_id": effective_session_id, "message_id": message_id, **fields,+ "messages": turn_messages, "usage": usage, "runtime": effective_runtime}))self._set_run_status(- run_id, "completed", session_id=effective_session_id, usage=usage,- last_event="run.completed",- **({"pending_steer": pending_steer} if pending_steer else {}))+ run_id, status, session_id=effective_session_id, usage=usage,+ last_event=f"run.{status}", **fields)except asyncio.CancelledError:self._set_run_status(run_id, "cancelled", last_event="run.cancelled")raisediff --git a/gateway/platforms/api_server_runs.py b/gateway/platforms/api_server_runs.pyindex 33f97555615..971175a503e 100644--- a/gateway/platforms/api_server_runs.py+++ b/gateway/platforms/api_server_runs.py@@ -9,7 +9,7 @@ import timeimport uuidfrom contextlib import suppressfrom dataclasses import dataclass-from typing import Any, Callable, Dict, List, Optional+from typing import Any, Callable, Dict, List, Optional, Tupletry:from aiohttp import web@@ -70,6 +70,28 @@ def _run_event(run_id: str, name: str, **fields: Any) -> Dict[str, Any]:return {"event": name, "run_id": run_id, "timestamp": time.time(), **fields}+def terminal_run_status(result: Dict[str, Any]) -> Tuple[str, Dict[str, Any]]:+ """Map a ``run_conversation`` result to its terminal run status and the wire fields every+ terminal event/status carries. An interrupted turn is ``cancelled``; a turn that ended+ without finishing (``failed``, ``partial``, or ``completed=False`` such as the iteration+ budget) is ``failed``, so ``completed: true`` never rides next to ``partial: true``."""+ interrupted = bool(result.get("interrupted"))+ finished = (+ not interrupted and not result.get("failed") and not result.get("partial")+ and result.get("completed") is not False+ )+ status = "cancelled" if interrupted else "completed" if finished else "failed"+ fields: Dict[str, Any] = {+ "completed": finished, "partial": bool(result.get("partial")), "interrupted": interrupted,+ }+ if not finished and result.get("turn_exit_reason"):+ fields["turn_exit_reason"] = str(result["turn_exit_reason"])+ if result.get("pending_steer"):+ # Undelivered steer text rides on every terminal event/status for client replay.+ fields["pending_steer"] = result["pending_steer"]+ return status, fields++def _run_not_found(_openai_error, run_id: str) -> "web.Response":return _json_error(_openai_error, f"Run not found: {run_id}", code="run_not_found", status=404)@@ -633,15 +655,14 @@ async def _execute_run(self, run: _RunLaunch, *, _api_server) -> None:None, lambda: _run_agent_sync(self, run, agent, approval_notify, _api_server=_api_server))if not isinstance(result, dict):result = {}- if run_id in self._stopping_run_ids and result.get("interrupted") is True:- _finish("cancelled")+ status, fields = terminal_run_status(result)+ if status == "cancelled":+ _finish("cancelled", fields)elif result.get("failed"):# Non-retryable client errors (401/400) return failed=True rather than raising.- _finish("failed", error=_redact_api_error_text(result.get("error") or "agent run failed"))+ _finish("failed", fields, error=_redact_api_error_text(result.get("error") or "agent run failed"))else:- # Undelivered steer text rides on the terminal event/status for client replay.- extra = {"pending_steer": result["pending_steer"]} if result.get("pending_steer") else {}- _finish("completed", extra, output=result.get("final_response", ""), usage=usage)+ _finish(status, fields, output=result.get("final_response", ""), usage=usage)except asyncio.CancelledError:_finish("cancelled")raisediff --git a/tests/agent/test_turn_finalizer_interrupt_alternation.py b/tests/agent/test_turn_finalizer_interrupt_alternation.pyindex c642dfe4894..5c7e365336d 100644--- a/tests/agent/test_turn_finalizer_interrupt_alternation.py+++ b/tests/agent/test_turn_finalizer_interrupt_alternation.py@@ -180,3 +180,18 @@ def test_interrupt_without_tool_tail_adds_nothing():_finalize(agent, messages, interrupted=True, final_response="partial reply")assert len(messages) == beforeassert messages[-1]["role"] == "assistant"+++def test_interrupted_turn_with_diagnostic_text_is_not_completed():+ """An interrupt mid-call leaves a diagnostic ``final_response`` ("Operation interrupted:+ waiting for model response"); the result must still say ``completed=False`` like the+ sibling producers (turn_recovery, codex_runtime) — the gateway stream gate and the API run+ status trust that flag (#111770)."""+ agent = _StubAgent()+ result = _finalize(+ agent, [{"role": "user", "content": "hi"}], interrupted=True,+ final_response="Operation interrupted: waiting for model response (0.1s elapsed).",+ )+ assert result["interrupted"] is True+ assert result["completed"] is False+ assert result["failed"] is Falsediff --git a/tests/gateway/test_api_server_runs.py b/tests/gateway/test_api_server_runs.pyindex 273ef8c91de..6a832cb1633 100644--- a/tests/gateway/test_api_server_runs.py+++ b/tests/gateway/test_api_server_runs.py@@ -670,6 +670,45 @@ class TestSteerRun:assert adapter._run_statuses[run_id]["status"] == "completed"assert adapter._run_statuses[run_id]["pending_steer"] == "tighten the ending"+ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("result", "expected_status"),+ [+ ({"final_response": "Operation interrupted.", "interrupted": True, "completed": False}, "cancelled"),+ ({"final_response": "Budget exhausted summary.", "completed": False,+ "turn_exit_reason": "max_iterations_reached(2/2)"}, "failed"),+ ({"final_response": "done", "completed": True}, "completed"),+ ],+ )+ async def test_run_terminal_status_follows_result_flags(self, adapter, result, expected_status):+ """A turn that ended interrupted or unfinished must not be booked as ``completed``+ (#111770): the persisted status, the ``completed`` flag and the terminal event name+ agree, and a late steer survives on every terminal status."""+ result["pending_steer"] = "tighten the ending"+ app = _create_runs_app(adapter)+ async with TestClient(TestServer(app)) as cli:+ with patch.object(adapter, "_create_agent") as mock_create:+ mock_agent = MagicMock()+ mock_agent.session_prompt_tokens = 0+ mock_agent.session_completion_tokens = 0+ mock_agent.session_total_tokens = 0+ mock_agent.run_conversation.return_value = result+ mock_create.return_value = mock_agent++ start_resp = await cli.post("/v1/runs", json={"input": "hello"})+ run_id = (await start_resp.json())["run_id"]+ for _ in range(40):+ if adapter._run_statuses.get(run_id, {}).get("status") == expected_status:+ break+ await asyncio.sleep(0.05)+ events = await (await cli.get(f"/v1/runs/{run_id}/events")).text()++ status = adapter._run_statuses[run_id]+ assert status["status"] == expected_status+ assert status["completed"] is (expected_status == "completed")+ assert status["pending_steer"] == "tighten the ending"+ assert f"run.{expected_status}" in events+@pytest.mark.asyncioasync def test_steer_requires_auth(self, auth_adapter):app = _create_runs_app(auth_adapter)diff --git a/tests/gateway/test_session_api.py b/tests/gateway/test_session_api.pyindex 4382cb61070..ab64ce12a1c 100644--- a/tests/gateway/test_session_api.py+++ b/tests/gateway/test_session_api.py@@ -385,6 +385,40 @@ async def test_session_chat_stream_run_completed_carries_turn_transcript(adapterassert any(m.get("tool_calls") for m in messages)+async def test_session_chat_stream_reports_interrupted_turn_as_not_completed(adapter, session_db):+ """The SSE terminal payload is derived from the result, never hard-coded: an interrupted+ turn streams ``completed: false`` / ``interrupted: true`` and ends with ``run.cancelled``,+ and the run status matches (#111770)."""+ import json as _json++ session_id = session_db.create_session("interrupted-session", "api_server")++ async def fake_run(**_kwargs):+ return {"final_response": "Operation interrupted.", "interrupted": True, "completed": False,+ "session_id": session_id}, {"total_tokens": 1}++ app = _create_session_app(adapter)+ with patch.object(adapter, "_run_agent", side_effect=fake_run):+ async with TestClient(TestServer(app)) as cli:+ resp = await cli.post(f"/api/sessions/{session_id}/chat/stream", json={"message": "hello"})+ body = await resp.text()++ payloads = {}+ for block in body.split("\n\n"):+ lines = block.splitlines()+ event = next((ln[7:] for ln in lines if ln.startswith("event: ")), None)+ data = next((ln[6:] for ln in lines if ln.startswith("data: ")), None)+ if event and data:+ payloads[event] = _json.loads(data)++ assert payloads["assistant.completed"]["completed"] is False+ assert payloads["assistant.completed"]["interrupted"] is True+ assert "run.cancelled" in payloads and "run.completed" not in payloads+ assert payloads["run.cancelled"]["completed"] is False+ assert next(iter(adapter._run_statuses.values()))["status"] == "cancelled"++# ---------------------------------------------------------------------------# Session-persisted model threading + provider-auth failure surfacing# (salvaged from PR #57947 by @FvanW and PR #59941 by @kaishi00)diff --git a/website/docs/developer-guide/programmatic-integration.md b/website/docs/developer-guide/programmatic-integration.mdindex 434489b1075..3d1d82cd6be 100644--- a/website/docs/developer-guide/programmatic-integration.md+++ b/website/docs/developer-guide/programmatic-integration.md@@ -168,7 +168,20 @@ Use `/v1/models` for OpenAI-client compatibility. Use `/api/model/options` or`/v1/runs/{id}/steer` is only accepted while the run status is `running`. Queued, approval-paused, stopping, cancelled, failed, and completed runs return `409 run_not_accepting_steer`, even if the server still retains internal agent references during cooperative shutdown.-A `200` (and the `run.steered` event) means the text was **queued**, not that the agent consumed it. If a steer lands after the agent's final response — with no later tool boundary to deliver it at — the undelivered text is returned as `pending_steer` on the terminal `run.completed` event and run status, so the client can replay it as the next user turn instead of losing it.+A `200` (and the `run.steered` event) means the text was **queued**, not that the agent consumed it. If a steer lands after the agent's final response — with no later tool boundary to deliver it at — the undelivered text is returned as `pending_steer` on the terminal event (`run.completed`, `run.failed`, or `run.cancelled`) and run status, so the client can replay it as the next user turn instead of losing it.++#### Terminal run status++The terminal status of a run is derived from how the agent's turn actually ended, and the terminal event name always matches it (`run.<status>`):++| Turn outcome | Status | Terminal event | Flags on the event / status |+|---|---|---|---|+| Final answer produced | `completed` | `run.completed` | `completed: true` |+| Interrupted (`/stop`, or an interrupt inside the agent) | `cancelled` | `run.cancelled` | `completed: false`, `interrupted: true` |+| Provider/agent failure | `failed` | `run.failed` | `completed: false`, `error` |+| Ended without finishing (iteration budget, truncated or partial reply) | `failed` | `run.failed` | `completed: false`, `partial` when applicable, `turn_exit_reason` (e.g. `max_iterations_reached(60/60)`), `output` with any fallback text |++A run is never reported as `completed` with `completed: false` or `partial: true` in the same payload. The same rule applies to `/api/sessions/{id}/chat/stream`, whose `assistant.completed` payload carries the real `completed` / `partial` / `interrupted` flags and whose terminal event is `run.completed`, `run.failed`, or `run.cancelled`.---diff --git a/website/docs/user-guide/features/api-server.md b/website/docs/user-guide/features/api-server.mdindex 78f3539ce01..8f641807498 100644--- a/website/docs/user-guide/features/api-server.md+++ b/website/docs/user-guide/features/api-server.md@@ -579,7 +579,7 @@ External UIs can manage Hermes sessions over REST without standing up the dashbo| `GET` | `/api/sessions/{id}/messages` | Message history for a session || `POST` | `/api/sessions/{id}/fork` | Branch the session via `SessionDB` lineage (matches CLI `/branch` semantics) || `POST` | `/api/sessions/{id}/chat` | Run one synchronous agent turn |-| `POST` | `/api/sessions/{id}/chat/stream` | SSE wrapper over a single turn — emits `assistant.delta`, `tool.started`, `tool.completed`, `run.completed` events |+| `POST` | `/api/sessions/{id}/chat/stream` | SSE wrapper over a single turn — emits `assistant.delta`, `tool.started`, `tool.completed`, then a terminal `run.completed` / `run.failed` / `run.cancelled` event that matches how the turn ended (see [Terminal run status](../../developer-guide/programmatic-integration.md#terminal-run-status)) |`/v1/capabilities` advertises the full surface via `session_*` feature flags and `endpoints.session_*` entries so external UIs can detect support and fall back safely. Inline images are supported in `chat` and `chat/stream` payloads (multimodal-aware path).