Commit Graph

174 Commits

Author SHA1 Message Date
yoniebans
23213d9003 refactor(agent): image-shrink recovery in its own compression sibling
The re-encode of oversized inline image parts after an image-too-large rejection moves unchanged from agent/conversation_compression.py into agent/conversation_compression_image_shrink.py, a topic of its own. The agent's shrink forward, the error classifier's size check and the tests import it from there; the facade no longer lists it.
2026-11-17 19:10:57 +01:00
Teknium
68f4cce2b7 OpenRouter's prompt-injection guardrail 403 no longer reads as a firewall/key problem (#155460, salvage #155472) (#155828)
* fix: classify OpenRouter Guardrails 403 as its own failure (#155460)

The guardrail body ("Request blocked: prompt injection patterns detected")
collided with the generic "request blocked" WAF pattern (surfacing
User-Agent/extra_headers advice) and fell to the auth copy on the streaming
path. Neither applies: an account-level content filter judged the request
payload, so the fix is the provider's guardrail setting, not the key or
a header.

- error_classifier: FailoverReason.guardrail_blocked + verbatim-phrase
  pattern matched in _provider_special_cases before the status rules;
  abort + fallback hints; POLICY_REFUSAL_REASONS membership.
- turn_failure_copy: dedicated non-retryable copy + failure-cause gloss.
- turn_recovery: non-retryable label, metadata.patterns extractor (JSON
  and SDK-repr quote styles), verbose hint with the dashboard path.
- tests: verdict, copy, extraction, and WAF/auth regression coverage.

* fix: name the guardrail block on TUI, cron and the error surface too

The classifier verdict only had CLI copy; TUI/Desktop turn cards and cron
failure notices fell back to generic copy, and error_surface treated the
verdict as retryable on legacy results. Trim the tests to two invariants.

* fix: carry guardrail matched patterns into the chat reply

The chat copy points at the error details for the pattern names, but the
shared summary kept only error.message; append them there once so the
card, the reply and the CLI line all show them.

---------

Co-authored-by: Sandeep Chauhan <200135069+sandeepc25@users.noreply.github.com>
2026-11-14 13:15:52 -08:00
kshitijk4poor
6b41bdf2ec docs(agent): route verdicts last until the route changes, not the session
The reasoning-effort, reasoning-disable, floor-effort and Codex replay notices
and comments said the setting held for the session; it now resets when the
route changes. The route_verdicts module docstring names the Codex replay pair
and the refresh and transport-recovery resets, and _reapply_route_client_config
names reset_route_verdicts_if_moved as the other path for a base_url move.
2026-11-08 17:34:10 +05:30
kshitijk4poor
7fcda591c1 refactor(aux): share the transient and policy-refusal reason sets
agent/error_classifier.py exports TRANSIENT_REASONS (timeout, overloaded,
server error), used by the auxiliary same-provider retry and the turn
recovery ladder in place of two private copies, and
POLICY_REFUSAL_REASONS (data policy, content policy), used by
resend_cannot_help and the quota-window shape fact.

classify_attempt uses is_cancellation for its interrupted-task check. The
probe client stub declares the provider tag slot, so the Nous refresh
tags it without suppressing AttributeError, and _classify_failure takes
base_url=None by default. No behaviour change.
2026-11-08 13:18:54 +05:30
kshitijk4poor
372ff7ec4d refactor(aux): drop a pass-through classifier wrapper and name shared labels
- Delete _attempt_failure; its three callers call _classify_failure.
- _call_fallback_candidate_async takes classify_as as a required
  keyword (its one caller already computes it before the async
  conversion drops the client's route tags).
- _403_404_WALL_PATTERNS names the 403/404 account-wall tuple once.
- MODEL_NOT_FOUND joins the policy's label constants; the candidate
  quarantine matches on it.
- Type _recover_provider_pool's verdict, and fix comments that still
  named the deleted _is_timeout_error/_is_connection_error predicates
  or said a classified failure surfaced unchanged.

No behaviour change.
2026-11-08 13:18:54 +05:30
kshitijk4poor
3c8d92593e fix(error-classifier): quota wording in a policy refusal does not bench the provider
A 403 data_policy_denied (or a content-policy refusal) whose message also
says "quota exceeded" got the aux-only quota_exhausted fact, so the
recovery ladder labelled it a payment error, marked the provider
unhealthy and fell back. The refusal is terminal: the fact is now kept
off data-policy and content-policy verdicts, and the ladder stops.
2026-11-08 13:18:54 +05:30
kshitijk4poor
90b40adb8f fix(error-classifier): drop the bare "credits" account-wall token
A 404 for a model named credits-v1, a 403 invalid-key body that links a
credits page, or a 429 pointing at a credits URL read as billing and
rotated or benched the key. The explicit credit phrases in the billing
patterns (insufficient credits, credits exhausted, no usable credits,
...) still match, so the main loop's verdicts for these bodies match
main again.
2026-11-08 13:18:54 +05:30
kshitijk4poor
21c4f99109 fix(aux): an upstream rate-limit verdict carries no quota_exhausted fact
OpenRouter's "Provider returned error" wrapper around an upstream 429 whose
raw body says "quota exceeded" is classified upstream_rate_limit (the key is
healthy). The extra quota_exhausted shape fact made benches_provider treat it
as a payment error and hide the whole provider. The fact is now withheld when
the verdict is upstream_rate_limit; main-loop verdicts are unchanged.
2026-11-08 13:18:54 +05:30
BearHuddleston
4db0ebfe54 fix(classifier): aux disconnect phrasings no longer widen the large-session overflow guess
The previous classifier commit moved the aux ladder's premature-close
phrasings ("connection reset", "response ended prematurely",
"RemoteProtocolError", "LocalProtocolError") into
_SERVER_DISCONNECT_PATTERNS for the new transport fact. That tuple is
also the main loop's "status-less disconnect on a large session is an
overflow" guess in _by_transport, so a relay "RemoteProtocolError: stream
reset" or a requests ChunkedEncodingError on a 150k-token / 250-message
session became context_overflow with should_compress=True, and
turn_overflow compressed history on a phantom overflow (#52310's concern).

_SERVER_DISCONNECT_PATTERNS is back to main's phrasings; the aux wording
lives in _PREMATURE_CLOSE_PATTERNS, which _by_transport classifies as a
plain transport timeout at any session size and _shape_context still
reports as transport=connection. A control row keeps main's
"peer closed connection" guess.

Review: BearHuddleston on #148403 (error_classifier.py L463).
2026-11-08 13:18:54 +05:30
kshitijk4poor
3425329bc7 fix(classifier): carry the auxiliary-only error phrasings and shape facts
The auxiliary client decides retry/fallback with private substring
predicates while the main loop uses classify_api_error. Before the aux
decisions can move onto the shared classifier, the classifier has to know
what the aux predicates know. This commit adds those phrasings to the
classifier's pattern tables and records the shape facts the aux recovery
paths branch on. Aux decisions still use their predicates here; the
switch follows in the next commit.

Phrasings (only those the aux predicates already matched; the bare
"billing" substring is not carried):
- an account wall (credits, budget/spending/key limits, subscription and
  upgrade walls, quota windows, RESOURCE_EXHAUSTED) on a 403 or 404, and
  "insufficient funds" / "can only afford" -> billing; a 404 "isn't
  available on the free tier" -> billing
- a 429 or status-less body naming a daily/weekly window with no reset
  signal -> billing; a bare RESOURCE_EXHAUSTED or per-minute quota stays
  a rate limit, and a 429 that says rate limit outranks a billing phrase
- xAI "unauthenticated:bad-credentials", a status-less "Error code: 401"
  and a status-less *AuthenticationError class -> auth that rotates
- "OpenRouter catalog" -> model_not_found
- account gating of the model itself ("model X is not supported for/when
  using this account") -> model_entitlement; a feature or parameter
  named first, and wall wording, are excluded
- "response ended prematurely", protocol-error text and a status-less
  SDK transport class by name (Connection/Timeout/DNS/SSL) -> transport
- botocore ClientError and httpx.HTTPStatusError statuses are read from
  their response objects
- InvalidProviderResponseError (new, agent/errors.py), an HTTP-200
  answer with no usable choices -> incomplete_response

Shape facts in error_context: transport ("timeout" | "connection"; a
connection or disconnect phrase sets it behind an HTTP status too, e.g.
a relay's 502 "connection reset by peer") and statusless_structured on
every verdict (keyed on the exception carrying no HTTP status, so an SSE
error body whose numeric code reads as a status still counts); quota_exhausted and route_rejects_model on built-in
verdicts only (a plugin or profile verdict is authoritative), which set
hook_declines_fallback instead when they say should_fallback=False. The
main loop reads none of them.

Tests: tests/agent/test_error_classifier_aux_phrasings.py, one table row
per phrasing and shape fact.

Part of the Code Health plan.
2026-11-08 13:18:54 +05:30
Teknium
889b81e555 fix(gemini): surface promptFeedback.blockReason as a terminal content-policy error
Gemini answers a blocked prompt with HTTP 200, promptFeedback.blockReason
and no candidates. The adapter translated that into an empty "stop" turn,
so the user saw silence. Both the unary and the SSE path now raise a
GeminiAPIError (code gemini_prompt_blocked, no synthesized HTTP status)
carrying per-reason guidance, and the classifier routes that structured
code to content_policy_blocked (non-retryable, fallback-eligible).
2026-11-04 21:47:30 -08:00
Teknium
17e3162e6d fix(agent): SDK-wrapped field-length 400s no longer count as a request byte cap
Review finding (BearHuddleston, 4473380964): the bare 'content length' guard
always passed for OpenAI/Anthropic-shaped 400s, because str(error) embeds the
parsed body and splitting on '_' turned 'invalid_request_error' / 'request_id'
into the word 'request'. Keep '_' inside words so only a genuinely named
request/bytes subject qualifies; the field-length control
('tools[0].description content length exceeds maximum allowed') fails fast
again in every envelope.
2026-11-04 21:26:16 -08:00
Teknium
371abaea41 fix(agent): keep token caps worded as size caps on the token-overflow path
Review should-fix: `_is_byte_size_limit_message` matched token caps that use
byte wording, e.g. GitHub Models / Azure AI Inference "Request body too large
for gpt-4.1 model. Max size: 8000 tokens." and "Payload size exceeds maximum
context length of 32768 tokens", and sent them to payload_too_large, whose
recovery never adopts the quoted limit. A message naming tokens is no longer a
byte cap, so these keep main's classification.

Also require the overflow verb to follow the size subject, so
"request size parameter page_size exceeds the maximum of 100" stays a
format_error instead of a body-size cap.
2026-11-04 21:26:16 -08:00
Teknium
ca570c12c8 fix(agent): classify request-body byte-cap 400s as payload_too_large
Byte-limited gateways reject an oversize request body with HTTP 400 (or a
status-less re-wrap) in wordings the exact 413 phrase list misses:
"RequestSize(bytes): N, Limit(bytes): M", Novita's "request body too large,
must be less than 20MB" (tagged INVALID_REQUEST_BODY, so it fell to
format_error) and Z.AI's "Request size exceeds the limit of {0}" (caught
by the token-overflow "exceeds the limit" rule). An image-heavy session,
large in bytes but small in tokens, then never recovered.

_is_byte_size_limit_message() needs a body/payload/request-size subject
plus an overflow signal, lowercases its own input, and never matches a
response-scoped subject. It runs on the 400 path ahead of the
invalid-body and overflow rules, and on the message path after the head
rules, routing to the existing payload_too_large compression recovery.
2026-11-04 21:26:16 -08:00
Victor Kyriazakos
e34d84897a fix(bedrock): Claude never gets a GPT turn's sealed reasoning on the Anthropic Messages path
A Bedrock session that switches from a reasoning GPT (Converse) to Claude with /model, or falls back
from one to the other, failed every Claude turn with
`HTTP 400: messages.N.content.M: Invalid `data` in `redacted_thinking` block` and then failed over to
GPT ("Fallback activated: <claude> -> <gpt> (bedrock)"). The only workaround was /new.

#142139 filters reasoning by issuing model on the Converse path only: a turn stamped by a non-Claude
model (CONVERSE_ISSUER_TYPE) replays no reasoning to Claude there. Claude on Bedrock runs on the
AnthropicBedrock (anthropic_messages) path, whose converter copied every thinking/redacted_thinking
block out of reasoning_details, GPT's sealed blob included. The classifier did not help either: the
rejection names none of the signature words, so it landed as format_error (non-retryable, fallback)
and never reached the existing thinking_signature strip-and-retry.

Two layers:

- Root: assistant_replay_carrier's reasoning_details carrier (_extract_preserved_thinking_blocks) yields
  nothing for a turn a non-Claude Converse model stamped, on every route and inside the in-flight tool
  loop. The predicate is #142139's, shared as bedrock_adapter.reasoning_minted_outside_claude (Converse's
  _reasoning_filter now calls the same helper). Claude's own turns (unstamped on AnthropicBedrock, or
  stamped by a Claude model on Converse) replay as before. Unstamped turns keep replaying, as on
  Converse: Claude mints redacted_thinking itself and its AnthropicBedrock turns carry no stamp, so
  "unstamped" cannot mean "foreign".
- Safety net: a 400 naming an invalid `redacted_thinking` block classifies as thinking_signature, so
  turn_recovery's one-shot strip (remember_rejected_thinking on signed-replay routes) removes the blob,
  persists the suppression for the session and retries on Claude. This covers unstamped GPT turns from
  sessions older than the stamp. It runs after the OpenAI Responses thinking_signature_invalid rule, so
  that class and invalid_encrypted_content keep winning.

Refs #142139
2026-10-28 19:21:51 -07:00
Teknium
2e30ce41c9 refactor(copilot): move credential logic behind generic ProviderProfile seams
GitHub->Copilot token exchange (hermes_cli/copilot_auth.py) moves into the
in-tree copilot plugin (plugins/model-providers/copilot/credentials.py), and
core's Copilot credential branches become generic profile hooks the plugin
fills: resolve_api_key_secret, runtime_base_url, prepare_pool_entry,
seed_pool_credentials, remove_credential_source, refresh_runtime_credentials,
is_stale_credential_error, request_rejection_hint, external_auth_evidence and
the ambient_credentials field. Behaviour-preserving (gh auth token fallback kept).
2026-10-25 18:04:13 -07:00
rob-maron
6adca16a77 Merge branch 'NousResearch:main' into window-plans 2026-10-21 23:07:58 -04:00
rob-maron
cafa03f7f4 PR review comments 2026-10-21 23:05:11 -04:00
Siddharth Balyan
0c07f21843 refactor(data-use): trim comments to the why 2026-10-21 15:46:19 +05:30
Siddharth Balyan
22fc809869 feat(data-use): route connector results that need no-training to qualifying Nous endpoints
The tool gateway now tags execute results with dataUse.requires (no_training,
zero_retention). Hermes keeps that as `data_use` metadata on the tool message
(content unchanged; a batch carries the union), persists it inside the existing
display_metadata column (no migration; /branch, resume and compaction copies
keep it), and strips it from every provider request. The Nous profile reads the
union over the outgoing messages and sends provider.data_collection=deny (+ zdr
for zero_retention) on both the chat-completions and Anthropic Messages paths;
no other provider sees it. A 403 data_policy_denied classifies as its own
non-retryable reason with no fallback and copy that tells the user to switch
model, compress, or start a new session.
2026-10-21 15:46:19 +05:30
rob-maron
0e29e8a25a fix tests 2026-10-20 22:18:49 -04:00
rob-maron
83c5737be2 merge main in 2026-10-20 21:19:31 -04:00
rob-maron
15307dece7 Usage-window plan support 2026-10-20 21:04:30 -04:00
Sergey Shabalin
5b7a75cbfd fix(agent): step up the reasoning effort when a 400 rejects the level's *value*
`is_reasoning_required_rejection` only matched wording that refuses a reasoning disable
by field name ("Reasoning is mandatory … cannot be disabled"). Alibaba token-plan /
DashScope routes publish a closed level set instead and refuse the thinking-off encoding
by value:

    400 invalid_parameter_error - "'reasoning_effort' must be one of:
    'minimal', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra'"

The field is understood and has to stay on the wire — only the disabled level ("none")
is invalid — so the recovery is the existing floor step-up ("none" -> "low"), not the
strip rung (that one is for an unknown field) and not an abort to the fallback chain.
The message matched neither marker family, so the thinking-off auxiliary title lane
failed with "Auxiliary title generation failed" and the main loop classified the same
400 as format_error (retryable=False, should_fallback=True).

- new `_REASONING_LEVEL_REJECTION_MARKERS` + `is_reasoning_level_rejection`, which
  requires the reasoning-field token next to the enum wording (an enum complaint about
  some other parameter is untouched);
- `is_reasoning_required_rejection` accepts the level case too -> the auxiliary ladder
  takes its floor rung;
- `classify_api_error`'s reasoning-mandatory branch consults it as well, so
  `turn_recovery` evaluates `_reasoning_floor_required` and steps the main-loop effort
  up to `low` instead of aborting to the fallback chain.

Verified live against a token-plan route on deepseek-v4.1-flash (none -> 400 -> low ->
200) and with 199 tests in tests/agent/, all passing; the new main-loop case fails on
origin/main (afc3b7c6f3) as format_error and passes with the change.
2026-10-19 11:09:38 -04:00
Teknium
42f210de11 fix: Alibaba's content guardrail ends the turn instead of a 4-minute retry loop
Qwen via OpenRouter / the Nous Portal relays Alibaba Model Studio's output
guardrail as an in-band 502 marked provider_unavailable ("Output data may
contain inappropriate content."), and its input guardrail as DashScope's 400
data_inspection_failed. Neither phrase was a content-policy pattern, so the
502 rode the server-error retry ladder and Hermes re-sent the same content
into the same refusal. Both now classify as content_policy_blocked.
2026-10-10 20:44:53 -07:00
Maciej Lisiewski
2ff58849f4 ci: ruff UP037 fixes 2026-10-09 17:34:38 +02:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
kshitijk4poor
b6a7e591b6 fix(free-tier): the 402 sign-in refusal applies on the welcome host only
The new 402 branch in _nous_welcome_tier keyed on the anonymous JWT alone, so a
free-tier credential that reached the paid host (user-set NOUS_INFERENCE_BASE_URL,
the case the route heal and its anon_on_paid_host copy exist for) got the
free-tier "refused" sign-in verdict instead of the ordinary 402 handling. The
module's own test docstring states the rule as "a 402 from the welcome host".

Test: anonymous 402 off the welcome host classifies as billing with no
welcome_refusal. Red on c4ba8b1e8e, green here.
2026-10-08 00:41:21 +05:30
alt-glitch
d86d8aa177 fix(free-tier): every free-tier rate limit offers sign-in
A free-tier 429 was a sign-in refusal only when its body carried a known
reason. A header-only 429 fell to the generic "add a backup provider"
copy, one with quota wording to the top-up card, and a 402 to "add
credits"; none offered sign-in.

For an anonymous request, _nous_welcome_tier now reads any 429 without a
known reason as a refusal built from its headers
(nous_rate_guard.welcome_refusal_from_headers): rate_limited when the wait
is 20 s or more or a bucket is empty, at_capacity otherwise, and a missing
wait stays 0 so the cross-session breaker never trips on a guess. A 402 on
an anonymous token is the tier refusing. Signed-in accounts are unchanged;
the test table runs every shape against both.
2026-10-07 12:07:57 +05:30
liuhao1024
48bf3118e9 fix(classifier): classify a retired free-route 404 as model_not_found
A Nous 404 answering "This model is no longer free. To continue using
the paid variant, switch to '<slug>'." fell through _404_RULES to
_V_UNKNOWN, so the retry loop kept retrying a slug that can never
succeed again. The route retirement is a model-lifecycle change, not a
missing model body or an account balance problem, so it now maps to
model_not_found: non-retryable, fallback armed (#123180).
2026-10-02 22:59:00 -05:00
kshitijk4poor
763646c30d fix(agent): only 4xx/5xx body codes count as a stream error's HTTP status (#121270)
A relay wrapping an error as {"code": 200, "success": false} must not route to
_by_status as a 200. Also reuse _error_obj for the error.* candidate walk and
point at the string-parsing text-SSE sibling.
2026-09-24 22:36:08 +05:30
kshitijk4poor
c9a1c3d6f5 refactor(agent): route status-less render errors through _MESSAGE_HEAD_RULES (#62662)
Drop the bespoke _streaming_render_error stage and its hand-built verdict: the
status-less message path already has a head table and _V_FORMAT_ERROR is the
canonical format_error/no-retry/fallback verdict. _by_status returns None when
there is no status, so the stage position bought nothing.
2026-09-24 22:36:08 +05:30
AlexFucuson9
d0dfea836b fix(agent): classify status-less streaming render errors as format_error
LM Studio / llama.cpp raise a bare status-less APIError when chat-template
Jinja rendering fails mid-stream; classify as format_error with fallback
instead of burning same-provider retries. Stage fires only when status_code
is None. Hand-applied from #64834 (supersedes #62673) onto the staged
classifier pipeline.

Fixes #62662
2026-09-24 22:36:08 +05:30
liuhao1024
0a661b7c94 fix(agent): an in-stream SSE error object's numeric code is its HTTP status
An aggregator can deliver an upstream failure as {"error": {"code": 403}}
inside an HTTP-200 SSE stream; the SDK then raises a status-less APIError
whose body carries the status. _extract_status_code only read
exc.status_code/.status, so the ban climbed the transient retry ladder
(api_max_retries resends, then 'temporarily unavailable, wait a minute')
which can never succeed for e.g. a banned account.

Fall back to a body-carried numeric code (100-599, int only — symbolic
string codes stay with _code_from_payload), mirroring the text-SSE path's
_status_code_from_payload. A 403 now classifies as auth: exactly one
request, fallback-eligible, no wait-and-retry advice.

Fixes #121270

(cherry picked from commit 8a09fc53614ea3b954faebb4bfcccc176116338c)
2026-09-24 22:36:08 +05:30
teknium1
2c948e6aa2 fix(agent): an upstream account ban relayed in a 200 stream fails once instead of retrying as an outage
OpenRouter relays OpenAI's "this user has been blocked for a previous
policy violation" as HTTP 200 + an SSE error event. The SDK raises a
status-less APIError that no classifier rule matched, so it landed in
the retryable `unknown` bucket: every retry was re-sent (3 streamed
requests by default), a configured fallback only engaged after the
ladder, and the user was told the provider "looks temporarily
unavailable. Wait a minute and send /retry".

- error_classifier: match the ban phrase status-agnostically in
  _provider_special_cases -> provider_policy_blocked (non-retryable,
  fallback, no credential rotation: every key on a banned account is
  banned; a 403 variant is not a bad key).
- turn_failure_copy: provider_policy_blocked chat copy now covers an
  account block as well as data/privacy settings; add its cause gloss
  so cron and subagent notices explain it instead of printing raw text.
- cron: provider_policy_blocked action (retrying won't help; pin another
  model).
- docs: FAQ entry for the reply; auto-recovery ladder exclusion list.
2026-09-23 10:40:08 -07:00
teknium1
30d14a3f73 fix: name the CommandCode upstream-outage pattern
The cherry-pick conflict dropped the contributor comment hunk; keep the WHY next to the entry.
2026-09-20 15:28:21 -07:00
fangliquan
1f3c882d81 fix(agent): narrow upstream outage matching 2026-09-20 15:28:21 -07:00
kshitijk4poor
838214c8f7 fix(error-classifier): a profile hook asking for fallback on a terminal reason is non-retryable
turn_api_error enters the fallback walk only for ``retryable=False`` verdicts outside the
retryable-client reasons; the built-in terminal verdicts pin retryable=False while the
rate-limit family stays retryable and cascades after backoff. A ``classify_api_error`` hook
returning ``{"reason": "billing", "should_fallback": True}`` therefore retried the dead
route instead of cascading (the #116408 test passed only because its hook also set
retryable=False). Default retryable to False for such verdicts, leaving rate-limit reasons on
the built-in retry-then-fallback shape; ``RETRYABLE_CLIENT_REASONS`` moves next to the
verdict table so both modules read one set. Contract documented in the plugin guide.
2026-09-20 12:17:52 +05:30
liuhao1024
d4f88f39ee fix(agent): classify CommandCode 'Content Exists Risk' 400 as a content-policy block
The CommandCode gateway (OpenAI-compatible aggregator fronting DeepSeek
models) rejects filtered prompts with a hard HTTP 400 whose message is the
verbatim string "Content Exists Risk" and whose nested param envelope
marks the rejection isRetryable=false. The pattern table in
_CONTENT_POLICY_BLOCKED_PATTERNS did not know this wording, so the 400
fell through to the generic format_error verdict: no fallback model was
tried and the surfaced copy blamed a malformed request even though the
request shape was fine (the same profile re-fires per prompt).

Add the verbatim phrase to the per-prompt safety-filter pattern list so
the classifier returns content_policy_blocked with should_fallback=True —
retryable unchanged-prompt attempts stop burning and the configured
fallback chain gets its turn. See #115218.
2026-09-19 23:39:24 -07:00
teknium1
1cd2c45fcb fix: credit-wall 404 is one billing table row; billing fallback warns with profile + remedy
Trim the salvage of #115706 to the existing seams:

- The structured code joins _BILLING_ERROR_CODES and _status_404 consults that table
  first, exactly like _status_429 (the status handler always returns, so _by_error_code
  never saw the code). Drops the duplicate _CREDIT_EXHAUSTION_404_CODES set, the
  message-substring scan, and the credit_exhaustion_code verdict marker.
- The log moves from two call sites in the turn loop into try_activate_fallback, the
  one chokepoint every fallback switch passes through. A billing switch is a WARNING
  naming the profile (resolved from the scoped home, so under multiplex it is the
  failing profile, not the launch profile), both models, and the `hermes [-p X] model`
  remedy; every other reason keeps the INFO line.
- Tests trimmed to two invariants (classifier row + control body; warning is
  profile-scoped A->B and non-billing stays INFO), both red on origin/main.

Co-authored-by: Yagna Vudathu <yagnavudathu@gmail.com>
2026-09-19 22:40:16 -07:00
Yagna Vudathu
d861bca178 fix: route 404 insufficient_credits_for_paid_model to fallback_model chain
A 404 carrying insufficient_credits_for_paid_model (paid model ungated
by credits) classified as unknown: retryable with no fallback, burning
retries and never switching models. Treat it like 429-exhaustion --
billing with rotate+fallback -- and log an actionable ERROR naming the
credits and the fallback target on activation.

Fixes #115702

(cherry picked from commit a1f7f9996bb82230c945340dcb279ffa923e90a1)
2026-09-19 22:40:16 -07:00
teknium1
bce20d0b1f feat: model-provider plugins classify their own API errors via ProviderProfile.classify_api_error
A kind: model-provider plugin is loaded by providers/ discovery and never enters the
PluginManager hook lifecycle, so transform_api_error_classification was unreachable for it
without shipping a second plugin component. The profile now carries an optional
classify_api_error(error, *, status_code, error_code, message, body, model) callable,
consulted as a classifier stage right after the generic plugin hooks and only for the
provider that produced the error. None or an unknown reason leaves the built-in verdict;
built-in providers are untouched (no name table, no lifecycle change).

Also: a plugin refresh_credential returning None/empty was treated as a successful refresh
(row marked ok, stale bearer replayed up to the refresh cap). It now benches the row like a
failed refresh POST, so the loop rotates or falls to the generic sign-in copy.

Part of #116408

(cherry picked from commit b8129fd6fd6a0cf4eeee6d95a5d5d823668a306d)
2026-09-19 21:24:05 -07:00
Teknium
656eb28309 Merge pull request #115822 from NousResearch/fix/boa-streaming-stalls-timeouts-reasoning-streak
fix(agent): Codex reasoning-only stalls switch to the fallback provider instead of ending incomplete (#67321, salvage #67336)
2026-09-19 11:09:15 -07:00
teknium1
e85cb94da1 chore: merge origin/main (resolve agent/error_classifier.py,tests/agent/test_error_classifier.py) 2026-09-19 10:51:40 -07:00
teknium1
8d1b2c5b6e chore: merge origin/main (resolve agent/chat_completion_helpers.py,tests/agent/test_error_classifier.py) 2026-09-19 10:51:36 -07:00
teknium1
05c95d216e fix: read a top-level detail error body so a descriptive 400 is not a bare 400
`agent/error_classifier.py::_body_message_candidates` never yielded the
FastAPI-style top-level `detail` key (string, or nested `{"message": ...}`),
so the Codex gateway's `{"detail": "The '<model>' model is not supported when
using Codex with a ChatGPT account."}` 400 read as a *bare* 400. On a large
session `_classify_400`'s generic-400 heuristic then classified it as
context_overflow: the loop burned compression attempts ("Context length
exceeded (109,962 tokens). Cannot compress further.") and, because
`is_client_error` excludes overflow, the entitlement marker from #106549 never
ran. Reading `detail` makes it a descriptive rejection (format_error: abort +
fall back, no compression) and surfaces the provider's text as the message
instead of `Error code: 400 - {...}`. The pydantic list shape of `detail` is
still handled by `_oversized_message_content_rejection` and is not yielded.

Slim re-port of #100783's detail-body half onto the rule-table classifier;
the session/weekly usage-limit half is a separate class and was dropped.

Refs #81558
Refs #106475
Co-authored-by: Oleg Nagornyy <nagornyy.o@gmail.com>
2026-09-19 10:23:44 -07:00
liuhao1024
3306e105b3 fix(agent): recover from strict OpenAI-compatible "regex lookaround is not supported" 400s
Strict OpenAI-compatible schema validators reject tool JSON Schemas whose
``pattern`` contains a lookahead/lookbehind with
"Invalid JSON schema: regex lookaround is not supported" (HTTP 400,
code invalid_json_schema). The classifier only knew the llama.cpp grammar
sentences, so the turn failed as a non-retryable client error even though
the existing strip-pattern/format retry path already fixes the request.

Match the lookaround sentence in the same grammar guard so it routes through
FailoverReason.llama_cpp_grammar_pattern and retries once with the sanitized
schemas. Ported from #42635 onto the current grammar_hit shape.

Co-authored-by: liuhao1024 <sunsky.lau@gmail.com>
2026-09-19 10:16:27 -07:00
teknium1
6f6ed01355 fix: WAF 403s stop reading as key rejections; anthropic_messages routes send custom_providers extra_headers
Two gaps for custom providers behind a WAF/CDN:

- `build_anthropic_client` never consulted `custom_providers[].extra_headers`,
  so a relay in `anthropic_messages` mode that rejects the SDK User-Agent kept
  403ing even with `extra_headers: {User-Agent: ...}` configured, while the
  OpenAI-wire clients already applied it. The lookup now lives in
  `_new_sdk_client`, the one constructor every builder path goes through
  (init, /model switch, rebuild, auxiliary), keyed by the caller's raw route
  because entries are keyed by the `/v1` form the normalizer strips.
  Salvaged direction of #46002 (@wait4xx). Fixes #24293, #9721.

- `_status_403` classified every non-billing 403 as `auth`, so a WAF's plain
  "Your request was blocked." or a Cloudflare browser challenge printed "Your
  API key was rejected" and could rotate a healthy credential. A 403 carrying
  established block/challenge markers is now `upstream_blocked`: no rotation,
  no retry, fallback allowed, WAF/User-Agent guidance on every surface (CLI
  loop, chat copy, cli chat error copy, TUI gateway + Ink TUI copy). Generic
  403 and all 401 keep the auth verdict. Salvaged direction of #70567
  (@ooiuuii) and #53114 (@AgenticSpark). Fixes #53099, #70566.
2026-09-19 09:57:21 -07:00
teknium1
5d0ddb7dd8 fix(agent): exhausted plan-quota 429 names its reset window instead of 'wait a minute'
_summarize_api_error reduces the usage_limit_reached body to 'HTTP 429: The
usage limit has been reached', so no text-based parser could ever reach the
8.6h reset from the in-loop failure path. _status_429 now stamps
error_context['reset_at'] from the body's reset fields, Retry-After or the
message grammar (same table the credential pool uses), and
max_retries_exhausted_result hands the remaining seconds to exhausted_copy,
which says 'its usage limit resets in ~9h. Send /retry after that' once the
window is >= 2 minutes. A throttle with no window keeps the short-wait copy.
Proven with a real openai.RateLimitError carrying resets_in_seconds=30995
driven through the production result builder. (#89401 atom 1)
2026-09-19 09:49:39 -07:00
teknium1
1213109474 fix: retry a 403 stamped code=upstream_unavailable instead of failing as auth
Some OpenAI-compatible gateways answer an upstream outage with HTTP 403
and a structured error code ``upstream_unavailable`` ("Upstream service
temporarily unavailable. Please retry later."). The 403 handler only
distinguished billing from auth, so this transient outage was classified
``auth``/non-retryable: agent.api_max_retries was ignored, the turn
died on attempt 1 and the credential was treated as refused. Give the
structured transient code precedence over the generic 403 default and
classify it as overloaded (retry with backoff, no credential rotation),
matching how the same condition is handled when it arrives as 503.

Part of #75388 (case 1; the content-policy retry-budget case is a
deliberate design from 0554ef1aa3 and needs a maintainer decision).
2026-09-19 09:48:02 -07:00