Skip to content

The agent that grows with you

feat: model-provider plugins classify their own API errors via ProviderProfile.classify_api_error

teknium1bce20d0b1f08
diff --git a/agent/credential_pool.py b/agent/credential_pool.py
index 556d8c5322c..124f22c5940 100644
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@ -1472,7 +1472,12 @@ class CredentialPool(CredentialPoolAdminMixin, CredentialPoolModelCooldownMixin)
entry = self._sync_entry_from_auth_store(entry)
updated = self._post_tokens_refresh(entry)
elif (plugin_refresh := plugin_refresh_hook(self.provider)) is not None:
- updated = apply_plugin_refresh_result(entry, plugin_refresh(entry))
+ rotated = plugin_refresh(entry)
+ if not rotated:
+ # ``None``/empty = the plugin could not rotate: bench like a failed refresh POST, never
+ # report the stale row as refreshed (the loop would replay the dead bearer).
+ raise RuntimeError("provider refresh_credential returned no rotated fields")
+ updated = apply_plugin_refresh_result(entry, rotated)
elif self.provider == "nous":
stale_key = entry.runtime_api_key or entry.agent_key or entry.access_token
synced = self._sync_nous_entry_from_auth_store(entry)
diff --git a/agent/credential_pool_plugin.py b/agent/credential_pool_plugin.py
index 3a4f238521f..58b593886a0 100644
--- a/agent/credential_pool_plugin.py
+++ b/agent/credential_pool_plugin.py
@@ -11,7 +11,8 @@ Contract (documented in website/docs/developer-guide/model-provider-plugin.md):
* the hook returns a mapping of rotated values — dataclass field names
(``access_token``, ``refresh_token``, ``expires_at_ms`` …) replace the row's
fields, every other key (``expires_in``, ``token_type``, ``scope`` — the
- natural token-endpoint shape) lands in ``entry.extra``; ``None`` = no rotation;
+ natural token-endpoint shape) lands in ``entry.extra``; ``None``/empty = could not
+ rotate and the pool benches the row like a failed refresh POST;
* raising ``AuthError(..., relogin_required=True)`` (or a grant-dead OAuth code)
is terminal: the row goes DEAD with a WARNING naming ``hermes auth add``;
any other exception is transient and only benches the row.
diff --git a/agent/error_classifier.py b/agent/error_classifier.py
index 52319b79585..1cdc7bcd959 100644
--- a/agent/error_classifier.py
+++ b/agent/error_classifier.py
@@ -700,6 +700,45 @@ def _plugin_verdict(c: _Ctx) -> Optional[Verdict]:
return verdict
+def _profile_verdict(c: _Ctx) -> Optional[Verdict]:
+ """The current provider's own ``ProviderProfile.classify_api_error`` verdict, or None.
+
+ A ``kind: model-provider`` plugin never enters the PluginManager hook lifecycle, so without this a
+ vendor-specific body (a 403 ``quota_exhausted`` that is billing, not auth) could only be corrected by
+ shipping a second plugin component. Scoped to the provider that produced the error; no name table."""
+ if not c.provider_slug:
+ return None
+ try:
+ from providers import get_provider_profile
+ hook = getattr(get_provider_profile(c.provider_slug), "classify_api_error", None)
+ if not callable(hook):
+ return None
+ result = hook(c.error, status_code=c.status_code, error_code=c.error_code, message=c.msg,
+ body=c.body, model=c.model)
+ except Exception as exc:
+ logger.debug("Provider profile error classification failed for %s: %s", c.provider_slug, exc)
+ return None
+ if not isinstance(result, dict):
+ return None
+ reason = result.get("reason")
+ if isinstance(reason, str):
+ try:
+ reason = FailoverReason(reason.strip().lower())
+ except ValueError:
+ return None
+ if not isinstance(reason, FailoverReason):
+ return None
+ verdict = _v(reason, **{k: bool(result[k]) for k in _HINT_FLAGS if k in result})
+ if isinstance(result.get("error_context"), dict):
+ verdict["error_context"] = result["error_context"]
+ logger.info("API error classified by provider profile: %s (provider=%s, status=%s)",
+ reason.value, c.provider, c.status_code)
+ return verdict
+
+
+_HINT_FLAGS = ("retryable", "should_compress", "should_rotate_credential", "should_fallback")
+
+
# A welcome-host 403 that spells one of these out is a safety block or a billing wall, not the
# tier refusing. The free-tier refusal phrases are left OUT: on the free route they mean exactly
# "the tier refused", and an anonymous session has no credits to check.
@@ -877,11 +916,11 @@ def _by_status(c: _Ctx) -> Optional[Verdict]:
return _STATUS_HANDLERS[status](c) if status in _STATUS_HANDLERS else default
-# Stage order: plugin hooks → provider-specific special cases → HTTP status →
-# MoA shapes → structured error code → message patterns → SSL → disconnect +
+# Stage order: plugin hooks → the provider's own profile hook → provider-specific special cases →
+# HTTP status → MoA shapes → structured error code → message patterns → SSL → disconnect +
# large session → transport types → unknown (retryable with backoff).
_STAGES: Sequence[Callable[[_Ctx], Optional[Verdict]]] = (
- _plugin_verdict, _provider_special_cases, _by_status, _moa_special_cases,
+ _plugin_verdict, _profile_verdict, _provider_special_cases, _by_status, _moa_special_cases,
_by_error_code, _by_message, _by_transport,
)
diff --git a/providers/base.py b/providers/base.py
index 6f780584d21..ec754709c7a 100644
--- a/providers/base.py
+++ b/providers/base.py
@@ -67,8 +67,13 @@ class ProviderProfile:
# ``refresh_credential(entry) -> Mapping | None``: the credential pool's refresh of a pooled OAuth
# row — return the rotated fields (``access_token``, ``refresh_token``, ``expires_at_ms`` …) or raise.
# Both own their own token endpoints; Hermes passes no secrets beyond the pooled row itself.
+ # ``classify_api_error(error, *, status_code, error_code, message, body, model) -> Mapping | None``:
+ # consulted by ``agent.error_classifier.classify_api_error`` for THIS provider's failures only, after
+ # the generic ``transform_api_error_classification`` plugin hooks and before the built-in pipeline.
+ # Return ``{"reason": <FailoverReason name>, ...hint flags}`` to override, ``None`` to decline.
auth_handler: Callable[[str, Any], Any] | None = None
refresh_credential: Callable[[Any], Any] | None = None
+ classify_api_error: Callable[..., Any] | None = None
# ── Vision support ────────────────────────────────────────
# True when the provider's API accepts image content inside
diff --git a/tests/agent/test_provider_profile_recovery_seam.py b/tests/agent/test_provider_profile_recovery_seam.py
new file mode 100644
index 00000000000..586d629bf44
--- /dev/null
+++ b/tests/agent/test_provider_profile_recovery_seam.py
@@ -0,0 +1,57 @@
+"""A pure model-provider plugin participates in error classification and the 401 refresh path through its
+``ProviderProfile`` hooks — no PluginManager hook lifecycle, no core provider-name table (#116408 §4)."""
+
+from __future__ import annotations
+
+import httpx
+import openai
+import pytest
+
+import providers
+from providers.base import ProviderProfile
+
+from agent.credential_pool import AUTH_TYPE_OAUTH, STATUS_EXHAUSTED, CredentialPool, PooledCredential
+from agent.error_classifier import FailoverReason, classify_api_error
+
+
+def _error(status: int, code: str) -> openai.APIStatusError:
+ body = {"error": {"message": "vendor refused", "code": code}}
+ resp = httpx.Response(status, json=body, request=httpx.Request("POST", "https://example.invalid/v1/chat"))
+ return openai.APIStatusError("vendor refused", response=resp, body=body)
+
+
+def plugin_profiles():
+ def classify(error, *, status_code, error_code, message, body, model):
+ if status_code == 403 and error_code == "quota_exhausted":
+ return {"reason": "billing", "retryable": False, "should_rotate_credential": True}
+ return None
+
+ providers.register_provider(ProviderProfile(name="example-oauth", auth_type="oauth_external",
+ base_url="https://example.invalid/v1", classify_api_error=classify,
+ refresh_credential=lambda entry: None))
+ providers.register_provider(ProviderProfile(name="example-nohook", auth_type="oauth_external",
+ base_url="https://example.invalid/v1"))
+ yield
+ for name in ("example-oauth", "example-nohook"):
+ providers._REGISTRY.pop(name, None)
+ providers._PROVIDER_LIST_CACHE = None
+
+
+def test_profile_hook_reclassifies_only_its_own_provider(plugin_profiles):
+ exc = _error(403, "quota_exhausted")
+ mine = classify_api_error(exc, provider="example-oauth", model="m")
+ assert (mine.reason, mine.should_rotate_credential, mine.retryable) == (FailoverReason.billing, True, False)
+ # Declining (None) and a profile without the hook both keep the built-in verdict.
+ assert classify_api_error(_error(403, "other"), provider="example-oauth", model="m").reason == FailoverReason.auth
+ assert classify_api_error(exc, provider="example-nohook", model="m").reason == FailoverReason.auth
+ assert classify_api_error(exc, provider="anthropic", model="m").reason == FailoverReason.auth
+
+
+def test_plugin_refresh_returning_none_benches_instead_of_phantom_success(plugin_profiles, monkeypatch):
+ entry = PooledCredential(provider="example-oauth", id="abc123", label="acme", auth_type=AUTH_TYPE_OAUTH, priority=0,
+ source="manual:example_device", access_token="tok-1", refresh_token="rt-1", extra={})
+ pool = CredentialPool("example-oauth", [entry])
+ monkeypatch.setattr(pool, "_persist", lambda *a, **k: None)
+ assert pool._refresh_entry_impl(entry, force=True) is None
+ assert pool.entries()[0].last_status == STATUS_EXHAUSTED
diff --git a/website/docs/developer-guide/model-provider-plugin.md b/website/docs/developer-guide/model-provider-plugin.md
index ba9c5e18fa8..54f337bc66d 100644
--- a/website/docs/developer-guide/model-provider-plugin.md
+++ b/website/docs/developer-guide/model-provider-plugin.md
@@ -102,6 +102,7 @@ Full definition in `providers/base.py`. The most useful ones:
| `auth_type` | str | `api_key` \| `oauth_device_code` \| `oauth_external` \| `copilot` \| `aws_sdk` \| `external_process` |
| `auth_handler` | `Callable \| None` | Provider-owned `hermes auth add/status/logout/refresh <name>` — see [Provider-owned auth](#provider-owned-auth-auth_handler-refresh_credential) |
| `refresh_credential` | `Callable \| None` | Provider-owned rotation of a pooled OAuth row — same section |
+| `classify_api_error` | `Callable \| None` | Provider-scoped error-classification override — see [Recovery and error classification](#recovery-and-error-classification) |
| `fallback_models` | `tuple[str, ...]` | Curated list shown when live catalog fetch fails — in the `/model` picker AND the first-time `hermes setup` / `hermes model` API-key flow, which resolve the catalog the same way (`fetch_models()` merged curated-first with `fallback_models`; `fallback_models` alone when the fetch returns `None` or raises) |
| `supports_vision` | bool | Declares the provider's API accepts image content inside **tool-result** messages (a provider-wide wire capability). Per-model user-image routing comes from `model_capabilities` / models.dev, not from this flag |
| `model_capabilities` | `dict[str, dict[str, Any]]` | Per-model capability declarations in the `model_overrides` schema — see [Declaring model capabilities](#declaring-model-capabilities) |
@@ -379,7 +380,7 @@ register_provider(ProviderProfile(
| Contract | |
|---|---|
| `auth_handler(action, args)` | `args` is the parsed `hermes auth` namespace for CLI actions; the interactive setup picker passes a minimal namespace carrying only `provider`, so read options with `getattr(args, name, None)`. Truthy = handled (Hermes prints nothing more, exit 0); falsy = fall back to the built-in path **for that action**. An exception becomes `SystemExit("<provider> auth handler failed for `&lt;action&gt;`: …")`. |
-| `refresh_credential(entry)` | Receives the `PooledCredential`; returns a mapping of rotated values or `None`. Keys that are `PooledCredential` fields (`access_token`, `refresh_token`, `expires_at_ms`, …) replace the row's fields; every other key (`expires_in`, `token_type`, `scope` — the raw token-endpoint shape) lands in `entry.extra` and round-trips through `auth.json`. `None` = no rotation happened, the row is marked ok. Its presence is what makes the provider *refreshable* — `hermes auth refresh <name>` and the main-loop 401 recovery call it through the pool with no core name list involved; the auxiliary client's 401 recovery reaches it only for pooled rows it already treats as recoverable (api-key rows and the built-in OAuth routes). |
+| `refresh_credential(entry)` | Receives the `PooledCredential`; returns a mapping of rotated values or `None`. Keys that are `PooledCredential` fields (`access_token`, `refresh_token`, `expires_at_ms`, …) replace the row's fields; every other key (`expires_in`, `token_type`, `scope` — the raw token-endpoint shape) lands in `entry.extra` and round-trips through `auth.json`. Returning `None`/an empty mapping means the plugin could not rotate: the row is benched exactly like a failed refresh request (never reported as refreshed, so a dead bearer is not replayed). Its presence is what makes the provider *refreshable* — `hermes auth refresh <name>` and the main-loop 401 recovery call it through the pool with no core name list involved; the auxiliary client's 401 recovery reaches it only for pooled rows it already treats as recoverable (api-key rows and the built-in OAuth routes). |
| Refresh failures | Raise `hermes_cli.auth_constants.AuthError(..., relogin_required=True)` (or with `code` `invalid_grant` / `invalid_token` / `refresh_token_reused`) when the grant is dead: the row goes **DEAD**, leaves rotation and Hermes logs a WARNING naming `hermes auth add <name>`. Any other exception (network, 429, 5xx) is transient — the row is benched for one cooldown and retried. |
| Concurrency | The hook runs under the shared `auth.json` lock. Before calling it the pool re-reads the row; if another Hermes process (gateway + CLI, two profiles) already rotated the pair, that pair is adopted and your hook is **not** called — safe for single-use refresh tokens. After the hook returns, the rotated row is written through to `auth.json`. |
| No hooks | `api_key` profiles behave exactly as before. Any other `auth_type` without `auth_handler` fails loud on `hermes auth add`. |
@@ -430,6 +431,35 @@ the listener binds the literal `127.0.0.1`; tokens, `state` and the PKCE verifie
Optional fields: `audience`, `extra_authorize_params`, `extra_token_params`, `redirect_path`,
`timeout_seconds`, `label`.
+## Recovery and error classification
+
+A `kind: model-provider` plugin is loaded by provider discovery, **not** by the generic plugin manager, so
+the `transform_api_error_classification` plugin hook is not reachable from it without shipping a second
+plugin component. The profile carries the equivalent seam instead:
+
+```python
+def classify(error, *, status_code, error_code, message, body, model):
+ # A vendor-specific 403 that is a spent plan, not a bad credential.
+ if status_code == 403 and error_code == "quota_exhausted":
+ return {"reason": "billing", "retryable": False, "should_rotate_credential": True, "should_fallback": True}
+ return None # decline → built-in classification
+
+
+register_provider(ProviderProfile(name="example-oauth", auth_type="oauth_external",
+ base_url="https://api.example.com/v1",
+ refresh_credential=example_refresh, classify_api_error=classify))
+```
+
+| Contract | |
+|---|---|
+| `classify_api_error(error, *, status_code, error_code, message, body, model)` | Consulted by `agent.error_classifier.classify_api_error` for failures of **this provider only**, after any generic `transform_api_error_classification` hooks and before the built-in pipeline. `message` is the lower-cased error text, `body` the parsed JSON body (may be empty). Return `{"reason": <FailoverReason name>}` plus optional `retryable` / `should_compress` / `should_rotate_credential` / `should_fallback` / `error_context` to override; `None` (or an unknown reason) leaves the built-in verdict. Exceptions are swallowed and logged at DEBUG. The verdict drives the same recovery as for built-ins — e.g. `billing` benches the credential for the billing TTL instead of the transient 403 cooldown. |
+| 401 on a plugin credential | Handled by the credential pool, no core edit: the failing pooled row is refreshed through `refresh_credential` once per attempt (capped at two refreshes per row per session), the client is rebuilt with the rotated token and the request retried. A `None`/empty return or an exception benches the row — the request then rotates or falls to the generic "sign in again: `hermes auth add <name>`" copy, never to a built-in provider's guidance. |
+| Auxiliary calls | Auxiliary-client 401s take the same pool refresh (`try_refresh_current` → `refresh_credential`). |
+
+Recovery that remains name-keyed in core is behaviour with no safe generic shape (a provider-specific
+token store to re-sync, a plan-tier entitlement wall, a single-use refresh-token quarantine). A plugin
+that needs one of those owns it inside `refresh_credential` / `classify_api_error`.
+
## Discovery timing
Provider discovery is **lazy** — triggered by the first `get_provider_profile()` or `list_providers()` call in the process. In practice this happens early at startup (`auth.py` module load extends `PROVIDER_REGISTRY` eagerly). If you need to verify your plugin loaded, run: