Skip to content

The agent that grows with you

Merge origin/main (63279301bcb): reasoning-mandatory 400 recovery folded into turn_recovery/error_classifier/models_reasoning_caps

Teknium022785a5413a
diff --cc agent/chat_completion_helpers.py
index 091b9052e71,4f91ec1c366..d95e5eac362
--- a/agent/chat_completion_helpers.py
+++ b/agent/chat_completion_helpers.py
@@@ -1323,129 -1969,256 +1323,149 @@@ def _consume_ephemeral_reasoning_off(ag
def _reasoning_config_for_wire(agent):
- """``agent.reasoning_config`` with the one-shot reasoning-off override applied."""
- if _consume_ephemeral_reasoning_off(agent):
- return {**(agent.reasoning_config or {}), "enabled": False, "effort": "none"}
- return agent.reasoning_config
+ """``agent.reasoning_config`` with the one-shot reasoning-off override applied.
+
+ Once the route has answered a disable with "reasoning is mandatory"
+ (``agent._reasoning_disable_rejected``), every disable — configured or
+ the one-shot continuation override — is dropped for the rest of the
+ session: the request goes out without a reasoning config and the route
+ applies its own default.
+ """
+ cfg = agent.reasoning_config
+ ephemeral_off = _consume_ephemeral_reasoning_off(agent)
+ if getattr(agent, "_reasoning_disable_rejected", False):
+ # The route rejects disables. Resend exactly what the session has
+ # been sending — the user's own config — so the retry lands on the
+ # same provider cache key as every prior request. Only a config that
+ # is itself a disable is dropped (omitted → route default), and that
+ # session has never sent anything else, so nothing warm is lost.
+ if isinstance(cfg, dict) and (
+ cfg.get("enabled") is False or cfg.get("effort") == "none"
+ ):
+ return None
+ return cfg
+ if ephemeral_off:
+ cfg = {**(cfg or {}), "enabled": False, "effort": "none"}
+ return cfg
-def build_api_kwargs(agent, api_messages: list, tools_for_api: list | None = None) -> dict:
- """Build the keyword arguments dict for the active API mode.
-
- Wraps the per-api_mode builder so the OpenCode ``x-opencode-session``
- affinity header rides on every OpenCode request regardless of transport
- (chat_completions / codex_responses / anthropic_messages all route
- OpenCode models). No-op for every other provider.
- """
- from agent.opencode_affinity import merge_opencode_session_headers
-
- kwargs = _build_api_kwargs_for_mode(agent, api_messages, tools_for_api)
- return merge_opencode_session_headers(
- kwargs,
- getattr(agent, "provider", None),
- getattr(agent, "base_url", None),
- getattr(agent, "session_id", None),
- )
-
-
-def _build_api_kwargs_for_mode(agent, api_messages: list, tools_for_api: list | None = None) -> dict:
- # One-shot continuation override — consumed exactly once, on the FIRST
- # request this call builds (only one api_mode branch runs per invocation).
- _wire_reasoning_config = _reasoning_config_for_wire(agent)
- if tools_for_api is None:
- tools_for_api = agent.tools
- # The one place request_overrides are consumed: static /fast values are
- # already pinned in agent.request_overrides; auto/cold windows layer the
- # fast override here, per request, only while the window is open.
- _request_overrides = effective_request_overrides(agent)
-
- if agent.api_mode == "anthropic_messages":
- _transport = agent._get_transport()
- anthropic_messages = agent._prepare_anthropic_messages_for_api(api_messages)
- ctx_len = getattr(agent, "context_compressor", None)
- ctx_len = ctx_len.context_length if ctx_len else None
- ephemeral_out = getattr(agent, "_ephemeral_max_output_tokens", None)
- if ephemeral_out is not None:
- agent._ephemeral_max_output_tokens = None # consume immediately
- anthropic_kwargs = _transport.build_kwargs(
- model=agent.model,
- messages=anthropic_messages,
- tools=tools_for_api,
- max_tokens=ephemeral_out if ephemeral_out is not None else agent.max_tokens,
- reasoning_config=_wire_reasoning_config,
- is_oauth=agent._is_anthropic_oauth,
- preserve_dots=agent._anthropic_preserve_dots(),
- context_length=ctx_len,
- base_url=getattr(agent, "_anthropic_base_url", None),
- fast_mode=_request_overrides.get("speed") == "fast",
- drop_context_1m_beta=bool(getattr(agent, "_oauth_1m_beta_disabled", False)),
- )
- # Nous Portal reads ``tags`` and ``session_id`` as top-level body fields
- # on its Messages route the same way it does on /chat/completions, but
- # the profile hook that produces them is only consulted by the
- # OpenAI-wire transport. Merge them here so Messages traffic keeps
- # product attribution and sticky routing.
- return _merge_nous_portal_messages_extra_body(agent, anthropic_kwargs)
-
- # AWS Bedrock native Converse API — bypasses the OpenAI client entirely.
- # The adapter handles message/tool conversion and boto3 calls directly.
- if agent.api_mode == "bedrock_converse":
- _bt = agent._get_transport()
- region = getattr(agent, "_bedrock_region", None) or "us-east-1"
- guardrail = getattr(agent, "_bedrock_guardrail_config", None)
- return _bt.build_kwargs(
- model=agent.model,
- messages=api_messages,
- tools=tools_for_api,
- max_tokens=agent.max_tokens or 4096,
- region=region,
- guardrail_config=guardrail,
- )
-
- # Rotation-stable logical cache scope, shared by every OpenAI-wire branch
- # below (codex + both chat_completions paths). Memoized on the agent —
- # cheap after the first call. Resolved after the anthropic/bedrock early
- # returns above, which don't use prompt_cache_key.
- _cache_scope_id = _prompt_cache_scope_for_agent(agent)
-
- if agent.api_mode == "codex_responses":
- _ct = agent._get_transport()
- from agent.codex_responses_adapter import classify_responses_route
-
- is_codex_backend, is_xai_responses, is_github_responses = (
- classify_responses_route(agent)
- )
- _msgs_for_codex = agent._prepare_messages_for_non_vision_model(api_messages)
-
- # Native server-side compaction (gpt-5.6 on direct OpenAI API /
- # ChatGPT Codex routes only) — None on every other route/model, in
- # which case the request is unchanged from pre-feature behavior.
- from agent.native_compaction import native_compaction_context_management
- _context_management = native_compaction_context_management(
- agent,
- is_codex_backend=is_codex_backend,
- is_xai_responses=is_xai_responses,
- is_github_responses=is_github_responses,
+def _alias_tool_search_bridge_for_xai(agent, transport, tools_for_api):
+ """xAI chat-completions reserves ``tool_search`` and 400s when the bridge declares
+ it (#95003): rename the wire declaration; ``normalize_response`` maps calls back
+ via the transport's ``_last_wire_aliases`` (reset here so a stale map can't
+ reverse-map a name this request never aliased). Deep-copy first (#27907)."""
+ if transport is not None and hasattr(transport, "_last_wire_aliases"):
+ transport._last_wire_aliases = {}
+ is_xai_chat = agent.provider in {"xai", "xai-oauth"} or agent._base_url_hostname == "api.x.ai"
+ if not (is_xai_chat and tools_for_api):
+ return tools_for_api
+ try:
+ import copy as _copy_xai
+ from agent.transports.chat_completions import _rename_tool_search_bridge_for_xai
+ has_bridge = any(
+ (t.get("function") or {}).get("name") == "tool_search" for t in tools_for_api if isinstance(t, dict)
)
+ if has_bridge:
+ tools_for_api = _copy_xai.deepcopy(tools_for_api)
+ tools_for_api, alias_map = _rename_tool_search_bridge_for_xai(tools_for_api)
+ if transport is not None:
+ transport._last_wire_aliases = alias_map
+ except Exception as exc:
+ logger.warning("%s⚠️ Failed to alias tool_search bridge for xAI: %s", getattr(agent, "log_prefix", ""), exc)
+ return tools_for_api
- # xAI's /responses endpoint rejects ``pattern`` and ``format`` keywords
- # in tool schemas (HTTP 400 "Invalid arguments passed to the model").
- # Most commonly hit when MCP-derived tools carry JSON Schema validation
- # keywords through. Strip them before building kwargs. See #27197.
- # It also rejects ``enum`` values containing ``/`` (HuggingFace IDs
- # like ``Qwen/Qwen3.5-0.8B`` shipped by MCP servers) — same 400 with
- # the same opaque message; strip those enums too.
- #
- # Deep-copy ``tools_for_api`` before sanitizing: the sanitizers
- # mutate in place (documented contract on ``strip_slash_enum`` /
- # ``strip_pattern_and_format``), and ``tools_for_api`` is a direct
- # reference to ``agent.tools``. Without the copy, the first xAI
- # request permanently strips constraints from the shared per-agent
- # tool registry — every subsequent non-xAI call from the same
- # agent (auxiliary task routed to Anthropic, OpenRouter fallback,
- # main-model swap) sees the already-stripped schema. See #27907.
- if is_xai_responses:
- try:
- import copy as _copy
- from tools.schema_sanitizer import (
- strip_pattern_and_format,
- strip_slash_enum,
- )
- tools_for_api = _copy.deepcopy(tools_for_api)
- tools_for_api, _ = strip_pattern_and_format(tools_for_api)
- tools_for_api, _ = strip_slash_enum(tools_for_api)
- except Exception as exc:
- logger.warning(
- "%s⚠️ Failed to sanitize tool schemas for xAI: %s",
- getattr(agent, "log_prefix", ""), exc,
- )
-
- return _ct.build_kwargs(
- model=agent.model,
- messages=_msgs_for_codex,
- tools=tools_for_api,
- reasoning_config=_wire_reasoning_config,
- session_id=getattr(agent, "session_id", None),
- cache_scope_id=_cache_scope_id,
- base_url=agent.base_url,
- max_tokens=agent.max_tokens,
- timeout=agent._resolved_api_call_timeout(),
- request_overrides=_request_overrides,
- provider=getattr(agent, "provider", None),
- is_github_responses=is_github_responses,
- is_codex_backend=is_codex_backend,
- is_xai_responses=is_xai_responses,
- github_reasoning_extra=agent._github_models_reasoning_extra_body() if is_github_responses else None,
- replay_encrypted_reasoning=bool(
- getattr(agent, "_codex_reasoning_replay_enabled", True)
- ),
- context_management=_context_management,
- )
- # ── chat_completions (default) ─────────────────────────────────────
- _ct = agent._get_transport()
-
- # xAI's chat-completions endpoint reserves the function name
- # ``tool_search`` for its native server-side tool and rejects the whole
- # request when the client Tool Search bridge declares it (HTTP 400
- # "The function name tool_search is reserved for the tool_search tool",
- # #95003) — same reserved-name class the codex_responses branch above
- # already sanitizes tools for (#27197). Rename the bridge's wire
- # declaration to an alias; normalize_response maps model calls back.
- # Deep-copy first (the #27907 in-place-mutation lesson): tools_for_api
- # aliases agent.tools, and renaming in place would corrupt the shared
- # per-agent tool registry for every later non-xAI request.
- _is_xai_chat = (
- agent.provider in {"xai", "xai-oauth"}
- or agent._base_url_hostname == "api.x.ai"
- )
- # Reset request-local alias provenance for THIS request; the rewrite
- # below repopulates it when it actually emits aliases. Without the
- # reset, a stale map from an earlier request on the same transport
- # could reverse-map a name this request never aliased.
- if _ct is not None and hasattr(_ct, "_last_wire_aliases"):
- _ct._last_wire_aliases = {}
- if _is_xai_chat and tools_for_api:
+def _consume_ephemeral_max_output(agent):
+ """Pop the one-shot ephemeral output cap; whichever path builds the request consumes it."""
+ ephemeral_out = getattr(agent, "_ephemeral_max_output_tokens", None)
+ if ephemeral_out is not None:
+ agent._ephemeral_max_output_tokens = None
+ return ephemeral_out
+
+
+def _build_anthropic_kwargs(agent, api_messages, tools_for_api, reasoning_config, request_overrides):
+ ctx_len = getattr(agent, "context_compressor", None)
+ ephemeral_out = _consume_ephemeral_max_output(agent)
+ anthropic_kwargs = agent._get_transport().build_kwargs(model=agent.model,
+ messages=agent._prepare_anthropic_messages_for_api(api_messages), tools=tools_for_api,
+ max_tokens=ephemeral_out if ephemeral_out is not None else agent.max_tokens,
+ reasoning_config=reasoning_config, is_oauth=agent._is_anthropic_oauth,
+ preserve_dots=agent._anthropic_preserve_dots(),
+ context_length=ctx_len.context_length if ctx_len else None,
+ base_url=getattr(agent, "_anthropic_base_url", None),
+ fast_mode=request_overrides.get("speed") == "fast",
+ drop_context_1m_beta=bool(getattr(agent, "_oauth_1m_beta_disabled", False)))
+ # Portal reads ``tags`` / ``session_id`` on its Messages route too, but the profile hook
+ # is only consulted by the OpenAI-wire transport — merge here to keep sticky routing.
+ return _merge_nous_portal_messages_extra_body(agent, anthropic_kwargs)
+
+
+def _build_bedrock_kwargs(agent, api_messages, tools_for_api):
+ # Bedrock Converse — the adapter converts messages/tools and calls boto3 directly.
+ return agent._get_transport().build_kwargs(model=agent.model, messages=api_messages, tools=tools_for_api,
+ max_tokens=agent.max_tokens or 4096, region=getattr(agent, "_bedrock_region", None) or "us-east-1",
+ guardrail_config=getattr(agent, "_bedrock_guardrail_config", None))
+
+
+def _build_codex_kwargs(agent, api_messages, tools_for_api, reasoning_config, request_overrides, cache_scope_id):
+ from agent.codex_responses_adapter import classify_responses_route
+ from agent.native_compaction import native_compaction_context_management
+ is_codex_backend, is_xai_responses, is_github_responses = classify_responses_route(agent)
+ # Native server-side compaction (gpt-5.6 on direct OpenAI / ChatGPT Codex routes
+ # only) — None on every other route/model, leaving the request unchanged.
+ context_management = native_compaction_context_management(agent, is_codex_backend=is_codex_backend,
+ is_xai_responses=is_xai_responses, is_github_responses=is_github_responses)
+ # xAI's /responses endpoint 400s on ``pattern``/``format`` schema keywords and on
+ # ``enum`` values containing ``/`` — strip them (#27197). Deep-copy first: the
+ # sanitizers mutate in place and tools_for_api aliases agent.tools (#27907).
+ if is_xai_responses:
try:
- import copy as _copy_xai
+ import copy as _copy
+ from tools.schema_sanitizer import strip_pattern_and_format, strip_slash_enum
+ tools_for_api = _copy.deepcopy(tools_for_api)
+ tools_for_api, _ = strip_pattern_and_format(tools_for_api)
+ tools_for_api, _ = strip_slash_enum(tools_for_api)
+ except Exception as exc:
+ logger.warning("%s⚠️ Failed to sanitize tool schemas for xAI: %s", getattr(agent, "log_prefix", ""), exc)
+ return agent._get_transport().build_kwargs(model=agent.model,
+ messages=agent._prepare_messages_for_non_vision_model(api_messages), tools=tools_for_api,
+ reasoning_config=reasoning_config, session_id=getattr(agent, "session_id", None),
+ cache_scope_id=cache_scope_id, base_url=agent.base_url, max_tokens=agent.max_tokens,
+ timeout=agent._resolved_api_call_timeout(), request_overrides=request_overrides,
+ provider=getattr(agent, "provider", None), is_github_responses=is_github_responses,
+ is_codex_backend=is_codex_backend, is_xai_responses=is_xai_responses,
+ github_reasoning_extra=agent._github_models_reasoning_extra_body() if is_github_responses else None,
+ replay_encrypted_reasoning=bool(getattr(agent, "_codex_reasoning_replay_enabled", True)),
+ context_management=context_management)
+
+
+def _anthropic_max_output_for_model(agent):
+ """Anthropic-compatible max-output fallback (last resort in build_kwargs, never
+ overriding an explicit value). Model-gated, not URL-gated: any proxy serving a
+ Claude/MiniMax/Qwen3 model needs max_tokens (Messages API treats it as
+ mandatory; proxies that omit it default as low as 4096)."""
+ with contextlib.suppress(Exception):
+ from agent.anthropic_adapter import _get_anthropic_max_output, _ANTHROPIC_OUTPUT_LIMITS
+ model_norm = (agent.model or "").lower().replace(".", "-")
+ if any(key in model_norm for key in _ANTHROPIC_OUTPUT_LIMITS):
+ return _get_anthropic_max_output(agent.model)
+ return None
- from agent.transports.chat_completions import (
- _rename_tool_search_bridge_for_xai,
- )
- _has_bridge = any(
- (t.get("function") or {}).get("name") == "tool_search"
- for t in tools_for_api
- if isinstance(t, dict)
- )
- if _has_bridge:
- tools_for_api = _copy_xai.deepcopy(tools_for_api)
- tools_for_api, _xai_alias_map = _rename_tool_search_bridge_for_xai(
- tools_for_api
- )
- # Record provenance so normalize_response reverses ONLY the
- # aliases this request put on the wire.
- if _ct is not None:
- _ct._last_wire_aliases = _xai_alias_map
- except Exception as exc:
- logger.warning(
- "%s⚠️ Failed to alias tool_search bridge for xAI: %s",
- getattr(agent, "log_prefix", ""), exc,
- )
+def _build_chat_completions_kwargs(agent, api_messages, tools_for_api, reasoning_config, request_overrides, cache_scope_id):
+ transport = agent._get_transport()
+ tools_for_api = _alias_tool_search_bridge_for_xai(agent, transport, tools_for_api)
- # Provider detection flags
_is_qwen = agent._is_qwen_portal()
_is_or = agent._is_openrouter_url()
- _is_gh = (
- base_url_host_matches(agent._base_url_lower, "models.github.ai")
- or base_url_host_matches(agent._base_url_lower, "githubcopilot.com")
- )
- _is_nous = base_url_host_matches(agent._base_url_lower, "nousresearch.com")
- _is_nvidia = base_url_host_matches(agent._base_url_lower, "integrate.api.nvidia.com")
- _is_kimi = (
- base_url_host_matches(agent.base_url, "api.kimi.com")
- or base_url_host_matches(agent.base_url, "moonshot.ai")
- or base_url_host_matches(agent.base_url, "moonshot.cn")
- )
- _is_tokenhub = base_url_host_matches(agent._base_url_lower, "tokenhub.tencentmaas.com")
+ _host = agent._base_url_lower
+ _is_gh = base_url_host_matches(_host, "models.github.ai") or base_url_host_matches(_host, "githubcopilot.com")
_is_lmstudio = (agent.provider or "").strip().lower() == "lmstudio"
- # Temperature: _fixed_temperature_for_model may return OMIT_TEMPERATURE
- # sentinel (temperature omitted entirely), a numeric override, or None.
- try:
+ # _fixed_temperature_for_model may return the OMIT_TEMPERATURE sentinel
+ # (temperature omitted entirely), a numeric override, or None.
+ _omit_temp, _fixed_temp = False, None
+ with contextlib.suppress(Exception):
from agent.auxiliary_client import _fixed_temperature_for_model, OMIT_TEMPERATURE
_ft = _fixed_temperature_for_model(agent.model, agent.base_url)
_omit_temp = _ft is OMIT_TEMPERATURE
diff --cc agent/error_classifier.py
index 0b8871feed3,94ade338b2b..093a79195a1
--- a/agent/error_classifier.py
+++ b/agent/error_classifier.py
@@@ -36,17 -57,26 +36,20 @@@ class FailoverReason(enum.Enum)
context_overflow = "context_overflow" # Context too large — compress, not failover
payload_too_large = "payload_too_large" # 413 — compress payload
image_too_large = "image_too_large" # Native image part exceeds provider's per-image limit — shrink and retry
- image_corrupt = "image_corrupt" # Provider says the image bytes are undecodable — shrinking won't help, strip and retry instead
-
- # Model / provider policy
+ image_corrupt = "image_corrupt" # Provider can't decode image bytes — strip and retry (shrinking won't help)
model_not_found = "model_not_found" # 404 or invalid model — fallback to different model
- provider_policy_blocked = "provider_policy_blocked" # Aggregator (e.g. OpenRouter) blocked the only endpoint due to account data/privacy policy
- content_policy_blocked = "content_policy_blocked" # Provider safety filter rejected this prompt — deterministic per-request, don't retry unchanged
-
- # Request format
+ provider_policy_blocked = "provider_policy_blocked" # Aggregator account data/privacy policy excluded the only endpoint
+ content_policy_blocked = "content_policy_blocked" # Provider safety filter rejected this prompt — don't retry unchanged
format_error = "format_error" # 400 bad request — abort or strip + retry
invalid_encrypted_content = "invalid_encrypted_content" # Responses replay blob rejected — strip replay state and retry
- multimodal_tool_content_unsupported = "multimodal_tool_content_unsupported" # Provider rejected list content in tool messages — downgrade to text
+ multimodal_tool_content_unsupported = "multimodal_tool_content_unsupported" # Provider rejected list-type content in tool messages (e.g. Xiaomi MiMo) — downgrade to text and retry
+ reasoning_mandatory = "reasoning_mandatory" # Route rejects reasoning: {enabled: false} — send the disable no more this session and retry
+
+ # Provider-specific
thinking_signature = "thinking_signature" # Anthropic thinking block sig invalid
long_context_tier = "long_context_tier" # Anthropic "extra usage" tier gate
- oauth_long_context_beta_forbidden = "oauth_long_context_beta_forbidden" # Anthropic OAuth subscription rejects 1M context beta — disable beta and retry
- llama_cpp_grammar_pattern = "llama_cpp_grammar_pattern" # llama.cpp json-schema-to-grammar rejects regex escapes in `pattern` / `format` — strip from tools and retry
-
- # Catch-all
+ oauth_long_context_beta_forbidden = "oauth_long_context_beta_forbidden" # Anthropic OAuth rejects 1M beta — disable beta and retry
+ llama_cpp_grammar_pattern = "llama_cpp_grammar_pattern" # llama.cpp grammar rejects regex `pattern`/`format` — strip from tools and retry
unknown = "unknown" # Unclassifiable — retry with backoff
@@@ -215,510 -525,1053 +218,518 @@@ _REQUEST_VALIDATION_PATTERNS =
_SERVER_INJECTED_PARAM_SENDERS: Dict[str, tuple] = {
"prompt_cache_retention": ("meta", "muse", "msl", "model-api", "bedrock", "mantle"),
}
+_PARAM_REJECTION_WORDS = ("not supported", "unsupported", "unknown", "unrecognized")
+# Anthropic thinking-block 400 wordings (see _provider_special_cases).
+_THINKING_MUTATION_WORDS = ("signature", "cannot be modified", "must remain as they were")
-def _is_server_injected_param_rejection(error_msg: str, provider: str) -> bool:
- """True when a 400 blames a parameter this route never sends.
-
- ``error_msg`` is the lowercased, concatenated message text; ``provider`` is
- the lowercased provider slug. A match means the rejection cannot be
- attributed to our own request shape, so the error is transient and retrying
- the identical request is the correct recovery.
-
- Deliberately conservative: it fires only for known one-route-only
- parameters AND only when the current provider is not one of the routes that
- actually sends them, so a genuine client-side bad parameter (``max_tokens``
- on a GPT-5 model) still fails fast as a ``format_error``.
- """
- if not error_msg:
- return False
- provider_slug = (provider or "").strip().lower()
- for param, senders in _SERVER_INJECTED_PARAM_SENDERS.items():
- if param not in error_msg:
- continue
- # Require the message to actually be a rejection of that parameter,
- # not an incidental mention.
- if not (
- "not supported" in error_msg
- or "unsupported" in error_msg
- or "unknown" in error_msg
- or "unrecognized" in error_msg
- ):
- continue
- if any(sender in provider_slug for sender in senders):
- # This route sends the field on purpose — a real request error.
- return False
- return True
- return False
-
+# Local MoA streaming adapter-shape bugs (see _moa_special_cases).
+_MOA_ADAPTER_SHAPE_BUGS = (
+ "'types.SimpleNamespace' object is not iterable", "'types.SimpleNamespace' object has no attribute 'index'",
+)
-# OpenRouter aggregator policy-block patterns.
-#
-# When a user's OpenRouter account privacy setting (or a per-request
-# `provider.data_collection: deny` preference) excludes the only endpoint
-# serving a model, OpenRouter returns 404 with a *specific* message that is
-# distinct from "model not found":
-#
-# "No endpoints available matching your guardrail restrictions and
-# data policy. Configure: https://openrouter.ai/settings/privacy"
-#
-# We classify this as `provider_policy_blocked` rather than
-# `model_not_found` because:
-# - The model *exists* — model_not_found is misleading in logs
-# - Provider fallback won't help: the account-level setting applies to
-# every call on the same OpenRouter account
-# - The error body already contains the fix URL, so the user gets
-# actionable guidance without us rewriting the message
-_PROVIDER_POLICY_BLOCKED_PATTERNS = [
- "no endpoints available matching your guardrail",
- "no endpoints available matching your data policy",
+# OpenRouter 404 when the account data policy excludes the only endpoint. Not
+# model_not_found: the model exists, fallback can't help, body has the fix URL.
+_PROVIDER_POLICY_BLOCKED_PATTERNS = (
+ "no endpoints available matching your guardrail", "no endpoints available matching your data policy",
"no endpoints found matching your data policy",
-]
-
-# Provider content-policy / safety-filter blocks. Distinct from
-# ``provider_policy_blocked`` above (which is an OpenRouter *account*-level
-# data/privacy guardrail) — these are *per-prompt* safety decisions made by
-# the upstream model provider. They are deterministic for the unchanged
-# request, so retrying the same prompt three times just reproduces the same
-# block and burns paid attempts on a refusal. The recovery is to switch to a
-# configured fallback model/provider immediately, or surface the block to
-# the user with actionable guidance if no fallback exists.
-#
-# Patterns are intentionally narrow — each phrase is a verbatim string from
-# a specific provider's safety pipeline, not a generic word like "policy" or
-# "violation" that could collide with billing/auth/format errors:
-# • OpenAI Codex cybersecurity refusal (gpt-5.5, the case from #18028)
-# • OpenAI moderation refusal ("violates our usage policies", with
-# "usage policies" disambiguating from billing's "exceeded ... policy")
-# • Anthropic safety refusal ("prompt was flagged by ... safety system")
-# • OpenAI Responses content filter
-_CONTENT_POLICY_BLOCKED_PATTERNS = [
- # OpenAI Codex (#18028) — message may arrive without an HTTP status
- "flagged for possible cybersecurity risk",
- "trusted access for cyber",
- # OpenAI moderation — chat completions / responses
- "violates our usage policies",
- "violates openai's usage policies",
- "your request was flagged by",
- # Anthropic safety system
- "prompt was flagged by our safety",
- "responses cannot be generated due to safety",
- # Generic content-filter wording seen on Azure / OpenAI Responses.
- # ``content_filter`` (underscore) is the OpenAI-standard error/finish
- # token surfaced verbatim by their SDKs when a request is blocked.
- # ``responsibleaipolicyviolation`` is Azure OpenAI's error code.
- # Deliberately NOT matching the space variant ("content filter") — it
- # appears in benign config descriptions and tooltip text that providers
- # echo back; the underscore form is provider-specific enough.
- "content_filter",
- "responsibleaipolicyviolation",
- # MiniMax output-layer safety filter. The error string is surfaced
- # verbatim by MiniMax SDK / OpenAI-compatible endpoints, usually in the
- # form "output new_sensitive (1027)" when the model's *output* (often a
- # large tool-call argument block) trips the upstream safety filter and
- # the SSE stream is truncated mid-flight. ``new_sensitive`` is the
- # filter name and is narrow enough that billing / format / auth error
- # strings will not collide. See #32421.
- "new_sensitive",
-]
-
-# Auth patterns (non-status-code signals)
-_AUTH_PATTERNS = [
- "invalid api key",
- "invalid_api_key",
- "gateway_auth_failed",
- "authentication",
- "unauthorized",
- "forbidden",
- "invalid token",
- "token expired",
- "token revoked",
- "access denied",
-]
-
-# Anthropic thinking block signature patterns
-_THINKING_SIG_PATTERNS = [
- "signature", # Combined with "thinking" check
-]
-
-# Message-string patterns that indicate a provider-side timeout even when
-# the exception type is generic (e.g. RuntimeError from a local shim that
-# wraps a subprocess timeout). Checked before the type-based transport
-# heuristics so custom-provider "timed out" errors don't fall through to
-# Provider empty-response advisories (OpenRouter / nano-gpt / similar).
-# Checked before context-overflow matching because the advisory text often
-# mentions "max_tokens" as a possible cause, which historically sat in
-# _CONTEXT_OVERFLOW_PATTERNS and sent healthy sessions into a compression
-# death spiral ending in "Cannot compress further".
-_EMPTY_PROVIDER_RESPONSE_PATTERNS = [
- "returned an empty response",
- "empty response despite retries",
- "provider returned an empty response",
- "model returning empty responses",
- "empty response stream",
-]
-
-# the unknown bucket and get misreported as empty responses.
-_TIMEOUT_MESSAGE_PATTERNS = [
- "timed out",
- "turn timed out",
- "request timed out",
- "deadline exceeded",
- "operation timed out",
+)
+
+# Per-prompt safety-filter blocks: deterministic for the unchanged request, so
+# fallback immediately. Each phrase is verbatim from one provider (Codex cyber
+# flags #18028, OpenAI moderation, Anthropic safety, Azure token, MiniMax
+# #32421) — never a generic word like "policy" that collides with billing/auth.
+# "content_filter" deliberately excludes the space variant seen in echoed config.
+_CONTENT_POLICY_BLOCKED_PATTERNS = (
+ "flagged for possible cybersecurity risk", "trusted access for cyber",
+ "violates our usage policies", "violates openai's usage policies", "your request was flagged by",
+ "prompt was flagged by our safety", "responses cannot be generated due to safety",
+ "content_filter", "responsibleaipolicyviolation", "new_sensitive",
+)
+
+# Auth patterns (non-status-code signals).
+_AUTH_PATTERNS = (
+ "invalid api key", "invalid_api_key", "gateway_auth_failed", "authentication", "unauthorized",
+ "forbidden", "invalid token", "token expired", "token revoked", "access denied",
+)
+
+# Empty-response advisories (OpenRouter / nano-gpt). Checked before overflow
+# because the text often mentions "max_tokens" (caused compression spirals).
+_EMPTY_PROVIDER_RESPONSE_PATTERNS = (
+ "returned an empty response", "empty response despite retries", "provider returned an empty response",
+ "model returning empty responses", "empty response stream",
+)
+
+# Timeout wording from generic exception types the type heuristics would miss.
+_TIMEOUT_MESSAGE_PATTERNS = (
+ "timed out", "turn timed out", "request timed out", "deadline exceeded", "operation timed out",
"upstream timed out",
-]
-
-# Connection-establishment / DNS failure message patterns. These surface
-# when the exception TYPE is generic (RuntimeError/Exception from a local
-# shim, MCP bridge, subprocess wrapper, or an SDK that re-raises without
-# chaining) so the _TRANSPORT_ERROR_TYPES check never fires, and the error
-# carries no HTTP status. Without message-level matching they fall through
-# to FailoverReason.unknown, which misses the transport eager-fallback path
-# in the retry loop (unknown retries the same dead endpoint for the full
-# budget before fallback). Ported from anomalyco/opencode#40707, which hit
-# the same bug shape: serialized midstream errors matched by type only.
-#
-# Deliberately EXCLUDES mid-stream disconnect strings ("connection reset by
-# peer", "peer closed connection", "unexpected eof", "socket hang up") —
-# those belong to _SERVER_DISCONNECT_PATTERNS, whose classification step
-# runs later and routes large sessions to context-overflow compression.
-# A connection that was never established cannot be a server-side overflow
-# rejection, so these are safe to classify as plain retryable transport.
-_CONNECTION_MESSAGE_PATTERNS = [
- # TCP connect failures
- "connection refused",
- "econnrefused",
- "no route to host",
- "network is unreachable",
- "network unreachable",
- # DNS resolution failures (Python, glibc, macOS, Node bridge phrasings)
- "name or service not known",
- "temporary failure in name resolution",
- "nodename nor servname provided",
- "getaddrinfo failed",
- "getaddrinfo enotfound",
- "eai_again",
- # Node/undici bridge generic network failure (MCP servers, local shims)
- "fetch failed",
- "failed to fetch",
- # Envoy/proxy upstream connect failure (cloud gateways)
+)
+
+# Connect/DNS failures from generic exception types with no status. EXCLUDES
+# mid-stream disconnects (_SERVER_DISCONNECT_PATTERNS may route large sessions
+# to compression; a never-established connection cannot be an overflow).
+# Groups: TCP connect; DNS (Python/glibc/macOS/Node); undici bridge; Envoy.
+_CONNECTION_MESSAGE_PATTERNS = (
+ "connection refused", "econnrefused", "no route to host", "network is unreachable", "network unreachable",
+ "name or service not known", "temporary failure in name resolution", "nodename nor servname provided",
+ "getaddrinfo failed", "getaddrinfo enotfound", "eai_again",
+ "fetch failed", "failed to fetch",
"upstream connect error",
-]
+)
-# Transport error type names
+# SSL names keep provider-wrapped SSL errors (chain lost) as transport, not
+# unknown; OpenAI SDK errors are not subclasses of Python builtins.
_TRANSPORT_ERROR_TYPES = frozenset({
- "ReadTimeout", "ConnectTimeout", "PoolTimeout",
- "ConnectError", "RemoteProtocolError",
- "ConnectionError", "ConnectionResetError",
- "ConnectionAbortedError", "BrokenPipeError",
- "TimeoutError", "ReadError",
- "ServerDisconnectedError",
- # SSL/TLS transport errors — transient mid-stream handshake/record
- # failures that should retry rather than surface as a stalled session.
- # ssl.SSLError subclasses OSError (caught by isinstance) but we list
- # the type names here so provider-wrapped SSL errors (e.g. when the
- # SDK re-raises without preserving the exception chain) still classify
- # as transport rather than falling through to the unknown bucket.
- "SSLError", "SSLZeroReturnError", "SSLWantReadError",
- "SSLWantWriteError", "SSLEOFError", "SSLSyscallError",
- # OpenAI SDK errors (not subclasses of Python builtins)
- "APIConnectionError",
- "APITimeoutError",
+ "ReadTimeout", "ConnectTimeout", "PoolTimeout", "ConnectError", "RemoteProtocolError",
+ "ConnectionError", "ConnectionResetError", "ConnectionAbortedError", "BrokenPipeError",
+ "TimeoutError", "ReadError", "ServerDisconnectedError",
+ "SSLError", "SSLZeroReturnError", "SSLWantReadError", "SSLWantWriteError", "SSLEOFError", "SSLSyscallError",
+ "APIConnectionError", "APITimeoutError",
})
-# Server disconnect patterns (no status code, but transport-level).
-# These are the "ambiguous" patterns — a plain connection close could be
-# transient transport hiccup OR server-side context overflow rejection
-# (common when the API gateway disconnects instead of returning an HTTP
-# error for oversized requests). A large session + one of these patterns
-# triggers the context-overflow-with-compression recovery path.
-_SERVER_DISCONNECT_PATTERNS = [
- "server disconnected",
- "peer closed connection",
- "connection reset by peer",
- "connection was closed",
- "network connection lost",
- "unexpected eof",
- "incomplete chunked read",
-]
-
-# SSL certificate verification failures — deterministic, NOT transient.
-#
-# A failed certificate chain (TLS-inspecting corporate proxy, missing
-# custom CA in the trust store, expired certificate, self-signed cert)
-# fails identically on every retry. Burning the retry budget before
-# surfacing the error hides the actionable fix from the user for minutes.
-# Inspired by Claude Code v2.1.199 (July 2026), which made SSL certificate
-# errors fail immediately with a fix hint instead of retrying.
-#
-# Must be checked BEFORE _SSL_TRANSIENT_PATTERNS — "certificate verify
-# failed" messages usually also contain "[SSL:" which would otherwise
-# match the transient list and retry forever.
-_SSL_CERT_VERIFY_PATTERNS = [
- "certificate verify failed", # Python ssl module canonical text
- "certificate_verify_failed", # OpenSSL error token
- "unable to get local issuer certificate",
- "self-signed certificate",
- "self signed certificate",
- "certificate has expired",
- "hostname mismatch, certificate is not valid",
- "unable to verify the first certificate", # Node/undici phrasing (MCP bridges)
-]
-
-# SSL/TLS transient failure patterns — intentionally distinct from
-# _SERVER_DISCONNECT_PATTERNS above.
-#
-# An SSL alert mid-stream is almost always a transport-layer hiccup
-# (flaky network, mid-session TLS renegotiation failure, load balancer
-# dropping the connection) — NOT a server-side context overflow signal.
-# So we want the retry path but NOT the compression path; lumping these
-# into _SERVER_DISCONNECT_PATTERNS would trigger unnecessary (and
-# expensive) context compression on any large-session SSL hiccup.
-#
-# The OpenSSL library constructs error codes by prepending a format string
-# to the uppercased alert reason; OpenSSL 3.x changed the separator
-# (e.g. `SSLV3_ALERT_BAD_RECORD_MAC` → `SSL/TLS_ALERT_BAD_RECORD_MAC`),
-# which silently stopped matching anything explicit. Matching on the
-# stable substrings (`bad record mac`, `ssl alert`, `tls alert`, etc.)
-# survives future OpenSSL format churn without code changes.
-_SSL_TRANSIENT_PATTERNS = [
- # Space-separated (human-readable form, Python ssl module, most SDKs)
- "bad record mac",
- "ssl alert",
- "tls alert",
- "ssl handshake failure",
- "tlsv1 alert",
- "sslv3 alert",
- # Underscore-separated (OpenSSL error code tokens, e.g.
- # `ERR_SSL_SSL/TLS_ALERT_BAD_RECORD_MAC`, `SSLV3_ALERT_BAD_RECORD_MAC`)
- "bad_record_mac",
- "ssl_alert",
- "tls_alert",
- "tls_alert_internal_error",
- # Python ssl module prefix, e.g. "[SSL: BAD_RECORD_MAC]"
- "[ssl:",
-]
+# Ambiguous disconnects (no status): transient hiccup OR a gateway dropping an
+# oversized request. A large session + one of these → context-overflow path.
+_SERVER_DISCONNECT_PATTERNS = (
+ "server disconnected", "peer closed connection", "connection reset by peer", "connection was closed",
+ "network connection lost", "unexpected eof", "incomplete chunked read",
+)
+
+# Deterministic cert failures (proxy, missing CA, expired/self-signed) — fail
+# fast. Checked BEFORE _SSL_TRANSIENT_PATTERNS: these also contain "[SSL:".
+_SSL_CERT_VERIFY_PATTERNS = (
+ "certificate verify failed", "certificate_verify_failed", "unable to get local issuer certificate",
+ "self-signed certificate", "self signed certificate", "certificate has expired",
+ "hostname mismatch, certificate is not valid", "unable to verify the first certificate",
+)
+
+# Transient SSL alerts: retry but NOT compression (kept apart from disconnects).
+# Both space and underscore forms because OpenSSL 3 changed token separators
+# (SSLV3_ALERT_... → SSL/TLS_ALERT_...); "[ssl:" is the Python ssl prefix.
+_SSL_TRANSIENT_PATTERNS = (
+ "bad record mac", "ssl alert", "tls alert", "ssl handshake failure", "tlsv1 alert", "sslv3 alert",
+ "bad_record_mac", "ssl_alert", "tls_alert", "tls_alert_internal_error", "[ssl:",
+)
+
+
+# ── Verdicts and rule tables ────────────────────────────────────────────
+# A verdict is the ClassifiedError kwargs a stage decided on: ``reason`` plus
+# hint overrides (unlisted hints keep dataclass defaults). Rule tables are
+# ordered ``(patterns, verdict)`` pairs matched first-hit; ``verdict`` may be
+# a callable of the error message.
+
+Verdict = Dict[str, Any]
+
+
+def _v(reason: FailoverReason, **hints: Any) -> Verdict:
+ return {"reason": reason, **hints}
+
+
+_ROTATE_FALLBACK = {"should_rotate_credential": True, "should_fallback": True}
+_ABORT_FALLBACK = {"retryable": False, "should_fallback": True}
+_R = FailoverReason
+
+_V_BILLING = _v(_R.billing, retryable=False, **_ROTATE_FALLBACK)
+_V_RATE_LIMIT = _v(_R.rate_limit, **_ROTATE_FALLBACK)
+_V_AUTH_ROTATE = _v(_R.auth, retryable=False, **_ROTATE_FALLBACK)
+_V_AUTH_FALLBACK = _v(_R.auth, **_ABORT_FALLBACK)
+_V_MODEL_NOT_FOUND = _v(_R.model_not_found, **_ABORT_FALLBACK)
+_V_CONTENT_BLOCKED = _v(_R.content_policy_blocked, **_ABORT_FALLBACK)
+_V_FORMAT_ERROR = _v(_R.format_error, **_ABORT_FALLBACK)
+_V_POLICY_BLOCKED = _v(_R.provider_policy_blocked, retryable=False)
+_V_SSL_CERT = _v(_R.ssl_cert_verification, retryable=False)
+_V_CONTEXT_OVERFLOW = _v(_R.context_overflow, should_compress=True)
+_V_PAYLOAD_TOO_LARGE = _v(_R.payload_too_large, should_compress=True)
+_V_OVERLOADED, _V_SERVER_ERROR, _V_TIMEOUT, _V_UNKNOWN = map(_v, (_R.overloaded, _R.server_error, _R.timeout, _R.unknown))
+_V_IMAGE_TOO_LARGE, _V_IMAGE_CORRUPT = _v(_R.image_too_large), _v(_R.image_corrupt)
+_V_MULTIMODAL, _V_INVALID_ENCRYPTED = _v(_R.multimodal_tool_content_unsupported), _v(_R.invalid_encrypted_content)
++_V_REASONING_MANDATORY = _v(_R.reasoning_mandatory, should_compress=False, should_fallback=False)
++# A reasoning-mandatory route answering ``reasoning: {enabled: false}`` (Nous Portal + OpenRouter wording).
++_REASONING_MANDATORY_PATTERN = "reasoning is mandatory"
-# ── Classification pipeline ─────────────────────────────────────────────
+def _billing_hints(error_msg: str) -> Verdict:
+ """Billing verdict carrying the #82154 ambiguity marker when applicable."""
+ ctx: Dict[str, Any] = {}
+ if any(p in error_msg for p in _UNVERIFIED_BILLING_PATTERNS):
+ ctx = {"billing_unverified": True, "possible_content_filter": True}
+ return {**_V_BILLING, "error_context": ctx}
-def classify_api_error(
- error: Exception,
- *,
- provider: str = "",
- model: str = "",
- approx_tokens: int = 0,
- context_length: int = 200000,
- num_messages: int = 0,
-) -> ClassifiedError:
- """Classify an API error into a structured recovery recommendation.
-
- Priority-ordered pipeline:
- 0. Plugin ``transform_api_error_classification`` hooks (first valid result wins)
- 1. Special-case provider-specific patterns (thinking sigs, tier gates)
- 2. HTTP status code + message-aware refinement
- 3. Error code classification (from body)
- 4. Message pattern matching (billing vs rate_limit vs context vs auth)
- 5. SSL/TLS transient alert patterns → retry as timeout
- 6. Server disconnect + large session → context overflow
- 7. Transport error heuristics
- 8. Fallback: unknown (retryable with backoff)
-
- Args:
- error: The exception from the API call.
- provider: Current provider name (e.g. "openrouter", "anthropic").
- model: Current model slug.
- approx_tokens: Approximate token count of the current context.
- context_length: Maximum context length for the current model.
-
- Returns:
- ClassifiedError with reason and recovery action hints.
- """
- status_code = _extract_status_code(error)
- error_type = type(error).__name__
- # Copilot/GitHub Models RateLimitError may not set .status_code; force 429
- # so downstream rate-limit handling (classifier reason, pool rotation,
- # fallback gating) fires correctly instead of misclassifying as generic.
- if status_code is None and error_type == "RateLimitError":
- status_code = 429
- body = _extract_error_body(error)
- error_code = _extract_error_code(body)
- response_headers = _extract_response_headers(error)
-
- # Build a comprehensive error message string for pattern matching.
- # str(error) alone may not include the body message (e.g. OpenAI SDK's
- # APIStatusError.__str__ returns the first arg, not the body). Append
- # the body message so patterns like "try again" in 402 disambiguation
- # are detected even when only present in the structured body.
- #
- # Also extract metadata.raw — OpenRouter wraps upstream provider errors
- # inside {"error": {"message": "Provider returned error", "metadata":
- # {"raw": "<actual error JSON>"}}} and the real error message (e.g.
- # "context length exceeded") is only in the inner JSON.
- _raw_msg = str(error).lower()
- _body_msg = ""
- _metadata_msg = ""
- if isinstance(body, dict):
- _err_obj = body.get("error", {})
- if isinstance(_err_obj, dict):
- _body_msg = str(_err_obj.get("message") or "").lower()
- # Parse metadata.raw for wrapped provider errors
- _metadata = _err_obj.get("metadata", {})
- if isinstance(_metadata, dict):
- _raw_json = _metadata.get("raw") or ""
- if isinstance(_raw_json, str) and _raw_json.strip():
- try:
- import json
- _inner = json.loads(_raw_json)
- if isinstance(_inner, dict):
- _inner_err = _inner.get("error", {})
- if isinstance(_inner_err, dict):
- _metadata_msg = str(_inner_err.get("message") or "").lower()
- except (json.JSONDecodeError, TypeError):
- pass
- if not _body_msg:
- _body_msg = str(body.get("message") or "").lower()
- # Combine all message sources for pattern matching
- parts = [_raw_msg]
- if _body_msg and _body_msg not in _raw_msg:
- parts.append(_body_msg)
- if _metadata_msg and _metadata_msg not in _raw_msg and _metadata_msg not in _body_msg:
- parts.append(_metadata_msg)
- error_msg = " ".join(parts)
- provider_lower = (provider or "").strip().lower()
- model_lower = (model or "").strip().lower()
-
- def _result(reason: FailoverReason, **overrides) -> ClassifiedError:
- defaults = {
- "reason": reason,
- "status_code": status_code,
- "provider": provider,
- "model": model,
- "message": _extract_message(error, body),
- }
- defaults.update(overrides)
- return ClassifiedError(**defaults)
-
- # ── 0. Plugin classifiers (first valid result wins) ─────────────
- #
- # Consulted BEFORE the built-in pipeline so a provider plugin can both
- # add classifications the core patterns miss and correct ones they get
- # wrong for its provider (see the ``transform_api_error_classification`` entry in
- # hermes_cli.plugins.VALID_HOOKS for the callback contract). Callback
- # exceptions are isolated inside invoke_hook and malformed returns are
- # dropped by the helper, so a broken plugin can never break
- # classification — the guard here only covers import/dispatch failure.
- try:
- from hermes_cli.plugins import get_plugin_error_classification
- plugin_classification = get_plugin_error_classification(
- provider=provider,
- model=model,
- status_code=status_code,
- error_type=error_type,
- error_code=error_code,
- error_message=error_msg,
- error_body=body,
- error=error,
- approx_tokens=approx_tokens,
- context_length=context_length,
- num_messages=num_messages,
- )
- except Exception as exc:
- logger.debug("Plugin error classification unavailable: %s", exc)
- plugin_classification = None
- if plugin_classification is not None:
- reason = plugin_classification.pop("reason")
- logger.info(
- "API error classified by plugin hook: %s (provider=%s, status=%s)",
- reason.value, provider, status_code,
- )
- return _result(reason, **plugin_classification)
-
- # ── 1. Provider-specific patterns (highest priority) ────────────
-
- # Provider content-policy / safety-filter block. The provider has made a
- # deterministic refusal decision about THIS prompt — retrying unchanged
- # just reproduces the same refusal and burns paid attempts. Must run
- # before status-based classification so a 400 safety block isn't
- # downgraded to a generic ``format_error`` and a status-less block
- # (OpenAI Codex SDK can raise without one) isn't left in the retryable
- # ``unknown`` bucket. See issue #18028.
- if any(p in error_msg for p in _CONTENT_POLICY_BLOCKED_PATTERNS):
- return _result(
- FailoverReason.content_policy_blocked,
- retryable=False,
- should_fallback=True,
- )
- # Anthropic thinking block recovery (400). Two distinct failure modes,
- # same recovery (strip all reasoning_details and retry without thinking
- # blocks — see the thinking_signature handler in conversation_loop.py):
- # 1. Signature mismatch: a thinking block is signed against the full
- # turn content; any upstream mutation (context compression, session
- # truncation, message merging) invalidates the signature.
- # Pattern: "signature" + "thinking".
- # 2. Frozen-block mutation: Anthropic rejects any change to the
- # thinking/redacted_thinking blocks in the *latest* assistant
- # message — "`thinking` or `redacted_thinking` blocks in the latest
- # assistant message cannot be modified. These blocks must remain as
- # they were in the original response." This carries no "signature"
- # token, so the original pattern missed it and the turn hard-aborted
- # as a non-retryable client error instead of self-healing.
- # Pattern: "thinking" + ("cannot be modified" | "must remain as they were").
- # Don't gate on provider — OpenRouter proxies Anthropic errors, so the
- # provider may be "openrouter" even though the error is Anthropic-specific.
- # The combined patterns are unique enough.
- if (
- status_code == 400
- and "thinking" in error_msg
- and (
- "signature" in error_msg
- or "cannot be modified" in error_msg
- or "must remain as they were" in error_msg
- )
- ):
- return _result(
- FailoverReason.thinking_signature,
- retryable=True,
- should_compress=False,
- )
+def _first_match(error_msg: str, rules: Sequence[tuple[Sequence[str], Any]]) -> Optional[Verdict]:
+ """Verdict of the first rule whose pattern list hits ``error_msg``."""
+ for patterns, verdict in rules:
+ if any(p in error_msg for p in patterns):
+ return verdict(error_msg) if callable(verdict) else verdict
+ return None
- # Anthropic long-context tier gate (429 "extra usage" + "long context")
- if (
- status_code == 429
- and "extra usage" in error_msg
- and "long context" in error_msg
- ):
- return _result(
- FailoverReason.long_context_tier,
- retryable=True,
- should_compress=True,
- )
- # Anthropic OAuth subscription rejects the 1M-context beta header.
- # Observed error body: "The long context beta is not yet available for
- # this subscription." Returned as HTTP 400 from native Anthropic when
- # the subscription doesn't include 1M context, even though the request
- # carries ``anthropic-beta: context-1m-2025-08-07``. The recovery path
- # in run_agent.py rebuilds the Anthropic client with the beta stripped
- # and retries once. Pattern is narrow enough that it won't collide with
- # the 429 tier-gate pattern above (different status, different phrase).
- if (
- status_code == 400
- and "long context beta" in error_msg
- and "not yet available" in error_msg
- ):
- return _result(
- FailoverReason.oauth_long_context_beta_forbidden,
- retryable=True,
- should_compress=False,
- )
+# Image/tool-content 400s, ordered: multimodal recovery ≠ image shrink; corrupt
+# bytes need strip not shrink; image-shrink is cheaper than context compression.
+_IMAGE_TOOL_RULES = (
+ (_MULTIMODAL_TOOL_CONTENT_PATTERNS, _V_MULTIMODAL), (_IMAGE_CORRUPT_PATTERNS, _V_IMAGE_CORRUPT),
+ (_IMAGE_TOO_LARGE_PATTERNS, _V_IMAGE_TOO_LARGE),
+)
+
+# Overflow signals arriving as 5xx (llama.cpp reports overflow as 500; busy /
+# model-load OOM as 503). Empty-response advisories must not enter compression.
+_OVERFLOW_AS_5XX_RULES = (
+ (_EMPTY_PROVIDER_RESPONSE_PATTERNS, _V_SERVER_ERROR), (_CONTEXT_OVERFLOW_PATTERNS, _V_CONTEXT_OVERFLOW),
+)
+
+# 404: Nous API surfaces credit depletion as a paid model vanishing from the
+# Free Tier (billing, not missing model); policy block before model_not_found.
+_404_RULES = (
+ (_BILLING_PATTERNS, _V_BILLING), (_PROVIDER_POLICY_BLOCKED_PATTERNS, _V_POLICY_BLOCKED),
+ (_MODEL_NOT_FOUND_PATTERNS, _V_MODEL_NOT_FOUND),
+)
+
+# 400 tail after the deterministic request-shape checks. Some providers return
+# model-not-found / rate-limit / billing as 400 instead of 404/429/402.
+_400_TAIL_RULES = _OVERFLOW_AS_5XX_RULES + (
+ (_PROVIDER_POLICY_BLOCKED_PATTERNS, _V_POLICY_BLOCKED), (_MODEL_NOT_FOUND_PATTERNS, _V_MODEL_NOT_FOUND),
+ (_RATE_LIMIT_PATTERNS, _V_RATE_LIMIT), (_BILLING_PATTERNS, _billing_hints),
+)
+
+# Status-less message path, head (before usage-limit disambiguation).
+_MESSAGE_HEAD_RULES = ((_PAYLOAD_TOO_LARGE_PATTERNS, _V_PAYLOAD_TOO_LARGE),) + _IMAGE_TOOL_RULES
+
+# Status-less tail. Overload before rate_limit/billing so "overloaded" backs off
+# instead of rotating; policy block before model_not_found; timeout/connection
+# wording last, classified as transport (never compression).
+_MESSAGE_TAIL_RULES = (
+ (_OVERLOADED_PATTERNS, _V_OVERLOADED), (_BILLING_PATTERNS, _billing_hints),
+ (_RATE_LIMIT_PATTERNS, _V_RATE_LIMIT), (_EMPTY_PROVIDER_RESPONSE_PATTERNS, _V_SERVER_ERROR),
+ (_CONTEXT_OVERFLOW_PATTERNS, _V_CONTEXT_OVERFLOW), (_AUTH_PATTERNS, _V_AUTH_ROTATE),
+ (_PROVIDER_POLICY_BLOCKED_PATTERNS, _V_POLICY_BLOCKED), (_MODEL_NOT_FOUND_PATTERNS, _V_MODEL_NOT_FOUND),
+ (_TIMEOUT_MESSAGE_PATTERNS, _V_TIMEOUT), (_CONNECTION_MESSAGE_PATTERNS, _V_TIMEOUT),
+)
+
+# Structured error code → verdict. The error-code rate_limit verdict rotates
+# but does not set should_fallback (unlike the message/status paths).
+_ERROR_CODE_VERDICTS: Dict[str, Verdict] = {
+ **dict.fromkeys(("resource_exhausted", "throttled", "rate_limit_exceeded"),
+ _v(_R.rate_limit, should_rotate_credential=True)),
+ **dict.fromkeys(_BILLING_ERROR_CODES, _V_BILLING),
+ **dict.fromkeys(("model_not_found", "model_not_available", "invalid_model"), _V_MODEL_NOT_FOUND),
+ **dict.fromkeys(("context_length_exceeded", "max_tokens_exceeded"), _V_CONTEXT_OVERFLOW),
+ "invalid_encrypted_content": _V_INVALID_ENCRYPTED,
+}
- # llama.cpp's ``json-schema-to-grammar`` converter (used by its OAI
- # server to build GBNF tool-call parsers) rejects regex escape classes
- # like ``\d``/``\w``/``\s`` and most ``format`` values. MCP servers
- # routinely emit ``"pattern": "\\d{4}-\\d{2}-\\d{2}"`` for date/phone/
- # email params. llama.cpp surfaces this as HTTP 400 with one of a few
- # recognizable phrases; on match we strip ``pattern``/``format`` from
- # ``self.tools`` in the retry loop and retry once. Cloud providers are
- # unaffected — they accept these keywords and we never hit this branch.
- #
- # Exclude Qwen/vLLM template raise_exception("No user query found…")
- # wrapped by some local engines as applyPromptTemplate / "Unable to
- # generate parser for this template". That is a poisoned transcript
- # shape (handled via _INVALID_MESSAGE_BODY_PATTERNS → format_error),
- # not a tool-schema grammar rejection — matching it here strips
- # pattern/format keywords and retries uselessly while the real fix
- # is /new (or a successful compression that preserves a user turn).
- if status_code == 400:
- _llama_cpp_grammar_hit = (
- "error parsing grammar" in error_msg
- or "json-schema-to-grammar" in error_msg
- or (
- "unable to generate parser" in error_msg
- and "template" in error_msg
- )
- )
- else:
- _llama_cpp_grammar_hit = False
- if (
- _llama_cpp_grammar_hit
- and _NO_USER_QUERY_SIGNAL not in error_msg
- ):
- return _result(
- FailoverReason.llama_cpp_grammar_pattern,
- retryable=True,
- should_compress=False,
- )
+# Generic ``invalid_request_error`` is deliberately NOT a 400 validation
+# signal — OpenAI stamps it on genuine overflow 400s too.
+_400_VALIDATION_CODES = {"unknown_parameter", "unsupported_parameter"}
+_5XX_VALIDATION_CODES = _400_VALIDATION_CODES | {"invalid_request_error"}
+_400_VALIDATION_PATTERNS = tuple(p for p in _REQUEST_VALIDATION_PATTERNS if p != "invalid_request_error")
- # xAI Grok subscription entitlement errors.
- #
- # xAI returns "You have either run out of available resources or do not
- # have an active Grok subscription" through two distinct code paths:
- #
- # • HTTP 403 — status_code is set; _classify_by_status (step 2) routes
- # it to FailoverReason.auth correctly, and _is_entitlement_failure
- # then prevents the credential-refresh loop.
- #
- # • SSE ``type=error`` frame — surfaced as _StreamErrorEvent with
- # status_code=None. _classify_by_status is skipped entirely, and
- # "grok subscription" / "out of available resources" appear in none
- # of the message-pattern lists below. Without this guard the error
- # falls through to FailoverReason.unknown (retryable=True), burning
- # max_retries before the agent stops — and _is_entitlement_failure
- # is never called because it only runs under FailoverReason.auth.
- #
- # Both X Premium+ and SuperGrok subscribers hit this path when their
- # subscription tier does not cover the requested model or feature.
- if (
- "do not have an active grok subscription" in error_msg
- or ("out of available resources" in error_msg and "grok" in error_msg)
- ):
- return _result(
- FailoverReason.auth,
- retryable=False,
- should_fallback=True,
- )
- # ── 2. HTTP status code classification ──────────────────────────
+# ── Classification pipeline ─────────────────────────────────────────────
- if status_code is not None:
- classified = _classify_by_status(
- status_code, error_msg, error_code, body,
- provider=provider_lower, model=model_lower,
- approx_tokens=approx_tokens, context_length=context_length,
- num_messages=num_messages,
- response_headers=response_headers,
- result_fn=_result,
- )
- if classified is not None:
- return classified
-
- # Local MoA streaming compatibility errors are adapter-shape bugs, not a
- # provider outage. Falling back to another model would silently switch the
- # user's selected MoA route to a single-model answer (#55933 follow-up).
- if provider_lower == "moa" and (
- "'types.SimpleNamespace' object is not iterable" in str(error)
- or "'types.SimpleNamespace' object has no attribute 'index'" in str(error)
- ):
- return _result(
- FailoverReason.format_error,
- retryable=False,
- should_fallback=False,
+@dataclass
+class _Ctx:
+ """Everything the classifier stages need about one failed call."""
+
+ error: Exception
+ status_code: Optional[int]
+ body: dict
+ msg: str # lowercased str(error) + body message(s)
+ provider: str # as passed by the caller
+ model: str
+ approx_tokens: int
+ context_length: int
+ num_messages: int
+
+ def __post_init__(self) -> None:
+ self.error_type = type(self.error).__name__
+ self.error_code = _extract_error_code(self.body)
+ self.code = self.error_code.lower()
+ self.headers = _from_cause_chain(self.error, _headers_of, {})
+ self.provider_slug = (self.provider or "").strip().lower()
+ self.model_slug = (self.model or "").strip().lower()
+
+ def large_session(self, frac: float, tokens: int, messages: int) -> bool:
+ """Absolute thresholds only proxy for smaller context windows."""
+ return self.approx_tokens > self.context_length * frac or (
+ self.context_length <= 256000 and (self.approx_tokens > tokens or self.num_messages > messages)
+ )
+
+
+def _plugin_verdict(c: _Ctx) -> Optional[Verdict]:
+ """First valid plugin classification (runs before the built-in pipeline so a
+ provider plugin can add or correct verdicts). invoke_hook isolates callback
+ failures; this guard only covers import/dispatch failure."""
+ try:
+ from hermes_cli.plugins import get_plugin_error_classification
+ verdict = get_plugin_error_classification(
+ provider=c.provider, model=c.model, status_code=c.status_code, error_type=c.error_type,
+ error_code=c.error_code, error_message=c.msg, error_body=c.body, error=c.error,
+ approx_tokens=c.approx_tokens, context_length=c.context_length, num_messages=c.num_messages,
)
+ except Exception as exc:
+ logger.debug("Plugin error classification unavailable: %s", exc)
+ return None
+ if verdict is not None:
+ logger.info("API error classified by plugin hook: %s (provider=%s, status=%s)",
+ verdict["reason"].value, c.provider, c.status_code)
+ return verdict
+
+
+def _provider_special_cases(c: _Ctx) -> Optional[Verdict]:
+ """Highest-priority provider-specific shapes that a status code would misroute."""
+ msg, status = c.msg, c.status_code
+ # Safety refusal before status classification so a 400 block isn't downgraded
+ # to format_error and a status-less block isn't left retryable (#18028).
+ if any(p in msg for p in _CONTENT_POLICY_BLOCKED_PATTERNS):
+ return _V_CONTENT_BLOCKED
+ # Anthropic thinking-block 400s (signature mismatch after transcript
+ # mutation). Not gated on provider — OpenRouter proxies Anthropic errors.
+ if status == 400 and "thinking" in msg and any(p in msg for p in _THINKING_MUTATION_WORDS):
+ return _v(_R.thinking_signature)
+ # Anthropic long-context tier gate (429 "extra usage" + "long context").
+ if status == 429 and "extra usage" in msg and "long context" in msg:
+ return _v(_R.long_context_tier, should_compress=True)
+ # Anthropic OAuth rejects the 1M beta header; run_agent retries without it.
+ if status == 400 and "long context beta" in msg and "not yet available" in msg:
+ return _v(_R.oauth_long_context_beta_forbidden)
+ # llama.cpp grammar rejects regex ``pattern``/``format`` in tool schemas; the
+ # retry loop strips them. Exclude the Qwen/vLLM "No user query found" error
+ # local engines wrap as "Unable to generate parser for this template" —
+ # that is a poisoned transcript (→ format_error), not a grammar problem.
+ grammar_hit = "error parsing grammar" in msg or "json-schema-to-grammar" in msg or (
+ "unable to generate parser" in msg and "template" in msg
+ )
+ if status == 400 and grammar_hit and _NO_USER_QUERY_SIGNAL not in msg:
+ return _v(_R.llama_cpp_grammar_pattern)
+ # xAI Grok entitlement as an SSE ``type=error`` frame: no status, matches no
+ # pattern list, would otherwise burn max_retries as ``unknown``.
+ if "do not have an active grok subscription" in msg or ("out of available resources" in msg and "grok" in msg):
+ return _V_AUTH_FALLBACK
+ return None
- # Local MoA config drift is deterministic: a persisted session can retain
- # a preset name that was later renamed/deleted. Retrying the same lookup
- # cannot recover and makes a clear config error look like an API outage.
- from agent.errors import MoAPresetNotFoundError
- if isinstance(error, MoAPresetNotFoundError):
- return _result(FailoverReason.model_not_found, retryable=False)
+def _moa_special_cases(c: _Ctx) -> Optional[Verdict]:
+ # Local MoA streaming adapter-shape bugs are not a provider outage; falling
+ # back would silently replace the MoA route with a single model (#55933).
+ if c.provider_slug == "moa" and any(s in str(c.error) for s in _MOA_ADAPTER_SHAPE_BUGS):
+ return _v(_R.format_error, retryable=False)
+ # Persisted MoA preset name that was renamed/deleted — deterministic config error.
+ from agent.errors import MoAPresetNotFoundError
+ return _v(_R.model_not_found, retryable=False) if isinstance(c.error, MoAPresetNotFoundError) else None
+
+
+def _by_error_code(c: _Ctx) -> Optional[Verdict]:
+ """Structured error codes from the response body."""
+ # Request-validation failure as plain-text ``event: error`` SSE data behind
+ # HTTP 200: retrying cannot succeed, a configured fallback still may.
+ if c.code == PROVIDER_STREAM_NON_JSON_ERROR_CODE and "request validation failed:" in c.msg:
+ return _V_FORMAT_ERROR
+ return _ERROR_CODE_VERDICTS.get(c.code)
+
+
+def _by_message(c: _Ctx) -> Optional[Verdict]:
+ """Message patterns when no status code settled it; status-less usage
+ limits get the same disambiguation as 402."""
+ head = _first_match(c.msg, _MESSAGE_HEAD_RULES)
+ if head is not None:
+ return head
+ usage_limit = any(p in c.msg for p in _USAGE_LIMIT_PATTERNS)
+ return _classify_402(c.msg, dict) if usage_limit else _first_match(c.msg, _MESSAGE_TAIL_RULES)
+
+
+def _by_transport(c: _Ctx) -> Optional[Verdict]:
+ """SSL, disconnect, circuit-breaker and transport-type heuristics, in that order."""
+ msg = c.msg
+ # Cert failure → fail fast (checked first: also contains "[ssl:"); transient
+ # alert → retry, before disconnects so a flaky handshake never compresses.
+ ssl = _first_match(msg, ((_SSL_CERT_VERIFY_PATTERNS, _V_SSL_CERT), (_SSL_TRANSIENT_PATTERNS, _V_TIMEOUT)))
+ if ssl is not None:
+ return ssl
+ # Disconnect + large session → probable overflow rejection, not a hiccup.
+ if any(p in msg for p in _SERVER_DISCONNECT_PATTERNS) and not c.status_code:
+ # Reasoning models: far more likely the gateway idle-killed a long
+ # thinking stream — never compress on a phantom overflow (#52310).
+ from agent.reasoning_timeouts import get_reasoning_stale_timeout_floor
+ if get_reasoning_stale_timeout_floor(c.model) is not None:
+ return _V_TIMEOUT
+ return _V_CONTEXT_OVERFLOW if c.large_session(0.6, 120000, 200) else _V_TIMEOUT
+ # Stale-call circuit breaker (_check_stale_giveup RuntimeError before any
+ # network call): as ``unknown`` it would burn every retry instantly.
+ if c.error_type == "RuntimeError" and "consecutive stale attempts" in msg and "aborting this call" in msg:
+ return _v(_R.timeout, **_ABORT_FALLBACK)
+ transport = c.error_type in _TRANSPORT_ERROR_TYPES or isinstance(c.error, (TimeoutError, ConnectionError, OSError))
+ return _V_TIMEOUT if transport else None
+
+
+def _by_status(c: _Ctx) -> Optional[Verdict]:
+ """HTTP status code with message-aware refinement (unlisted 4xx/5xx → generic)."""
+ status = c.status_code
+ if status is None:
+ return None
+ default = _V_FORMAT_ERROR if 400 <= status < 500 else _V_SERVER_ERROR if 500 <= status < 600 else None
+ return _STATUS_HANDLERS[status](c) if status in _STATUS_HANDLERS else default
- # ── 3. Error code classification ────────────────────────────────
- if error_code:
- classified = _classify_by_error_code(error_code, error_msg, _result)
- if classified is not None:
- return classified
+# Stage order: plugin hooks → provider-specific special cases → HTTP status →
+# MoA shapes → structured error code → message patterns → SSL → disconnect +
+# large session → transport types → unknown (retryable with backoff).
+_STAGES: Sequence[Callable[[_Ctx], Optional[Verdict]]] = (
+ _plugin_verdict, _provider_special_cases, _by_status, _moa_special_cases,
+ _by_error_code, _by_message, _by_transport,
+)
- # ── 4. Message pattern matching (no status code) ────────────────
- classified = _classify_by_message(
- error_msg, error_type,
- approx_tokens=approx_tokens,
- context_length=context_length,
- result_fn=_result,
+def classify_api_error(
+ error: Exception, *, provider: str = "", model: str = "",
+ approx_tokens: int = 0, context_length: int = 200000, num_messages: int = 0,
+) -> ClassifiedError:
+ """Classify an API error into a structured recovery recommendation (see ``_STAGES``)."""
+ status_code = _extract_status_code(error)
+ # Copilot/GitHub Models RateLimitError may not set .status_code; force 429.
+ if status_code is None and type(error).__name__ == "RateLimitError":
+ status_code = 429
+ body = _extract_error_body(error)
+ c = _Ctx(
+ error, status_code, body, _build_error_msg(error, body), provider, model,
+ approx_tokens, context_length, num_messages,
)
- if classified is not None:
- return classified
-
- # ── 5. SSL certificate verification failures → fail fast ────────
- # A broken certificate chain (TLS-inspecting proxy, missing custom CA,
- # expired/self-signed cert) is deterministic for the host — every retry
- # reproduces the identical handshake failure. Fail immediately with
- # actionable guidance instead of burning the retry budget first.
- # Checked BEFORE the transient-SSL patterns: cert-verify messages also
- # contain "[ssl:" which would otherwise match the transient list.
- # Inspired by Claude Code v2.1.199 (July 2026).
- if any(p in error_msg for p in _SSL_CERT_VERIFY_PATTERNS):
- return _result(
- FailoverReason.ssl_cert_verification,
- retryable=False,
- should_fallback=False,
- )
-
- # ── 5b. SSL/TLS transient errors → retry as timeout (not compression) ──
- # SSL alerts mid-stream are transport hiccups, not server-side context
- # overflow signals. Classify before the disconnect check so a large
- # session doesn't incorrectly trigger context compression when the real
- # cause is a flaky TLS handshake. Also matches when the error is
- # wrapped in a generic exception whose message string carries the SSL
- # alert text but the type isn't ssl.SSLError (happens with some SDKs
- # that re-raise without chaining).
- if any(p in error_msg for p in _SSL_TRANSIENT_PATTERNS):
- return _result(FailoverReason.timeout, retryable=True)
-
- # ── 6. Server disconnect + large session → context overflow ─────
- # Must come BEFORE generic transport error catch — a disconnect on
- # a large session is more likely context overflow than a transient
- # transport hiccup. Without this ordering, RemoteProtocolError
- # always maps to timeout regardless of session size.
-
- is_disconnect = any(p in error_msg for p in _SERVER_DISCONNECT_PATTERNS)
- if is_disconnect and not status_code:
- # Reasoning-model override: a transport disconnect on a reasoning
- # model is much more likely the upstream proxy idle-killing a
- # long thinking stream than a true context overflow — even on
- # large sessions. The default disconnect+large-session routing
- # below would otherwise send the user into the compression
- # branch (should_compress=True) and silently delete
- # conversation history on a phantom context-length error.
- # Reasoning models have multi-minute thinking phases that
- # routinely exceed the cloud gateway's idle window (NVIDIA
- # NIM ~120s — first-party repro at NVIDIA/NemoClaw#4846;
- # OpenAI worker / Anthropic stream-idle similar). The
- # per-reasoning-model stale-timeout floor in
- # agent/reasoning_timeouts.py raises the stale-detector
- # threshold to tolerate long thinking, so a true
- # transport-layer failure here is recoverable via the retry
- # path — not via context compression. Reclassify as timeout.
- # (Part 1 of Fixes #52310.)
- from agent.reasoning_timeouts import get_reasoning_stale_timeout_floor
- if get_reasoning_stale_timeout_floor(model) is not None:
- return _result(FailoverReason.timeout, retryable=True)
- # Absolute token/message-count thresholds are only a proxy for smaller
- # context windows. Large-context sessions can have hundreds of
- # messages while still being far below their actual token budget.
- is_large = approx_tokens > context_length * 0.6 or (
- context_length <= 256000 and (approx_tokens > 120000 or num_messages > 200)
- )
- if is_large:
- return _result(
- FailoverReason.context_overflow,
- retryable=True,
- should_compress=True,
- )
- return _result(FailoverReason.timeout, retryable=True)
-
- # ── 7b. Stale-call circuit breaker → failover immediately ──────
- # _check_stale_giveup() in agent/chat_completion_helpers.py raises a
- # RuntimeError when the provider has been unresponsive for N
- # consecutive stale attempts (default 5). The error is NOT a transport
- # timeout — the circuit breaker fires *before* any network call to avoid
- # an indefinite stall. Without this classification the RuntimeError
- # falls through to FailoverReason.unknown (retryable=True), which burns
- # all max_retries against the same dead provider (each retry hitting the
- # circuit breaker instantly with zero network overhead) before fallback
- # is attempted. Classify as non-retryable + should_fallback so the
- # retry loop activates the next fallback provider on the first hit.
- if (
- error_type == "RuntimeError"
- and "consecutive stale attempts" in error_msg
- and "aborting this call" in error_msg
- ):
- return _result(
- FailoverReason.timeout,
- retryable=False,
- should_fallback=True,
- )
-
- # ── 8. Transport / timeout heuristics ───────────────────────────
-
- if error_type in _TRANSPORT_ERROR_TYPES or isinstance(error, (TimeoutError, ConnectionError, OSError)):
- return _result(FailoverReason.timeout, retryable=True)
-
- # ── 9. Fallback: unknown ────────────────────────────────────────
-
- return _result(FailoverReason.unknown, retryable=True)
-
-
-# ── Status code classification ──────────────────────────────────────────
-
-def _classify_by_status(
- status_code: int,
- error_msg: str,
- error_code: str,
- body: dict,
- *,
- provider: str,
- model: str,
- approx_tokens: int,
- context_length: int,
- num_messages: int = 0,
- response_headers=None,
- result_fn,
-) -> Optional[ClassifiedError]:
- """Classify based on HTTP status code with message-aware refinement."""
-
- if status_code == 401:
- # Not retryable on its own — credential pool rotation and
- # provider-specific refresh (Codex, Anthropic, Nous) run before
- # the retryability check in run_agent.py. If those succeed, the
- # loop `continue`s. If they fail, retryable=False ensures we
- # hit the client-error abort path (which tries fallback first).
- return result_fn(
- FailoverReason.auth,
- retryable=False,
- should_rotate_credential=True,
- should_fallback=True,
- )
-
- if status_code == 403:
- # OpenRouter 403 "key limit exceeded" is actually billing. Other
- # providers also use 403 for account-plan or credit exhaustion.
- if (
- (
- provider == "xai-oauth"
- and error_code.lower() == _XAI_SPENDING_LIMIT_ERROR_CODE
- )
- or "key limit exceeded" in error_msg
- or "spending limit" in error_msg
- or any(p in error_msg for p in _BILLING_PATTERNS)
- ):
- return result_fn(
- FailoverReason.billing,
- retryable=False,
- should_rotate_credential=True,
- should_fallback=True,
- )
- return result_fn(
- FailoverReason.auth,
- retryable=False,
- should_fallback=True,
- )
+ verdict = next((v for v in (stage(c) for stage in _STAGES) if v is not None), _V_UNKNOWN)
+ base = {"status_code": status_code, "provider": provider, "model": model, "message": _extract_message(error, body)}
+ return ClassifiedError(**{**base, **verdict})
+
+
+# ── Status code handlers ────────────────────────────────────────────────
+
+def _status_403(c: _Ctx) -> Verdict:
+ # OpenRouter 403 "key limit exceeded" and similar plan/credit exhaustion are billing.
+ xai_spend = c.provider_slug == "xai-oauth" and c.code == _XAI_SPENDING_LIMIT_ERROR_CODE
+ billing = xai_spend or any(p in c.msg for p in ("key limit exceeded", "spending limit") + _BILLING_PATTERNS)
+ return _V_BILLING if billing else _V_AUTH_FALLBACK
+
+
+def _status_404(c: _Ctx) -> Verdict:
+ verdict = _first_match(c.msg, _404_RULES)
+ if verdict is not None:
+ return verdict
+ # Bare id the catalogue only knows prefixed → malformed id (NVIDIA NIM "404
+ # page not found", #78796). A generic 404 (wrong path, proxy glitch) stays
+ # unknown so the real error surfaces instead of a silent misreported fallback.
+ return _V_MODEL_NOT_FOUND if _model_id_missing_known_prefix(c.model_slug, c.provider_slug) else _V_UNKNOWN
+
+
+def _status_429(c: _Ctx) -> Verdict:
+ # Z.AI/Zhipu reuse 429 for server-wide overload: back off on the same
+ # key instead of burning the pool (#14038).
+ if any(p in c.msg for p in _OVERLOADED_PATTERNS):
+ return _V_OVERLOADED
+ # OpenRouter-wrapped upstream 429: the key is healthy — fall back, don't bench.
+ if _is_openrouter_upstream_error(c.body, c.provider_slug):
+ upstream = _extract_upstream_provider_name(c.body)
+ ctx = {"upstream_provider": upstream} if upstream else {}
+ return _v(_R.upstream_rate_limit, should_fallback=True, error_context=ctx)
+ # Quota walls as 429 (Anthropic ``usage_limit_reached``, "quota", billing
+ # phrases) are billing ONLY when the body is not itself a rate-limit phrase
+ # ("Rate limit exceeded" contains "limit exceeded") and carries no reset/
+ # retry signal (#93419, #39441).
+ quota_wall = c.code == "usage_limit_reached" or any(
+ p in c.msg for p in ("usage_limit_reached",) + _USAGE_LIMIT_PATTERNS + _BILLING_PATTERNS
+ )
+ explicit_rate_limit = any(p in c.msg for p in _RATE_LIMIT_PATTERNS)
+ if quota_wall and not explicit_rate_limit and not _has_usage_limit_transient_signal(c.msg, c.body, c.headers):
+ return _V_BILLING
+ return _V_RATE_LIMIT
- if status_code == 402:
- return _classify_402(error_msg, result_fn)
-
- if status_code == 404:
- # Nous API currently surfaces HA/NAS credit depletion as a paid model
- # becoming unavailable on the Free Tier, returned as 404 rather than
- # 402. Treat that as entitlement/billing exhaustion, not a missing
- # model, so the retry loop can show credit/top-up guidance.
- if any(p in error_msg for p in _BILLING_PATTERNS):
- return result_fn(
- FailoverReason.billing,
- retryable=False,
- should_rotate_credential=True,
- should_fallback=True,
- )
- # OpenRouter policy-block 404 — distinct from "model not found".
- # The model exists; the user's account privacy setting excludes the
- # only endpoint serving it. Falling back to another provider won't
- # help (same account setting applies). The error body already
- # contains the fix URL, so just surface it.
- if any(p in error_msg for p in _PROVIDER_POLICY_BLOCKED_PATTERNS):
- return result_fn(
- FailoverReason.provider_policy_blocked,
- retryable=False,
- should_fallback=False,
- )
- if any(p in error_msg for p in _MODEL_NOT_FOUND_PATTERNS):
- return result_fn(
- FailoverReason.model_not_found,
- retryable=False,
- should_fallback=True,
- )
- # A bare id that the provider's catalogue only knows in prefixed form
- # is a malformed model id, not a routing glitch — NVIDIA NIM answers
- # one with a naked ``404 page not found`` that names nothing, so the
- # generic branch below burns three retries and reports what looks
- # like an outage (#78796). Deterministic: don't retry, and let the
- # model_not_found surface carry the real cause.
- if _model_id_missing_known_prefix(model, provider):
- return result_fn(
- FailoverReason.model_not_found,
- retryable=False,
- should_fallback=True,
- )
- # Generic 404 with no "model not found" signal — could be a wrong
- # endpoint path (common with local llama.cpp / Ollama / vLLM when
- # the URL is slightly misconfigured), a proxy routing glitch, or
- # a transient backend issue. Classifying these as model_not_found
- # silently falls back to a different provider and tells the model
- # the model is missing, which is wrong and wastes a turn. Treat
- # as unknown so the retry loop surfaces the real error instead.
- return result_fn(
- FailoverReason.unknown,
- retryable=True,
- )
- if status_code == 413:
- return result_fn(
- FailoverReason.payload_too_large,
- retryable=True,
- should_compress=True,
- )
+def _status_5xx(c: _Ctx) -> Verdict:
+ # Request-validation errors as 5xx (codex.nekos.me) fail fast instead of
+ # retry-flooding — unless the parameter was injected server-side.
+ validation = any(p in c.msg for p in _REQUEST_VALIDATION_PATTERNS) or c.code in _5XX_VALIDATION_CODES
+ if validation and not _is_server_injected_param_rejection(c.msg, c.provider_slug):
+ return _V_FORMAT_ERROR
+ return _first_match(c.msg, _OVERFLOW_AS_5XX_RULES) or _V_SERVER_ERROR
- if status_code == 429:
- # Already checked long_context_tier above. Some providers (notably
- # Z.AI / Zhipu) reuse HTTP 429 for server-wide overload — same status
- # code as a true per-credential rate limit, but the credential is
- # valid and the correct recovery is "back off and retry the same key",
- # NOT "rotate the credential" (which exhausts the pool while the
- # endpoint is still busy, and does nothing for a single-key user).
- # Disambiguate on the error body so an overload 429 takes the
- # transient-overload path instead of burning the pool. (#14038)
- if any(p in error_msg for p in _OVERLOADED_PATTERNS):
- return result_fn(
- FailoverReason.overloaded,
- retryable=True,
- )
- # Distinguish an OpenRouter-aggregator upstream 429 (an upstream model
- # like DeepSeek rate-limited OpenRouter's aggregate traffic) from an
- # account-level 429 (the user's key is actually throttled). OpenRouter
- # wraps upstream errors with the outer message "Provider returned
- # error" — the user's key is healthy, so marking it exhausted / rotating
- # is wrong and burns the key for ~24min. Fall back to a different model.
- if _is_openrouter_upstream_error(body, provider):
- upstream_provider = _extract_upstream_provider_name(body)
- ctx = {"upstream_provider": upstream_provider} if upstream_provider else {}
- return result_fn(
- FailoverReason.upstream_rate_limit,
- retryable=True,
- should_rotate_credential=False,
- should_fallback=True,
- error_context=ctx,
- )
- # Account/subscription usage exhaustion is a quota wall, not a
- # request-rate throttle. Anthropic returns this as 429, so the generic
- # branch below used to retry it and Desktop rendered a provider error
- # instead of the billing/quota recovery. Preserve periodic quotas when
- # the response supplies an explicit reset/retry signal.
- #
- # The check covers the narrow #93419 core (Anthropic's
- # ``usage_limit_reached``) plus the broader ``_USAGE_LIMIT_PATTERNS``
- # ("quota", "limit exceeded", "key limit exceeded") so other providers'
- # hard quota walls also route to billing — but ONLY when the message is
- # not itself an explicit rate-limit phrase. Without that guard,
- # "Rate limit exceeded" ("limit exceeded" substring) would wrongly
- # promote to non-retryable billing. (broadening + guard credit #39441)
- has_usage_limit = (
- error_code.lower() == "usage_limit_reached"
- or "usage_limit_reached" in error_msg
- or any(p in error_msg for p in _USAGE_LIMIT_PATTERNS)
- )
- # Explicit billing phrases in a 429 body are a hard wall regardless of
- # usage-limit wording — a provider that wraps "insufficient credits" in
- # a 429 (rather than 402) was previously retried as a rate limit and
- # burned the pool. (credit #39441)
- has_billing = any(p in error_msg for p in _BILLING_PATTERNS)
- has_explicit_rate_limit = any(
- p in error_msg for p in _RATE_LIMIT_PATTERNS
- )
- has_transient_signal = _has_usage_limit_transient_signal(
- error_msg,
- body,
- response_headers,
- )
- if (
- (has_billing or has_usage_limit)
- and not has_explicit_rate_limit
- and not has_transient_signal
- ):
- return result_fn(
- FailoverReason.billing,
- retryable=False,
- should_rotate_credential=True,
- should_fallback=True,
- )
- return result_fn(
- FailoverReason.rate_limit,
- retryable=True,
- should_rotate_credential=True,
- should_fallback=True,
- )
- if status_code == 400:
- return _classify_400(
- error_msg, error_code, body,
- provider=provider, model=model,
- approx_tokens=approx_tokens,
- context_length=context_length,
- num_messages=num_messages,
- result_fn=result_fn,
- )
+def _classify_402(error_msg: str, result_fn: Callable[..., Any]) -> Any:
+ """Disambiguate 402: "usage limit, try again in 5 minutes" is a periodic quota, not billing."""
+ transient = any(p in error_msg for p in _USAGE_LIMIT_PATTERNS) and any(
+ p in error_msg for p in _USAGE_LIMIT_TRANSIENT_SIGNALS
+ )
+ return result_fn(**(_V_RATE_LIMIT if transient else _V_BILLING))
+
+
+def _classify_400(c: _Ctx) -> Verdict:
+ """400 Bad Request — image/tool shapes, request-shape rejections, overflow, or generic."""
+ msg, code = c.msg, c.code
+ verdict = _first_match(msg, _IMAGE_TOOL_RULES)
+ if verdict is not None:
+ return verdict
+ # Invalid encrypted reasoning replay blob (OpenAI Responses); before
+ # overflow because "encrypted content … could not be verified" trips it.
+ if code == "invalid_encrypted_content" or "invalid_encrypted_content" in msg or (
+ "encrypted content for item" in msg and "could not be verified" in msg
+ ) or "could not decrypt the provided encrypted_content" in msg:
+ return _V_INVALID_ENCRYPTED
++ # Reasoning-mandatory route rejecting a disable (GLM-5.3 on Nous Portal / OpenRouter). Deterministic
++ # for the request shape, but the only bad field is ``reasoning: {enabled: false}`` — the loop drops
++ # the disable and retries once. Must precede request-validation, which would abort as format_error.
++ if _REASONING_MANDATORY_PATTERN in msg:
++ return _V_REASONING_MANDATORY
+ # 400 blaming a field this route never sent (Codex OAuth injects then rejects
+ # prompt_cache_retention ~20% of the time): transient, retry identical request.
+ if _is_server_injected_param_rejection(msg, c.provider_slug):
+ return _V_SERVER_ERROR
+ # Before overflow: GPT-5's "Unsupported parameter: 'max_tokens'" contains it.
+ if any(p in msg for p in _400_VALIDATION_PATTERNS) or code in _400_VALIDATION_CODES:
+ return _V_FORMAT_ERROR
+ # Malformed message array before overflow: input can be tiny and compression
+ # cannot fix it. litellm/Bedrock proxies use errorCode=INVALID_REQUEST_BODY.
+ if any(p in msg for p in _INVALID_MESSAGE_BODY_PATTERNS) or code == "invalid_request_body":
+ logger.warning(
+ "Malformed message array 400 (invalid request body) classified as format_error, NOT context "
+ "overflow — failing fast + falling back instead of entering the compression loop. This usually "
+ "means an empty-content assistant stub is in the transcript; num_messages=%s approx_tokens=%s. "
+ "error=%.200s", c.num_messages, c.approx_tokens, msg,
+ )
+ return _V_FORMAT_ERROR
+ verdict = _first_match(msg, _400_TAIL_RULES)
+ if verdict is not None:
+ return verdict
+ # Generic 400 + large session → probable overflow (Anthropic can return a
+ # bare "Error"); proxy shapes are read so a descriptive rejection isn't "bare".
+ body_msg = next((m for m in (str(x or "").strip().lower() for x in _body_message_candidates(c.body)) if m), "")
+ is_generic = len(body_msg) < 30 or body_msg in {"error", ""}
+ if is_generic and c.large_session(0.4, 80000, 80):
+ return _V_CONTEXT_OVERFLOW
+ return _V_FORMAT_ERROR
+
+
+# 401 not retryable on its own: rotation/refresh run before the retryability
+# check, then the client-error abort path (fallback first) is correct. 408 is
+# retry-safe (RFC 9110 §15.5.9; proxies emit it when generation outruns the
+# read window). Unlisted 4xx → format_error, 5xx → server_error.
+_STATUS_HANDLERS: Dict[int, Callable[[_Ctx], Verdict]] = {
+ 400: _classify_400, 401: lambda c: _V_AUTH_ROTATE, 402: lambda c: _classify_402(c.msg, dict),
+ 403: _status_403, 404: _status_404, 408: lambda c: _V_TIMEOUT, 413: lambda c: _V_PAYLOAD_TOO_LARGE,
+ 429: _status_429, 500: _status_5xx, 502: _status_5xx,
+ 503: lambda c: _first_match(c.msg, _OVERFLOW_AS_5XX_RULES) or _V_OVERLOADED,
+ 529: lambda c: _first_match(c.msg, _OVERFLOW_AS_5XX_RULES) or _V_OVERLOADED,
+}
- if status_code in {500, 502}:
- # Some OpenAI-compatible gateways return request-validation errors
- # with a 5xx status (codex.nekos.me returns 502 for unknown/
- # unsupported parameters). These are deterministic — every retry
- # gets the identical rejection — so the generic "5xx → retryable
- # server_error" rule turns one bad request into a retry flood.
- # Detect the unambiguous request-validation signals (in either the
- # message text or the structured error code) and fail fast.
- #
- # Exception: a parameter WE never sent on this route was injected by
- # the provider/proxy itself, so the rejection is not deterministic and
- # the generic retryable-5xx handling is correct. Mirrors the guard in
- # _classify_400 — see _is_server_injected_param_rejection.
- if (
- any(p in error_msg for p in _REQUEST_VALIDATION_PATTERNS)
- or error_code.lower() in {"invalid_request_error", "unknown_parameter",
- "unsupported_parameter"}
- ) and not _is_server_injected_param_rejection(error_msg, provider):
- return result_fn(
- FailoverReason.format_error,
- retryable=False,
- should_fallback=True,
- )
- # Some local inference servers (notably llama.cpp / llama-server)
- # report context overflow with an HTTP 500 instead of the standard
- # 400/413. The request-validation guard above already ran, so any
- # remaining explicit context-overflow signal routes into the
- # compression-and-retry path (mirroring _classify_400) instead of
- # blind server_error retries that exhaust and drop the turn.
- # Empty-response advisories that mention "max_tokens" must not enter
- # that compression path.
- if any(p in error_msg for p in _EMPTY_PROVIDER_RESPONSE_PATTERNS):
- return result_fn(
- FailoverReason.server_error,
- retryable=True,
- should_compress=False,
- )
- if any(p in error_msg for p in _CONTEXT_OVERFLOW_PATTERNS):
- return result_fn(
- FailoverReason.context_overflow,
- retryable=True,
- should_compress=True,
- )
- return result_fn(FailoverReason.server_error, retryable=True)
-
- if status_code in {503, 529}:
- # Same overflow-as-5xx variant (server busy / model-load OOM, or a
- # Cloudflare/Tailscale hop relabeling the status). Route explicit
- # overflow bodies into compression; otherwise treat as transient
- # overload and retry.
- if any(p in error_msg for p in _EMPTY_PROVIDER_RESPONSE_PATTERNS):
- return result_fn(
- FailoverReason.server_error,
- retryable=True,
- should_compress=False,
- )
- if any(p in error_msg for p in _CONTEXT_OVERFLOW_PATTERNS):
- return result_fn(
- FailoverReason.context_overflow,
- retryable=True,
- should_compress=True,
- )
- return result_fn(FailoverReason.overloaded, retryable=True)
-
- # 408 Request Timeout — a transient timing failure the server itself flags
- # as safe to retry (RFC 9110 §15.5.9), not a malformed request. Commonly
- # emitted by reverse proxies sitting in front of self-hosted backends
- # (llama.cpp / Ollama / vLLM) when a long generation outruns the proxy's
- # request-read window. Route to the dedicated ``timeout`` reason (rebuild
- # client + retry) instead of falling through to the generic 4xx bucket
- # below, which would abort the turn on a retry-safe error the same way it
- # aborts a 400 Bad Request.
- if status_code == 408:
- return result_fn(FailoverReason.timeout, retryable=True)
-
- # Other 4xx — non-retryable
- if 400 <= status_code < 500:
- return result_fn(
- FailoverReason.format_error,
- retryable=False,
- should_fallback=True,
- )
- # Other 5xx — retryable
- if 500 <= status_code < 600:
- return result_fn(FailoverReason.server_error, retryable=True)
+# ── Helpers ─────────────────────────────────────────────────────────────
- return None
+_RESET_FIELDS = ("resets_in_seconds", "resets_at", "reset_at", "retry_after")
+_RESET_HEADERS = ("retry-after", "Retry-After", "x-ratelimit-reset", "X-RateLimit-Reset")
-def _has_usage_limit_transient_signal(
- error_msg: str,
- body: dict,
- response_headers,
-) -> bool:
- """Return whether a usage-limit response identifies a reset window."""
+def _has_usage_limit_transient_signal(error_msg: str, body: dict, response_headers) -> bool:
+ """Whether a usage-limit response identifies a reset window (message, body fields, or headers)."""
if any(pattern in error_msg for pattern in _USAGE_LIMIT_TRANSIENT_SIGNALS):
return True
-
- payloads = [body]
- if isinstance(body, dict) and isinstance(body.get("error"), dict):
- payloads.append(body["error"])
- reset_fields = ("resets_in_seconds", "resets_at", "reset_at", "retry_after")
- for payload in payloads:
- if not isinstance(payload, dict):
- continue
- if any(
- payload.get(field) is not None and payload.get(field) != ""
- for field in reset_fields
- ):
- return True
-
+ payloads = [p for p in (body, _error_obj(body)) if isinstance(p, dict)]
+ if any(payload.get(f) not in (None, "") for payload in payloads for f in _RESET_FIELDS):
+ return True
if response_headers and hasattr(response_headers, "get"):
- for header in (
- "retry-after",
- "Retry-After",
- "x-ratelimit-reset",
- "X-RateLimit-Reset",
- ):
- value = response_headers.get(header)
- if value is not None and value != "":
- return True
+ return any(response_headers.get(h) not in (None, "") for h in _RESET_HEADERS)
return False
diff --cc agent/turn_recovery.py
index c781ac81166,00000000000..ceb549067ed
mode 100644,000000..100644
--- a/agent/turn_recovery.py
+++ b/agent/turn_recovery.py
@@@ -1,1369 -1,0 +1,1389 @@@
+"""Recovery-branch handlers for the conversation turn's inner retry loop.
+
+When the model call raises, one-shot recovery chains run before the generic retry/backoff
+path. Handlers return ``True`` (request repaired in place; loop ``continue``s with the same
+``retry_count``) or ``False`` (fall through). Guards live on ``TurnRetryState``; handlers
+mutate ``agent`` / ``messages`` / ``api_messages`` in place. Logger name stays
+``agent.conversation_loop`` (caplog pins); that module is only imported lazily (cycle + patch sites).
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+import time
+from dataclasses import dataclass
+from typing import Any, Dict, List, Optional, Tuple
+
+from agent.conversation_compression import COMPRESSION_RETRY_CONTEXT_REDUCED_STATUS_TEMPLATE
+from agent.model_metadata import is_output_cap_error, parse_available_output_tokens_from_error
+from agent.retry_utils import is_zai_coding_overload_error, zai_coding_overload_retry_ceiling
+from agent.error_classifier import FailoverReason
+from agent.message_sanitization import (
+ _looks_like_image_content_rejection, _sanitize_messages_non_ascii,
+ _sanitize_messages_surrogates, _sanitize_structure_non_ascii, _sanitize_structure_surrogates,
+ _sanitize_tools_non_ascii, _strip_images_from_messages, _strip_non_ascii,
+ close_interrupted_tool_sequence,
+)
+from agent.thinking_timeout_guidance import build_thinking_timeout_guidance, is_thinking_timeout
+from agent.turn_retry_state import TurnRetryState
+from utils import base_url_host_matches
+
+logger = logging.getLogger("agent.conversation_loop")
+
+
+def _vlines(agent: Any, *lines: str) -> None:
+ """Force-``_vprint`` each line prefixed with ``agent.log_prefix``."""
+ for line in lines:
+ agent._vprint(f"{agent.log_prefix}{line}", force=True)
+
+
+def _plines(agent: Any, *lines: str) -> None:
+ """``print`` each line prefixed with ``agent.log_prefix``."""
+ for line in lines:
+ print(f"{agent.log_prefix}{line}")
+
+
+def _blines(agent: Any, *lines: str) -> None:
+ """``_buffer_vprint`` each line (surfaces only if every retry+fallback exhausts)."""
+ for line in lines:
+ agent._buffer_vprint(line)
+
+
+def _image_error_max_dimension(error: Exception) -> Optional[int]:
+ """Extract a provider-reported image dimension ceiling, if present."""
+ parts = []
+ for value in (error, getattr(error, "message", None), getattr(error, "body", None)):
+ if value:
+ try:
+ parts.append(str(value))
+ except Exception:
+ pass
+ text = " ".join(parts).lower()
+ if "image" not in text or "dimension" not in text or "max allowed size" not in text:
+ return None
+ match = re.search(r"max allowed size(?:\s+for [^:]+)?:\s*(\d{3,5})\s*pixels?", text)
+ if not match:
+ return None
+ try:
+ max_dimension = int(match.group(1))
+ except ValueError:
+ return None
+ return max_dimension if 512 <= max_dimension <= 8000 else None
+
+
+def _try_refresh_nous_paid_entitlement_credentials(agent) -> bool:
+ """Refresh Nous runtime credentials after a fresh paid-entitlement check."""
+ try:
+ from hermes_cli.nous_account import get_nous_portal_account_info
+
+ if get_nous_portal_account_info(force_fresh=True).paid_service_access is not True:
+ return False
+ return agent._try_refresh_nous_client_credentials(force=True)
+ except Exception:
+ return False
+
+
+def _recover_unicode_encode_error(
+ agent: Any, api_error: Exception, messages: List[Dict[str, Any]], api_messages: Any,
+ api_kwargs: Any, active_system_prompt: Any,
+) -> Tuple[bool, Any]:
+ """UnicodeEncodeError recovery: lone surrogates (clipboard paste) first, then an ASCII
+ codec under a non-UTF-8 locale. Sanitizes in place; bounded by the caller's
+ ``_unicode_sanitization_passes < 2`` guard (surrogate strip, then ASCII-only)."""
+ _err_str = str(api_error).lower()
+ _is_ascii_codec = "'ascii'" in _err_str or "ascii" in _err_str
+ # utf-8 refusing U+D800..U+DFFF ("surrogates not allowed").
+ _is_surrogate_error = "surrogate" in _err_str or ("'utf-8'" in _err_str and not _is_ascii_codec)
+ # Sanitize `messages` AND `api_messages` (may carry reasoning_content/reasoning_details),
+ # plus `api_kwargs` and `prefill_messages`. Every sanitizer runs (no short-circuit).
+ _prefill = getattr(agent, "prefill_messages", None)
+ _surrogates_found = _sanitize_messages_surrogates(messages)
+ _surrogates_found |= isinstance(api_messages, list) and _sanitize_messages_surrogates(api_messages)
+ _surrogates_found |= isinstance(api_kwargs, dict) and _sanitize_structure_surrogates(api_kwargs)
+ _surrogates_found |= isinstance(_prefill, list) and _sanitize_messages_surrogates(_prefill)
+ # Gate the retry on the error type, not on whether anything was found — a new
+ # transformed field could slip through.
+ if _surrogates_found or _is_surrogate_error:
+ agent._unicode_sanitization_passes += 1
+ agent._buffer_vprint(
+ "⚠️ Stripped invalid surrogate characters from messages. Retrying..."
+ if _surrogates_found else
+ "⚠️ Surrogate encoding error — retrying after full-payload sanitization..."
+ )
+ return True, active_system_prompt
+ if not _is_ascii_codec:
+ return False, active_system_prompt
+
+ agent._force_ascii_payload = True
+ # Strip all non-ASCII from messages/tool schemas and retry; api_kwargs too so a
+ # non-ASCII transformed field doesn't survive via _build_api_kwargs cache paths.
+ _messages_sanitized = _sanitize_messages_non_ascii(messages)
+ if isinstance(api_messages, list):
+ _sanitize_messages_non_ascii(api_messages)
+ if isinstance(api_kwargs, dict):
+ _sanitize_structure_non_ascii(api_kwargs)
+ _prefill_sanitized = isinstance(_prefill, list) and _sanitize_messages_non_ascii(_prefill)
+ _tools = getattr(agent, "tools", None)
+ _tools_sanitized = isinstance(_tools, list) and _sanitize_tools_non_ascii(_tools)
+
+ _system_sanitized = False
+ if isinstance(active_system_prompt, str):
+ _sanitized_system = _strip_non_ascii(active_system_prompt)
+ if _sanitized_system != active_system_prompt:
+ active_system_prompt = agent._cached_system_prompt = _sanitized_system
+ _system_sanitized = True
+ _ephemeral = getattr(agent, "ephemeral_system_prompt", None)
+ if isinstance(_ephemeral, str) and _strip_non_ascii(_ephemeral) != _ephemeral:
+ agent.ephemeral_system_prompt = _strip_non_ascii(_ephemeral)
+ _system_sanitized = True
+
+ _client_kwargs = getattr(agent, "_client_kwargs", None)
+ _default_headers = _client_kwargs.get("default_headers") if isinstance(_client_kwargs, dict) else None
+ _headers_sanitized = isinstance(_default_headers, dict) and _sanitize_structure_non_ascii(_default_headers)
+
+ # Non-ASCII in the API key makes httpx fail encoding the Authorization header — the
+ # usual persistent cause after message/tool sanitization. Entra ID bearer providers
+ # are callables minting ASCII JWTs; skip them (``_strip_non_ascii`` would crash).
+ _credential_sanitized = False
+ _raw_key = getattr(agent, "api_key", None) or ""
+ if _raw_key and isinstance(_raw_key, str):
+ _clean_key = _strip_non_ascii(_raw_key)
+ if _clean_key != _raw_key:
+ agent.api_key = _clean_key
+ if isinstance(getattr(agent, "_client_kwargs", None), dict):
+ agent._client_kwargs["api_key"] = _clean_key
+ # The live client reads its own api_key copy on every request.
+ if getattr(agent, "client", None) is not None and hasattr(agent.client, "api_key"):
+ agent.client.api_key = _clean_key
+ _credential_sanitized = True
+ _vlines(
+ agent,
+ "⚠️ API key contained non-ASCII characters (bad copy-paste?) — stripped them. "
+ "If auth fails, re-copy the key from your provider's dashboard.",
+ )
+
+ # Always retry on ASCII codec detection: _force_ascii_payload sanitizes the full
+ # api_kwargs next iteration even when the checks above find nothing.
+ agent._unicode_sanitization_passes += 1
+ _vlines(
+ agent,
+ "⚠️ System encoding is ASCII — stripped non-ASCII characters from request payload. Retrying..."
+ if (_messages_sanitized or _prefill_sanitized or _tools_sanitized or _system_sanitized
+ or _headers_sanitized or _credential_sanitized) else
+ "⚠️ System encoding is ASCII — enabling full-payload sanitization for retry...",
+ )
+ return True, active_system_prompt
+
+
+def recover_before_classification(
+ agent: Any, api_error: Exception, *, messages: List[Dict[str, Any]], api_messages: Any,
+ api_kwargs: Any, active_system_prompt: Any,
+) -> Tuple[bool, Any]:
+ """Recovery branches that run BEFORE ``classify_api_error``: UnicodeEncodeError
+ sanitization, provider image-content rejection (switch session to text-only), and the
+ Bedrock AnthropicBedrock SDK streaming fallback. Returns ``(retry_now,
+ active_system_prompt)``; the prompt may be ASCII-sanitized in place."""
+ if isinstance(api_error, UnicodeEncodeError) and getattr(agent, '_unicode_sanitization_passes', 0) < 2:
+ _recovered, active_system_prompt = _recover_unicode_encode_error(
+ agent, api_error, messages, api_messages, api_kwargs, active_system_prompt
+ )
+ if _recovered:
+ return True, active_system_prompt
+
+ # Some providers 4xx on image_url content: strip images, mark session
+ # vision-unsupported, retry text-only. English phrase match; extend it.
+ _err_body = ""
+ try:
+ _err_body = str(getattr(api_error, "body", None) or getattr(api_error, "message", None) or str(api_error))
+ except Exception:
+ pass
+ _err_status = getattr(api_error, "status_code", None)
+ # 4xx-only gate: 5xx/timeouts are transient and take the retry path.
+ _status_ok = _err_status is None or (400 <= int(_err_status) < 500)
+ if getattr(agent, "_vision_supported", True) and _looks_like_image_content_rejection(_err_body) and _status_ok:
+ agent._vision_supported = False
+ _imgs_removed = _strip_images_from_messages(messages)
+ if isinstance(api_messages, list):
+ _strip_images_from_messages(api_messages)
+ _vlines(
+ agent,
+ "⚠️ Server rejected image content — switching to text-only mode for this session"
+ + (". Stripped images from history and retrying." if _imgs_removed else "."),
+ )
+ return True, active_system_prompt
+
+ # AnthropicBedrock SDK raises "Unexpected event order" when Bedrock errors before
+ # message_start; fall back to native Converse for this session.
+ if (
+ isinstance(api_error, RuntimeError)
+ and "unexpected event order" in str(api_error).lower()
+ and getattr(agent, "provider", "") == "bedrock"
+ and agent.api_mode == "anthropic_messages"
+ and not getattr(agent, "_bedrock_converse_fallback_attempted", False)
+ ):
+ agent._bedrock_converse_fallback_attempted = True
+ agent.api_mode = "bedrock_converse"
+ agent._bedrock_region = getattr(agent, "_bedrock_region", None) or "us-east-1"
+ agent.client = None # Drop the AnthropicBedrock client
+ agent._client_kwargs = {}
+ _vlines(agent, "⚠️ AnthropicBedrock SDK streaming failed — falling back to native Converse API for this session.")
+ return True, active_system_prompt
+ return False, active_system_prompt
+
+
+def _print_nous_401_diagnostics(agent: Any, api_error: Exception) -> None:
+ """Nous 401 that survived a credential refresh: likely Portal OAuth expired/revoked,
+ no credits, or agent key blocked."""
+ from agent.conversation_loop import _print_nous_entitlement_guidance
+ from hermes_constants import display_hermes_home
+ _body_text = ""
+ try:
+ _body = getattr(api_error, "body", None) or getattr(api_error, "response", None)
+ if _body is not None:
+ _body_text = str(_body)[:200]
+ except Exception:
+ pass
+ _plines(agent, "🔐 Nous 401 — Portal authentication failed.")
+ if _body_text:
+ _plines(agent, f" Response: {_body_text}")
+ if not _print_nous_entitlement_guidance(agent, "Nous model access"):
+ _plines(agent, " Most likely: Portal OAuth expired, account out of credits, or agent key revoked.")
+ _plines(
+ agent,
+ " Troubleshooting:",
+ " • Re-authenticate: hermes auth add nous",
+ " • Check credits / billing: https://portal.nousresearch.com",
+ f" • Verify stored credentials: {display_hermes_home()}/auth.json",
+ " • Switch providers temporarily: /model <model> --provider openrouter",
+ )
+
+
+def _print_anthropic_401_diagnostics(agent: Any, key: Any) -> None:
+ """Anthropic 401 that survived a credential refresh: show auth method + fixes."""
+ from agent.anthropic_adapter import _is_oauth_token
+ from agent.azure_identity_adapter import is_token_provider
+ from hermes_constants import display_hermes_home
+ _plines(agent, "🔐 Anthropic 401 — authentication failed.")
+ if is_token_provider(key):
+ # Azure Foundry Entra ID: JWT minted per-request by an httpx hook; 401 = Azure
+ # rejected it (RBAC, az login, IMDS).
+ _plines(
+ agent,
+ " Auth method: Microsoft Entra ID (httpx event hook)",
+ " Run `hermes doctor` for credential-chain diagnostics, or",
+ " `az login` if your developer session expired.",
+ )
+ else:
+ auth_method = "Bearer (OAuth/setup-token)" if _is_oauth_token(key) else "x-api-key (API key)"
+ _plines(
+ agent,
+ f" Auth method: {auth_method}",
+ f" Token prefix: {key[:12]}..." if isinstance(key, str) and len(key) > 12 else " Token: (empty or short)",
+ )
+ _dhh = display_hermes_home()
+ _plines(
+ agent,
+ " Troubleshooting:",
+ f" • Check ANTHROPIC_TOKEN in {_dhh}/.env for Hermes-managed OAuth/setup tokens",
+ f" • Check ANTHROPIC_API_KEY in {_dhh}/.env for API keys or legacy token values",
+ " • For API keys: verify at https://platform.claude.com/settings/keys",
+ " • For Claude Code: run 'claude /login' to refresh, then retry",
+ " • Legacy cleanup: hermes config set ANTHROPIC_TOKEN \"\"",
+ " • Clear stale keys: hermes config set ANTHROPIC_API_KEY \"\"",
+ )
+
+
+def _refresh_credentials_after_401(
+ agent: Any, api_error: Exception, _retry: TurnRetryState, status_code: Optional[int]
+) -> bool:
+ """Per-provider one-shot credential refresh on 401 (codex/xai, vertex, nous, copilot,
+ anthropic), printing user-facing diagnostics when the nous/anthropic refresh fails.
+ Returns True when a refresh succeeded and the call should be retried."""
+ from agent.conversation_loop import _is_copilot_provider
+
+ if status_code != 401:
+ return False
+ if (
+ agent.api_mode == "codex_responses"
+ and agent.provider in {"openai-codex", "xai-oauth"}
+ and not _retry.codex_auth_retry_attempted
+ ):
+ _retry.codex_auth_retry_attempted = True
+ if agent._try_refresh_codex_client_credentials(force=True):
+ _label = "xAI OAuth" if agent.provider == "xai-oauth" else "Codex"
+ agent._buffer_vprint(f"🔐 {_label} auth refreshed after 401. Retrying request...")
+ return True
+ if agent.api_mode == "chat_completions" and agent.provider == "vertex" and not _retry.vertex_auth_retry_attempted:
+ _retry.vertex_auth_retry_attempted = True
+ if agent._try_refresh_vertex_client_credentials():
+ agent._buffer_vprint("🔐 Vertex AI token refreshed after 401. Retrying request...")
+ return True
+ if (
+ agent.api_mode in ("chat_completions", "anthropic_messages")
+ and agent.provider == "nous"
+ and not _retry.nous_auth_retry_attempted
+ ):
+ _retry.nous_auth_retry_attempted = True
+ if agent._try_refresh_nous_client_credentials(force=True):
+ agent._buffer_vprint("🔐 Nous agent key refreshed after 401. Retrying request...")
+ return True
+ _print_nous_401_diagnostics(agent, api_error)
+ if _is_copilot_provider(agent) and not _retry.copilot_auth_retry_attempted:
+ _retry.copilot_auth_retry_attempted = True
+ if agent._try_refresh_copilot_client_credentials():
+ agent._buffer_vprint("🔐 Copilot credentials refreshed after 401. Retrying request...")
+ return True
+ if (
+ agent.api_mode == "anthropic_messages"
+ and hasattr(agent, '_anthropic_api_key')
+ and not _retry.anthropic_auth_retry_attempted
+ ):
+ _retry.anthropic_auth_retry_attempted = True
+ if agent._try_refresh_anthropic_client_credentials():
+ _plines(agent, "🔐 Anthropic credentials refreshed after 401. Retrying request...")
+ return True
+ _print_anthropic_401_diagnostics(agent, agent._anthropic_api_key)
+ return False
+
+def _recover_format_errors(
+ agent: Any, api_error: Exception, classified: Any, _retry: TurnRetryState,
+ messages: List[Dict[str, Any]], api_messages: Any,
+) -> bool:
+ """One-shot format-recovery strips: thinking-signature → invalid-encrypted-content
+ replay disable → native-compaction reject → llama.cpp grammar strip. Returns True when
+ the request was repaired and should be retried."""
+ # Upstream mutation invalidates Anthropic's thinking-block signature (400). Strip
+ # ``reasoning_details`` from ``api_messages`` only, never ``messages`` (state.db).
+ if classified.reason == FailoverReason.thinking_signature and not _retry.thinking_sig_retry_attempted:
+ _retry.thinking_sig_retry_attempted = True
+ _api_stripped = 0
+ for _m in api_messages:
+ if isinstance(_m, dict) and "reasoning_details" in _m:
+ _m.pop("reasoning_details", None)
+ _api_stripped += 1
+ _vlines(agent, "⚠️ Thinking block signature invalid, stripped reasoning_details from api_messages for retry...")
+ logger.warning(
+ "%sThinking block signature recovery: stripped "
+ "reasoning_details from %d api_messages "
+ "(canonical messages unchanged)",
+ agent.log_prefix, _api_stripped,
+ )
+ return True
+
+ # 400 ``invalid_encrypted_content`` on a stale ``codex_reasoning_items`` blob:
+ # disable replay for the session, strip cached items, retry once.
+ if (
+ classified.reason == FailoverReason.invalid_encrypted_content
+ and not _retry.invalid_encrypted_content_retry_attempted
+ and agent.api_mode == "codex_responses"
+ and bool(getattr(agent, "_codex_reasoning_replay_enabled", True))
+ and any(
+ isinstance(_m, dict)
+ and _m.get("role") == "assistant"
+ and isinstance(_m.get("codex_reasoning_items"), list)
+ and _m.get("codex_reasoning_items")
+ for _m in messages
+ )
+ ):
+ _retry.invalid_encrypted_content_retry_attempted = True
+ replay_stats = agent._disable_codex_reasoning_replay(messages)
+ _vlines(
+ agent,
+ f"⚠️ Encrypted reasoning replay was rejected by the provider — "
+ f"disabled replay and stripped {replay_stats['items']} item(s) from "
+ f"{replay_stats['messages']} message(s), retrying...",
+ )
+ logger.warning(
+ "%sInvalid encrypted reasoning recovery: disabled replay and stripped %d items from %d messages",
+ agent.log_prefix, replay_stats["items"], replay_stats["messages"],
+ )
+ return True
+
+ # Structured 400 naming ``context_management``: disable native compaction for the
+ # session, retry once; local compression takes over.
+ if (
+ agent.api_mode == "codex_responses"
+ and not _retry.native_compaction_reject_retry_attempted
+ and bool(getattr(agent, "codex_responses_native_compaction", False))
+ ):
+ from agent.native_compaction import is_native_compaction_rejection
+ if is_native_compaction_rejection(api_error, getattr(api_error, "status_code", None)):
+ _retry.native_compaction_reject_retry_attempted = True
+ agent.codex_responses_native_compaction = False
+ _vlines(
+ agent,
+ "⚠️ Provider rejected native compaction (context_management) — disabled for this session, "
+ "local compression stays active. Retrying...",
+ )
+ logger.warning(
+ "%sNative compaction rejection recovery: disabled "
+ "codex_responses_native for this session and retrying",
+ agent.log_prefix,
+ )
+ return True
+
+ # llama.cpp ``json-schema-to-grammar`` rejects regex escapes and most ``format``
+ # values: strip ``pattern``/``format`` from ``agent.tools``, retry once.
+ if classified.reason == FailoverReason.llama_cpp_grammar_pattern and not _retry.llama_cpp_grammar_retry_attempted:
+ _retry.llama_cpp_grammar_retry_attempted = True
+ try:
+ from tools.schema_sanitizer import strip_pattern_and_format
+ _, _stripped = strip_pattern_and_format(agent.tools)
+ except Exception as _strip_exc: # pragma: no cover — defensive
+ logger.warning("%sllama.cpp grammar recovery: strip helper failed: %s", agent.log_prefix, _strip_exc)
+ _stripped = 0
+ if _stripped:
+ _vlines(agent, f"⚠️ llama.cpp rejected tool schema grammar — stripped {_stripped} pattern/format keyword(s), retrying...")
+ logger.warning(
+ "%sllama.cpp grammar recovery: stripped %d "
+ "pattern/format keyword(s) from tool schemas",
+ agent.log_prefix, _stripped,
+ )
+ return True
+ # Nothing to strip — fall through to normal retry rather than loop on the same error.
+ logger.warning(
+ "%sllama.cpp grammar error but no pattern/format "
+ "keywords to strip — falling through to normal retry",
+ agent.log_prefix,
+ )
+ return False
+
+
+def recover_after_classification(
+ agent: Any, api_error: Exception, classified: Any, _retry: TurnRetryState, *,
+ status_code: Optional[int], error_context: Any, messages: List[Dict[str, Any]],
+ api_messages: Any,
+) -> Tuple[bool, bool]:
+ """One-shot recovery chain that runs AFTER ``classify_api_error`` and before the
+ generic retry path. Order is load-bearing (each branch may ``return`` early):
+ Nous paid-entitlement refresh → credential-pool rotation → image shrink →
+ multimodal-tool-content strip → corrupt-image strip → Anthropic OAuth 1M-beta
+ disable → per-provider 401 credential refresh → format-recovery strips.
+ Returns ``(retry_now, recovered_with_pool)``; the latter feeds the Nous rate-limit guard."""
+ from agent.conversation_loop import _is_nous_inference_route
+
+ if (
+ classified.reason == FailoverReason.billing
+ and _is_nous_inference_route(
+ getattr(agent, "provider", "") or "", getattr(agent, "base_url", "") or ""
+ )
+ and not _retry.nous_paid_entitlement_refresh_attempted
+ ):
+ _retry.nous_paid_entitlement_refresh_attempted = True
+ if _try_refresh_nous_paid_entitlement_credentials(agent):
+ _vlines(agent, "🔐 Nous paid access verified — refreshed runtime credentials and retrying request...")
+ return True, False
+
+ recovered_with_pool, _retry.has_retried_429 = agent._recover_with_credential_pool(
+ status_code=status_code, has_retried_429=_retry.has_retried_429,
+ classified_reason=classified.reason, error_context=error_context,
+ billing_unverified=classified.billing_unverified,
+ )
+ if recovered_with_pool:
+ return True, recovered_with_pool
+
+ # Shrink oversized native image parts in-place and retry once.
+ if classified.reason == FailoverReason.image_too_large and not _retry.image_shrink_retry_attempted:
+ _retry.image_shrink_retry_attempted = True
+ if agent._try_shrink_image_parts_in_messages(
+ api_messages, max_dimension=_image_error_max_dimension(api_error) or 8000
+ ):
+ _vlines(agent, "📐 Image(s) exceeded provider size limit — shrank and retrying...")
+ return True, recovered_with_pool
+ logger.info(
+ "image-shrink recovery: no data-URL image parts found "
+ "or shrink didn't reduce size; surfacing original error."
+ )
+
+ # Strict OpenAI-spec providers 400 on list-type tool content: strip images, mark
+ # (provider, model) no-list-tool-content for the session, retry once.
+ if (
+ classified.reason == FailoverReason.multimodal_tool_content_unsupported
+ and not _retry.multimodal_tool_content_retry_attempted
+ ):
+ _retry.multimodal_tool_content_retry_attempted = True
+ if agent._try_strip_image_parts_from_tool_messages(api_messages):
+ _vlines(agent, "📐 Provider rejected list-type tool content — downgraded screenshots to text and retrying...")
+ return True, recovered_with_pool
+ logger.info(
+ "multimodal-tool-content recovery: no list-type tool "
+ "messages with image parts found; surfacing original error."
+ )
+
++ # Reasoning-mandatory route (Nous Portal / OpenRouter, e.g. GLM-5.3) 400s on
++ # ``reasoning: {enabled: false}``. The catalog guard in the provider profile normally swallows
++ # the disable, but a process that warmed its caps cache before the route flipped keeps sending
++ # it. One-shot: never send a disable again this session (the wire builder omits it → upstream
++ # default thinking), queue a catalog refresh so the guard is right next time, retry.
++ if (
++ classified.reason == FailoverReason.reasoning_mandatory
++ and not _retry.reasoning_mandatory_retry_attempted
++ ):
++ _retry.reasoning_mandatory_retry_attempted = True
++ agent._reasoning_disable_rejected = True
++ try:
++ from hermes_cli.models import refresh_reasoning_caps_async
++ refresh_reasoning_caps_async(agent.provider)
++ except Exception:
++ pass
++ _vlines(agent, f"⚠️ {agent.model} requires reasoning — thinking stays on for this session, retrying...")
++ logger.warning("%sReasoning-mandatory recovery: dropping reasoning disable for %s", agent.log_prefix, agent.model)
++ return True, recovered_with_pool
++
+ # Provider rejected the image bytes; shrinking can't help, so strip image parts.
+ # Strip ONLY the per-call copy: replacing msg["content"] on the shallow api_messages
+ # rows keeps canonical history's images (transient rejection must not erase history).
+ if classified.reason == FailoverReason.image_corrupt:
+ if isinstance(api_messages, list) and _strip_images_from_messages(api_messages):
+ _vlines(agent, "⚠️ Provider rejected a corrupted image — stripped images from the retry payload and retrying...")
+ return True, recovered_with_pool
+ logger.info("image-corrupt recovery: no image parts found to strip; surfacing original error.")
+
+ # Anthropic OAuth subscription rejected the 1M-context beta: disable it for this
+ # session, rebuild the client, retry once. Reactive so capable subscriptions keep 1M.
+ if (
+ classified.reason == FailoverReason.oauth_long_context_beta_forbidden
+ and agent.api_mode == "anthropic_messages"
+ and agent._is_anthropic_oauth
+ and not _retry.oauth_1m_beta_retry_attempted
+ ):
+ _retry.oauth_1m_beta_retry_attempted = True
+ if not getattr(agent, "_oauth_1m_beta_disabled", False):
+ agent._oauth_1m_beta_disabled = True
+ try:
+ agent._anthropic_client.close()
+ except Exception:
+ pass
+ agent._rebuild_anthropic_client()
+ _vlines(agent, "🔕 OAuth subscription doesn't support the 1M-context beta — disabled for this session and retrying...")
+ return True, recovered_with_pool
+
+ if _refresh_credentials_after_401(agent, api_error, _retry, status_code):
+ return True, recovered_with_pool
+
+ if _recover_format_errors(agent, api_error, classified, _retry, messages, api_messages):
+ return True, recovered_with_pool
+ return False, recovered_with_pool
+
+
+def _failed_turn_result(final_response: str, messages: Any, api_call_count: int, error: str) -> Dict[str, Any]:
+ """Base failed-turn result dict shared by the two terminal paths."""
+ return {
+ "final_response": final_response, "messages": messages, "api_calls": api_call_count,
+ "completed": False, "failed": True, "error": error,
+ }
+
+
+def _print_nonretryable_auth_guidance(
+ agent: Any, classified: Any, *, status_code: Optional[int], provider: Any, base_url: Any, model: Any,
+) -> None:
+ """Actionable guidance for a terminal auth / billing error."""
+ from agent.conversation_loop import _print_billing_or_entitlement_guidance, _print_nous_entitlement_guidance
+
+ if classified.reason == FailoverReason.billing and _print_billing_or_entitlement_guidance(
+ agent, capability="model access", provider=provider, base_url=str(base_url),
+ model=model, unverified=classified.billing_unverified,
+ ):
+ return
+ if provider == "nous" and _print_nous_entitlement_guidance(agent, "Nous model access"):
+ return
+ if provider in {"openai-codex", "xai-oauth", "nous"} and status_code == 401:
+ if provider == "openai-codex":
+ _vlines(
+ agent,
+ " 💡 Codex OAuth token was rejected (HTTP 401). Your token may have been",
+ " refreshed by another client (Codex CLI, VS Code). To fix:",
+ " 1. Run `codex` in your terminal to generate fresh tokens.",
+ " 2. Then run `hermes auth` to re-authenticate.",
+ )
+ elif provider == "xai-oauth":
+ _vlines(
+ agent,
+ " 💡 xAI OAuth token was rejected (HTTP 401). To fix:",
+ " re-authenticate with xAI Grok OAuth (SuperGrok / Premium+) from `hermes model`.",
+ )
+ else: # nous
+ _vlines(
+ agent,
+ " 💡 Nous Portal OAuth token was rejected (HTTP 401). Your token may be",
+ " expired, revoked, or your account may be out of credits. To fix:",
+ " 1. Re-authenticate: hermes portal",
+ " 2. Check your portal account: https://portal.nousresearch.com",
+ )
+ # ``:free`` is OpenRouter slug syntax; Nous Portal will reject the model
+ # name even after a successful re-auth.
+ if isinstance(model, str) and model.endswith(":free"):
+ _vlines(
+ agent,
+ f" ⚠️ Note: `{model}` looks like an OpenRouter slug (`:free` suffix).",
+ " Nous Portal won't recognize that model name. Either switch to a",
+ f" Nous catalog model, or run `/model openrouter:{model}` to use OpenRouter.",
+ )
+ return
+ _vlines(
+ agent,
+ " 💡 Your API key was rejected by the provider. Check:",
+ " • Is the key valid? Run: hermes setup",
+ f" • Does your account have access to {model}?",
+ )
+ if base_url_host_matches(str(base_url), "openrouter.ai"):
+ _vlines(agent, " • Check credits: https://openrouter.ai/settings/credits")
+
+
+# Terminal status label per non-retryable reason (default names the HTTP status).
+_NONRETRYABLE_LABELS = {
+ FailoverReason.content_policy_blocked: "Provider safety filter blocked this request",
+ FailoverReason.ssl_cert_verification: "TLS certificate verification failed",
+}
+
+
+def nonretryable_client_error_result(
+ agent: Any, api_error: Exception, classified: Any, *, status_code: Optional[int],
+ api_kwargs: Any, api_messages: Any, messages: List[Dict[str, Any]], conversation_history: Any,
+ api_call_count: int, approx_tokens: int, provider: Any, base_url: Any, model: Any,
+) -> Dict[str, Any]:
+ """Terminal path for a non-retryable 4xx once fallback is exhausted: debug dump, flush
+ the retry trace, print auth / billing / content-policy / TLS guidance, persist (skipped
+ for likely context-overflow 400s so the failure does not grow the session), build result."""
+ # Result/guidance helpers stay in the loop module (tests import + patch them there).
+ from agent.conversation_loop import (
+ _CONTENT_POLICY_RECOVERY_HINT, _billing_failure_result, _content_policy_blocked_result,
+ )
+
+ if api_kwargs is not None:
+ agent._dump_api_request_debug(api_kwargs, reason="non_retryable_client_error", error=api_error)
+ # Terminal — flush buffered context so the user sees what was tried before the abort.
+ agent._flush_status_buffer()
+ # Summarize once: Cloudflare/proxy HTML pages and raw provider bodies must be
+ # collapsed here or they leak verbatim via the ``error`` field.
+ _nonretryable_summary = agent._summarize_api_error(api_error)
+ _label = _NONRETRYABLE_LABELS.get(classified.reason, f"Non-retryable error (HTTP {status_code})")
+ agent._emit_status(f"❌ {_label}: {_nonretryable_summary}")
+ _vlines(
+ agent,
+ f"❌ Non-retryable client error (HTTP {status_code}). Aborting.",
+ f" 🔌 Provider: {provider} Model: {model}",
+ f" 🌐 Endpoint: {base_url}",
+ )
+ if classified.is_auth or classified.reason == FailoverReason.billing:
+ _print_nonretryable_auth_guidance(
+ agent, classified, status_code=status_code, provider=provider, base_url=base_url, model=model
+ )
+ else:
+ _vlines(agent, " 💡 This type of error won't be fixed by retrying.")
+ # Content-policy blocks: the provider refused this prompt, so recovery is a rephrase
+ # or another model, not key/retry advice.
+ if classified.reason == FailoverReason.content_policy_blocked:
+ _vlines(
+ agent,
+ " 💡 The provider's safety filter rejected this specific prompt.",
+ " • Try rephrasing the request, narrowing the context, or splitting into smaller steps.",
+ " • Configure a fallback provider so future blocks route automatically:",
+ " hermes fallback add (interactive picker — same as `hermes model`)",
+ )
+ # TLS certificate failures are environment problems — name the knobs for each cause.
+ if classified.reason == FailoverReason.ssl_cert_verification:
+ _vlines(
+ agent,
+ " 💡 The TLS certificate chain could not be verified. This fails the same",
+ " way on every retry — fix the environment, then try again:",
+ " • Corporate TLS-inspecting proxy? Point Python at its CA bundle:",
+ " export SSL_CERT_FILE=/path/to/corp-ca.pem (also REQUESTS_CA_BUNDLE)",
+ " • Missing/stale system CA store? Install/refresh it:",
+ " pip install --upgrade certifi (macOS: run 'Install Certificates.command')",
+ " • Self-signed local endpoint (llama.cpp, LM Studio, vLLM)? Use http://",
+ " for localhost, or add the server's cert to your trust store.",
+ )
+ logger.error("%sNon-retryable client error: %s", agent.log_prefix, api_error)
+ # Skip persistence on likely context-overflow (400 + large session): persisting the
+ # failed message grows the session and repeats the failure.
+ if status_code == 400 and (approx_tokens > 50000 or len(api_messages) > 80):
+ _vlines(agent, "⚠️ Skipping session persistence for large failed session to prevent growth loop.")
+ else:
+ agent._persist_session(messages, conversation_history)
+ if classified.reason == FailoverReason.content_policy_blocked:
+ _policy_response = (
+ "⚠️ The model provider's safety filter blocked this request "
+ "(not a Hermes/gateway failure).\n\n"
+ f"Provider message: {_nonretryable_summary}\n\n"
+ f"{_CONTENT_POLICY_RECOVERY_HINT}"
+ )
+ return _content_policy_blocked_result(
+ messages, api_call_count, final_response=_policy_response, error_detail=_nonretryable_summary,
+ )
+ # Billing walls get the same structured recovery descriptor as the max-retries path
+ # so every surface renders one consistent signal.
+ if classified.reason == FailoverReason.billing:
+ return _billing_failure_result(
+ classified=classified, summary=_nonretryable_summary, messages=messages,
+ api_call_count=api_call_count, provider=provider, base_url=base_url, model=model,
+ )
+ return _failed_turn_result(_nonretryable_summary, messages, api_call_count, _nonretryable_summary)
+
+
+_STREAM_DROP_MARKERS = (
+ "connection lost", "connection reset", "connection closed", "network connection",
+ "network error", "terminated",
+)
+
+
+def max_retries_exhausted_result(
+ agent: Any, api_error: Exception, classified: Any, *, max_retries: int, is_rate_limited: bool,
+ error_msg: str, api_kwargs: Any, api_messages: Any, messages: List[Dict[str, Any]],
+ conversation_history: Any, api_call_count: int, approx_tokens: int, provider: Any,
+ base_url: Any, model: Any,
+) -> Dict[str, Any]:
+ """Terminal path once retries, transport recovery and fallback all failed: flush the
+ trace, emit the billing / rate-limit / generic status, print stream-drop or thinking-timeout
+ guidance (the latter wins), persist, build the result with ``failure_reason`` /
+ ``failure_retryable`` / ``billing_block``."""
+ # Result/guidance helpers stay in the loop module (tests import + patch them there).
+ from agent.conversation_loop import (
+ _billing_block_dict, _billing_or_entitlement_message, _billing_terminal_label,
+ _print_billing_or_entitlement_guidance,
+ )
+
+ agent._flush_status_buffer()
+ _final_summary = agent._summarize_api_error(api_error)
+ _billing_guidance = ""
+ _is_billing = classified.reason == FailoverReason.billing
+ if _is_billing:
+ if classified.billing_unverified:
+ # Ambiguous body — hedge the terminal line.
+ agent._emit_status(
+ "❌ Provider reported usage/credit exhaustion "
+ f"(unverified — may be a content-filter rejection) — {_final_summary}"
+ )
+ else:
+ agent._emit_status(f"❌ Billing or credits exhausted — {_final_summary}")
+ _billing_kw = dict(
+ capability="model access", provider=provider, base_url=str(base_url), model=model,
+ unverified=classified.billing_unverified,
+ )
+ _billing_guidance = _billing_or_entitlement_message(**_billing_kw)
+ _print_billing_or_entitlement_guidance(agent, **_billing_kw)
+ elif is_rate_limited:
+ agent._emit_status(f"❌ Rate limited after {max_retries} retries — {_final_summary}")
+ else:
+ agent._emit_status(f"❌ API failed after {max_retries} retries — {_final_summary}")
+ _vlines(agent, f" 💀 Final error: {_final_summary}")
+
+ # SSE stream-drop (e.g. "Network connection lost"): usually a proxy/CDN cutting a very
+ # large tool call mid-response.
+ _is_stream_drop = (
+ not getattr(api_error, "status_code", None)
+ and any(p in error_msg for p in _STREAM_DROP_MARKERS)
+ )
+ if _is_stream_drop:
+ _vlines(
+ agent,
+ " 💡 The provider's stream connection keeps dropping. This often happens "
+ "when the model tries to write a very large file in a single tool call.",
+ " Try asking the model to use execute_code with Python's open() for "
+ "large files, or to write the file in smaller sections.",
+ )
+
+ # A known reasoning model hit a transport error before the first content token.
+ # Distinct from _is_stream_drop; detection lives in agent.thinking_timeout_guidance.
+ _is_thinking_timeout = is_thinking_timeout(classified, model, error_msg)
+ if _is_thinking_timeout:
+ _vlines(
+ agent,
+ " 💡 The model's thinking phase exceeded the upstream proxy's idle "
+ "timeout before the first content token arrived. This is a known issue with "
+ "reasoning models behind cloud gateways (NVIDIA NIM, OpenAI, Anthropic, DeepSeek).",
+ " Workarounds in priority order:",
+ f" 1. Set `providers.{provider}.models.{model}.stale_timeout_seconds: 900` "
+ "in `~/.hermes/config.yaml` to extend the per-call timeout. (Hermes's built-in floor is 600s for "
+ "known reasoning models — if you still see this after raising, the upstream cap is even shorter.)",
+ " 2. Lower `reasoning_budget` or set `reasoning_effort: medium` on this model if the provider supports it.",
+ " 3. Use a smaller / faster reasoning model if the task doesn't require deep thinking.",
+ )
+
+ logger.error(
+ "%sAPI call failed after %s retries. %s | provider=%s model=%s msgs=%s tokens=~%s",
+ agent.log_prefix, max_retries, _final_summary,
+ provider, model, len(api_messages), f"{approx_tokens:,}",
+ )
+ if api_kwargs is not None:
+ agent._dump_api_request_debug(api_kwargs, reason="max_retries_exhausted", error=api_error)
+ agent._persist_session(messages, conversation_history)
+ _billing_block = None
+ _billing_unverified = False
+ if _is_billing:
+ _billing_unverified = classified.billing_unverified
+ _final_response = _billing_terminal_label(_final_summary, _billing_unverified)
+ if _billing_guidance:
+ _final_response += f"\n\n{_billing_guidance}"
+ # Structured recovery descriptor so every surface renders the same link + label.
+ _billing_block = _billing_block_dict(
+ provider, base_url, model, _billing_guidance, unverified=_billing_unverified
+ )
+ else:
+ _final_response = f"API call failed after {max_retries} retries: {_final_summary}"
+ if _is_thinking_timeout:
+ # Thinking-timeout guidance overrides stream-drop guidance, which would wrongly
+ # suggest splitting large file writes.
+ _final_response += build_thinking_timeout_guidance(provider=provider, model=model)
+ elif _is_stream_drop:
+ _final_response += (
+ "\n\nThe provider's stream connection keeps "
+ "dropping — this often happens when generating "
+ "very large tool call responses (e.g. write_file "
+ "with long content). Try asking me to use "
+ "execute_code with Python's open() for large "
+ "files, or to write in smaller sections."
+ )
+ result = _failed_turn_result(_final_response, messages, api_call_count, _final_summary)
+ result.update({
+ # Classified reason so callers (kanban worker in cli.py) can tell a quota wall
+ # (``rate_limit`` / ``billing``) from a task failure.
+ "failure_reason": classified.reason.value,
+ # The classifier's own retry verdict — UI surfaces use this, not the reason string.
+ "failure_retryable": bool(classified.retryable),
+ # True when the billing verdict rests on an ambiguous body.
+ "billing_unverified": _billing_unverified,
+ # Present only for billing walls: (provider, billing_url, is_nous, message).
+ "billing_block": _billing_block,
+ })
+ return result
+
+
+def log_api_error_attempt(
+ agent: Any, api_error: Exception, *, retry_count: int, max_retries: int,
+ status_code: Optional[int], elapsed_time: float, api_messages: Any, approx_tokens: int,
+) -> Tuple[str, str, Any, Any, Any]:
+ """Log one failed API attempt (warning + buffered retry trace, OpenRouter "no tool
+ endpoints" hint, bare-404 missing-vendor-prefix hint); the buffer only surfaces if every
+ retry+fallback exhausts. Returns ``(error_type, error_msg, provider, base_url, model)``."""
+ error_type = type(api_error).__name__
+ error_msg = str(api_error).lower()
+ _error_summary = agent._summarize_api_error(api_error)
+ logger.warning(
+ "API call failed (attempt %s/%s) error_type=%s %s summary=%s",
+ retry_count, max_retries, error_type, agent._client_log_context(), _error_summary,
+ )
+
+ _provider = getattr(agent, "provider", "unknown")
+ _base = getattr(agent, "base_url", "unknown")
+ _model = getattr(agent, "model", "unknown")
+ _status_code_str = f" [HTTP {status_code}]" if status_code else ""
+ _blines(
+ agent,
+ f"⚠️ API call failed (attempt {retry_count}/{max_retries}): {error_type}{_status_code_str}",
+ f" 🔌 Provider: {_provider} Model: {_model}",
+ f" 🌐 Endpoint: {_base}",
+ f" 📝 Error: {_error_summary}",
+ )
+ if status_code and status_code < 500:
+ _err_body = getattr(api_error, "body", None)
+ _err_body_str = str(_err_body)[:300] if _err_body else None
+ if _err_body_str:
+ _blines(agent, f" 📋 Details: {_err_body_str}")
+ _blines(agent, f" ⏱️ Elapsed: {elapsed_time:.2f}s Context: {len(api_messages)} msgs, ~{approx_tokens:,} tokens")
+
+ if agent._is_openrouter_url() and "support tool use" in error_msg:
+ _blines(agent, f" 💡 No OpenRouter providers for {_model} support tool calling with your current settings.")
+ if agent.providers_allowed:
+ _blines(
+ agent,
+ " Your provider_routing.only restriction is filtering out tool-capable providers.",
+ " Try removing the restriction or adding providers that support tools for this model.",
+ )
+ _blines(agent, f" Check which providers support tools: https://openrouter.ai/models/{_model}")
+
+ # Bare 404 on a ``vendor/model`` catalogue usually means the id lost its prefix; the
+ # provider never names the model, so we do.
+ if getattr(api_error, "status_code", None) == 404:
+ try:
+ from hermes_cli.model_normalize import suggest_prefixed_model_id
+
+ _suggestion = suggest_prefixed_model_id(_provider, _model)
+ except Exception:
+ _suggestion = None
+ if _suggestion:
+ _blines(
+ agent,
+ f" 💡 Model '{_model}' is not a valid id for provider {_provider} — it is missing its vendor prefix.",
+ f" Did you mean '{_suggestion}'? Re-pick it with `hermes model`.",
+ )
+ return error_type, error_msg, _provider, _base, _model
+
+
+def abort_turn_on_interrupt(
+ agent: Any, messages: List[Dict[str, Any]], conversation_history: Any, api_call_count: int, *,
+ abort_message: str, interrupt_text: str,
+) -> Dict[str, Any]:
+ """Announce ``abort_message``, close any open tool sequence with ``interrupt_text``,
+ persist, clear the interrupt and return the ``interrupted`` result dict."""
+ _vlines(agent, f"⚡ {abort_message}")
+ close_interrupted_tool_sequence(messages, interrupt_text)
+ agent._persist_session(messages, conversation_history)
+ agent.clear_interrupt()
+ return {
+ "final_response": interrupt_text, "messages": messages, "api_calls": api_call_count,
+ "completed": False, "interrupted": True,
+ }
+
+
+def interruptible_backoff_sleep(
+ agent: Any, wait_time: float, _retry: Optional[TurnRetryState], *,
+ messages: List[Dict[str, Any]], conversation_history: Any, api_call_count: int,
+ abort_message: str, interrupt_text: str, activity_label: str,
+) -> Optional[Dict[str, Any]]:
+ """Sleep ``wait_time`` in 200 ms slices so interrupts are honoured promptly, touching
+ activity every ~30 s so the gateway's inactivity monitor knows we are alive.
+
+ On interrupt with ``_retry`` given and a redirect pending: preserve the redirect, arm
+ ``_retry.restart_with_redirected_messages`` and return ``None`` (caller rebuilds the
+ turn). Otherwise return the ``interrupted`` result dict. ``None`` when the wait completed."""
+ sleep_end = time.time() + wait_time
+ _touch_counter = 0
+ while time.time() < sleep_end:
+ if agent._interrupt_requested:
+ if _retry is not None and agent.clear_interrupt(preserve_redirect=True):
+ _retry.restart_with_redirected_messages = True
+ return None
+ return abort_turn_on_interrupt(
+ agent, messages, conversation_history, api_call_count,
+ abort_message=abort_message, interrupt_text=interrupt_text,
+ )
+ time.sleep(0.2)
+ _touch_counter += 1
+ if _touch_counter % 150 == 0: # 150 × 0.2s = 30s
+ agent._touch_activity(f"{activity_label}, {int(sleep_end - time.time())}s remaining")
+ return None
+
+
+_ZAI_POLICY_NOTES = {
+ "zai_coding_overload_long": " (Z.AI Coding overload adaptive long backoff)",
+ "zai_coding_overload_short": " (Z.AI Coding overload short retry)",
+}
+
+
+def compute_error_backoff(
+ agent: Any, api_error: Exception, *, retry_count: int, max_retries: int, is_rate_limited: bool,
+ is_zai_coding_overload: bool, base_url: Any, model: Any,
+) -> float:
+ """Pick the wait before the next API retry and announce it. Retry-After wins for rate
+ limits (capped at 600s: Anthropic Tier 1 buckets reset in ~171s, so a 120s cap re-tripped
+ the limit); otherwise jittered backoff, replaced by the adaptive policy for 429s / Z.AI
+ overloads. Normal retries are buffered; long Z.AI Coding waits surface immediately."""
+ # Resolved through the loop module so tests that patch
+ # ``agent.conversation_loop.jittered_backoff`` / ``adaptive_rate_limit_backoff``
+ # (incl. the run_agent conftest fast-backoff fixture) keep intercepting.
+ from agent.conversation_loop import adaptive_rate_limit_backoff, jittered_backoff
+
+ _retry_after = None
+ _resp_headers = getattr(getattr(api_error, "response", None), "headers", None) if is_rate_limited else None
+ if _resp_headers and hasattr(_resp_headers, "get"):
+ _ra_raw = _resp_headers.get("retry-after") or _resp_headers.get("Retry-After")
+ if _ra_raw:
+ try:
+ _retry_after = min(float(_ra_raw), 600)
+ except (TypeError, ValueError):
+ pass
+ wait_time = _retry_after if _retry_after else jittered_backoff(retry_count, base_delay=2.0, max_delay=60.0)
+ _backoff_policy = None
+ _adaptive = is_rate_limited or is_zai_coding_overload
+ if _adaptive and not _retry_after:
+ wait_time, _backoff_policy = adaptive_rate_limit_backoff(
+ retry_count, base_url=str(base_url), model=model, error=api_error, default_wait=wait_time,
+ )
+ if _adaptive:
+ _policy_note = _ZAI_POLICY_NOTES.get(_backoff_policy or "", "")
+ _wait_reason = "Provider overloaded" if is_zai_coding_overload and not is_rate_limited else "Rate limited"
+ _rate_limit_status = f"⏱️ {_wait_reason}. Waiting {wait_time:.1f}s (attempt {retry_count + 1}/{max_retries}){_policy_note}..."
+ if _backoff_policy == "zai_coding_overload_long":
+ agent._emit_status(_rate_limit_status)
+ else:
+ agent._buffer_status(_rate_limit_status)
+ else:
+ agent._buffer_status(f"⏳ Retrying in {wait_time:.1f}s (attempt {retry_count}/{max_retries})...")
+ logger.warning(
+ "Retrying API call in %ss (attempt %s/%s) %s policy=%s error=%s",
+ wait_time, retry_count, max_retries, agent._client_log_context(),
+ _backoff_policy or "default", api_error,
+ )
+ return wait_time
+
+
+def validate_response_shape(agent: Any, response: Any) -> Tuple[bool, List[str]]:
+ """Validate the raw provider response via the transport; ``(response_invalid,
+ error_details)``. A Codex ``failed``/``cancelled`` status (e.g. quota exhaustion) is
+ invalid so the fallback chain triggers; an empty Codex ``output`` with non-empty
+ ``output_text`` is deferred to normalization."""
+ if agent._get_transport().validate_response(response):
+ return False, []
+ if response is None:
+ return True, ["response is None"]
+ if agent.api_mode == "codex_responses":
+ _codex_resp_status = str(getattr(response, "status", "") or "").strip().lower()
+ if _codex_resp_status in {"failed", "cancelled"}:
+ _codex_error_obj = getattr(response, "error", None)
+ _codex_error_msg = (
+ _codex_error_obj.get("message") if isinstance(_codex_error_obj, dict)
+ else str(_codex_error_obj) if _codex_error_obj
+ else f"Responses API returned status '{_codex_resp_status}'"
+ )
+ logger.warning(
+ "Codex response status='%s' (error=%s). Routing to fallback. %s",
+ _codex_resp_status, _codex_error_msg, agent._client_log_context(),
+ )
+ return True, [f"response.status={_codex_resp_status}: {_codex_error_msg}"]
+ # Stream backfill may have failed but normalize can still recover from output_text.
+ _out_text = getattr(response, "output_text", None)
+ _out_text_stripped = _out_text.strip() if isinstance(_out_text, str) else ""
+ if _out_text_stripped:
+ logger.debug(
+ "Codex response.output is empty but output_text is present "
+ "(%d chars); deferring to normalization.",
+ len(_out_text_stripped),
+ )
+ return False, []
+ logger.warning(
+ "Codex response.output is empty after stream backfill "
+ "(status=%s, incomplete_details=%s, model=%s). %s",
+ getattr(response, "status", None), getattr(response, "incomplete_details", None),
+ getattr(response, "model", None),
+ f"api_mode={agent.api_mode} provider={agent.provider}",
+ )
+ return True, ["response.output is empty"]
+ if agent.api_mode == "anthropic_messages":
+ detail = "response.content invalid (not a non-empty list)"
+ elif agent.api_mode == "bedrock_converse":
+ detail = "Bedrock response invalid (no output or choices)"
+ elif not hasattr(response, 'choices'):
+ detail = "response has no 'choices' attribute"
+ elif response.choices is None:
+ detail = "response.choices is None"
+ else:
+ detail = "response.choices is empty"
+ return True, [detail]
+
+
+def describe_invalid_response(agent: Any, response: Any, api_duration: float) -> Tuple[str, str, str]:
+ """Diagnostics for an empty/malformed response: ``(error_msg, provider_name,
+ failure_hint)``. The hint is derived from the provider error code (524/504/429/
+ 5xx) and the response time, instead of always assuming rate limiting."""
+ error_msg = "Unknown"
+ provider_name = "Unknown"
+ _has_error = bool(response and hasattr(response, 'error') and response.error)
+ if _has_error:
+ error_msg = str(response.error)
+ if hasattr(response.error, 'metadata') and response.error.metadata:
+ provider_name = response.error.metadata.get('provider_name', 'Unknown')
+ elif response and hasattr(response, 'message') and response.message:
+ error_msg = str(response.message)
+
+ # OpenRouter often returns the actual model used.
+ if provider_name == "Unknown" and response and hasattr(response, 'model') and response.model:
+ provider_name = f"model={response.model}"
+
+ if provider_name == "Unknown" and response:
+ resp_attrs = {k: str(v)[:100] for k, v in vars(response).items() if not k.startswith('_')}
+ if agent.verbose_logging:
+ logging.debug(f"Response attributes for invalid response: {resp_attrs}")
+
+ _resp_error_code = None
+ if _has_error:
+ _code_raw = getattr(response.error, 'code', None)
+ if _code_raw is None and isinstance(response.error, dict):
+ _code_raw = response.error.get('code')
+ if _code_raw is not None:
+ try:
+ _resp_error_code = int(_code_raw)
+ except (TypeError, ValueError):
+ pass
+
+ return error_msg, provider_name, _failure_hint_for(_resp_error_code, api_duration)
+
+
+def _failure_hint_for(code: Optional[int], api_duration: float) -> str:
+ """Human-readable hint from the provider error code and response time."""
+ if code == 524:
+ return f"upstream provider timed out (Cloudflare 524, {api_duration:.0f}s)"
+ if code == 504:
+ return f"upstream gateway timeout (504, {api_duration:.0f}s)"
+ if code == 429:
+ return "rate limited by upstream provider (429)"
+ if code in {500, 502}:
+ return f"upstream server error ({code}, {api_duration:.0f}s)"
+ if code in {503, 529}:
+ return f"upstream provider overloaded ({code})"
+ if code is not None:
+ return f"upstream error (code {code}, {api_duration:.0f}s)"
+ if api_duration < 10:
+ return f"fast response ({api_duration:.1f}s) — likely rate limited"
+ if api_duration > 60:
+ return f"slow response ({api_duration:.0f}s) — likely upstream timeout"
+ return f"response time {api_duration:.1f}s"
+
+
+@dataclass
+class ClassifiedErrorVerdict:
+ """Outcome of ``route_classified_error``. ``action``: ``"return"`` (terminal result),
+ ``"break"`` (restart armed on ``_retry``), ``"continue"`` (re-enter the retry loop; Nous
+ guard re-check) or ``"fallthrough"`` (proceed to overflow / client-error / backoff
+ handling). The remaining fields are loop locals the router rebound or computed."""
+
+ action: str
+ result: Optional[Dict[str, Any]]
+ status_code: Optional[int]
+ messages: List[Dict[str, Any]]
+ active_system_prompt: Any
+ conversation_history: Any
+ retry_count: int
+ max_retries: int
+ compression_attempts: int
+ provider_overflow_recovery_pending: bool
+ is_rate_limited: bool
+ wrapped_output_cap_budget: Optional[int]
+ is_zai_coding_overload: bool
+
+
+_OVERFLOW_REASONS = frozenset({
+ FailoverReason.long_context_tier, FailoverReason.payload_too_large, FailoverReason.context_overflow,
+})
+_RATE_LIMIT_REASONS = frozenset({
+ FailoverReason.rate_limit, FailoverReason.billing, FailoverReason.upstream_rate_limit,
+})
+_TRANSPORT_FAILURE_REASONS = frozenset({FailoverReason.timeout, FailoverReason.overloaded})
+
+
+_LONG_CONTEXT_TIER_CAP = 200000
+
+
+def _cap_long_context_tier(agent: Any) -> int:
+ """Cap the compressor's context window at the long-context tier limit; returns the
+ previous ``context_length``."""
+ compressor = agent.context_compressor
+ old_ctx = compressor.context_length
+ if old_ctx > _LONG_CONTEXT_TIER_CAP:
+ compressor.update_model(
+ model=agent.model, context_length=_LONG_CONTEXT_TIER_CAP, base_url=agent.base_url,
+ api_key=getattr(agent, "api_key", ""), provider=agent.provider, api_mode=agent.api_mode,
+ )
+ # Context probing flags exist only on the built-in compressor (plugin engines
+ # manage their own). Don't persist — a tier limit, not a model capability;
+ # 1M should return if extra usage is enabled.
+ if hasattr(compressor, "_context_probed"):
+ compressor._context_probed = True
+ compressor._context_probe_persistable = False
+ agent._buffer_vprint(
+ f"⚠️ Anthropic long-context tier "
+ f"requires extra usage — reducing context: "
+ f"{old_ctx:,} → {_LONG_CONTEXT_TIER_CAP:,} tokens"
+ )
+ return old_ctx
+
+
+def _eager_fallback_status(classified: Any, is_upstream: bool, is_transport_failure: bool) -> str:
+ """Status line announcing an eager fallback switch."""
+ if is_upstream:
+ _upstream_name = (classified.error_context or {}).get("upstream_provider", "aggregator")
+ return f"⚠️ Upstream {_upstream_name} rate-limited — switching to fallback model..."
+ if classified.reason == FailoverReason.billing:
+ if classified.billing_unverified:
+ # Ambiguous body — don't assert billing.
+ return (
+ "⚠️ Provider reported usage/credit exhaustion "
+ "(unverified — may be a content-filter rejection) "
+ "— switching to fallback provider..."
+ )
+ return "⚠️ Billing or credits exhausted — switching to fallback provider..."
+ if is_transport_failure:
+ return "⚠️ Provider unreachable — switching to fallback provider..."
+ return "⚠️ Rate limited — switching to fallback provider..."
+
+
+def _is_genuine_nous_rate_limit(agent: Any, api_error: Exception, error_context: Any) -> bool:
+ """Record a genuine account-level Nous 429 to the cross-session breaker; upstream
+ capacity 429s (no exhausted bucket in headers or last-known state) are left alone."""
+ _genuine = False
+ try:
+ from agent.nous_rate_guard import is_genuine_nous_rate_limit, record_nous_rate_limit
+ _err_resp = getattr(api_error, "response", None)
+ _err_hdrs = getattr(_err_resp, "headers", None) if _err_resp else None
+ _genuine = is_genuine_nous_rate_limit(headers=_err_hdrs, last_known_state=agent._rate_limit_state)
+ if _genuine:
+ record_nous_rate_limit(headers=_err_hdrs, error_context=error_context)
+ else:
+ logger.info(
+ "Nous 429 looks like upstream capacity "
+ "(no exhausted bucket in headers or "
+ "last-known state) -- not tripping "
+ "cross-session breaker."
+ )
+ except Exception:
+ pass
+ return _genuine
+
+
+def route_classified_error(
+ agent: Any, api_error: Exception, classified: Any, _retry: TurnRetryState, *, error_msg: str,
+ error_context: Any, recovered_with_pool: bool, base_url: Any, model: Any,
+ messages: List[Dict[str, Any]], api_messages: Any, system_message: Any,
+ active_system_prompt: Any, conversation_history: Any, retry_count: int, max_retries: int,
+ compression_attempts: int, max_compression_attempts: int, api_call_count: int,
+ effective_task_id: Any,
+) -> ClassifiedErrorVerdict:
+ """Ordered (load-bearing) recovery steps between classification and overflow handling:
+ compaction-disabled overflow → terminal error (output-cap errors exempt); Anthropic
+ long-context tier 429 → cap at 200k and compress; eager fallback for rate-limit/billing
+ (immediately) and transport failures (after 1 retry) unless credential-pool rotation may
+ still recover (upstream-aggregator 429s always fall back); persistent 401/403 → fallback
+ chain once; genuine Nous 429 → cross-session breaker + re-enter the loop exactly once."""
+ from agent.conversation_loop import (
+ _arm_fallback_restart, _ra, conversation_history_after_compression,
+ estimate_request_tokens_rough,
+ )
+
+ _provider_overflow_recovery_pending = False
+ is_rate_limited = False
+ _wrapped_output_cap_budget = None
+ _is_zai_coding_overload = False
+ status_code = getattr(api_error, "status_code", None)
+
+ def _verdict(action: str, result: Optional[Dict[str, Any]] = None) -> ClassifiedErrorVerdict:
+ return ClassifiedErrorVerdict(
+ action=action, result=result, status_code=status_code, messages=messages,
+ active_system_prompt=active_system_prompt, conversation_history=conversation_history,
+ retry_count=retry_count, max_retries=max_retries,
+ compression_attempts=compression_attempts,
+ provider_overflow_recovery_pending=_provider_overflow_recovery_pending,
+ is_rate_limited=is_rate_limited, wrapped_output_cap_budget=_wrapped_output_cap_budget,
+ is_zai_coding_overload=_is_zai_coding_overload,
+ )
+
+ def _fallback_break() -> ClassifiedErrorVerdict:
+ nonlocal active_system_prompt, retry_count, compression_attempts
+ active_system_prompt = _arm_fallback_restart(agent, api_messages, active_system_prompt, _retry)
+ retry_count = 0
+ compression_attempts = 0
+ return _verdict("break")
+
+ # ``compression.enabled: false`` forbids every automatic trigger, incl. these
+ # overflow recovery paths; error out. Output-cap errors exempt.
+ _is_output_cap_error = (
+ is_output_cap_error(error_msg) or parse_available_output_tokens_from_error(error_msg) is not None
+ )
+ if (
+ classified.reason in _OVERFLOW_REASONS
+ and not getattr(agent, "compression_enabled", True)
+ and not _is_output_cap_error
+ ):
+ agent._flush_status_buffer()
+ _vlines(
+ agent,
+ "❌ Context overflow, but auto-compaction is disabled (compression.enabled: false).",
+ " 💡 Run /compress to compact manually, /new to start fresh, "
+ "switch to a larger-context model, or reduce attachments.",
+ )
+ logger.error(
+ f"{agent.log_prefix}Context overflow ({classified.reason.value}) with "
+ f"auto-compaction disabled — not compressing."
+ )
+ agent._persist_session(messages, conversation_history)
+ _final_response = (
+ "Context overflow and auto-compaction is disabled "
+ "(compression.enabled: false). Run /compress to compact manually, "
+ "/new to start fresh, or switch to a larger-context model."
+ )
+ return _verdict("return", {
+ "final_response": _final_response, "messages": messages, "completed": False,
+ "api_calls": api_call_count, "error": _final_response, "partial": True, "failed": True,
+ "compaction_disabled": True,
+ })
+
+ # Anthropic 429 "Extra usage is required for long context requests" is a
+ # subscription-tier limit, not transient: cap at 200k and compress.
+ if classified.reason == FailoverReason.long_context_tier:
+ old_ctx = _cap_long_context_tier(agent)
+ compression_attempts += 1
+ if compression_attempts <= max_compression_attempts:
+ original_len = len(messages)
+ # Overhead-aware request size so recovery arms on the true request
+ # (msgs + tools + system), not the tool-blind message count.
+ messages, active_system_prompt = agent._compress_context(
+ messages, system_message,
+ approx_tokens=estimate_request_tokens_rough(api_messages, tools=agent.tools or None),
+ task_id=effective_task_id,
+ )
+ conversation_history = conversation_history_after_compression(agent, messages, conversation_history)
+ if len(messages) < original_len or old_ctx > _LONG_CONTEXT_TIER_CAP:
+ agent._buffer_status(
+ COMPRESSION_RETRY_CONTEXT_REDUCED_STATUS_TEMPLATE.format(
+ new_ctx=_LONG_CONTEXT_TIER_CAP, old_ctx=old_ctx
+ )
+ )
+ time.sleep(2)
+ # Provider proved the request doesn't fit the reduced window; row count
+ # isn't proof the rebuilt one does. Recheck before the next call.
+ _provider_overflow_recovery_pending = True
+ _retry.restart_with_compressed_messages = True
+ return _verdict("break")
+ # Compression exhausted or didn't help: fall through to normal error handling.
+
+ # Eager fallback: rate-limit/billing switch immediately (primary won't recover in
+ # the retry window); transport errors get 1 retry first.
+ is_rate_limited = classified.reason in _RATE_LIMIT_REASONS
+ # Some relays wrap upstream output-cap 400s as 429 (rate_limit). Only the max_tokens
+ # clamp fixes it. Parsed once; gates the eager-fallback exemption and overflow entry.
+ _wrapped_output_cap_budget = (
+ parse_available_output_tokens_from_error(error_msg)
+ if classified.reason == FailoverReason.rate_limit else None
+ )
+ _is_transport_failure = classified.reason in _TRANSPORT_FAILURE_REASONS
+ # Z.AI overload 429s classify `overloaded`, which `is_rate_limited` excludes. Detect
+ # directly so the long backoff runs, and raise the ceiling to reach it.
+ _is_zai_coding_overload = is_zai_coding_overload_error(base_url=str(base_url), model=model, error=api_error)
+ if _is_zai_coding_overload:
+ max_retries = max(max_retries, zai_coding_overload_retry_ceiling())
+ _should_fallback = (
+ (is_rate_limited and _wrapped_output_cap_budget is None)
+ or (_is_transport_failure and retry_count >= 2)
+ )
+ if _should_fallback and agent._fallback_index < len(agent._fallback_chain):
+ # No eager fallback while credential pool rotation may recover. Exception: an
+ # upstream-aggregator 429 — the pool can't help, always fall back.
+ _is_upstream = classified.reason == FailoverReason.upstream_rate_limit
+ pool_may_recover = (
+ False if _is_upstream else _ra()._pool_may_recover_from_rate_limit(agent._credential_pool)
+ )
+ if not pool_may_recover:
+ agent._buffer_status(_eager_fallback_status(classified, _is_upstream, _is_transport_failure))
+ if agent._try_activate_fallback(reason=classified.reason):
+ return _fallback_break()
+
+ # A 401/403 surviving credential refresh means a broken credential or endpoint:
+ # escalate to the fallback chain once; False -> terminal handling.
+ if (
+ classified.is_auth
+ and not _retry.auth_failover_attempted
+ and agent._fallback_index < len(agent._fallback_chain)
+ ):
+ _retry.auth_failover_attempted = True
+ agent._buffer_status(
+ "🔐 Authentication failed and could not be refreshed — "
+ "switching to fallback provider..."
+ )
+ if agent._try_activate_fallback(reason=classified.reason):
+ return _fallback_break()
+
+ # Nous Portal: a genuine account-level 429 is recorded to a shared file so ALL
+ # sessions back off; is_genuine_nous_rate_limit excludes upstream 429s.
+ if (
+ is_rate_limited
+ and agent.provider == "nous"
+ and classified.reason == FailoverReason.rate_limit
+ and not recovered_with_pool
+ and _is_genuine_nous_rate_limit(agent, api_error, error_context)
+ ):
+ # Re-enter the loop exactly once so the top-of-loop Nous guard runs
+ # (retry_count = max_retries would skip it entirely).
+ retry_count = max(0, max_retries - 1)
+ return _verdict("continue")
+ # Upstream capacity 429: normal retry logic will typically succeed.
+ return _verdict("fallthrough")
diff --cc hermes_cli/models.py
index 5849ac3ca03,4207e962ea9..68175056250
--- a/hermes_cli/models.py
+++ b/hermes_cli/models.py
@@@ -25,93 -26,8 +25,94 @@@ if TYPE_CHECKING
from typing import TypeGuard
from hermes_cli import __version__ as _HERMES_VERSION
-from hermes_cli.urllib_security import open_credentialed_url, url_origin
-from utils import atomic_json_write, base_url_host_matches
+from hermes_cli.urllib_security import open_credentialed_url
+from hermes_cli.models_catalog_static import ( # noqa: F401 (re-exported; tests patch hermes_cli.models.<name>)
+ CANONICAL_PROVIDERS,
+ OPENROUTER_MODELS,
+ PREFERRED_SILENT_DEFAULT_MODEL,
+ PROVIDER_GROUPS,
+ ProviderEntry,
+ VERCEL_AI_GATEWAY_MODELS,
+ _AGGREGATOR_PROVIDERS,
+ _AZURE_FOUNDRY_RESPONSES_PREFIXES,
+ _BORROWED_MODEL_PROVIDERS,
+ _COPILOT_MODEL_ALIASES,
+ _KEYLESS_STABLE_CACHE_PROVIDERS,
+ _LIVE_FIRST_PICKER_PROVIDERS,
+ _MODELS_DEV_PREFERRED,
+ _OPENAI_FAST_MODE_PREFIXES,
+ _OPENROUTER_VARIANT_SUFFIXES,
+ _PROVIDER_ALIASES,
+ _PROVIDER_LABELS,
+ _PROVIDER_MODELS,
+ _PROVIDER_RETIRED_ALIASES,
+ _SILENT_DEFAULT_PROVIDERS,
+ _xai_finalize_catalog,
+ group_providers,
+ provider_group_for_slug)
+from hermes_cli.models_reasoning_caps import ( # noqa: F401 (re-exported; tests patch hermes_cli.models.<name>)
+ _OPENROUTER_CATALOG_URL,
+ _read_reasoning_caps_disk,
+ _reasoning_caps_disk_path,
+ _save_reasoning_caps_disk,
+ _seed_reasoning_caps,
+ nous_catalog_url,
+ nous_model_reasoning_capabilities,
+ openrouter_model_reasoning_capabilities,
+ parse_openrouter_reasoning_capabilities,
++ refresh_reasoning_caps_async,
+ warm_nous_reasoning_caps_async,
+ warm_openrouter_reasoning_caps_async)
+from hermes_cli.models_local import ( # noqa: F401 (re-exported; tests patch hermes_cli.models.<name>)
+ LMStudioLoadResult,
+ _OLLAMA_LOCAL_MODELS_CACHE,
+ _OLLAMA_LOCAL_MODELS_CACHE_TTL,
+ _OLLAMA_LOCAL_PROBE_FAILURE_CACHE,
+ _OLLAMA_LOCAL_PROBE_REACHABLE,
+ _get_ollama_base_url,
+ _get_ollama_native_headers,
+ _get_ollama_request_headers,
+ _lmstudio_fetch_raw_models,
+ _lmstudio_server_root,
+ _normalize_openai_base_url,
+ _ollama_local_catalog,
+ _ollama_probe_cache_key,
+ _root_for_ollama_native_api,
+ _same_ollama_native_root,
+ _strip_ollama_cloud_suffix,
+ ensure_lmstudio_model_loaded,
+ fetch_lmstudio_models,
+ fetch_ollama_cloud_models,
+ fetch_ollama_local_models,
+ lmstudio_model_reasoning_options,
+ ollama_model_supports_thinking,
+ probe_lmstudio_models,
+ probe_ollama_local_models,
+ should_use_ollama_native_catalog)
+from hermes_cli.models_pricing import ( # noqa: F401 (re-exported; tests patch hermes_cli.models.<name>)
+ _FAILED_CATALOG_TTL_SECONDS,
+ _NOUS_CATALOG_TTL_SECONDS,
+ _NOUS_POLICY_APPEND_MAX,
+ _cache_catalog,
+ _cached_catalog,
+ _fetch_deepinfra_pricing,
+ _fetch_novita_pricing,
+ _format_price_per_mtok,
+ _pricing_auth_fingerprint,
+ _pricing_cache,
+ _pricing_cache_retry_after,
+ _resolve_nous_pricing_credentials,
+ compute_sale_discount,
+ fetch_ai_gateway_pricing,
+ fetch_models_with_pricing,
+ _pricing_provider_cache_keys,
+ get_cached_nous_inference_base_url,
+ get_pricing_for_provider,
+ nous_policy_allowed_ids,
+ peek_cached_pricing,
+ pricing_cache_scope,
+ restrict_to_nous_policy)
+from hermes_cli.models_validate import validate_requested_model # noqa: F401 (re-exported)
logger = logging.getLogger(__name__)
diff --cc hermes_cli/models_reasoning_caps.py
index 5d7738d6225,00000000000..7df6de89245
mode 100644,000000..100644
--- a/hermes_cli/models_reasoning_caps.py
+++ b/hermes_cli/models_reasoning_caps.py
@@@ -1,272 -1,0 +1,286 @@@
+"""Per-model reasoning capabilities from OpenRouter-schema ``/v1/models`` catalogs.
+
+Split out of ``hermes_cli.models``; every public/patched name is re-imported there. OpenRouter and
+Nous Portal share one implementation parametrized by :class:`_CapsSource`; the per-source module
+globals (``_openrouter_reasoning_caps_cache``, ``_nous_caps_disk_checked``, ...) stay defined on
+``hermes_cli.models`` — tests reset them there — and are read/written by attribute name.
+
+Tri-state contract for callers deciding whether to emit reasoning controls: a dict with
+``supports_reasoning: True`` (+ ``supported_efforts``, ``mandatory``) — the route advertises
+reasoning controls; ``supports_reasoning: False`` — the catalog knows the model and it does NOT
+accept them (definitive negative); ``None`` — unknown (catalog not loaded, model not listed,
+malformed).
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import os
+import threading
+import time
+import urllib.request
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, Callable, Optional
+
+
+logger = logging.getLogger("hermes_cli.models")
+
+Caps = dict[str, Optional[dict[str, Any]]]
+
+
+def _origin():
+ from hermes_cli import models
+ return models
+
+
+def parse_openrouter_reasoning_capabilities(item: Any) -> Optional[dict[str, Any]]:
+ """Normalize one OpenRouter catalog entry's reasoning metadata.
+
+ ``supported_parameters`` contains ``"reasoning"`` when the route accepts reasoning controls at
+ all; a top-level ``reasoning`` object may add ``mandatory`` / ``supported_efforts``. A missing
+ or malformed ``supported_parameters`` is "unknown" (None), like ``_openrouter_model_supports_tools``.
+ """
+ if not isinstance(item, dict):
+ return None
+ params = item.get("supported_parameters")
+ if not isinstance(params, list):
+ return None
+ if "reasoning" not in params:
+ return {"supports_reasoning": False}
+ reasoning = item.get("reasoning")
+ if not isinstance(reasoning, dict):
+ reasoning = {}
+ raw_efforts = reasoning.get("supported_efforts")
+ efforts: Optional[list[str]] = None
+ if isinstance(raw_efforts, list):
+ efforts = list(dict.fromkeys(str(e).strip().lower() for e in raw_efforts if str(e).strip()))
+ return {"supports_reasoning": True, "supported_efforts": efforts, "mandatory": reasoning.get("mandatory") is True}
+
+
+# ── Disk mirror ────────────────────────────────────────────────────────
+#
+# In-process caches are always cold in a short-lived process, and every consumer is on a hot path
+# that must never block on HTTP — so without a disk copy, `hermes -p`, a cron job, or a freshly
+# booted gateway answers "capability unknown" for its whole first turn. One file holds every
+# catalog keyed by URL: OpenRouter and the Portal list different models, and a staging Portal must
+# not answer for production.
+_REASONING_CAPS_DISK_TTL_SECONDS = 24 * 3600
+
+
+def _reasoning_caps_disk_path() -> Path:
+ from hermes_constants import get_hermes_home
+ return get_hermes_home() / "cache" / "reasoning_caps.json"
+
+
+def _read_reasoning_caps_disk() -> dict[str, Any]:
+ from hermes_cli.models import _read_json_cache
+ return _read_json_cache(_reasoning_caps_disk_path()) or {}
+
+
+def _load_reasoning_caps_disk(url: str) -> tuple[Optional[Caps], float]:
+ """Return ``(caps, age_seconds)`` for *url*, or ``(None, 0.0)``."""
+ entry = _origin()._read_reasoning_caps_disk().get(url)
+ caps = entry.get("caps") if isinstance(entry, dict) else None
+ if not isinstance(caps, dict) or not caps:
+ return None, 0.0
+ try:
+ age = max(0.0, time.time() - float(entry.get("ts") or 0))
+ except (TypeError, ValueError):
+ age = float(_REASONING_CAPS_DISK_TTL_SECONDS)
+ return {str(mid): model_caps for mid, model_caps in caps.items()}, age
+
+
+def _save_reasoning_caps_disk(url: str, caps: Caps) -> None:
+ """Merge *url*'s catalog into the shared disk mirror, atomically."""
+ from hermes_cli.models import _write_json_cache
+ try:
+ data = _origin()._read_reasoning_caps_disk()
+ data[url] = {"ts": time.time(), "caps": caps}
+ _write_json_cache(_reasoning_caps_disk_path(), data, indent=0, separators=(",", ":"))
+ except Exception as exc:
+ logger.debug("Failed to save reasoning-caps disk cache: %s", exc)
+
+
+def _warm_reasoning_caps_async(refresh) -> None:
+ """Run *refresh* in a daemon thread (fire-and-forget) so a cold/stale cache is warm for the
+ next call or, via the disk mirror, the next process without this turn blocking on HTTP.
+ Callers own the once-per-process guard; the fetch keeps its own failure TTL."""
+ if os.environ.get("PYTEST_CURRENT_TEST"):
+ return
+ threading.Thread(target=refresh, name="reasoning-caps-warm", daemon=True).start()
+
+
+def _hydrate_reasoning_caps_from_disk(url: str, refresh) -> Optional[Caps]:
+ """The disk copy of *url*'s catalog, queueing *refresh* when it's stale. A copy past its TTL is
+ still returned — a stale verdict beats no verdict, and capabilities change rarely."""
+ caps, age = _load_reasoning_caps_disk(url)
+ if caps is not None and age >= _REASONING_CAPS_DISK_TTL_SECONDS:
+ _warm_reasoning_caps_async(refresh)
+ return caps
+
+
+def _seed_reasoning_caps(url: str, items: Any) -> Optional[Caps]:
+ """Parse a ``/v1/models`` ``data`` array and mirror it for *url*.
+
+ Takes the payload rather than fetching it, so picker and pricing fetches (same document) leave
+ the mirror warm at no network cost. None when the array has no usable entries — callers
+ remember that as a failure rather than caching empty.
+ """
+ if not isinstance(items, list):
+ return None
+ caps_by_id: Caps = {}
+ for item in items:
+ mid = str(item.get("id") or "").strip() if isinstance(item, dict) else ""
+ if mid:
+ caps_by_id[mid] = parse_openrouter_reasoning_capabilities(item)
+ if not caps_by_id:
+ return None
+ _save_reasoning_caps_disk(url, caps_by_id)
+ return caps_by_id
+
+
+def _fetch_reasoning_caps_catalog(url: str, timeout: float) -> Optional[Caps]:
+ """Fetch one OpenRouter-shaped ``/v1/models`` catalog → per-model caps; None when unreachable or
+ empty so callers remember the failure. Sends a User-Agent: the Portal 403s anonymous reads."""
+ m = _origin()
+ try:
+ req = urllib.request.Request(url, headers={"Accept": "application/json", "User-Agent": m._HERMES_USER_AGENT})
+ with m._urlopen_model_catalog_request(req, timeout=timeout) as resp:
+ payload = json.loads(resp.read().decode())
+ except Exception:
+ return None
+ return _seed_reasoning_caps(url, payload.get("data"))
+
+
+# ── Per-source cache (OpenRouter, Nous Portal) ─────────────────────────
+
+@dataclass(frozen=True)
+class _CapsSource:
+ """One catalog's cache slots on ``hermes_cli.models`` plus how to name its URL.
+
+ ``cache``: model id → parsed caps from one full-catalog fetch, kept for the process lifetime.
+ ``failed_at``: monotonic timestamp of the last FAILED fetch; suppresses re-fetch storms from
+ per-turn callers for 60s (mirrors the LM Studio/Ollama probe caching). ``disk_checked`` /
+ ``warm_started``: once-per-process guards for the disk hydrate and the background warm.
+ """
+ cache: str
+ failed_at: str
+ disk_checked: str
+ warm_started: str
+ url: Callable[[], str]
+
+ def get(self, slot: str):
+ return getattr(_origin(), getattr(self, slot))
+
+ def set(self, slot: str, value) -> None:
+ setattr(_origin(), getattr(self, slot), value)
+
+
+def _fetch_caps(src: _CapsSource, timeout: float = 6.0, *, force: bool = False) -> Optional[Caps]:
+ """Fetch + cache the source's per-model caps. None (without poisoning the cache) when
+ unreachable, so callers retry later and fall back meanwhile."""
+ cached = src.get("cache")
+ if cached is not None and not force:
+ return cached
+ failed_at = src.get("failed_at")
+ if failed_at is not None and (time.monotonic() - failed_at) < 60:
+ return None
+ caps_by_id = _fetch_reasoning_caps_catalog(src.url(), timeout)
+ if caps_by_id is None:
+ src.set("failed_at", time.monotonic())
+ return None
+ src.set("cache", caps_by_id)
+ return caps_by_id
+
+
+def _caps_cached(src: _CapsSource) -> Optional[Caps]:
+ """Cache-only caps: memory, else the disk mirror. Never HTTP.
+
+ One disk attempt per process: for the Portal, naming the catalog means resolving credentials,
+ which can itself reach the network to refresh a token — too expensive for a per-turn caller.
+ """
+ if src.get("cache") is None and not src.get("disk_checked"):
+ src.set("disk_checked", True)
+ src.set("cache", _hydrate_reasoning_caps_from_disk(src.url(), lambda: _fetch_caps(src, force=True)))
+ return src.get("cache")
+
+
+def _model_caps(src: _CapsSource, model_id: Optional[str], *, timeout: float, allow_fetch: bool) -> Optional[dict[str, Any]]:
+ model = str(model_id or "").strip()
+ if not model:
+ return None
+ caps_by_id = _caps_cached(src)
+ if caps_by_id is None and allow_fetch:
+ caps_by_id = _fetch_caps(src, timeout=timeout)
+ return caps_by_id.get(model) if caps_by_id is not None else None
+
+
+def _warm_caps_async(src: _CapsSource) -> None:
+ if src.get("warm_started") or _caps_cached(src) is not None:
+ return
+ src.set("warm_started", True)
+ _warm_reasoning_caps_async(lambda: _fetch_caps(src, force=True))
+
+
++def refresh_reasoning_caps_async(provider: Optional[str]) -> None:
++ """Force a background re-fetch of *provider*'s reasoning-capability catalog.
++
++ The in-memory cache is otherwise held for the process lifetime, so a route that flips to
++ reasoning-mandatory mid-process (GLM-5.3-flash, Sep 2026) keeps being sent disables it now
++ rejects. Called from the conversation loop's reasoning_mandatory recovery so the profile guard
++ is right again on the next request; no-op for providers without a catalog.
++ """
++ src = {"nous": _NOUS_CAPS, "nous-portal": _NOUS_CAPS, "nousresearch": _NOUS_CAPS,
++ "openrouter": _OPENROUTER_CAPS}.get(str(provider or "").strip().lower())
++ if src is not None:
++ _warm_reasoning_caps_async(lambda: _fetch_caps(src, force=True))
++
++
+_OPENROUTER_CATALOG_URL = "https://openrouter.ai/api/v1/models"
+
+_OPENROUTER_CAPS = _CapsSource(
+ "_openrouter_reasoning_caps_cache", "_openrouter_reasoning_caps_failed_at",
+ "_openrouter_caps_disk_checked", "_openrouter_caps_warm_started",
+ lambda: _OPENROUTER_CATALOG_URL,
+)
+# Nous Portal serves OpenRouter's catalog schema, so the same parser and contract apply. Its own
+# cache because the two catalogs list different models (and different capabilities for shared ids).
+_NOUS_CAPS = _CapsSource(
+ "_nous_reasoning_caps_cache", "_nous_reasoning_caps_failed_at",
+ "_nous_caps_disk_checked", "_nous_caps_warm_started",
+ lambda: _origin().nous_catalog_url(),
+)
+
+
+def nous_catalog_url() -> str:
+ """The Portal ``/v1/models`` URL for the endpoint we actually talk to (``NOUS_INFERENCE_BASE_URL``
+ → resolved credential base → prod), so a staging profile reads staging's capabilities."""
+ return f"{_origin()._resolve_nous_pricing_credentials()[1]}/v1/models"
+
+
+def openrouter_model_reasoning_capabilities(
+ model_id: Optional[str], *, timeout: float = 6.0, allow_fetch: bool = False,
+) -> Optional[dict[str, Any]]:
+ """Live-catalog reasoning capabilities for an OpenRouter model (tri-state, see module doc).
+ CACHE-ONLY by default — safe on per-request hot paths (never blocks on HTTP)."""
+ return _model_caps(_OPENROUTER_CAPS, model_id, timeout=timeout, allow_fetch=allow_fetch)
+
+
+def nous_model_reasoning_capabilities(
+ model_id: Optional[str], *, timeout: float = 6.0, allow_fetch: bool = False,
+) -> Optional[dict[str, Any]]:
+ """Nous Portal counterpart of :func:`openrouter_model_reasoning_capabilities`; warm the cache
+ with :func:`warm_nous_reasoning_caps_async` from hot paths."""
+ return _model_caps(_NOUS_CAPS, model_id, timeout=timeout, allow_fetch=allow_fetch)
+
+
+def warm_openrouter_reasoning_caps_async() -> None:
+ """Warm the OpenRouter reasoning-capability cache in the background."""
+ _warm_caps_async(_OPENROUTER_CAPS)
+
+
+def warm_nous_reasoning_caps_async() -> None:
+ """Nous Portal counterpart of :func:`warm_openrouter_reasoning_caps_async`."""
+ _warm_caps_async(_NOUS_CAPS)
diff --cc plugins/model-providers/openrouter/__init__.py
index 391167b4090,3ae39250ff8..44bdd4b4f18
--- a/plugins/model-providers/openrouter/__init__.py
+++ b/plugins/model-providers/openrouter/__init__.py
@@@ -46,15 -50,28 +46,26 @@@ class OpenRouterProfile(ProviderProfile
"""OpenRouter aggregator — provider preferences, reasoning config passthrough."""
@staticmethod
- def _clamp_reasoning_to_catalog(cfg: dict[str, Any], model: str | None) -> dict[str, Any]:
- """Clamp ``cfg["effort"]`` to the nearest LOWER catalog-advertised level. No-op when the
- catalog is unreachable, the model is unlisted, or no supported_efforts list is published."""
+ def _clamp_reasoning_to_catalog(cfg: dict[str, Any], model: str | None) -> dict[str, Any] | None:
+ """Clamp ``cfg["effort"]`` to the model's catalog-advertised levels.
+
+ Returns None when the config is a disable and the catalog marks the
+ route reasoning-mandatory (the caller omits the field).
+
+ OpenRouter's /v1/models entries publish ``reasoning.supported_efforts``
+ per model (ported from PrimeIntellect-ai/prime-agent#1258). Sending an
+ unsupported effort (e.g. ``ultra`` to a route that stops at ``high``)
+ yields provider 4xx errors; clamp to the nearest LOWER supported level
+ instead. No-op when the catalog is unreachable, the model is unlisted,
+ or no supported_efforts list is published (None = all levels accepted).
+ """
effort = cfg.get("effort")
- if not effort or cfg.get("enabled") is False:
+ disabled = cfg.get("enabled") is False or effort == "none"
+ if not effort and not disabled:
return cfg
try:
- from hermes_cli.models import (
- clamp_reasoning_effort_to_supported,
- openrouter_model_reasoning_capabilities,
- )
+ from hermes_cli.models import clamp_reasoning_effort_to_supported, openrouter_model_reasoning_capabilities
+
caps = openrouter_model_reasoning_capabilities(model)
if not caps or not caps.get("supports_reasoning"):
return cfg
@@@ -126,13 -221,29 +144,17 @@@
if cfg.get("enabled", True) is not False and effort and effort != "none":
top_level["verbosity"] = effort
elif reasoning_config is not None:
- extra_body["reasoning"] = self._clamp_reasoning_to_catalog(dict(reasoning_config), model)
+ clamped = self._clamp_reasoning_to_catalog(
+ dict(reasoning_config), model
+ )
+ if clamped is not None:
+ extra_body["reasoning"] = clamped
else:
extra_body["reasoning"] = {"enabled": True, "effort": "medium"}
-
- # Same resolution as build_extra_body: xAI's prompt cache is pinned per
- # backend server via this header, and aux calls pass no session_id, so
- # reading the ambient conversation keeps compression/vision/MoA traffic
- # on the same Grok backend as the conversation it belongs to.
- grok_conv_id = _cache_scope_from_session_id(
- get_affinity_scope() or get_conversation_context() or session_id
- )
+ # xAI's prompt cache is pinned per backend server via this header.
+ grok_conv_id = _sticky_key(session_id)
if grok_conv_id and model and model.startswith(("x-ai/grok-", "xai/grok-")):
- extra_headers["x-grok-conv-id"] = grok_conv_id
- if extra_headers:
- top_level["extra_headers"] = extra_headers
-
+ top_level["extra_headers"] = {"x-grok-conv-id": grok_conv_id}
return extra_body, top_level