The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent): error_classifier — unify billing/rate-limit/overflow verdict helpers, drop dead _THINKING_SIG_PATTERNS, compact incident narratives
Teknium68be67e0d0c1
diff --git a/agent/error_classifier.py b/agent/error_classifier.pyindex 7bcfbaf0cb4..2b066e66fa5 100644--- a/agent/error_classifier.py+++ b/agent/error_classifier.py@@ -1,12 +1,9 @@"""API error classification for smart failover and recovery.-Provides a structured taxonomy of API errors and a priority-ordered-classification pipeline that determines the correct recovery action-(retry, rotate credential, fallback to another provider, compress-context, or abort).--Replaces scattered inline string-matching with a centralized classifier-that the main retry loop in run_agent.py consults for every API failure.+A structured taxonomy of API errors plus a priority-ordered classification+pipeline that picks the recovery action (retry, rotate credential, fall back+to another provider, compress context, or abort). The retry loop in+run_agent.py consults it for every API failure instead of inline matching."""from __future__ import annotations@@ -18,10 +15,9 @@ from typing import Any, Dict, Optionallogger = logging.getLogger(__name__)-# Synthetic error code used when the OpenAI SDK rejects a provider's SSE-# ``data:`` field before Hermes receives a completion chunk. Keeping this-# distinct from generic JSON parse failures lets the classifier make narrow,-# provider-stream-specific recovery decisions without inventing an HTTP status.+# Synthetic error code for the OpenAI SDK rejecting a provider's SSE ``data:``+# field before any completion chunk arrives. Distinct from generic JSON parse+# failures so stream-specific recovery needs no invented HTTP status.PROVIDER_STREAM_NON_JSON_ERROR_CODE = "provider_stream_non_json_data"@@ -37,8 +33,8 @@ class FailoverReason(enum.Enum):# Billing / quotabilling = "billing" # 402 or confirmed credit exhaustion — rotate immediatelyrate_limit = "rate_limit" # 429 or quota-based throttling — backoff then rotate- # Upstream model rate-limited (aggregator 429) — fallback to a different- # model, NOT credential rotation. The user's key is healthy.+ # Aggregator 429 from the upstream model: fall back to another model, NOT+ # credential rotation — the user's key is healthy.upstream_rate_limit = "upstream_rate_limit"# Server-side@@ -47,33 +43,31 @@ class FailoverReason(enum.Enum):# Transporttimeout = "timeout" # Connection/read timeout — rebuild client + retry- # TLS certificate verification failure — deterministic for the host- # (TLS-inspecting proxy, missing/expired CA bundle, self-signed cert).- # Retrying reproduces the identical handshake failure, so fail fast- # with actionable guidance instead of burning retries.+ # TLS cert verification failure is deterministic for the host (inspecting+ # proxy, missing/expired CA, self-signed) — fail fast with guidance.ssl_cert_verification = "ssl_cert_verification"# Context / payloadcontext_overflow = "context_overflow" # Context too large — compress, not failoverpayload_too_large = "payload_too_large" # 413 — compress payloadimage_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+ image_corrupt = "image_corrupt" # Image bytes undecodable — shrinking won't help, strip and retry# Model / provider policymodel_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+ provider_policy_blocked = "provider_policy_blocked" # Aggregator (e.g. OpenRouter) blocked the only endpoint via account data/privacy policy+ content_policy_blocked = "content_policy_blocked" # Provider safety filter rejected this prompt — deterministic, don't retry unchanged# Request formatformat_error = "format_error" # 400 bad request — abort or strip + retryinvalid_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-type content in tool messages (e.g. Xiaomi MiMo) — downgrade to text and retry+ multimodal_tool_content_unsupported = "multimodal_tool_content_unsupported" # Provider rejected list-type tool content (e.g. Xiaomi MiMo) — downgrade to text and retry# Provider-specificthinking_signature = "thinking_signature" # Anthropic thinking block sig invalidlong_context_tier = "long_context_tier" # Anthropic "extra usage" tier gateoauth_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+ llama_cpp_grammar_pattern = "llama_cpp_grammar_pattern" # llama.cpp grammar converter rejects regex escapes in `pattern` / `format` — strip from tools and retry# Catch-allunknown = "unknown" # Unclassifiable — retry with backoff@@ -92,8 +86,7 @@ class ClassifiedError:message: str = ""error_context: Dict[str, Any] = field(default_factory=dict)- # Recovery action hints — the retry loop checks these instead of- # re-classifying the error itself.+ # Recovery hints — the retry loop checks these instead of re-classifying.retryable: bool = Trueshould_compress: bool = Falseshould_rotate_credential: bool = False@@ -113,10 +106,9 @@ class ClassifiedError:return bool(self.error_context.get("billing_unverified"))-# ── Provider-specific patterns ──────────────────────────────────────────-# Patterns that indicate billing exhaustion (not transient rate limit)+# Billing exhaustion (not transient rate limit)_BILLING_PATTERNS = ["insufficient credits","insufficient_quota",@@ -141,16 +133,12 @@ _BILLING_PATTERNS = ["not available on the free tier",]-# Billing-pattern matches that are NOT proof of billing exhaustion. Anthropic-# returns the identical "out of extra usage" body on a subscription OAuth-# token both when the overage bucket is genuinely depleted AND when its-# server-side content filter rejects part of the request (#82154) — the two-# are indistinguishable from the response. Classification stays ``billing``-# (rotation + fallback remain the right recovery either way), but the-# ambiguity is carried in ``error_context`` so downstream surfaces hedge-# instead of asserting exhaustion as fact, and the credential pool applies a-# short cooldown instead of the one-hour billing bench (a content-filter-# rejection leaves the credential perfectly healthy).+# Billing matches that are NOT proof of exhaustion. Anthropic returns the same+# "out of extra usage" body on a subscription OAuth token both when the overage+# bucket is depleted AND when its content filter rejects the request (#82154).+# Classification stays ``billing`` (rotation + fallback are right either way),+# but ``error_context`` carries the ambiguity so surfaces hedge and the pool+# applies a short cooldown instead of the one-hour billing bench._UNVERIFIED_BILLING_PATTERNS = ("out of extra usage",)@@ -160,14 +148,13 @@ def _billing_ambiguity_context(error_msg: str) -> Dict[str, Any]:return {"billing_unverified": True, "possible_content_filter": True}return {}-# xAI's explicit Grok credit-exhaustion code. Keep the HTTP 403 special case-# provider-scoped: other providers' generic billing codes historically remain-# auth failures when they arrive as 403.++# xAI's explicit Grok credit-exhaustion code, returned as HTTP 403 not 402.+# Kept provider-scoped: other providers' billing codes stay auth on 403._XAI_SPENDING_LIMIT_ERROR_CODE = "personal-team-blocked:spending-limit"-# Structured provider codes that mean the account cannot serve paid traffic-# until credits/subscription capacity is restored. xAI returns its explicit-# Grok spending-limit signal as HTTP 403 rather than 402.+# Structured codes meaning the account cannot serve paid traffic until+# credits/subscription capacity is restored._BILLING_ERROR_CODES = frozenset({"insufficient_quota","billing_not_active",@@ -180,7 +167,7 @@ _BILLING_ERROR_CODES = frozenset({_XAI_SPENDING_LIMIT_ERROR_CODE,})-# Patterns that indicate rate limiting (transient, will resolve)+# Rate limiting (transient, will resolve)_RATE_LIMIT_PATTERNS = ["rate limit","rate_limit",@@ -197,26 +184,21 @@ _RATE_LIMIT_PATTERNS = ["throttlingexception","too many concurrent requests","servicequotaexceededexception",- # Generic throttle prefix — Bedrock (and some proxies) surface throttling- # as "Throttling error: Too many tokens, please wait before trying- # again." Without this entry the message falls through to the- # context-overflow list (which contains "too many tokens") and the retry- # loop compresses a healthy session instead of backing off. Matched- # BEFORE _CONTEXT_OVERFLOW_PATTERNS in the message-only path, so the- # throttle wins. (port of anomalyco/opencode#37848's exclusion guard)+ # Generic throttle prefix — Bedrock/proxies say "Throttling error: Too many+ # tokens...". Without it the message hits the context-overflow list ("too+ # many tokens") and a healthy session gets compressed instead of backing+ # off. Rate-limit runs BEFORE overflow in the message-only path so the+ # throttle wins. (port of anomalyco/opencode#37848)"throttling",]-# Patterns that indicate provider-side overload, NOT a per-credential rate-# limit or billing problem. The credential is valid — the server is just-# busy — so the correct recovery is "back off and retry the same key", never-# "rotate the credential" (rotating exhausts the pool while the endpoint is-# still busy; a single-key user has nothing to rotate to). Some providers-# (notably Z.AI / Zhipu) reuse HTTP 429 for server-wide overload, so the 429-# status path matches the body against this list before falling through to-# the rate_limit default. Phrases are kept narrow and overload-flavoured so a-# normal rate-limit message ("you have been rate-limited") doesn't hit this-# bucket. (#14038, #15297)+# Provider-side overload, NOT a per-credential rate limit or billing problem.+# The key is valid, so recover by "back off and retry the same key", never+# rotate (rotation exhausts the pool while the endpoint is busy; single-key+# users have nothing to rotate to). Z.AI/Zhipu reuse HTTP 429 for overload, so+# the 429 path checks this list before defaulting to rate_limit. Phrases are+# kept overload-flavoured so "you have been rate-limited" doesn't land here.+# (#14038, #15297)_OVERLOADED_PATTERNS = ["overloaded","temporarily overloaded",@@ -232,7 +214,7 @@ _OVERLOADED_PATTERNS = ["over capacity",]-# Usage-limit patterns that need disambiguation (could be billing OR rate_limit)+# Usage-limit patterns needing disambiguation (billing OR rate_limit)_USAGE_LIMIT_PATTERNS = ["usage limit","quota",@@ -240,7 +222,7 @@ _USAGE_LIMIT_PATTERNS = ["key limit exceeded",]-# Patterns confirming usage limit is transient (not billing)+# Signals that a usage limit is transient (not billing)_USAGE_LIMIT_TRANSIENT_SIGNALS = ["try again","retry",@@ -257,25 +239,21 @@ _USAGE_LIMIT_TRANSIENT_SIGNALS = ["per second",]-# Payload-too-large patterns detected from message text (no status_code attr).-# Proxies and some backends embed the HTTP status in the error message.+# Payload-too-large from message text (no status_code attr) — proxies and some+# backends embed the HTTP status in the message._PAYLOAD_TOO_LARGE_PATTERNS = ["request entity too large","payload too large","error code: 413",- # Anthropic's structured 413 error type. Normally arrives with an HTTP- # 413 status (handled by the status path), but aggregators/proxies can- # re-wrap it into a plain message with no status attribute — route it to- # the same compression recovery. (port of anomalyco/opencode#37848)+ # Anthropic's structured 413 type; proxies may re-wrap it into a plain+ # message with no status — same compression recovery. (port of anomalyco/opencode#37848)"request_too_large","request exceeds the maximum size",]-# Image-size patterns. Matched against 400 bodies (not 413) because most-# providers return a 400 with a specific image-too-big message before the-# whole request hits the 413 size limit. Anthropic's wording is the most-# important here (hard 5 MB per image, returned as-# "messages.N.content.K.image.source.base64: image exceeds 5 MB maximum").+# Image-size patterns, matched against 400 bodies (not 413): most providers+# return a specific image-too-big 400 before the request hits the 413 limit.+# Anthropic's hard 5 MB per-image cap matters most._IMAGE_TOO_LARGE_PATTERNS = ["image exceeds", # Anthropic: "image exceeds 5 MB maximum""image too large", # generic@@ -284,42 +262,23 @@ _IMAGE_TOO_LARGE_PATTERNS = ["image dimensions exceed", # Anthropic: "image dimensions exceed max allowed size: 8000 pixels""dimensions exceed max allowed size", # Anthropic dimension-cap (wording variant)"max allowed size: 8000", # Anthropic dimension-cap (explicit pixel ceiling)- # Vendors that reject the same oversized image without using the word- # "image". MiniMax's Anthropic-compatible endpoint returns- # "media exceeds size limit: max 10485760 bytes (2013)" for a native- # image part above its 10 MB ceiling (#76039). Matched on the "media"- # fragment to mirror "image exceeds" above and catch reworded variants.- # A non-image media rejection (audio/video) that lands here is safe: the- # shrink pass finds no image parts, returns False, and the caller- # surfaces the original error unchanged.+ # MiniMax's Anthropic-compatible endpoint: "media exceeds size limit: max+ # 10485760 bytes (2013)" for an oversized native image (#76039). A+ # non-image media rejection landing here is safe: the shrink pass finds no+ # image parts and the caller surfaces the original error unchanged."media exceeds","media too large",- # "request_too_large" on a request known to contain an image → image is- # the likely culprit; we still try the shrink path before giving up.+ # "request_too_large" on a request with an image → image is the likely+ # culprit; the shrink path is still tried first.]-# Image-corruption patterns — distinct from _IMAGE_TOO_LARGE_PATTERNS above.-# These fire when the provider can decode the request but not the image-# bytes themselves (e.g. a re-serialized image part in replayed history that-# lost data along the way). Re-encoding/shrinking corrupt bytes does not fix-# corruption, so this list is routed to the strip-and-retry path-# (FailoverReason.image_corrupt), never to the shrink path.-#-# xAI wording: {"code":"invalid-argument","error":"...Invalid PNG image."}-# xAI has a second wording for the same failure class depending on where-# the truncation lands: "Invalid PNG image." for aligned truncation,-# "base64 string of provided image cannot be decoded" for unaligned-# truncation (confirmed by the issue reporter — same root cause, two wire-# messages).-# A third xAI wording covers the URL-image path — the provider downloads-# the image itself and rejects the fetched bytes:-# {"code":"invalid-argument","error":"code: 'Client specified an invalid-# argument', message: \"Downloaded response does not contain a valid JPG,-# PNG, WebP, or ICO image.\""}-# Matched as the full observed sentence on purpose — shorter fragments-# ("downloaded response does not contain a valid") also match non-image-# download failures and would misroute them into strip-and-retry.-# See: https://github.com/NousResearch/hermes-agent/issues/69078+# Image corruption — the provider decodes the request but not the image bytes+# (e.g. a re-serialized part in replayed history). Shrinking can't fix that,+# so this routes to strip-and-retry (image_corrupt), never the shrink path.+# xAI has two wordings for truncated bytes ("Invalid PNG image." aligned,+# "base64 string ... cannot be decoded" unaligned) and a third for URL images+# it downloads itself. The last is matched as the full sentence on purpose —+# shorter fragments also match non-image download failures. (#69078)_IMAGE_CORRUPT_PATTERNS = ["invalid png image","invalid jpeg image",@@ -327,17 +286,11 @@ _IMAGE_CORRUPT_PATTERNS = ["downloaded response does not contain a valid jpg, png, webp, or ico image",]-# Providers that follow the OpenAI spec strictly require tool message-# ``content`` to be a string. Some (Anthropic native, Codex Responses,-# Gemini native, first-party OpenAI) extend this to accept a content-parts-# list (text + image_url) so screenshots from computer_use survive. Others-# (Xiaomi MiMo, some Alibaba endpoints, a long tail of OpenAI-compatible-# providers) reject the list with a 400 — the patterns below are the most-# common error shapes we see. Recovery: strip image parts from tool-# messages in-place, record the (provider, model) for the rest of the-# session so we don't waste another call learning the same lesson, retry.-#-# See: https://github.com/NousResearch/hermes-agent/issues/27344+# Strict OpenAI-spec providers require tool message ``content`` to be a string;+# some (Anthropic native, Codex, Gemini, first-party OpenAI) accept a parts+# list so computer_use screenshots survive, others (Xiaomi MiMo, some Alibaba+# endpoints, a long tail) reject it with a 400. Recovery: strip image parts+# from tool messages, remember (provider, model) for the session, retry. (#27344)_MULTIMODAL_TOOL_CONTENT_PATTERNS = [# Xiaomi MiMo: {"error":{"code":"400","message":"Param Incorrect","param":"text is not set"}}"text is not set",@@ -345,8 +298,7 @@ _MULTIMODAL_TOOL_CONTENT_PATTERNS = ["tool message content must be a string","tool content must be a string","tool message must be a string",- # OpenAI-compat servers that reject list-type tool content with a- # schema-validation message+ # OpenAI-compat schema-validation messages for list-type tool content"expected string, got list","expected string, got array",# Alibaba/DashScope variant@@ -365,11 +317,10 @@ _CONTEXT_OVERFLOW_PATTERNS = ["context window","prompt is too long","prompt exceeds max length",- # NOTE: bare "max_tokens" is load-bearing — the output-cap-retry path keys- # off it (e.g. "max_tokens: 65536 > context_window: 200000 ..."). Do NOT- # remove it. Provider empty-response advisories also contain "very low- # max_tokens", but those are intercepted by _EMPTY_PROVIDER_RESPONSE_PATTERNS- # BEFORE this list is consulted, so they never mis-route into compression.+ # Bare "max_tokens" is load-bearing — the output-cap-retry path keys off it+ # ("max_tokens: 65536 > context_window: 200000"). Do NOT remove. Empty-+ # response advisories also say "very low max_tokens" but are intercepted by+ # _EMPTY_PROVIDER_RESPONSE_PATTERNS BEFORE this list is consulted."max_tokens","maximum number of tokens",# vLLM / local inference server patterns@@ -394,9 +345,8 @@ _CONTEXT_OVERFLOW_PATTERNS = ["max input token","input token","exceeds the maximum number of input tokens",- # Together/Fireworks-style: "Input length 131393 exceeds the maximum- # allowed input length of 131040 tokens." No other pattern in this list- # matches that wording. (port of anomalyco/opencode#37848)+ # Together/Fireworks: "Input length 131393 exceeds the maximum allowed+ # input length of 131040 tokens." (port of anomalyco/opencode#37848)"maximum allowed input length",]@@ -410,14 +360,10 @@ _MODEL_NOT_FOUND_PATTERNS = ["no such model","unknown model","unsupported model",- # OpenRouter returns 404 with this message when none of the candidate- # endpoints for the selected model support tool/function calling.- # Classifying this as model_not_found triggers fallback to a different- # model or provider that does support tools. Without this entry the- # pattern falls through to ``unknown`` with ``retryable=True``, the- # retry loop burns all attempts on the same deterministic rejection,- # and the error surfaces as a confusing "model not found" message- # instead of automatically failing over. See PR #58446.+ # OpenRouter 404 when no endpoint for the model supports tool calling.+ # model_not_found triggers fallback to a model/provider that does; without+ # it the error is ``unknown``/retryable and burns every attempt on the+ # same deterministic rejection. (PR #58446)"no endpoints found that support tool use",]@@ -425,16 +371,13 @@ _MODEL_NOT_FOUND_PATTERNS = [def _model_id_missing_known_prefix(model: str, provider: str) -> bool:"""True when a bare model id is only known to the provider as ``vendor/id``.- Some providers answer a malformed model id with a naked 404 that names- nothing — NVIDIA NIM returns ``404 page not found`` for a bare- ``nemotron-3-ultra-550b-a55b``, indistinguishable from a bad endpoint- path. Consulting the curated catalogue tells the two apart: if the id- carries no ``/`` but the catalogue has exactly one entry ending in- ``/<id>``, the prefix was dropped and the failure is deterministic.-- Never guesses — an id absent from the catalogue (a local NIM container,- a proxied model) returns False so genuine endpoint problems keep their- retryable ``unknown`` classification.+ Some providers answer a malformed id with a naked 404 (NVIDIA NIM: ``404+ page not found`` for a bare ``nemotron-3-ultra-550b-a55b``), indistinguishable+ from a bad endpoint path. If the id has no ``/`` but the curated catalogue+ has exactly one entry ending in ``/<id>``, the prefix was dropped and the+ failure is deterministic. Never guesses: an id absent from the catalogue+ (local NIM container, proxied model) returns False so genuine endpoint+ problems keep their retryable ``unknown`` classification."""name = (model or "").strip()if not name or "/" in name:@@ -447,27 +390,20 @@ def _model_id_missing_known_prefix(model: str, provider: str) -> bool:return False-# Malformed-message-array 400s. Deterministic request-shape rejections that-# describe the *transcript* being invalid, not a parameter. The canonical-# case: a stream dies mid-response and Hermes persists a content-less-# assistant stub; on the next turn the Anthropic message schema (and the-# litellm/Bedrock proxies in front of it) reject the whole request with-# "all messages must have non-empty content except for the optional final-# assistant message" / errorCode INVALID_REQUEST_BODY-# These are NOT context overflow — the input may be tiny — but a large-# session used to mis-route them into the compression loop via the generic-# "400 + large session" heuristic below, ending in "Cannot compress further"-# every retry (the input is unchanged, so compression cannot help). Match-# the message-shape signals explicitly and fail fast as a format_error so the-# loop stops looping. The empty-stub creation is the root cause (fixed in-# chat_completion_helpers); this pattern stops the misclassification symptom-# for transcripts that already contain a poisoned stub.-# Qwen/vLLM chat-template raise_exception("No user query found in messages")-# — shared between _INVALID_MESSAGE_BODY_PATTERNS (→ format_error) and the-# llama.cpp grammar exclusion guard below. Keeping a single constant prevents-# the two sites from silently drifting if the phrase is ever changed.+# Qwen/vLLM chat-template raise_exception("No user query found in messages").+# Shared by _INVALID_MESSAGE_BODY_PATTERNS (→ format_error) and the llama.cpp+# grammar exclusion guard so the two sites cannot drift._NO_USER_QUERY_SIGNAL = "no user query found"+# Malformed-message-array 400s: deterministic rejections of the *transcript*+# shape, not a parameter. Canonical case: a stream dies mid-response, Hermes+# persists a content-less assistant stub, and next turn Anthropic (or the+# litellm/Bedrock proxies in front of it) reject "all messages must have+# non-empty content ..." / errorCode INVALID_REQUEST_BODY. NOT context overflow+# — the input may be tiny — but the "400 + large session" heuristic used to+# route them into compression, ending in "Cannot compress further" every retry.+# Match explicitly and fail fast as format_error. (Stub creation is fixed in+# chat_completion_helpers; this covers transcripts already poisoned.)_INVALID_MESSAGE_BODY_PATTERNS = ["must have non-empty content","messages must have non-empty",@@ -475,26 +411,19 @@ _INVALID_MESSAGE_BODY_PATTERNS = ["text content blocks must be non-empty","content field is required","messages: at least one message is required",- # Qwen / vLLM chat templates raise this when the request has no surviving- # non-empty user turn (oversized session truncation, compression that- # dropped the only user message, or a resumed lineage that opens with- # assistant/tool). Deterministic — compression cannot invent a user- # query the template already rejected. Fail fast as format_error so we- # do not thrash the compression loop or mis-route into llama.cpp- # grammar recovery when local engines wrap the raise_exception as- # applyPromptTemplate / "Unable to generate parser for this template".+ # Qwen/vLLM templates raise this when no non-empty user turn survives+ # (truncation, compression that dropped the only user message, a lineage+ # opening with assistant/tool). Compression cannot invent a user query, so+ # fail fast rather than thrash — and don't mis-route into llama.cpp grammar+ # recovery when local engines wrap it as "Unable to generate parser ..."._NO_USER_QUERY_SIGNAL,]-# Request-validation patterns — the request is malformed and will fail-# identically on every retry. Some OpenAI-compatible gateways (notably-# codex.nekos.me) return these as 5xx instead of the standard 4xx, which-# makes the generic "5xx → retryable server_error" rule misfire: the retry-# loop hammers the same deterministic rejection 3+ times, then the-# transport-recovery path resets the counter and does it again, producing-# a request flood. When a 5xx body carries one of these unambiguous-# request-validation signals, classify as a non-retryable format_error so-# the loop fails fast and falls back instead of looping.+# Request-validation patterns — malformed request, fails identically on every+# retry. Some OpenAI-compatible gateways (codex.nekos.me) return these as 5xx,+# so the generic "5xx → retryable server_error" rule would hammer the same+# rejection, reset the counter via transport recovery, and flood. A 5xx body+# carrying one of these is classified as non-retryable format_error._REQUEST_VALIDATION_PATTERNS = ["unknown parameter","unsupported parameter",@@ -504,19 +433,15 @@ _REQUEST_VALIDATION_PATTERNS = ["unsupported_parameter",]-# Request parameters that Hermes sends on SOME routes only, paired with the-# providers/hosts where sending them is deliberate.-#-# When a host that is NOT in the allowed set rejects one of these fields, the-# client never put it in the body — the provider's own gateway injected it —-# so the 400 is a server-side flake rather than a deterministic request-shape-# error. See ``_is_server_injected_param_rejection`` and the branch in-# ``_classify_400``.-#+# Params Hermes sends on SOME routes only → the providers/hosts where sending+# them is deliberate. When a host NOT in the set rejects one, the client never+# sent it — the provider's own gateway injected it — so the 400 is a server+# flake, not a deterministic request-shape error (see+# _is_server_injected_param_rejection and its branch in _classify_400).# ``prompt_cache_retention`` is only sent for api.meta.ai and bedrock-mantle-# hosts (agent/transports/codex.py::_default_prompt_cache_retention_for_request).-# The Codex OAuth backend rejects it spontaneously on requests that provably-# never carried it.+# (agent/transports/codex.py::_default_prompt_cache_retention_for_request);+# the Codex OAuth backend rejects it spontaneously on requests that never+# carried it._SERVER_INJECTED_PARAM_SENDERS: Dict[str, tuple] = {"prompt_cache_retention": ("meta", "muse", "msl", "model-api", "bedrock", "mantle"),}@@ -525,15 +450,12 @@ _SERVER_INJECTED_PARAM_SENDERS: Dict[str, tuple] = {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``.+ ``error_msg`` is lowercased concatenated text; ``provider`` the lowercased+ slug. A match means the rejection isn't our request shape, so retrying+ the identical request is the correct recovery. Deliberately conservative:+ fires only for known one-route-only params AND only when the provider is+ not a route that sends them, so a genuine bad parameter (``max_tokens``+ on GPT-5) still fails fast as ``format_error``."""if not error_msg:return False@@ -541,8 +463,7 @@ def _is_server_injected_param_rejection(error_msg: str, provider: str) -> bool: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.+ # Must be a rejection of that parameter, not an incidental mention.if not ("not supported" in error_msgor "unsupported" in error_msg@@ -550,80 +471,52 @@ def _is_server_injected_param_rejection(error_msg: str, provider: str) -> bool: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+ # This route sends the field on purpose — a real request error.+ return not any(sender in provider_slug for sender in senders)return False-# 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+# OpenRouter aggregator policy block: an account privacy setting (or a+# per-request ``provider.data_collection: deny``) excludes the only endpoint+# serving a model → 404 "No endpoints available matching your guardrail+# restrictions and data policy. Configure: https://openrouter.ai/settings/privacy".+# Classified ``provider_policy_blocked`` not ``model_not_found``: the model+# exists, fallback won't help (account-level setting applies to every call),+# and the body already carries 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+# Provider content-policy / safety-filter blocks — *per-prompt* decisions by+# the upstream model provider (unlike the OpenRouter account-level block+# above). Deterministic for the unchanged request, so retrying burns paid+# attempts on a refusal; switch to a fallback immediately or surface guidance.+# Patterns are verbatim strings from specific safety pipelines, never generic+# words ("policy", "violation") that collide with billing/auth/format errors._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+ # OpenAI moderation — chat completions / responses ("usage policies"+ # disambiguates from billing's "exceeded ... policy")"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.+ # Azure / OpenAI Responses: ``content_filter`` is the OpenAI-standard+ # error/finish token; ``responsibleaipolicyviolation`` is Azure's code.+ # Deliberately NOT the space variant ("content filter") — it appears in+ # benign config/tooltip text that providers echo back."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.+ # MiniMax output-layer safety filter, surfaced verbatim as "output+ # new_sensitive (1027)" when the model's *output* (often a big tool-call+ # block) trips the filter and the SSE stream is truncated. Narrow enough+ # not to collide with billing/format/auth strings. (#32421)"new_sensitive",]@@ -641,19 +534,9 @@ _AUTH_PATTERNS = ["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+# Checked before context-overflow matching: the advisory often mentions+# "max_tokens" as a cause, which sent healthy sessions into a compression# death spiral ending in "Cannot compress further"._EMPTY_PROVIDER_RESPONSE_PATTERNS = ["returned an empty response",@@ -663,7 +546,10 @@ _EMPTY_PROVIDER_RESPONSE_PATTERNS = ["empty response stream",]-# the unknown bucket and get misreported as empty responses.+# Provider-side timeout wording when the exception type is generic (e.g.+# RuntimeError from a local shim wrapping a subprocess timeout). Checked+# before the type-based transport heuristics so these don't fall into the+# unknown bucket and get misreported as empty responses._TIMEOUT_MESSAGE_PATTERNS = ["timed out","turn timed out",@@ -673,22 +559,15 @@ _TIMEOUT_MESSAGE_PATTERNS = ["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.-#+# Connection-establishment / DNS failure wording for generic exception types+# (local shim, MCP bridge, SDK re-raising without chaining) where+# _TRANSPORT_ERROR_TYPES never fires and there is no HTTP status. Without+# message matching these become ``unknown`` and miss the transport+# eager-fallback path. (ported from anomalyco/opencode#40707)# 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.+# peer", "unexpected eof", ...) — those belong to _SERVER_DISCONNECT_PATTERNS,+# which runs later and routes large sessions to compression. A connection+# never established cannot be a server-side overflow rejection._CONNECTION_MESSAGE_PATTERNS = [# TCP connect failures"connection refused",@@ -718,12 +597,9 @@ _TRANSPORT_ERROR_TYPES = frozenset({"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.+ # Transient mid-stream SSL/TLS failures. ssl.SSLError is an OSError (caught+ # by isinstance) but the names are listed so provider-wrapped SSL errors+ # that lose the exception chain still classify as transport."SSLError", "SSLZeroReturnError", "SSLWantReadError","SSLWantWriteError", "SSLEOFError", "SSLSyscallError",# OpenAI SDK errors (not subclasses of Python builtins)@@ -731,12 +607,10 @@ _TRANSPORT_ERROR_TYPES = frozenset({"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 (no status code, transport-level). Ambiguous: a+# plain close may be a transient hiccup OR a server-side context-overflow+# rejection (gateways disconnect instead of returning an HTTP error for+# oversized requests). Large session + one of these → compression recovery._SERVER_DISCONNECT_PATTERNS = ["server disconnected","peer closed connection",@@ -747,18 +621,11 @@ _SERVER_DISCONNECT_PATTERNS = ["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 certificate verification failures — deterministic, NOT transient (TLS-+# inspecting proxy, missing CA, expired/self-signed cert). Burning the retry+# budget hides the actionable fix for minutes. Must be checked BEFORE+# _SSL_TRANSIENT_PATTERNS: these 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@@ -770,22 +637,11 @@ _SSL_CERT_VERIFY_PATTERNS = ["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/TLS transient failures — distinct from _SERVER_DISCONNECT_PATTERNS. A+# mid-stream SSL alert is a transport hiccup (flaky network, renegotiation,+# LB drop), NOT an overflow signal: retry but never compress. OpenSSL 3.x+# changed the code separator (SSLV3_ALERT_BAD_RECORD_MAC → SSL/TLS_ALERT_...),+# so match stable substrings that survive format churn._SSL_TRANSIENT_PATTERNS = [# Space-separated (human-readable form, Python ssl module, most SDKs)"bad record mac",@@ -794,8 +650,7 @@ _SSL_TRANSIENT_PATTERNS = ["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`)+ # Underscore-separated OpenSSL tokens (ERR_SSL_SSL/TLS_ALERT_BAD_RECORD_MAC)"bad_record_mac","ssl_alert","tls_alert",@@ -807,6 +662,76 @@ _SSL_TRANSIENT_PATTERNS = [# ── Classification pipeline ─────────────────────────────────────────────+def _billing_verdict(result_fn, **overrides) -> ClassifiedError:+ """Non-retryable billing: rotate credential and fall back."""+ return result_fn(+ FailoverReason.billing,+ retryable=False,+ should_rotate_credential=True,+ should_fallback=True,+ **overrides,+ )+++def _rate_limit_verdict(result_fn) -> ClassifiedError:+ """Retryable rate limit: rotate credential and fall back."""+ return result_fn(+ FailoverReason.rate_limit,+ retryable=True,+ should_rotate_credential=True,+ should_fallback=True,+ )+++def _overflow_or_empty_response(error_msg: str, result_fn) -> Optional[ClassifiedError]:+ """Shared body-refinement for 400/5xx: empty-response advisory vs overflow.++ Empty-provider-response advisories often mention "max_tokens" and must+ NOT enter compression (they used to thrash until "Cannot compress+ further" on a healthy session); an explicit overflow signal routes to+ compress-and-retry. Order matters: advisories first.+ """+ 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 None+++def _policy_or_model_not_found(error_msg: str, result_fn) -> Optional[ClassifiedError]:+ """Aggregator policy block (checked first so it isn't mislabelled as a+ missing model), then model-not-found."""+ 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)+ return None+++def _body_error_message(body: dict) -> str:+ """Lowercased message from ``error.message``, then flat ``message``.++ Also reads litellm/Bedrock proxy shapes ({"errorMessage", "errorArgs":+ {"reason"}}): without them a long descriptive rejection looks like a bare+ "generic" error and, on a large session, mis-routes into compression.+ """+ if not isinstance(body, dict):+ return ""+ err_obj = body.get("error", {})+ msg = ""+ if isinstance(err_obj, dict):+ msg = str(err_obj.get("message") or "").strip().lower()+ if not msg:+ msg = str(body.get("message") or "").strip().lower()+ if not msg:+ msg = str(body.get("errorMessage") or "").strip().lower()+ if not msg:+ args = body.get("errorArgs")+ if isinstance(args, dict):+ msg = str(args.get("reason") or "").strip().lower()+ return msg++def classify_api_error(error: Exception,*,@@ -824,42 +749,28 @@ def classify_api_error(2. HTTP status code + message-aware refinement3. 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+ 5. SSL cert-verify → fail fast; SSL/TLS transient alerts → retry as timeout6. Server disconnect + large session → context overflow- 7. Transport error heuristics+ 7. Stale-call circuit breaker → failover; transport error heuristics8. 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.+ ``approx_tokens``/``context_length``/``num_messages`` feed the large-session+ heuristics; ``provider``/``model`` are echoed into the result."""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.+ # so rate-limit handling (reason, pool rotation, fallback gating) fires.if status_code is None and error_type == "RateLimitError":status_code = 429body = _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.+ # Build the pattern-matching text. str(error) alone may omit the body+ # message (OpenAI SDK APIStatusError.__str__ returns the first arg), so+ # append it; also unwrap OpenRouter's metadata.raw, where the real upstream+ # message ("context length exceeded") lives inside an inner JSON string._raw_msg = str(error).lower()_body_msg = ""_metadata_msg = ""@@ -867,7 +778,6 @@ def classify_api_error(_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 ""@@ -883,7 +793,6 @@ def classify_api_error(passif not _body_msg:_body_msg = str(body.get("message") or "").lower()- # Combine all message sources for pattern matchingparts = [_raw_msg]if _body_msg and _body_msg not in _raw_msg:parts.append(_body_msg)@@ -905,14 +814,11 @@ def classify_api_error(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.+ # Consulted BEFORE the built-in pipeline so a provider plugin can add or+ # correct classifications (contract: ``transform_api_error_classification``+ # in hermes_cli.plugins.VALID_HOOKS). Callback exceptions and malformed+ # returns are handled inside the helper; this guard only covers+ # import/dispatch failure, so a broken plugin never breaks classification.try:from hermes_cli.plugins import get_plugin_error_classificationplugin_classification = get_plugin_error_classification(@@ -941,38 +847,23 @@ def classify_api_error(# ── 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.+ # Content-policy / safety block: deterministic refusal of THIS prompt.+ # Runs before status classification so a 400 block isn't downgraded to+ # ``format_error`` and a status-less block (OpenAI Codex SDK) isn't left+ # retryable in ``unknown``. (#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,- )+ 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.+ # Anthropic thinking-block 400s. Two failure modes, one recovery (strip+ # reasoning_details and retry without thinking blocks — see the+ # thinking_signature handler in conversation_loop.py):+ # 1. Signature mismatch — blocks are signed against the full turn; any+ # mutation (compression, truncation, merging) invalidates it.# 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.+ # 2. Frozen-block mutation — "`thinking` ... blocks in the latest+ # assistant message cannot be modified ... must remain as they were".+ # No "signature" token, so it used to hard-abort as a client error.+ # Not gated on provider: OpenRouter proxies Anthropic errors verbatim.if (status_code == 400and "thinking" in error_msg@@ -982,108 +873,50 @@ def classify_api_error(or "must remain as they were" in error_msg)):- return _result(- FailoverReason.thinking_signature,- retryable=True,- should_compress=False,- )+ return _result(FailoverReason.thinking_signature, retryable=True, should_compress=False)# 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,- )-- # 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 == 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 (400 "The+ # long context beta is not yet available for this subscription."). The+ # recovery in run_agent.py rebuilds the client without the beta and retries+ # once. Different status + phrase from the 429 tier gate above.+ 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)++ # llama.cpp's json-schema-to-grammar rejects regex escapes (``\d``/``\w``)+ # and most ``format`` values that MCP servers routinely emit in ``pattern``.+ # On match the retry loop strips pattern/format from the tools and retries+ # once; cloud providers accept these keywords and never hit this branch.+ # Exclude the Qwen/vLLM "No user query found" template failure that local+ # engines wrap as "Unable to generate parser for this template" — that is a+ # poisoned transcript (→ _INVALID_MESSAGE_BODY_PATTERNS / format_error),+ # and stripping keywords would retry uselessly.if status_code == 400:_llama_cpp_grammar_hit = ("error parsing grammar" in error_msgor "json-schema-to-grammar" in error_msg- or (- "unable to generate parser" in error_msg- and "template" 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,- )-- # 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 _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)++ # xAI Grok subscription entitlement ("run out of available resources or do+ # not have an active Grok subscription") arrives two ways: HTTP 403, which+ # _classify_by_status routes to auth and _is_entitlement_failure then+ # stops the refresh loop; or an SSE ``type=error`` frame with+ # status_code=None, which skips the status path and matches no message+ # list — without this guard it falls to retryable ``unknown`` and+ # _is_entitlement_failure never runs (it only fires under auth).if ("do not have an active grok subscription" in error_msgor ("out of available resources" in error_msg and "grok" in error_msg)):- return _result(- FailoverReason.auth,- retryable=False,- should_fallback=True,- )+ return _result(FailoverReason.auth, retryable=False, should_fallback=True)# ── 2. HTTP status code classification ──────────────────────────@@ -1100,21 +933,16 @@ def classify_api_error(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).+ # provider outage; falling back would silently swap the MoA route for 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,- )+ return _result(FailoverReason.format_error, retryable=False, should_fallback=False)- # 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.+ # Local MoA config drift (persisted session names a renamed/deleted preset)+ # is deterministic — retrying makes a config error look like an outage.from agent.errors import MoAPresetNotFoundErrorif isinstance(error, MoAPresetNotFoundError):@@ -1129,104 +957,60 @@ def classify_api_error(# ── 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,- )+ classified = _classify_by_message(error_msg, _result)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).+ # Deterministic for the host; checked BEFORE the transient-SSL patterns+ # because cert-verify messages also contain "[ssl:".if any(p in error_msg for p in _SSL_CERT_VERIFY_PATTERNS):- return _result(- FailoverReason.ssl_cert_verification,- retryable=False,- should_fallback=False,- )+ 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).+ # Mid-stream SSL alerts are transport hiccups, not overflow signals; checked+ # before the disconnect step so a large session isn't compressed for a+ # flaky handshake. Also catches SDK re-raises that lose the ssl.SSLError type.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.-+ # Must precede the generic transport catch: a disconnect on a large+ # session is more likely overflow than a hiccup; otherwise+ # RemoteProtocolError always maps to timeout regardless of 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.)+ # Reasoning-model override: a disconnect here is far more likely the+ # upstream proxy idle-killing a multi-minute thinking stream (NVIDIA NIM+ # ~120s, NVIDIA/NemoClaw#4846; OpenAI/Anthropic similar) than a true+ # overflow, even on large sessions — compressing would silently delete+ # history on a phantom context-length error. The per-model stale-timeout+ # floor in agent/reasoning_timeouts.py makes a real transport failure+ # recoverable via retry, so reclassify as timeout. (Part 1 of #52310)from agent.reasoning_timeouts import get_reasoning_stale_timeout_floorif 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.+ # Absolute token/message thresholds only proxy for smaller windows;+ # large-context sessions can hold hundreds of messages well under 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.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.+ # _check_stale_giveup() (agent/chat_completion_helpers.py) raises+ # RuntimeError after N consecutive stale attempts, *before* any network+ # call. Not a transport timeout: as ``unknown``/retryable it would burn+ # all max_retries instantly against the same dead provider before+ # fallback. Non-retryable + should_fallback activates fallback on first hit.if (error_type == "RuntimeError"and "consecutive stale attempts" in error_msgand "aborting this call" in error_msg):- return _result(- FailoverReason.timeout,- retryable=False,- should_fallback=True,- )+ return _result(FailoverReason.timeout, retryable=False, should_fallback=True)# ── 8. Transport / timeout heuristics ───────────────────────────@@ -1257,11 +1041,10 @@ def _classify_by_status("""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).+ # Not retryable on its own — pool rotation and provider refresh (Codex,+ # Anthropic, Nous) run before the retryability check in run_agent.py+ # and ``continue`` on success; on failure retryable=False hits the+ # client-error abort path (which tries fallback first).return result_fn(FailoverReason.auth,retryable=False,@@ -1270,112 +1053,55 @@ def _classify_by_status()if status_code == 403:- # OpenRouter 403 "key limit exceeded" is actually billing. Other- # providers also use 403 for account-plan or credit exhaustion.+ # OpenRouter 403 "key limit exceeded" is 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- )+ (provider == "xai-oauth" and error_code.lower() == _XAI_SPENDING_LIMIT_ERROR_CODE)or "key limit exceeded" in error_msgor "spending limit" in error_msgor 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,- )+ return _billing_verdict(result_fn)+ return result_fn(FailoverReason.auth, retryable=False, should_fallback=True)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.+ # Nous API surfaces HA/NAS credit depletion as a paid model becoming+ # unavailable on the Free Tier (404, not 402) — billing, not a missing+ # model, so the loop can show 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.+ return _billing_verdict(result_fn)+ # OpenRouter policy-block 404 first (model exists; fallback won't help;+ # body carries the fix URL), then model-not-found.+ classified = _policy_or_model_not_found(error_msg, result_fn)+ if classified is not None:+ return classified+ # A bare id the catalogue only knows prefixed is a malformed model id:+ # NVIDIA NIM answers with a naked "404 page not found", so the generic+ # branch below would burn retries and report an outage (#78796).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,- )+ return result_fn(FailoverReason.model_not_found, retryable=False, should_fallback=True)+ # Generic 404 with no model signal: wrong endpoint path (local+ # llama.cpp/Ollama/vLLM misconfig), proxy glitch, or transient backend+ # issue. model_not_found would silently fall back and tell the model+ # it is missing — wrong and wastes a turn. Let the loop surface it.+ return result_fn(FailoverReason.unknown, retryable=True)if status_code == 413:- return result_fn(- FailoverReason.payload_too_large,- retryable=True,- should_compress=True,- )+ return result_fn(FailoverReason.payload_too_large, retryable=True, should_compress=True)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)+ # long_context_tier already handled upstream. Z.AI/Zhipu reuse 429 for+ # server-wide overload: the credential is valid, so back off and retry+ # the same key rather than rotating (burns the pool, useless for a+ # single-key user). (#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.+ return result_fn(FailoverReason.overloaded, retryable=True)+ # OpenRouter-wrapped upstream 429 ("Provider returned error"): the+ # upstream model is throttled, the user's key is healthy — rotating+ # would bench it ~24min for nothing. 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 {}@@ -1386,59 +1112,30 @@ def _classify_by_status(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)+ # Account/subscription usage exhaustion is a quota wall, not a rate+ # throttle; Anthropic returns it as 429 (``usage_limit_reached``,+ # #93419) and the generic branch used to retry it. Also covers+ # _USAGE_LIMIT_PATTERNS for other providers' hard quota walls, but ONLY+ # when the message isn't an explicit rate-limit phrase — otherwise+ # "Rate limit exceeded" ("limit exceeded") would promote to billing.+ # Periodic quotas with an explicit reset/retry signal stay rate_limit.+ # Explicit billing phrases in a 429 body are a hard wall too (#39441).has_usage_limit = (error_code.lower() == "usage_limit_reached"or "usage_limit_reached" in error_msgor 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,- )+ 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 _billing_verdict(result_fn)+ return _rate_limit_verdict(result_fn)if status_code == 400:return _classify_400(error_msg, error_code, body,- provider=provider, model=model,+ provider=provider,approx_tokens=approx_tokens,context_length=context_length,num_messages=num_messages,@@ -1446,87 +1143,44 @@ def _classify_by_status()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.+ # Some OpenAI-compatible gateways (codex.nekos.me → 502) return+ # request-validation errors as 5xx. Deterministic, so the generic+ # "5xx → retryable" rule would turn one bad request into a retry+ # flood: detect the signals (message or structured code) and fail fast.+ # Exception: a param WE never sent on this route was injected by the+ # provider itself, so retrying is correct (mirrors _classify_400).if (any(p in error_msg for p in _REQUEST_VALIDATION_PATTERNS)- or error_code.lower() in {"invalid_request_error", "unknown_parameter",- "unsupported_parameter"}+ 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.format_error, retryable=False, should_fallback=True)+ # llama.cpp/llama-server report context overflow as HTTP 500 instead of+ # 400/413; route explicit overflow into compression (mirroring+ # _classify_400) instead of blind server_error retries that drop the turn.+ classified = _overflow_or_empty_response(error_msg, result_fn)+ if classified is not None:+ return classifiedreturn 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,- )+ # Cloudflare/Tailscale hop relabeling the status); otherwise transient+ # overload.+ classified = _overflow_or_empty_response(error_msg, result_fn)+ if classified is not None:+ return classifiedreturn 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.+ # 408 Request Timeout is retry-safe by definition (RFC 9110 §15.5.9), not a+ # malformed request; reverse proxies in front of llama.cpp/Ollama/vLLM emit+ # it when a long generation outruns the read window. Route to ``timeout``+ # rather than the generic 4xx abort below.if status_code == 408:return result_fn(FailoverReason.timeout, retryable=True)# Other 4xx — non-retryableif 400 <= status_code < 500:- return result_fn(- FailoverReason.format_error,- retryable=False,- should_fallback=True,- )+ return result_fn(FailoverReason.format_error, retryable=False, should_fallback=True)# Other 5xx — retryableif 500 <= status_code < 600:@@ -1535,11 +1189,7 @@ def _classify_by_status(return None-def _has_usage_limit_transient_signal(- error_msg: str,- body: dict,- response_headers,-) -> bool:+def _has_usage_limit_transient_signal(error_msg: str, body: dict, response_headers) -> bool:"""Return whether a usage-limit response identifies a reset window."""if any(pattern in error_msg for pattern in _USAGE_LIMIT_TRANSIENT_SIGNALS):return True@@ -1551,19 +1201,11 @@ def _has_usage_limit_transient_signal(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- ):+ if any(payload.get(f) is not None and payload.get(f) != "" for f in reset_fields):return Trueif response_headers and hasattr(response_headers, "get"):- for header in (- "retry-after",- "Retry-After",- "x-ratelimit-reset",- "X-RateLimit-Reset",- ):+ 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@@ -1573,30 +1215,14 @@ def _has_usage_limit_transient_signal(def _classify_402(error_msg: str, result_fn) -> ClassifiedError:"""Disambiguate 402: billing exhaustion vs transient usage limit.- The key insight from OpenClaw: some 402s are transient rate limits- disguised as payment errors. "Usage limit, try again in 5 minutes"- is NOT a billing problem — it's a periodic quota that resets.+ Some 402s are rate limits disguised as payment errors — "Usage limit, try+ again in 5 minutes" is a periodic quota that resets, not a billing problem."""- # Check for transient usage-limit signals firsthas_usage_limit = any(p in error_msg for p in _USAGE_LIMIT_PATTERNS)has_transient_signal = any(p in error_msg for p in _USAGE_LIMIT_TRANSIENT_SIGNALS)-if has_usage_limit and has_transient_signal:- # Transient quota — treat as rate limit, not billing- return result_fn(- FailoverReason.rate_limit,- retryable=True,- should_rotate_credential=True,- should_fallback=True,- )-- # Confirmed billing exhaustion- return result_fn(- FailoverReason.billing,- retryable=False,- should_rotate_credential=True,- should_fallback=True,- )+ return _rate_limit_verdict(result_fn)+ return _billing_verdict(result_fn)def _classify_400(@@ -1605,123 +1231,75 @@ def _classify_400(body: dict,*,provider: str,- model: str,approx_tokens: int,context_length: int,num_messages: int = 0,result_fn,) -> ClassifiedError:- """Classify 400 Bad Request — context overflow, format error, or generic."""-- # Multimodal tool content rejected from 400. Must be checked BEFORE- # image_too_large because the recovery is different (strip image parts- # from tool messages, mark the model as no-list-tool-content for the- # rest of the session) and BEFORE context_overflow because some of the- # patterns ("text is not set") are ambiguous in isolation but become- # specific when combined with a 400 on a request known to contain- # multimodal tool content.+ """Classify 400 Bad Request — context overflow, format error, or generic.++ Ordering is load-bearing; every early branch below explains why it must+ precede context_overflow.+ """++ # Multimodal tool content rejected. BEFORE image_too_large (different+ # recovery: strip image parts from tool messages, mark the model+ # no-list-tool-content for the session) and BEFORE context_overflow+ # because "text is not set" is ambiguous alone but specific for a 400 on a+ # request known to carry multimodal tool content.if any(p in error_msg for p in _MULTIMODAL_TOOL_CONTENT_PATTERNS):- return result_fn(- FailoverReason.multimodal_tool_content_unsupported,- retryable=True,- )+ return result_fn(FailoverReason.multimodal_tool_content_unsupported, retryable=True)- # Image-corruption from 400 (xAI's undecodable-image check fires this way).- # Must be checked BEFORE image_too_large: both are image-shaped 400s, but- # corrupt bytes need strip-and-retry, not shrink-and-retry — shrinking- # can't repair a truncated/malformed PNG.+ # Image corruption (xAI's undecodable-image check). BEFORE image_too_large:+ # corrupt bytes need strip-and-retry — shrinking can't repair a bad PNG.if any(p in error_msg for p in _IMAGE_CORRUPT_PATTERNS):- return result_fn(- FailoverReason.image_corrupt,- retryable=True,- )+ return result_fn(FailoverReason.image_corrupt, retryable=True)- # Image-too-large from 400 (Anthropic's 5 MB per-image check fires this way).- # Must be checked BEFORE context_overflow because messages can trip both- # patterns ("exceeds" + "image") and image-shrink is a cheaper recovery.+ # Image too large (Anthropic's 5 MB per-image check). BEFORE context_overflow:+ # messages can trip both ("exceeds" + "image") and shrinking is cheaper.if any(p in error_msg for p in _IMAGE_TOO_LARGE_PATTERNS):- return result_fn(- FailoverReason.image_too_large,- retryable=True,- )+ return result_fn(FailoverReason.image_too_large, retryable=True)- # Invalid encrypted reasoning replay blob (OpenAI Responses API). Must be- # checked BEFORE context_overflow because some surfaces emit messages that- # contain context-like phrasing ("encrypted content … could not be- # verified") which could otherwise trip the context_overflow heuristics.- # ``error_msg`` is lowercased upstream — match accordingly.+ # Invalid encrypted reasoning replay blob (OpenAI Responses). BEFORE+ # context_overflow: "encrypted content ... could not be verified" can trip+ # the overflow heuristics. ``error_msg`` is lowercased upstream.error_code_lower = (error_code or "").lower()if (error_code_lower == "invalid_encrypted_content"or "invalid_encrypted_content" in error_msg- or (- "encrypted content for item" in error_msg- and "could not be verified" in error_msg- )+ or ("encrypted content for item" in error_msg and "could not be verified" in error_msg)or "could not decrypt the provided encrypted_content" in error_msg):- return result_fn(- FailoverReason.invalid_encrypted_content,- retryable=True,- should_fallback=False,- )-- # Server-injected parameter rejection: a 400 blaming a request field the- # client never sent. MUST be checked BEFORE the request-validation branch- # below, which would otherwise class it as a deterministic format_error and- # abort the turn.- #- # Observed live on the Codex OAuth backend (chatgpt.com/backend-api/codex):- # it intermittently adds ``prompt_cache_retention`` to its own upstream- # call and then rejects it, so a byte-identical request succeeds on retry- # (measured ~20% failure over n=20 on a minimal 1-message request that- # provably carried no cache parameters). Retrying is the correct and only- # recovery; failing fast burnt an entire large-context request per attempt.+ return result_fn(FailoverReason.invalid_encrypted_content, retryable=True, should_fallback=False)++ # Server-injected parameter rejection: a 400 blaming a field the client+ # never sent. MUST precede the request-validation branch, which would abort+ # the turn as a deterministic format_error. Observed live on the Codex+ # OAuth backend: it intermittently adds ``prompt_cache_retention`` to its+ # own upstream call and rejects it (~20% over n=20 on a 1-message request+ # with no cache params); a byte-identical retry succeeds.if _is_server_injected_param_rejection(error_msg, provider):- return result_fn(- FailoverReason.server_error,- retryable=True,- # The request shape was fine — never route this into compression.- should_compress=False,- )-- # Request-validation errors (unsupported / unknown parameter) MUST be- # checked BEFORE context_overflow. A GPT-5 model rejecting max_tokens- # returns:- # "Unsupported parameter: 'max_tokens' is not supported with this model.- # Use 'max_completion_tokens' instead."- # That string contains the literal substring "max_tokens", which historically- # sat in _CONTEXT_OVERFLOW_PATTERNS — so without this guard the 400 is- # misclassified as context_overflow, routed into the compression loop,- # re-sent with the same bad parameter, and ends in "Cannot compress- # further". These errors are deterministic (every retry gets the identical- # rejection), so classify as a non-retryable format_error and fall back.- #- # NOTE: we deliberately do NOT key off the generic ``invalid_request_error``- # code here — OpenAI stamps that same code on genuine context-overflow 400s,- # so matching it would mis-route real overflows away from compression. The- # unambiguous signals are the explicit "unsupported/unknown parameter"- # message text and the specific parameter-level error codes.+ # The request shape was fine — never route this into compression.+ return result_fn(FailoverReason.server_error, retryable=True, should_compress=False)++ # Request-validation (unsupported/unknown parameter) MUST precede+ # context_overflow: GPT-5 rejecting max_tokens says "Unsupported parameter:+ # 'max_tokens' ... Use 'max_completion_tokens'", and "max_tokens" is an+ # overflow pattern — without this guard the 400 enters the compression+ # loop and ends in "Cannot compress further". Deterministic → fail fast.+ # NOTE: deliberately NOT keyed off generic ``invalid_request_error`` —+ # OpenAI stamps that code on genuine overflow 400s too.if (- any(p in error_msg for p in _REQUEST_VALIDATION_PATTERNS- if p != "invalid_request_error")+ any(p in error_msg for p in _REQUEST_VALIDATION_PATTERNS if p != "invalid_request_error")or error_code_lower in {"unknown_parameter", "unsupported_parameter"}):- return result_fn(- FailoverReason.format_error,- retryable=False,- should_fallback=True,- )+ return result_fn(FailoverReason.format_error, retryable=False, should_fallback=True)- # Malformed message array (empty-content assistant stub, etc.). Must be- # checked BEFORE context_overflow: the input can be tiny, so the generic- # "400 + large session" heuristic would otherwise mis-route it into the- # compression loop and thrash until "Cannot compress further" on every- # retry (the request is unchanged, so compression cannot fix it). This is- # a deterministic request-shape rejection — fail fast as a non-retryable- # format_error and fall back. Checked against the message text AND the- # structured error code, since proxies (litellm/Bedrock) surface the- # signal in errorCode=INVALID_REQUEST_BODY.+ # Malformed message array (empty-content assistant stub, etc.). BEFORE+ # context_overflow: the input can be tiny, so the "400 + large session"+ # heuristic would thrash compression on an unchanged request. Checked+ # against message text AND the structured code (litellm/Bedrock surface+ # errorCode=INVALID_REQUEST_BODY).if (any(p in error_msg for p in _INVALID_MESSAGE_BODY_PATTERNS)or error_code_lower == "invalid_request_body"@@ -1734,289 +1312,120 @@ def _classify_400("approx_tokens=%s. error=%.200s",num_messages, approx_tokens, error_msg,)- return result_fn(- FailoverReason.format_error,- retryable=False,- should_fallback=True,- )-- # Empty-provider-response advisories must not enter compression. They- # often mention "max_tokens" as a possible cause and used to match the- # bare overflow pattern, then thrash compress until "Cannot compress- # further" on an otherwise healthy session (custom endpoints / nano-gpt).- if any(p in error_msg for p in _EMPTY_PROVIDER_RESPONSE_PATTERNS):- return result_fn(- FailoverReason.server_error,- retryable=True,- should_compress=False,- )+ return result_fn(FailoverReason.format_error, retryable=False, should_fallback=True)- # Context overflow from 400- if any(p in error_msg for p in _CONTEXT_OVERFLOW_PATTERNS):- return result_fn(- FailoverReason.context_overflow,- retryable=True,- should_compress=True,- )+ # Empty-response advisory (no compression) / explicit context overflow.+ classified = _overflow_or_empty_response(error_msg, result_fn)+ if classified is not None:+ return classified- # Some providers return model-not-found as 400 instead of 404 (e.g. OpenRouter).- 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,- )+ # Some providers return policy-block / model-not-found as 400 instead of 404.+ classified = _policy_or_model_not_found(error_msg, result_fn)+ if classified is not None:+ return classified- # Some providers return rate limit / billing errors as 400 instead of 429/402.- # Check these patterns before falling through to format_error.+ # Some providers return rate limit / billing as 400 instead of 429/402.if any(p in error_msg for p in _RATE_LIMIT_PATTERNS):- return result_fn(- FailoverReason.rate_limit,- retryable=True,- should_rotate_credential=True,- should_fallback=True,- )+ return _rate_limit_verdict(result_fn)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,- # "out of extra usage" on a 400 is ambiguous — it can also be a- # content-filter rejection (#82154). Mark the verdict unverified- # so downstream hedges and the pool skips the 1-hour bench.- error_context=_billing_ambiguity_context(error_msg),- )+ # "out of extra usage" on a 400 may be a content-filter rejection+ # (#82154): mark unverified so surfaces hedge and the pool skips the bench.+ return _billing_verdict(result_fn, error_context=_billing_ambiguity_context(error_msg))- # Generic 400 + large session → probable context overflow- # Anthropic sometimes returns a bare "Error" message when context is too large- err_body_msg = ""- if isinstance(body, dict):- err_obj = body.get("error", {})- if isinstance(err_obj, dict):- err_body_msg = str(err_obj.get("message") or "").strip().lower()- # Responses API (and some providers) use flat body: {"message": "..."}- if not err_body_msg:- err_body_msg = str(body.get("message") or "").strip().lower()- # litellm / Bedrock proxies use a custom shape: {"errorMessage": "...",- # "errorCode": "...", "errorArgs": {"reason": "..."}}. Without these- # keys err_body_msg stays "" and a long, descriptive rejection is- # wrongly treated as a "generic" (bare) error below, which — on a- # large session — mis-routes into the compression loop. Recognize- # them so the is_generic heuristic sees the real message length.- if not err_body_msg:- err_body_msg = str(body.get("errorMessage") or "").strip().lower()- if not err_body_msg:- _args = body.get("errorArgs")- if isinstance(_args, dict):- err_body_msg = str(_args.get("reason") or "").strip().lower()+ # Generic 400 + large session → probable context overflow (Anthropic can+ # return a bare "Error" message when context is too large).+ err_body_msg = _body_error_message(body)is_generic = len(err_body_msg) < 30 or err_body_msg in {"error", ""}- # Absolute token/message-count thresholds are only a proxy for smaller- # context windows. Large-context sessions can have many messages while- # still being far below their actual token budget.+ # Absolute token/message thresholds only proxy for smaller windows;+ # large-context sessions can hold many messages well under budget.is_large = approx_tokens > context_length * 0.4 or (context_length <= 256000 and (approx_tokens > 80000 or num_messages > 80))-if is_generic and is_large:- return result_fn(- FailoverReason.context_overflow,- retryable=True,- should_compress=True,- )+ return result_fn(FailoverReason.context_overflow, retryable=True, should_compress=True)# Non-retryable format error- return result_fn(- FailoverReason.format_error,- retryable=False,- should_fallback=True,- )+ return result_fn(FailoverReason.format_error, retryable=False, should_fallback=True)# ── Error code classification ───────────────────────────────────────────-def _classify_by_error_code(- error_code: str, error_msg: str, result_fn,-) -> Optional[ClassifiedError]:+def _classify_by_error_code(error_code: str, error_msg: str, result_fn) -> Optional[ClassifiedError]:"""Classify by structured error codes from the response body."""code_lower = error_code.lower()- if (- code_lower == PROVIDER_STREAM_NON_JSON_ERROR_CODE- and "request validation failed:" in error_msg- ):- # Some OpenAI-compatible endpoints encode deterministic request- # validation failures as plain-text ``event: error`` SSE data behind- # HTTP 200. Retrying the unchanged request cannot succeed, but a- # configured provider fallback still may.- return result_fn(- FailoverReason.format_error,- retryable=False,- should_fallback=True,- )+ # Some OpenAI-compatible endpoints encode deterministic request-validation+ # failures as plain-text ``event: error`` SSE data behind HTTP 200. The+ # unchanged request cannot succeed, but a configured fallback still may.+ if code_lower == PROVIDER_STREAM_NON_JSON_ERROR_CODE and "request validation failed:" in error_msg:+ return result_fn(FailoverReason.format_error, retryable=False, should_fallback=True)if code_lower in {"resource_exhausted", "throttled", "rate_limit_exceeded"}:- return result_fn(- FailoverReason.rate_limit,- retryable=True,- should_rotate_credential=True,- )+ return result_fn(FailoverReason.rate_limit, retryable=True, should_rotate_credential=True)if code_lower in _BILLING_ERROR_CODES:- return result_fn(- FailoverReason.billing,- retryable=False,- should_rotate_credential=True,- should_fallback=True,- )+ return _billing_verdict(result_fn)if code_lower in {"model_not_found", "model_not_available", "invalid_model"}:- return result_fn(- FailoverReason.model_not_found,- retryable=False,- should_fallback=True,- )+ return result_fn(FailoverReason.model_not_found, retryable=False, should_fallback=True)if code_lower in {"context_length_exceeded", "max_tokens_exceeded"}:- return result_fn(- FailoverReason.context_overflow,- retryable=True,- should_compress=True,- )+ return result_fn(FailoverReason.context_overflow, retryable=True, should_compress=True)if code_lower == "invalid_encrypted_content":- return result_fn(- FailoverReason.invalid_encrypted_content,- retryable=True,- should_fallback=False,- )+ return result_fn(FailoverReason.invalid_encrypted_content, retryable=True, should_fallback=False)return None# ── Message pattern classification ──────────────────────────────────────-def _classify_by_message(- error_msg: str,- error_type: str,- *,- approx_tokens: int,- context_length: int,- result_fn,-) -> Optional[ClassifiedError]:- """Classify based on error message patterns when no status code is available."""+def _classify_by_message(error_msg: str, result_fn) -> Optional[ClassifiedError]:+ """Classify on message patterns when no status code is available.- # Payload-too-large patterns (from message text when no status_code)+ Mirrors the 400 path's ordering (payload → multimodal → image corrupt →+ image too large → usage limit → overloaded → billing → rate limit →+ empty-response/overflow → auth → policy/model → timeout → connection).+ """if any(p in error_msg for p in _PAYLOAD_TOO_LARGE_PATTERNS):- return result_fn(- FailoverReason.payload_too_large,- retryable=True,- should_compress=True,- )+ return result_fn(FailoverReason.payload_too_large, retryable=True, should_compress=True)- # Multimodal tool content patterns (from message text when no status_code)if any(p in error_msg for p in _MULTIMODAL_TOOL_CONTENT_PATTERNS):- return result_fn(- FailoverReason.multimodal_tool_content_unsupported,- retryable=True,- )+ return result_fn(FailoverReason.multimodal_tool_content_unsupported, retryable=True)- # Image-corruption patterns (from message text when no status_code)if any(p in error_msg for p in _IMAGE_CORRUPT_PATTERNS):- return result_fn(- FailoverReason.image_corrupt,- retryable=True,- )+ return result_fn(FailoverReason.image_corrupt, retryable=True)- # Image-too-large patterns (from message text when no status_code)if any(p in error_msg for p in _IMAGE_TOO_LARGE_PATTERNS):- return result_fn(- FailoverReason.image_too_large,- retryable=True,- )-- # Usage-limit patterns need the same disambiguation as 402: some providers- # surface "usage limit" errors without an HTTP status code. A transient- # signal ("try again", "resets at", …) means it's a periodic quota, not- # billing exhaustion.- has_usage_limit = any(p in error_msg for p in _USAGE_LIMIT_PATTERNS)- if has_usage_limit:- has_transient_signal = any(p in error_msg for p in _USAGE_LIMIT_TRANSIENT_SIGNALS)- if has_transient_signal:- return result_fn(- FailoverReason.rate_limit,- retryable=True,- should_rotate_credential=True,- should_fallback=True,- )- return result_fn(- FailoverReason.billing,- retryable=False,- should_rotate_credential=True,- should_fallback=True,- )-- # Overloaded / server-busy patterns — must come BEFORE the rate_limit and- # billing checks so that a message-only "overloaded" (no 503/529 status,- # e.g. some Anthropic-compatible proxies) classifies as a transient- # overload (backoff + retry) instead of falling through to `unknown` or- # incorrectly triggering credential rotation.+ return result_fn(FailoverReason.image_too_large, retryable=True)++ # Usage-limit needs the same disambiguation as 402: a transient signal+ # ("try again", "resets at") means a periodic quota, not exhaustion.+ if any(p in error_msg for p in _USAGE_LIMIT_PATTERNS):+ if any(p in error_msg for p in _USAGE_LIMIT_TRANSIENT_SIGNALS):+ return _rate_limit_verdict(result_fn)+ return _billing_verdict(result_fn)++ # Overloaded BEFORE rate_limit/billing so a message-only "overloaded" (no+ # 503/529, e.g. Anthropic-compatible proxies) backs off instead of falling+ # to ``unknown`` or rotating credentials.if any(p in error_msg for p in _OVERLOADED_PATTERNS):- return result_fn(- FailoverReason.overloaded,- retryable=True,- )+ return result_fn(FailoverReason.overloaded, retryable=True)- # Billing patternsif any(p in error_msg for p in _BILLING_PATTERNS):- return result_fn(- FailoverReason.billing,- retryable=False,- should_rotate_credential=True,- should_fallback=True,- # Status-less path: adapters can strip the HTTP status from the- # Anthropic "out of extra usage" 400, so the same ambiguity- # marking applies here (#82154).- error_context=_billing_ambiguity_context(error_msg),- )+ # Adapters can strip the status from Anthropic's "out of extra usage"+ # 400, so the same ambiguity marking applies here (#82154).+ return _billing_verdict(result_fn, error_context=_billing_ambiguity_context(error_msg))- # Rate limit patternsif any(p in error_msg for p in _RATE_LIMIT_PATTERNS):- return result_fn(- FailoverReason.rate_limit,- retryable=True,- should_rotate_credential=True,- should_fallback=True,- )+ return _rate_limit_verdict(result_fn)- # Empty-provider-response advisories (often mention "max_tokens") must- # retry without compression — see the matching 400-path guard above.- if any(p in error_msg for p in _EMPTY_PROVIDER_RESPONSE_PATTERNS):- return result_fn(- FailoverReason.server_error,- retryable=True,- should_compress=False,- )-- # Context overflow patterns- if any(p in error_msg for p in _CONTEXT_OVERFLOW_PATTERNS):- return result_fn(- FailoverReason.context_overflow,- retryable=True,- should_compress=True,- )+ classified = _overflow_or_empty_response(error_msg, result_fn)+ if classified is not None:+ return classified- # Auth patterns- # Auth errors should NOT be retried directly — the credential is invalid and- # retrying with the same key will always fail. Set retryable=False so the- # caller triggers credential rotation (should_rotate_credential=True) or- # provider fallback rather than an immediate retry loop.+ # Auth is never retried directly — the key is invalid and will fail again;+ # retryable=False makes the caller rotate or fall back instead.if any(p in error_msg for p in _AUTH_PATTERNS):return result_fn(FailoverReason.auth,@@ -2025,38 +1434,19 @@ def _classify_by_message(should_fallback=True,)- # Provider policy-block (aggregator-side guardrail) — check before- # model_not_found so we don't mis-label as a missing model.- 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,- )-- # Model not found patterns- 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,- )+ classified = _policy_or_model_not_found(error_msg, result_fn)+ if classified is not None:+ return classified- # Timeout message patterns — generic exception types (e.g. RuntimeError)- # raised by local shims or custom providers that internally wrap a- # subprocess/HTTP timeout. Classified as transport timeout so the retry- # loop rebuilds the client instead of treating the turn as an empty- # model response.+ # Timeout wording from generic exception types (local shims / custom+ # providers wrapping a subprocess/HTTP timeout): transport timeout so the+ # loop rebuilds the client instead of treating the turn as empty output.if any(p in error_msg for p in _TIMEOUT_MESSAGE_PATTERNS):return result_fn(FailoverReason.timeout, retryable=True)- # Connection-establishment / DNS failure message patterns — same shim- # problem as the timeout patterns above: the wrapping exception type is- # generic, so _TRANSPORT_ERROR_TYPES never matches and the error would- # fall through to FailoverReason.unknown. Classified as timeout (the- # transport bucket) so the retry loop's eager transport fallback and- # client rebuild apply. Never routes to compression: a connection that- # was never established is not a context-overflow signal.+ # Connection/DNS failure wording — same generic-type problem; classified+ # as timeout (the transport bucket) so eager transport fallback and client+ # rebuild apply. Never compression: nothing was ever sent.if any(p in error_msg for p in _CONNECTION_MESSAGE_PATTERNS):return result_fn(FailoverReason.timeout, retryable=True)@@ -2065,10 +1455,20 @@ def _classify_by_message(# ── Helpers ─────────────────────────────────────────────────────────────+def _cause_chain(error: Exception, depth: int = 5):+ """Yield ``error`` then its __cause__/__context__ chain, bounded to ``depth``."""+ current = error+ for _ in range(depth):+ yield current+ cause = getattr(current, "__cause__", None) or getattr(current, "__context__", None)+ if cause is None or cause is current:+ break+ current = cause++def _extract_status_code(error: Exception) -> Optional[int]:"""Walk the error and its cause chain to find an HTTP status code."""- current = error- for _ in range(5): # Max depth to prevent infinite loops+ for current in _cause_chain(error):code = getattr(current, "status_code", None)if isinstance(code, int):return code@@ -2076,18 +1476,12 @@ def _extract_status_code(error: Exception) -> Optional[int]:code = getattr(current, "status", None)if isinstance(code, int) and 100 <= code < 600:return code- # Walk cause chain- cause = getattr(current, "__cause__", None) or getattr(current, "__context__", None)- if cause is None or cause is current:- break- current = causereturn Nonedef _extract_error_body(error: Exception) -> dict:"""Extract the structured error body from an SDK exception or its cause chain."""- current = error- for _ in range(5): # Match _extract_status_code() traversal depth.+ for current in _cause_chain(error):body = getattr(current, "body", None)if isinstance(body, dict):return body@@ -2100,58 +1494,52 @@ def _extract_error_body(error: Exception) -> dict:return json_bodyexcept Exception:pass- cause = getattr(current, "__cause__", None) or getattr(current, "__context__", None)- if cause is None or cause is current:- break- current = causereturn {}def _extract_response_headers(error: Exception):"""Walk the error and its cause chain to find response headers."""- current = error- for _ in range(5):- response = getattr(current, "response", None)- headers = getattr(response, "headers", None)+ for current in _cause_chain(error):+ headers = getattr(getattr(current, "response", None), "headers", None)if headers and hasattr(headers, "get"):return headers- cause = getattr(current, "__cause__", None) or getattr(current, "__context__", None)- if cause is None or cause is current:- break- current = causereturn {}+def _clean_code(code) -> str:+ """Stringify a code/type value; drop blanks and the useless literal "400"."""+ if isinstance(code, (str, int)):+ text = str(code).strip()+ if text and text != "400":+ return text+ return ""++def _extract_error_code(body: dict) -> str:"""Extract an error code string from the response body."""if not body:return ""def _code_from_payload(payload) -> str:- """Extract a code/type from a nested error payload dict (defensive)."""+ """Code/type from a nested error payload dict (defensive)."""if not isinstance(payload, dict):return ""payload_error = payload.get("error", {})if isinstance(payload_error, dict):nested = payload_error.get("code") or payload_error.get("type") or ""- if isinstance(nested, str) and nested.strip() and nested.strip() != "400":- return nested.strip()- code = payload.get("code") or payload.get("error_code") or ""- if isinstance(code, (str, int)):- text = str(code).strip()- if text and text != "400":- return text- return ""+ if isinstance(nested, str) and _clean_code(nested):+ return _clean_code(nested)+ return _clean_code(payload.get("code") or payload.get("error_code") or "")error_obj = body.get("error", {})if isinstance(error_obj, dict):code = error_obj.get("code") or error_obj.get("type") or ""- if isinstance(code, str) and code.strip() and code.strip() != "400":- return code.strip()+ if isinstance(code, str) and _clean_code(code):+ return _clean_code(code)# Some providers wrap the real JSON error body as a string inside- # error.message — peek into it for a nested code (e.g. Responses API- # surfaces ``invalid_encrypted_content`` this way).+ # error.message — peek for a nested code (Responses API surfaces+ # ``invalid_encrypted_content`` this way).message = error_obj.get("message")if isinstance(message, str) and message.strip().startswith("{"):import json@@ -2164,68 +1552,48 @@ def _extract_error_code(body: dict) -> str:return nested_code# Top-level code- code = body.get("code") or body.get("error_code") or body.get("errorCode") or ""- if isinstance(code, (str, int)):- text = str(code).strip()- if text and text != "400":- return text- return ""+ return _clean_code(body.get("code") or body.get("error_code") or body.get("errorCode") or "")def _extract_message(error: Exception, body: dict) -> str:- """Extract the most informative error message."""- # Try structured body first+ """Extract the most informative error message (structured body first)."""if body:error_obj = body.get("error", {})+ candidates = []if isinstance(error_obj, dict):- msg = error_obj.get("message", "")- if isinstance(msg, str) and msg.strip():- return msg.strip()[:500]- msg = body.get("message", "")- if isinstance(msg, str) and msg.strip():- return msg.strip()[:500]- # litellm / Bedrock proxy shape: {"errorMessage": "...",- # "errorArgs": {"reason": "..."}}.- msg = body.get("errorMessage", "")- if isinstance(msg, str) and msg.strip():- return msg.strip()[:500]+ candidates.append(error_obj.get("message", ""))+ candidates.append(body.get("message", ""))+ # litellm / Bedrock proxy shape: {"errorMessage": ..., "errorArgs": {"reason": ...}}+ candidates.append(body.get("errorMessage", ""))args = body.get("errorArgs")if isinstance(args, dict):- reason = args.get("reason", "")- if isinstance(reason, str) and reason.strip():- return reason.strip()[:500]- # Fallback to str(error)+ candidates.append(args.get("reason", ""))+ for msg in candidates:+ if isinstance(msg, str) and msg.strip():+ return msg.strip()[:500]return str(error)[:500]def _is_openrouter_upstream_error(body: Any, provider: str) -> bool:"""Detect OpenRouter's aggregator-wrapped upstream provider errors.- OpenRouter returns errors from upstream model providers (DeepSeek,- Anthropic, etc.) wrapped with the outer message "Provider returned error"- and the real error nested in ``metadata.raw``. This signal means the- user's OpenRouter key is healthy — the upstream provider is the one that- failed — so credential rotation is the wrong recovery.+ OpenRouter wraps upstream errors (DeepSeek, Anthropic, ...) with the outer+ message "Provider returned error" and the real error in ``metadata.raw``.+ The user's OpenRouter key is healthy, so credential rotation is wrong."""if not isinstance(body, dict):return False- provider_lower = (provider or "").strip().lower()err = body.get("error")if not isinstance(err, dict):return False- outer_msg = str(err.get("message") or "").strip().lower()- if outer_msg != "provider returned error":+ if str(err.get("message") or "").strip().lower() != "provider returned error":return False- # Require either the explicit OpenRouter provider OR the metadata shape- # that only OpenRouter produces (metadata.raw / metadata.provider_name).- if provider_lower == "openrouter":+ # Require the explicit OpenRouter provider OR the metadata shape only+ # OpenRouter produces (metadata.raw / metadata.provider_name).+ if (provider or "").strip().lower() == "openrouter":return Truemetadata = err.get("metadata")- if isinstance(metadata, dict) and (- "raw" in metadata or "provider_name" in metadata- ):- return True- return False+ return isinstance(metadata, dict) and ("raw" in metadata or "provider_name" in metadata)def _extract_upstream_provider_name(body: Any) -> Optional[str]: