Skip to content

The agent that grows with you

feat(auth): brokered PKCE, expiry-driven rotation and aux on plugin OAuth rows

Tekniumf12e6b66d960
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index 5c7a9da8bd4..d2ecf7c8341 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -5401,12 +5401,6 @@ def _resolve_registry_branch(req: _ResolveRequest) -> _ResolveResult:
arm = REGISTRY_AUTHTYPE_ARMS.get(auth_type)
if arm is not None:
return arm(req)
- if auth_type in {"oauth_device_code", "oauth_external"}:
- # nous / openai-codex / xai-oauth already returned from their explicit branches.
- _log_once_debug(_LOGGED_UNSUPPORTED_OAUTH_KEYS, provider,
- "resolve_provider_client: OAuth provider %s not "
- "directly supported, try 'auto'", provider)
- return None, None
# The first occurrence surfaces a real schema-drift bug; per-call retries stay silent.
_log_once_debug(_LOGGED_UNHANDLED_AUTHTYPE_KEYS, (auth_type, provider),
"resolve_provider_client: unhandled auth_type %s for %s",
diff --git a/agent/auxiliary_client_registry.py b/agent/auxiliary_client_registry.py
index ec344e687b3..e1bd44469fd 100644
--- a/agent/auxiliary_client_registry.py
+++ b/agent/auxiliary_client_registry.py
@@ -116,6 +116,11 @@ def _resolve_minimax_oauth_arm(req: _ResolveRequest) -> _ResolveResult:
return _route_client(req, client, final_model)
+def _resolve_plugin_oauth_arm(req: _ResolveRequest) -> _ResolveResult:
+ from agent.auxiliary_plugin_oauth import resolve_plugin_oauth_client
+ return resolve_plugin_oauth_client(req)
+
+
# ``api_key`` / ``external_process`` arms stay on the facade (they share its credential
# resolvers); the table maps the auth types whose arms are build-and-route one-liners
# or live here as topical arms.
@@ -123,4 +128,7 @@ REGISTRY_AUTHTYPE_ARMS: Dict[str, Callable[[_ResolveRequest], _ResolveResult]] =
"vertex": _resolve_vertex_arm,
"aws_sdk": _resolve_bedrock_arm,
"oauth_minimax": _resolve_minimax_oauth_arm,
+ # Plugin OAuth: nous / openai-codex / xai-oauth returned from their explicit branches.
+ "oauth_device_code": _resolve_plugin_oauth_arm,
+ "oauth_external": _resolve_plugin_oauth_arm,
}
diff --git a/agent/auxiliary_plugin_oauth.py b/agent/auxiliary_plugin_oauth.py
new file mode 100644
index 00000000000..6b61116b33c
--- /dev/null
+++ b/agent/auxiliary_plugin_oauth.py
@@ -0,0 +1,45 @@
+"""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)
+ 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)
diff --git a/agent/credential_pool.py b/agent/credential_pool.py
index 0cda36c68c5..d6df1850b9f 100644
--- a/agent/credential_pool.py
+++ b/agent/credential_pool.py
@@ -22,7 +22,7 @@ from hermes_cli.config import load_env
from agent.secret_scope import get_secret as _get_secret, get_secret_str
from agent.retry_utils import reset_delay_from_message
from hermes_cli.auth_plugin_providers import plugin_refresh_hook
-from agent.credential_pool_plugin import apply_plugin_refresh_result, recover_failed_plugin_refresh
+from agent.credential_pool_plugin import apply_plugin_refresh_result, plugin_row_is_expiring, recover_failed_plugin_refresh
from agent.credential_persistence import (
fingerprint_secret_value,
is_borrowed_credential_source,
@@ -1232,8 +1232,9 @@ class CredentialPool(CredentialPoolAdminMixin, CredentialPoolModelCooldownMixin)
normalized_error = _normalize_error_context(error_context)
# Permanent OAuth failures become STATUS_DEAD, not STATUS_EXHAUSTED:
# otherwise a revoked credential re-enters rotation every hour and
- # fails immediately until the user removes it (#32849).
- terminal = self._is_terminal_auth_failure(status_code, normalized_error)
+ # fails immediately until the user removes it (#32849); a row whose
+ # refresh grant just went DEAD stays DEAD on the 401 that follows.
+ terminal = entry.last_status == STATUS_DEAD or self._is_terminal_auth_failure(status_code, normalized_error)
# Carry the classifier's verdict so the cooldown is sized by what
# actually failed (a billing 403 must not get the sole-credential
# transient cooldown); absent a classification, clear a stale one.
@@ -1983,10 +1984,8 @@ class CredentialPool(CredentialPoolAdminMixin, CredentialPoolModelCooldownMixin)
def _entry_needs_refresh(self, entry: PooledCredential) -> bool:
if entry.auth_type != AUTH_TYPE_OAUTH:
return False
- if self.provider == "anthropic":
- if entry.expires_at_ms is None:
- return False
- return int(entry.expires_at_ms) <= int(time.time() * 1000) + 120_000
+ if self.provider == "anthropic" or plugin_refresh_hook(self.provider) is not None:
+ return plugin_row_is_expiring(entry) # expiry-stamped rows: rotate 2 min ahead of expires_at_ms
if self.provider == "openai-codex":
return _codex_access_token_is_expiring(entry.access_token, CODEX_ACCESS_TOKEN_REFRESH_SKEW_SECONDS)
if self.provider == "xai-oauth":
diff --git a/agent/credential_pool_plugin.py b/agent/credential_pool_plugin.py
index 58b593886a0..cb6e93f1c3c 100644
--- a/agent/credential_pool_plugin.py
+++ b/agent/credential_pool_plugin.py
@@ -21,6 +21,7 @@ Contract (documented in website/docs/developer-guide/model-provider-plugin.md):
from __future__ import annotations
import logging
+import time
from dataclasses import fields, replace
from typing import TYPE_CHECKING, Any, Mapping, Optional, Tuple
@@ -32,6 +33,17 @@ if TYPE_CHECKING: # pragma: no cover
logger = logging.getLogger(__name__)
+_EXPIRY_SKEW_MS = 120_000
+
+
+def plugin_row_is_expiring(entry: "PooledCredential") -> bool:
+ """An expiry-stamped OAuth row (a plugin's, or Anthropic's) is due within the skew of ``expires_at_ms``.
+
+ The token endpoint's ``expires_in`` is the only clock: many providers issue opaque bearers (Google's
+ ``ya29.*``) with no JWT ``exp`` to decode, so without this a long session sends the dead bearer.
+ """
+ return entry.expires_at_ms is not None and int(entry.expires_at_ms) <= int(time.time() * 1000) + _EXPIRY_SKEW_MS
+
def apply_plugin_refresh_result(entry: "PooledCredential", result: Any) -> "PooledCredential":
"""Merge a ``refresh_credential`` return value into *entry*.
diff --git a/agent/gemini_native_adapter.py b/agent/gemini_native_adapter.py
index 6aafc1aaff3..913a7a63590 100644
--- a/agent/gemini_native_adapter.py
+++ b/agent/gemini_native_adapter.py
@@ -779,7 +779,10 @@ def _error_object(body_text: str) -> Dict[str, Any]:
def gemini_http_error(
response: httpx.Response, *, body_text: Optional[str] = None, api_key: str = "", base_url: str = "",
+ key_guidance: bool = True,
) -> GeminiAPIError:
+ """``key_guidance=False`` for OAuth-bearer callers: the API-key fixes (free tier, Standard key, wrong
+ key surface) are wrong advice when the credential is a user's OAuth access token."""
status = response.status_code
body_text = (_response_text(response) if body_text is None else body_text) or ""
err_obj = _error_object(body_text)
@@ -793,11 +796,11 @@ def gemini_http_error(
# Users who bypassed the setup wizard (raw GOOGLE_API_KEY in .env) still need to learn the free
# tier cannot sustain an agent session; a legacy "Standard" key gets the real fix (Google's raw
# 401 asks for OAuth; after Sept 2026 the same AIza key is often a 400 API_KEY_INVALID).
- if status == 429 and is_free_tier_quota_error(err_message or body_text):
+ if key_guidance and status == 429 and is_free_tier_quota_error(err_message or body_text):
message += _FREE_TIER_GUIDANCE
- if is_standard_key_auth_error(status, err_message or body_text, reason, api_key=api_key):
+ if key_guidance and is_standard_key_auth_error(status, err_message or body_text, reason, api_key=api_key):
message += _STANDARD_KEY_GUIDANCE
- if status == 403:
+ if key_guidance and status == 403:
message += wrong_gemini_surface_guidance(base_url, api_key, err_status)
return GeminiAPIError(
message, code=_HTTP_ERROR_CODES.get(status, f"gemini_http_{status}"), status_code=status, response=response,
@@ -811,13 +814,17 @@ class GeminiNativeClient:
# For agent/auxiliary_client.py: a complete client, never re-dispatched through a wire adapter.
# (No HERMES_SKIP_ASYNC_WRAP β€” the async path has a real conversion, AsyncGeminiNativeClient.)
HERMES_SKIP_TRANSPORT_WRAP = True
+ # Seams for a subclass that speaks the same wire under another credential (an OAuth bearer on the
+ # per-user-quota methods): RPC method names, the missing-credential text, and ``_auth_headers``.
+ GENERATE_METHOD, STREAM_METHOD = "generateContent", "streamGenerateContent"
+ MISSING_KEY_ERROR = _MISSING_KEY_ERROR
def __init__(
self, *, api_key: str, base_url: Optional[str] = None, default_headers: Optional[Dict[str, str]] = None,
timeout: Any = None, http_client: Optional[httpx.Client] = None, **_: Any,
) -> None:
if not (api_key or "").strip():
- raise RuntimeError(_MISSING_KEY_ERROR)
+ raise RuntimeError(self.MISSING_KEY_ERROR)
self.api_key, self.is_closed = api_key, False
self.base_url = normalize_gemini_base_url(base_url)
self._default_headers = dict(default_headers or {})
@@ -836,10 +843,16 @@ class GeminiNativeClient:
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
+ def _auth_headers(self) -> Dict[str, str]:
+ return {"x-goog-api-key": self.api_key}
+
def _headers(self) -> Dict[str, str]:
- return {"Content-Type": "application/json", "Accept": "application/json", "x-goog-api-key": self.api_key,
+ return {"Content-Type": "application/json", "Accept": "application/json", **self._auth_headers(),
"User-Agent": f"{_API_CLIENT} (gemini-native)", "X-Goog-Api-Client": _API_CLIENT, **self._default_headers}
+ def _http_error(self, response: httpx.Response, body_text: Optional[str] = None) -> "GeminiAPIError":
+ return gemini_http_error(response, body_text=body_text, api_key=self.api_key, base_url=self.base_url)
+
@staticmethod
def _advance_stream_iterator(iterator: Iterator[_GeminiStreamChunk]) -> tuple[bool, Optional[_GeminiStreamChunk]]:
chunk = next(iterator, _END)
@@ -861,10 +874,10 @@ class GeminiNativeClient:
model = bare_gemini_model_id(model)
url = f"{self.base_url}/models/{model}:"
if stream:
- return self._stream_completion(model, url + "streamGenerateContent?alt=sse", request, timeout)
- response = self._http.post(url + "generateContent", json=request, headers=self._headers(), timeout=timeout)
+ return self._stream_completion(model, f"{url}{self.STREAM_METHOD}?alt=sse", request, timeout)
+ response = self._http.post(url + self.GENERATE_METHOD, json=request, headers=self._headers(), timeout=timeout)
if response.status_code != 200:
- raise gemini_http_error(response, api_key=self.api_key, base_url=self.base_url)
+ raise self._http_error(response)
try:
payload = response.json()
except ValueError as exc:
@@ -878,9 +891,7 @@ class GeminiNativeClient:
headers = {**self._headers(), "Accept": "text/event-stream"}
with self._http.stream("POST", url, json=request, headers=headers, timeout=timeout) as response:
if response.status_code != 200:
- raise gemini_http_error(
- response, body_text=read_streaming_error_body(response), api_key=self.api_key, base_url=self.base_url,
- )
+ raise self._http_error(response, read_streaming_error_body(response))
tool_call_indices: Dict[str, Dict[str, Any]] = {}
for event in _iter_sse_events(response):
yield from translate_stream_event(event, model, tool_call_indices)
diff --git a/agent/turn_recovery.py b/agent/turn_recovery.py
index 8472141cdb5..a20d8873bcf 100644
--- a/agent/turn_recovery.py
+++ b/agent/turn_recovery.py
@@ -902,6 +902,12 @@ def _print_nonretryable_auth_guidance(
f" Nous catalog model, or run `/model openrouter:{model}` to use OpenRouter.",
)
return
+ from hermes_cli.auth_plugin_providers import plugin_refresh_hook
+ if status_code == 401 and plugin_refresh_hook(str(provider or "")) is not None:
+ # A plugin OAuth grant the pool could not refresh: the fix is a fresh sign-in, not a key.
+ from agent.turn_failure_copy import oauth_relogin_command
+ _vlines(agent, f" πŸ’‘ {provider} sign-in was rejected (HTTP 401). Sign in again: `{oauth_relogin_command(provider)}`")
+ return
_vlines(
agent,
" πŸ’‘ Your API key was rejected by the provider. Check:",
diff --git a/hermes_cli/auth_oauth_pkce_plugin.py b/hermes_cli/auth_oauth_pkce_plugin.py
index c10d56e5132..6f7702ca8a8 100644
--- a/hermes_cli/auth_oauth_pkce_plugin.py
+++ b/hermes_cli/auth_oauth_pkce_plugin.py
@@ -54,6 +54,11 @@ class OAuthPKCEConfig:
allowed_hosts: Tuple[str, ...] = ()
timeout_seconds: float = 180.0
label: str = ""
+ # Confidential client behind a broker: called with the grant fields (``grant_type``, ``code`` /
+ # ``refresh_token``, ``redirect_uri``, ``code_verifier``) INSTEAD of POSTing ``token_url``; returns
+ # the token-endpoint JSON or raises ``AuthError``. The broker holds the client secret, so the
+ # plugin owns that transport and ``token_url`` is unused.
+ token_request: Optional[Callable[[Dict[str, str]], Mapping[str, Any]]] = None
def _err(provider: str, message: str, code: str):
@@ -78,6 +83,8 @@ def _endpoint_host(provider: str, name: str, url: str) -> str:
def validate_config(provider: str, cfg: OAuthPKCEConfig) -> None:
"""Refuse a misdeclared config before any network request (login AND refresh call this)."""
+ if cfg.token_request is not None:
+ return # brokered: no client or token endpoint of our own to check
if not str(cfg.client_id or "").strip():
raise _err(provider, "OAuth client_id is missing.", "oauth_client_id_missing")
authorize_host = _endpoint_host(provider, "authorize_url", cfg.authorize_url)
@@ -91,10 +98,13 @@ def validate_config(provider: str, cfg: OAuthPKCEConfig) -> None:
def _post_token(provider: str, cfg: OAuthPKCEConfig, data: Dict[str, str], *, code: str) -> Dict[str, Any]:
- """POST the token endpoint and return the rotated pool fields; the payload is never logged."""
- from hermes_cli.auth import _coerce_ttl_seconds, _default_verify, _utc_now_z
+ """POST the token endpoint (or the plugin's broker) and return the rotated pool fields; the payload
+ is never logged."""
+ from hermes_cli.auth import _default_verify
from hermes_cli.auth_constants import httpx
+ if cfg.token_request is not None:
+ return _token_fields(provider, cfg.token_request(dict(data)), data, code)
body = {**cfg.extra_token_params, **data, "client_id": cfg.client_id}
if cfg.audience:
body.setdefault("audience", cfg.audience)
@@ -105,7 +115,13 @@ def _post_token(provider: str, cfg: OAuthPKCEConfig, data: Dict[str, str], *, co
raise _err(provider, f"OAuth token request failed: {type(exc).__name__}", code) from exc
if response.status_code >= 400:
raise _token_http_error(provider, response, code)
- payload = response.json()
+ return _token_fields(provider, response.json(), data, code)
+
+
+def _token_fields(provider: str, payload: Mapping[str, Any], data: Dict[str, str], code: str) -> Dict[str, Any]:
+ """Pool fields from a token-endpoint payload; a response without ``refresh_token`` keeps the old one."""
+ from hermes_cli.auth import _coerce_ttl_seconds, _utc_now_z
+
access_token = str(payload.get("access_token") or "").strip()
if not access_token:
raise _err(provider, "OAuth token response carried no access_token.", code)
diff --git a/website/docs/developer-guide/model-provider-plugin.md b/website/docs/developer-guide/model-provider-plugin.md
index 850fc5ce117..e620d7e98a5 100644
--- a/website/docs/developer-guide/model-provider-plugin.md
+++ b/website/docs/developer-guide/model-provider-plugin.md
@@ -99,6 +99,7 @@ Full definition in `providers/base.py`. The most useful ones:
| `display_name` | str | Human label shown in `hermes model` picker |
| `description` | str | Picker subtitle |
| `signup_url` | str | Shown during first-run setup ("get an API key here") |
+| `hidden` | bool | Pre-release: kept off every discovery surface (provider pickers, setup list, dashboard accounts tab) until `listed()` is true β€” by default once the user signs in by name (`hermes auth add <name>` writes a pool row). Resolution by name is never gated |
| `env_vars` | `tuple[str, ...]` | API-key env vars in priority order; a final `*_BASE_URL` entry is used as the user base-URL override |
| `base_url` | str | Default inference endpoint |
| `models_url` | str | Explicit catalog URL (falls back to `{base_url}/models`) |
@@ -478,6 +479,13 @@ 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`.
+A confidential client whose secret lives behind your own broker sets `token_request` instead of
+`token_url`: Hermes calls it with the grant fields (`grant_type`, `code` / `refresh_token`,
+`redirect_uri`, `code_verifier`) and stores whatever token-endpoint JSON it returns, keeping the old
+`refresh_token` when the response omits one. Raise `AuthError(..., relogin_required=True)` for a grant
+the broker reports dead. Rows rotate ahead of their stored `expires_at_ms`, so opaque (non-JWT) access
+tokens refresh on time; the auxiliary client (compression, titles) leases the same pooled row.
+
## Recovery and error classification
A `kind: model-provider` plugin is loaded by provider discovery, **not** by the generic plugin manager, so
@@ -501,7 +509,7 @@ register_provider(ProviderProfile(name="example-oauth", auth_type="oauth_externa
|---|---|
| `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 (for terminal reasons β€” billing, auth, model_not_found … β€” `should_fallback: True` implies `retryable: False` unless you set it, because the fallback chain only runs for non-retryable verdicts; rate-limit reasons keep the built-in retry-then-fallback shape); `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`). |
+| Auxiliary calls | An `oauth_external` / `oauth_device_code` plugin that ships `create_client` serves auxiliary tasks on its pooled row (an expiring row is rotated first); auxiliary 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