The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix: reject the HTTP-200 router timeout shim in every OpenAI-compatible consumer
teknium122753744fbe9
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex 3c4dde5bde1..8f7327a99b0 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -6615,6 +6615,11 @@ def _validate_llm_response(f"adapter or custom endpoint compatibility.") from excresponse = recovered+ from agent.transports.chat_completions import is_router_timeout_shim+ if is_router_timeout_shim(response):+ # HTTP-200 router failure shim (#68396): invalid like a malformed shape so the+ # auxiliary fallback chain moves to the next candidate instead of titling with it.+ raise RuntimeError(f"Auxiliary {task or 'call'}: provider returned a timeout shim instead of a completion")# Retain the provider-reported model for terminal relay route attribution.context = _RELAY_AUX_CALL_CONTEXT.get()if context is not None:diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex c700f02c6bd..ec2dd261f94 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -30,6 +30,7 @@ from agent.error_classifier import (from agent.sdk_transform_bypass import bypass_chat_sdk_request_transformfrom agent.errors import EmptyStreamErrorfrom agent.chat_completion_stream_monitor import StreamingWaitMonitor+from agent.transports.chat_completions import is_router_timeout_shim, router_timeout_shim_may_followfrom agent.fast_mode import effective_request_overridesfrom agent.turn_context import substitute_api_contentfrom agent.gemini_native_adapter import is_native_gemini_base_url@@ -2128,6 +2129,10 @@ def _managed_summary_call(agent, api_request_id: str, request, callback, *, retrdef _summary_text(agent, response, **normalize_kwargs) -> str:+ if is_router_timeout_shim(response):+ # Router failure in a 200 envelope (#68396): an empty summary takes the retry slot.+ logger.warning("Iteration summary returned a router timeout shim; retrying")+ return ""normalized = agent._get_transport().normalize_response(response, **normalize_kwargs)if normalized.tool_calls:# No summary path executes tool calls; log so a tool-only response that falls into the@@ -3003,9 +3008,11 @@ class _StreamingCall(StreamingWaitMonitor):content_parts.append(delta_content)if tool_calls_acc:self._route_suppressed_text(delta_content)- elif pending_text_parts or _provider_stream_text_may_be_sse(delta_content):+ elif (pending_text_parts or _provider_stream_text_may_be_sse(delta_content)+ or router_timeout_shim_may_follow("".join(content_parts))):pending_text_parts.append(delta_content)- if not _provider_stream_text_may_be_sse("".join(pending_text_parts)):+ pending = "".join(pending_text_parts)+ if not (_provider_stream_text_may_be_sse(pending) or router_timeout_shim_may_follow(pending)):_flush_pending_stream_text()continueelse:@@ -3118,7 +3125,6 @@ class _StreamingCall(StreamingWaitMonitor):full_content or "", effective_finish_reason, response=getattr(stream, "response", None))if provider_stream_error is not None:raise provider_stream_error- flush_pending()message = SimpleNamespace(role=role, content=full_content, tool_calls=mock_tool_calls, reasoning_content=full_reasoning,# ``normalize_response`` reads ``message.refusal`` — same contract as the non-streaming object.refusal="".join(refusal_parts or ()) or None)@@ -3128,9 +3134,14 @@ class _StreamingCall(StreamingWaitMonitor):message.reasoning_details = reasoning_details# The provider's id when the chunks carried one (chatcmpl-/gen-...): it is what a provider needs to# look a request up. Fabricated only when the stream never sent one.- return SimpleNamespace(id=response_id or ("stream-" + str(uuid.uuid4())), model=model_name, usage=usage_obj,+ response = SimpleNamespace(id=response_id or ("stream-" + str(uuid.uuid4())), model=model_name, usage=usage_obj,provider=upstream_provider,choices=[SimpleNamespace(index=0, message=message, finish_reason=effective_finish_reason)])+ # A held router timeout shim (#68396) is rejected by validate_response and retried;+ # releasing its text here would show the provider failure as assistant output.+ if not is_router_timeout_shim(response):+ flush_pending()+ return response# ── anthropic_messages wire ─────────────────────────────────────────diff --git a/agent/transports/chat_completions.py b/agent/transports/chat_completions.pyindex d23af22306d..ee11801b382 100644--- a/agent/transports/chat_completions.py+++ b/agent/transports/chat_completions.py@@ -122,8 +122,21 @@ def _has_positive_completion_tokens(usage: Any) -> bool:return False-def _is_router_timeout_shim(response: Any) -> bool:- """Recognize a router failure encoded as a successful ChatCompletion."""+def router_timeout_shim_may_follow(text: str) -> bool:+ """True while streamed text is still a prefix of the shim sentinel (hold it back until judged)."""+ return bool(text) and _ROUTER_TIMEOUT_SHIM.startswith(text.lstrip())+++def is_router_timeout_shim(response: Any) -> bool:+ """Recognize a router failure encoded as a successful ChatCompletion (#68396).++ Some OpenAI-compatible routers answer an upstream connect timeout with HTTP 200 and the+ sentinel as the sole assistant message. Only the exact sentinel, with no tool calls and no+ positive ``completion_tokens``/``output_tokens`` proof of generation, is a shim — a model+ that really produced those words keeps its usage evidence. Shared by every consumer of an+ OpenAI-compatible response: ``validate_response``, the stream assembler, the+ iteration-limit summary and the auxiliary ``_validate_llm_response``.+ """choices = getattr(response, "choices", None)if not isinstance(choices, list) or len(choices) != 1:return False@@ -632,7 +645,7 @@ class ChatCompletionsTransport(ProviderTransport):"""Check that response has valid choices and is not a router failure shim."""if response is None or not getattr(response, "choices", None):return False- return not _is_router_timeout_shim(response)+ return not is_router_timeout_shim(response)def extract_cache_stats(self, response: Any) -> dict[str, int] | None:"""Cache stats from prompt_tokens_details (OpenRouter/OpenAI) or DeepSeek's top-level prompt_cache_hit_tokens."""diff --git a/tests/agent/test_router_timeout_shim.py b/tests/agent/test_router_timeout_shim.pynew file mode 100644index 00000000000..c0501e6f5e5--- /dev/null+++ b/tests/agent/test_router_timeout_shim.py@@ -0,0 +1,67 @@+"""HTTP-200 router timeout shim (#68396) in the OpenAI-compatible consumers that bypass+``validate_response``: the stream assembler and the auxiliary ``_validate_llm_response``.++Some routers answer an upstream connect timeout with a 200 ChatCompletion whose only+assistant text is ``Connect timeout, please try again later.`` and zero completion tokens.+The shared ``is_router_timeout_shim`` predicate must keep that text out of every surface.+"""+from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import pytest++SHIM = "Connect timeout, please try again later."+++def _chunk(content=None, finish_reason=None, usage=None):+ delta = SimpleNamespace(content=content, tool_calls=None, reasoning_content=None, reasoning=None)+ return SimpleNamespace(choices=[SimpleNamespace(index=0, delta=delta, finish_reason=finish_reason)],+ model="m", usage=usage)+++ ("chunks", "expect_streamed", "expect_valid"),+ [+ # Shim split across deltas, zero completion tokens: nothing reaches the live display and+ # the assembled response is rejected so the main loop retries / falls back.+ ([_chunk("Connect timeout, "), _chunk("please try again later."),+ _chunk(finish_reason="stop", usage=SimpleNamespace(completion_tokens=0))], "", False),+ # Control: the same words really generated (positive usage) are released and valid.+ ([_chunk(SHIM), _chunk(finish_reason="stop", usage=SimpleNamespace(completion_tokens=9))], SHIM, True),+ # Control: text that merely starts like the shim is released once it diverges.+ ([_chunk("Connect timeout, "), _chunk("then success: done."), _chunk(finish_reason="stop")],+ "Connect timeout, then success: done.", True),+ ],+)+@patch("run_agent.AIAgent._create_request_openai_client")+@patch("run_agent.AIAgent._close_request_openai_client")+def test_stream_holds_router_timeout_shim_until_judged(mock_close, mock_create, chunks, expect_streamed, expect_valid):+ from run_agent import AIAgent++ deltas = []+ mock_client = MagicMock()+ mock_client.chat.completions.create.return_value = iter(chunks)+ mock_create.return_value = mock_client+ agent = AIAgent(api_key="test-key", base_url="https://openrouter.ai/api/v1", model="test/model", quiet_mode=True,+ skip_context_files=True, skip_memory=True, stream_delta_callback=deltas.append)+ agent.api_mode = "chat_completions"+ agent._interrupt_requested = False++ response = agent._interruptible_streaming_api_call({})++ assert "".join(deltas) == expect_streamed+ assert agent._get_transport().validate_response(response) is expect_valid+++def test_auxiliary_validation_rejects_router_timeout_shim():+ """The auxiliary fallback chain treats the shim like a malformed response, not a title."""+ from agent.auxiliary_client import _validate_llm_response++ shim = SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=SHIM, tool_calls=None))],+ usage=SimpleNamespace(completion_tokens=0), model="m")+ with pytest.raises(RuntimeError, match="timeout shim"):+ _validate_llm_response(shim, "title")++ generated = SimpleNamespace(choices=[SimpleNamespace(message=SimpleNamespace(content=SHIM, tool_calls=None))],+ usage=SimpleNamespace(completion_tokens=9), model="m")+ assert _validate_llm_response(generated, "title") is generateddiff --git a/website/docs/user-guide/features/fallback-providers.md b/website/docs/user-guide/features/fallback-providers.mdindex 5e3a92210d3..fcb033ca108 100644--- a/website/docs/user-guide/features/fallback-providers.md+++ b/website/docs/user-guide/features/fallback-providers.md@@ -116,7 +116,7 @@ The fallback activates automatically when the primary model fails with:- **Server errors** (HTTP 500, 502, 503) — after exhausting retry attempts- **Auth failures** (HTTP 401, 403) — immediately (no point retrying)- **Not found** (HTTP 404) — immediately-- **Invalid responses** — when the API returns malformed or empty responses repeatedly. A streamed refusal (the model declining with an explanation on the refusal channel) is a terminal `content_filter` result, not an empty response, so it is surfaced rather than retried. On the native Anthropic wire a `stop_reason: refusal` arrives with an empty body; Hermes reports the reason from the response's `stop_details` (category and, when present, explanation) in the refusal message and in the log line (`native_stop_reason=… stop_details=…`).+- **Invalid responses** — when the API returns malformed or empty responses repeatedly. An HTTP-200 body whose only assistant text is a router's `Connect timeout, please try again later.` with zero completion tokens counts as invalid too (streamed or not, in the main loop, the iteration-limit summary and auxiliary calls), so it is retried instead of shown as the answer. A streamed refusal (the model declining with an explanation on the refusal channel) is a terminal `content_filter` result, not an empty response, so it is surfaced rather than retried. On the native Anthropic wire a `stop_reason: refusal` arrives with an empty body; Hermes reports the reason from the response's `stop_details` (category and, when present, explanation) in the refusal message and in the log line (`native_stop_reason=… stop_details=…`).When triggered, Hermes: