The auxiliary client decided every recovery step (same-provider retry, credential refresh, pool rotation, unhealthy mark, provider fallback) with private substring predicates and consulted classify_api_error only to label telemetry. The logged reason and the action taken could disagree, plugin transform_api_error_classification hooks and ProviderProfile.classify_api_error overrides never steered an aux decision, and the tables had drifted from the main loop's. What changed: - Each failed request is classified once, on the backend, model, endpoint and credential it was sent with (_classify_failure): the primary, a same-provider retry (its rebuilt client and model), a refreshed Nous client or healed model, a parameter-rung or backoff re-send, and a fallback candidate (its effective provider or destination; an async candidate classifies on the sync client it was converted from). The streamed-negotiation and affordable-402 checks classify on the same attempted provider, passed in by the caller. Every later rung reads the resulting Failure (error, verdict, whether a parameter rung's detector names the rejected field). A request boundary that already classified (a rebuilt same-provider retry, a judged stream negotiation) raises the typed _ClassifiedAttempt carrying its Failure, and recovery reads that instead of classifying again. The relay logical call records each failed attempt with the ladder's Failure for it and reports that verdict at close (one classification only when no verdict exists): classifier hooks fire once per failed request. - The primary's retries, the candidates' parameter rungs and the ladder driver handle a failure after its except block ends, so a retry's own failure is classified as itself instead of through the previous error's context. The stream watchdogs raise their timeout from None. - agent/auxiliary_error_policy.py (new): small pure functions over the verdict (same_provider_retry, auth_refresh, same_key_retry, benches_provider, fallback_label, ladder_accepts, stream_negotiation_reraises). - The sync and async fallback-candidate helpers share one generator. - context_compressor classifies a summary failure once; its session-preserving abort keys on the verdict's transport fact. - The parameter rungs return a _ParameterRepair NamedTuple whose repaired flag tells provider fallback a rung changed the request. - Deleted: the private _is_*_error predicates, _credential_rung_accepts, _FALLBACK_REASONS, the keyword tables, fallback_candidate_unavailable_ reason and agent/auxiliary_error_shapes.py. Behaviour changes: - Transient failures (5xx, 408, overload, timeouts, connection failures incl. DNS/ECONNREFUSED and SDK transport classes) retry the same provider, then fall back. - A missing model falls back on every route; a 404 free-tier body falls back; 400-coded billing and rate-limit bodies bench / rotate and fall back. - RESOURCE_EXHAUSTED on a 429 is a rate limit unless it names a daily or weekly window, which is billing and benches the provider. - An OpenRouter-wrapped upstream 429 and a 429 "overloaded" do not rotate a healthy key; a 429 naming a rate limit and a billing phrase stays a rate limit. - A generic 403 falls back (auto routes; an explicit provider only with its task fallback_chain) without a credential refresh. - Account gating of the model rotates (model-scoped) before falling back; a feature restriction falls back without touching the key. - A rejection naming a request parameter with no applicable rung re-raises (primary and candidates); after a spent rung it falls back. - A verdict with retryable=False skips the same-provider retry and the same-key rate-limit backoff; a plugin or profile verdict with should_fallback=False never reaches provider fallback. A verdict that is neither retryable nor should_fallback (data_policy_denied, the model's malformed tool-call arguments) re-raises even after a parameter rung changed the request: another provider would get the same content. - An InterruptedError (a cancelled Codex stream) stops the call: no retry, no fallback. - A missing or route-refused model on a fallback candidate quarantines that model only (model-scoped unhealthy key); siblings on the same provider stay eligible. The key holds the provider-normalized model, so a configured name and its resolved form (gpt-x / openai/gpt-x) match, and the discovery chain skips a hidden resolved model too. - Aux pool selection (_select_pool_entry, _peek_pool_entry and the OpenRouter, Codex, Anthropic, xAI OAuth, plugin OAuth, named custom and API-key builders) passes the requested model, so a model-scoped cooldown on a key does not hide it from sibling models; CredentialPool.peek takes model= like select. - 429 then a generic 403 on an explicit provider with no task chain re-raises the 403. - Plugin and provider-profile classifiers steer every aux decision. Tests: tests/agent/test_auxiliary_error_policy.py drives call_llm end to end over one table of the behaviour decisions, plus regressions for a failure after a 401 refresh, 429-then-403, retryable=False, OpenCode Go classification (sync and async), a refreshed candidate's bad answer, a Nous SSE error after refresh, a terminal verdict after a spent parameter rung, one hook call per failed request (primary, retry and candidate; streamed and plain, sync and async), TLS failure and a 502 connection reset in compression, plugin overrides, an interrupt, a pinned custom provider's model-scoped rotation, a candidate's model-scoped quarantine under its resolved name, a sibling model keeping a pooled key, and a rebuilt retry classified on its own model. Tests of the removed predicates are deleted; ladder-internals tests are adapted to the Failure tuple. Part of the Code Health plan.
46 lines
2.4 KiB
Python
46 lines
2.4 KiB
Python
"""Auxiliary client for OAuth-shaped model-provider plugins (``auth_type`` oauth_external / oauth_device_code).
|
|
|
|
Built-in OAuth routes (nous, openai-codex, xai-oauth) have their own branches in ``auxiliary_client``.
|
|
A plugin OAuth provider reaches this one: its credential is the pooled row ``hermes auth add <name>``
|
|
wrote, and its transport comes from ``ProviderProfile.create_client``. ``CredentialPool.select()``
|
|
rotates an expiring row before leasing it, so compression and titling never send a dead bearer.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
|
|
def _configured_endpoint(provider: str) -> str:
|
|
"""The endpoint the main runtime would use: ``model.base_url`` when ``model.provider`` is this
|
|
provider (a relay / proxy override), else the registered profile's own."""
|
|
from hermes_cli.auth import PROVIDER_REGISTRY
|
|
from hermes_cli.runtime_provider import _config_base_url_for_provider, _get_model_config
|
|
pconfig = PROVIDER_REGISTRY.get(provider)
|
|
return _config_base_url_for_provider(_get_model_config(), provider) or (pconfig.inference_base_url if pconfig else "")
|
|
|
|
|
|
def resolve_plugin_oauth_client(req: Any) -> tuple[Any, Any]:
|
|
"""``(client, model)`` for ``req.provider``, or ``(None, None)`` when signed out or transport-less.
|
|
|
|
An explicit key from the main runtime wins, so aux shares the session's bearer.
|
|
"""
|
|
from agent import auxiliary_client as aux
|
|
|
|
provider = req.provider
|
|
api_key = aux._normalize_api_key(req.explicit_api_key)
|
|
entry = None
|
|
if not api_key:
|
|
_exists, entry = aux._select_pool_entry(provider, req.model)
|
|
api_key = str(getattr(entry, "runtime_api_key", "") or "") if entry is not None else ""
|
|
base_url = (req.explicit_base_url or str(getattr(entry, "runtime_base_url", "") or "")
|
|
or _configured_endpoint(provider)).strip().rstrip("/")
|
|
client = aux._api_key_profile_supplied_client(provider, api_key=api_key, base_url=base_url) if api_key else None
|
|
if client is None:
|
|
aux._log_once_debug(aux._LOGGED_UNSUPPORTED_OAUTH_KEYS, provider,
|
|
"resolve_provider_client: OAuth provider %s has no signed-in credential or "
|
|
"plugin transport, try 'auto'", provider)
|
|
return None, None
|
|
model = aux._normalize_resolved_model(req.model or aux._get_aux_model_for_provider(provider), provider)
|
|
return aux._route_client(req, client, model)
|