The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(auth): OAuth-shaped provider plugins register, log in and refresh through their profile
teknium1dce233e80989
diff --git a/agent/credential_pool.py b/agent/credential_pool.pyindex 56de2f87408..c51c1ff86a4 100644--- a/agent/credential_pool.py+++ b/agent/credential_pool.py@@ -21,6 +21,7 @@ from hermes_constants import OPENROUTER_BASE_URLfrom hermes_cli.config import load_envfrom agent.secret_scope import get_secret as _get_secret, get_secret_strfrom agent.retry_utils import reset_delay_from_message+from hermes_cli.auth_plugin_providers import plugin_refresh_hookfrom agent.credential_persistence import (fingerprint_secret_value,is_borrowed_credential_source,@@ -251,7 +252,10 @@ class PooledCredential:# Rehydrated last_status_at may be an ISO string from to_dict() — normalize to float epochif isinstance(data.get("last_status_at"), str):data["last_status_at"] = _parse_absolute_timestamp(data["last_status_at"])- data["extra"] = {k: payload[k] for k in _EXTRA_KEYS if payload.get(k) is not None}+ # Every non-field key rides in ``extra`` (to_dict writes them all back), so metadata a plugin+ # stores on its own rows survives load -> save -> load. ``_EXTRA_KEYS`` stays the attribute+ # surface for core logic; unknown keys are opaque payload.+ data["extra"] = {k: v for k, v in payload.items() if k not in field_names and v is not None}data.setdefault("id", uuid.uuid4().hex[:6])data.setdefault("label", payload.get("source", provider))data.setdefault("auth_type", AUTH_TYPE_API_KEY)@@ -760,8 +764,10 @@ _TOKENS_SINGLETON_PROVIDERS: Dict[str, Tuple[str, str, str, str]] = {"xai-oauth": ("xAI OAuth", "xAI", "refresh_xai_oauth_pure", "_is_terminal_xai_oauth_refresh_error"),}-# Providers whose pooled OAuth entries ``_refresh_entry_impl`` can actually refresh. Any other-# provider is returned unchanged by that path, so callers must not report a refresh for them.+# Built-in providers whose pooled OAuth entries ``_refresh_entry_impl`` can actually refresh. Plugin+# providers are refreshable when their profile ships ``refresh_credential`` (see+# ``hermes_cli.auth_plugin_providers.is_refreshable_oauth_provider``); any other provider is returned+# unchanged by that path, so callers must not report a refresh for them.REFRESHABLE_OAUTH_PROVIDERS = frozenset({"anthropic", "nous", *_TOKENS_SINGLETON_PROVIDERS})# Providers whose refresh tokens are single-use: the sync -> POST -> write-back@@ -1456,6 +1462,8 @@ class CredentialPool(CredentialPoolAdminMixin, CredentialPoolModelCooldownMixin)elif self.provider in _TOKENS_SINGLETON_PROVIDERS: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 = replace(entry, **dict(plugin_refresh(entry) or {}))elif self.provider == "nous":stale_key = entry.runtime_api_key or entry.agent_key or entry.access_tokensynced = self._sync_nous_entry_from_auth_store(entry)diff --git a/hermes_cli/auth.py b/hermes_cli/auth.pyindex 286f7ff0ea0..058ca6da25c 100644--- a/hermes_cli/auth.py+++ b/hermes_cli/auth.py@@ -254,66 +254,10 @@ PROVIDER_REGISTRY: Dict[str, ProviderConfig] = {from hermes_cli.config import ( # noqa: E402get_hermes_home, get_config_path, read_raw_config, require_readable_config_before_write)-# Providers handled outside the registry: copilot/kimi/zai have bespoke token refresh here;-# openrouter/custom are aggregator/user-supplied and runtime_provider relies on-# ``openrouter not in PROVIDER_REGISTRY``.-_REGISTRY_PLUGIN_SKIP = frozenset({"copilot", "kimi-coding", "kimi-coding-cn", "zai", "openrouter", "custom"})---def _register_plugin_provider(pp: Any) -> None:- """Auto-register one providers/ profile (plugins/model-providers/<name>/) not declared above.-- External-process (ACP) providers have no API-key env vars; registering them is what lets an- out-of-tree provider pass ``resolve_provider()``'s known-provider gate ("Unknown provider")."""- if pp.auth_type == "external_process":- pconfig = ProviderConfig(- pp.name, pp.display_name or pp.name, "external_process", inference_base_url=pp.base_url)- elif pp.auth_type == "api_key" and pp.env_vars and pp.name not in _REGISTRY_PLUGIN_SKIP:- is_url = lambda v: v.endswith("_BASE_URL") or v.endswith("_URL") # noqa: E731- pconfig = _api_key_provider(- pp.name, pp.display_name or pp.name, pp.base_url,- tuple(v for v in pp.env_vars if not is_url(v)) or pp.env_vars,- next((v for v in pp.env_vars if is_url(v)), None) or "")- else:- return- PROVIDER_REGISTRY[pp.name] = pconfig- for alias in pp.aliases: # so resolve_provider() resolves them too- PROVIDER_REGISTRY.setdefault(alias, pconfig)---def sync_plugin_provider_registry() -> int:- """Mirror provider-plugin profiles into ``PROVIDER_REGISTRY``; return how many were added.-- Idempotent and cheap (only missing names are registered, existing entries are never replaced),- so it is safe from resolution paths. It runs once at import below and again whenever a name is- missing (:func:`_registry_lookup`) or when ``providers`` finishes discovery, because the- import-time pass can observe a *partial* profile list: if a plugin's own imports pull this- module in while ``providers._discover_providers()`` is still iterating the plugin directories,- ``list_providers()`` returns only what has been registered so far (the discovery guard is- already set) and every plugin discovered after that point would otherwise be invisible to- ``resolve_provider()`` and fail with "Unknown provider". See #102123."""- try:- from providers import list_providers as _list_providers_for_registry- profiles = _list_providers_for_registry()- except Exception:- return 0- added = 0- for pp in profiles:- if pp.name in PROVIDER_REGISTRY:- continue- _register_plugin_provider(pp)- if pp.name in PROVIDER_REGISTRY:- added += 1- return added---def _registry_lookup(provider_id: str) -> Optional[ProviderConfig]:- """``PROVIDER_REGISTRY.get`` that re-syncs plugin profiles on a miss."""- pconfig = PROVIDER_REGISTRY.get(provider_id)- if pconfig is None and sync_plugin_provider_registry():- pconfig = PROVIDER_REGISTRY.get(provider_id)- return pconfig-+# Plugin profiles (plugins/model-providers/<name>/) are mirrored into PROVIDER_REGISTRY with the+# auth_type they declare; the mirror lives in the sibling so it can be re-run after discovery.+from hermes_cli.auth_plugin_providers import ( # noqa: E402+ registry_lookup as _registry_lookup, sync_plugin_provider_registry)sync_plugin_provider_registry()diff --git a/hermes_cli/auth_commands.py b/hermes_cli/auth_commands.pyindex 0b7bc4ee69f..c4c3520b8de 100644--- a/hermes_cli/auth_commands.py+++ b/hermes_cli/auth_commands.py@@ -3,8 +3,6 @@from __future__ import annotationsfrom hermes_cli.cli_output import line_input-import asyncio-import inspectimport mathimport sysimport time@@ -16,11 +14,13 @@ import uuidfrom agent.credential_pool import (AUTH_TYPE_API_KEY, AUTH_TYPE_OAUTH, CUSTOM_POOL_PREFIX, SOURCE_MANUAL,SOURCE_MANUAL_DEVICE_CODE, STATUS_EXHAUSTED, STRATEGY_FILL_FIRST, STRATEGY_ROUND_ROBIN,- STRATEGY_RANDOM, STRATEGY_LEAST_USED, PooledCredential, REFRESHABLE_OAUTH_PROVIDERS, _codex_principal_identity,+ STRATEGY_RANDOM, STRATEGY_LEAST_USED, PooledCredential, _codex_principal_identity,_exhausted_until, _normalize_custom_pool_name, get_pool_strategy, label_from_token, list_custom_pool_providers,load_pool)import hermes_cli.auth as auth_modfrom hermes_cli.auth import PROVIDER_REGISTRY+from hermes_cli.auth_plugin_providers import (+ dispatch_plugin_auth, is_refreshable_oauth_provider, plugin_missing_auth_handler_error)from hermes_constants import OPENROUTER_BASE_URLfrom hermes_cli.secret_prompt import masked_secret_prompt@@ -89,83 +89,6 @@ def _normalize_provider(provider: str) -> str:or auth_mod._plugin_aliases().get(normalized) or normalized)-# ── Provider-owned interactive auth ──────────────────────────────────────────-# A `kind: model-provider` plugin can set ``ProviderProfile.auth_handler`` and own-# the interactive login flow for its provider (device-code, OIDC, …) without-# shipping a second standalone command plugin — model-provider manifests are-# skipped by the generic command-plugin loader on purpose. The four actions-# below consult that handler FIRST; a provider without one (or a handler that-# declines an action by returning falsy) keeps the built-in behavior untouched.--def _provider_auth_handler(provider: str) -> tuple[Any, Callable | None]:- """Return ``(profile, handler)`` when *provider*'s plugin owns its own auth.-- ``(None, None)`` when no profile is registered for the name, ``(profile,- None)`` when one is registered without an auth handler.- """- try:- from providers import get_provider_profile- except Exception: # provider layer unavailable — built-in path only- return None, None- profile = get_provider_profile(provider)- handler = profile.auth_handler if profile is not None else None- return (profile, handler) if callable(handler) else (profile, None)---def _await_from_sync(coro):- """Run a provider handler's coroutine from the sync CLI path.-- Safe inside a running loop too (gateway/embedded callers) — same idiom as- ``agent.context_references.preprocess_context_references``.- """- try:- asyncio.get_running_loop()- except RuntimeError:- return asyncio.run(coro)- import concurrent.futures- with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:- return pool.submit(asyncio.run, coro).result()---def _dispatch_provider_auth(action: str, args, provider: str) -> bool:- """Offer ``hermes auth <action> <provider>`` to the provider's auth handler.-- Returns True when the provider owned the action (core prints nothing more- and returns); False when the caller must run the built-in path. A handler- that fails becomes a readable ``SystemExit`` naming provider and action- instead of a raw traceback.- """- _profile, handler = _provider_auth_handler(provider)- if handler is None:- return False- try:- result = handler(action, args)- if inspect.isawaitable(result):- result = _await_from_sync(result)- except SystemExit:- raise- except Exception as exc:- raise SystemExit(- f"{provider} auth handler failed for `{action}`: {type(exc).__name__}: {exc}"- ) from exc- return bool(result)---def _unknown_provider_error(provider: str, action: str) -> SystemExit:- """The existing ``Unknown provider`` exit, with a hint for plugin providers.-- A registered model-provider profile that reaches this point offers no- ``auth_handler`` for the requested action (or declined it) — say so rather- than pretending the provider is unknown.- """- profile, _handler = _provider_auth_handler(provider)- if profile is not None:- return SystemExit(- f"Unknown provider: {provider} — the `{profile.name}` model-provider plugin does "- f"not provide auth handling for `hermes auth {action} {provider}`.")- return _unknown_provider_exit(provider)--def _migrate_legacy_custom_pool_key(provider: str, legacy_key: str) -> None:"""Move a keyed provider's old ``custom:`` pool into its runtime slug."""with auth_mod._auth_store_lock():@@ -453,11 +376,13 @@ def _add_api_key_credential(args, provider: str, pool) -> PooledCredential:def auth_add_command(args) -> None:provider = _normalize_provider(getattr(args, "provider", ""))- if _dispatch_provider_auth("add", args, provider):+ if dispatch_plugin_auth("add", args, provider):returnconfigured_provider = _configured_provider_entry(provider)if not _is_known_provider(provider, configured_provider):- raise _unknown_provider_error(provider, "add")+ raise _unknown_provider_exit(provider)+ if (error := plugin_missing_auth_handler_error(provider, "add")) is not None:+ raise errorif configured_provider is not None:_migrate_legacy_custom_pool_key(provider, configured_provider["pool_key"])@@ -681,7 +606,7 @@ def auth_refresh_command(args) -> None:429s and benches it again. Failure leaves the pool's own verdict in place."""provider = _normalize_provider(getattr(args, "provider", ""))- if _dispatch_provider_auth("refresh", args, provider):+ if dispatch_plugin_auth("refresh", args, provider):returntarget = getattr(args, "target", None)pool = load_pool(provider)@@ -698,7 +623,7 @@ def auth_refresh_command(args) -> None:index, matched, error = pool.resolve_target(target)if matched is None or index is None:raise SystemExit(f"{error} Provider: {provider}.")- if (provider not in REFRESHABLE_OAUTH_PROVIDERS or matched.auth_type != AUTH_TYPE_OAUTH+ if (not is_refreshable_oauth_provider(provider) or matched.auth_type != AUTH_TYPE_OAUTHor not matched.refresh_token):raise SystemExit(f"{provider} credential #{index} ({matched.label}) is not a refreshable OAuth "@@ -731,7 +656,7 @@ def auth_status_command(args) -> None:provider = _normalize_provider(getattr(args, "provider", "") or "")if not provider:raise SystemExit("Provider is required. Example: `hermes auth status spotify`.")- if _dispatch_provider_auth("status", args, provider):+ if dispatch_plugin_auth("status", args, provider):returnstatus = auth_mod.get_auth_status(provider)if status.get("free_tier"):@@ -757,7 +682,7 @@ def auth_logout_command(args) -> None:# The built-in path keeps receiving the raw provider id (byte-for-byte# unchanged); the normalized alias is used only for the handler lookup.raw_provider = getattr(args, "provider", None)- if _dispatch_provider_auth("logout", args, _normalize_provider(raw_provider or "")):+ if dispatch_plugin_auth("logout", args, _normalize_provider(raw_provider or "")):returnauth_mod.logout_command(SimpleNamespace(provider=raw_provider))@@ -866,11 +791,13 @@ def _pick_provider(prompt: str = "Provider") -> str:def _interactive_add() -> None:provider = _pick_provider("Provider to add credential for")- if _dispatch_provider_auth("add", SimpleNamespace(provider=provider), provider):+ if dispatch_plugin_auth("add", SimpleNamespace(provider=provider), provider):returnconfigured_provider = _configured_provider_entry(provider)if not _is_known_provider(provider, configured_provider):- raise _unknown_provider_error(provider, "add")+ raise _unknown_provider_exit(provider)+ if (error := plugin_missing_auth_handler_error(provider, "add")) is not None:+ raise errorauth_type = "api_key"if provider in _OAUTH_CAPABLE_PROVIDERS:diff --git a/hermes_cli/auth_plugin_providers.py b/hermes_cli/auth_plugin_providers.pynew file mode 100644index 00000000000..a7c1d8a7664--- /dev/null+++ b/hermes_cli/auth_plugin_providers.py@@ -0,0 +1,152 @@+"""Model-provider plugins as first-class citizens of ``hermes auth`` and the credential pool.++A ``plugins/model-providers/<name>/`` profile (``providers.base.ProviderProfile``) is mirrored into+``hermes_cli.auth.PROVIDER_REGISTRY`` with the ``auth_type`` it declares, so ``resolve_provider()``+accepts it whatever its auth shape. Non-api-key plugins own their login through two optional profile+callables that core consults BEFORE any built-in, name-keyed path:++- ``auth_handler(action, args) -> bool`` for ``hermes auth add|status|logout|refresh <name>``+ (``args`` is the parsed CLI namespace; truthy = the plugin owned the action, falsy = built-in path).+- ``refresh_credential(entry) -> Mapping | None`` for the credential pool: given the pooled+ ``PooledCredential`` it returns the rotated fields (``access_token``, ``refresh_token``,+ ``expires_at_ms`` …) or raises. A separate hook rather than ``auth_handler("refresh", …)`` because+ the pool has a credential row, not an argparse namespace, and needs tokens back, not a bool.++Every function here late-imports ``hermes_cli.auth`` names: this module is imported by the auth facade+right after ``PROVIDER_REGISTRY`` exists, and by ``agent.credential_pool``.+"""+from __future__ import annotations++import logging+from typing import Any, Callable, Optional++logger = logging.getLogger(__name__)++# Providers handled outside the registry: copilot/kimi/zai have bespoke token refresh in auth.py;+# openrouter/custom are aggregator/user-supplied and runtime_provider relies on+# ``openrouter not in PROVIDER_REGISTRY``.+_REGISTRY_PLUGIN_SKIP = frozenset({"copilot", "kimi-coding", "kimi-coding-cn", "zai", "openrouter", "custom"})++PLUGIN_AUTH_ACTIONS = ("add", "status", "logout", "refresh")+++def register_plugin_provider(pp: Any) -> None:+ """Mirror one profile into ``PROVIDER_REGISTRY`` under the ``auth_type`` it declares.++ Registering is what lets an out-of-tree provider pass ``resolve_provider()``'s known-provider+ gate ("Unknown provider"); OAuth-shaped plugins carry their own login via ``auth_handler``.+ """+ from hermes_cli.auth import PROVIDER_REGISTRY, ProviderConfig, _api_key_provider++ if pp.name in _REGISTRY_PLUGIN_SKIP:+ return+ if pp.auth_type == "api_key":+ if not pp.env_vars:+ return+ is_url = lambda v: v.endswith("_BASE_URL") or v.endswith("_URL") # noqa: E731+ pconfig = _api_key_provider(+ pp.name, pp.display_name or pp.name, pp.base_url,+ tuple(v for v in pp.env_vars if not is_url(v)) or pp.env_vars,+ next((v for v in pp.env_vars if is_url(v)), None) or "")+ else:+ pconfig = ProviderConfig(pp.name, pp.display_name or pp.name, pp.auth_type, inference_base_url=pp.base_url)+ PROVIDER_REGISTRY[pp.name] = pconfig+ for alias in pp.aliases: # so resolve_provider() resolves them too+ PROVIDER_REGISTRY.setdefault(alias, pconfig)+++def sync_plugin_provider_registry() -> int:+ """Mirror provider-plugin profiles into ``PROVIDER_REGISTRY``; return how many were added.++ Idempotent (existing entries are never replaced), so it is safe from resolution paths. It runs at+ auth import and again whenever a name is missing (:func:`registry_lookup`) or when ``providers``+ finishes discovery, because the import-time pass can observe a *partial* profile list: a plugin+ whose own imports pull ``hermes_cli.auth`` in mid-``_discover_providers()`` sees only what was+ registered so far, and every later plugin would otherwise fail with "Unknown provider" (#102123).+ """+ from hermes_cli.auth import PROVIDER_REGISTRY++ try:+ from providers import list_providers+ profiles = list_providers()+ except Exception:+ return 0+ added = 0+ for pp in profiles:+ if pp.name in PROVIDER_REGISTRY:+ continue+ register_plugin_provider(pp)+ added += pp.name in PROVIDER_REGISTRY+ return added+++def registry_lookup(provider_id: str) -> Optional[Any]:+ """``PROVIDER_REGISTRY.get`` that re-syncs plugin profiles on a miss."""+ from hermes_cli.auth import PROVIDER_REGISTRY++ pconfig = PROVIDER_REGISTRY.get(provider_id)+ if pconfig is None and sync_plugin_provider_registry():+ pconfig = PROVIDER_REGISTRY.get(provider_id)+ return pconfig+++def plugin_profile(provider: str) -> Optional[Any]:+ """The registered ``ProviderProfile`` for *provider*, or None (also when the layer is unavailable)."""+ try:+ from providers import get_provider_profile+ except Exception:+ return None+ return get_provider_profile(provider)+++def _profile_hook(provider: str, name: str) -> Optional[Callable[..., Any]]:+ hook = getattr(plugin_profile(provider), name, None)+ return hook if callable(hook) else None+++def plugin_auth_handler(provider: str) -> Optional[Callable[[str, Any], Any]]:+ return _profile_hook(provider, "auth_handler")+++def plugin_refresh_hook(provider: str) -> Optional[Callable[[Any], Any]]:+ """The profile's ``refresh_credential`` hook, i.e. whether its pooled OAuth rows are refreshable."""+ return _profile_hook(provider, "refresh_credential")+++def is_refreshable_oauth_provider(provider: str) -> bool:+ """Built-in refreshable set OR a plugin profile shipping ``refresh_credential``."""+ from agent.credential_pool import REFRESHABLE_OAUTH_PROVIDERS++ return provider in REFRESHABLE_OAUTH_PROVIDERS or plugin_refresh_hook(provider) is not None+++def dispatch_plugin_auth(action: str, args: Any, provider: str) -> bool:+ """Offer ``hermes auth <action> <provider>`` to the provider's ``auth_handler``.++ True = the plugin owned the action (core prints nothing more). False = run the built-in path. A+ handler exception becomes a readable ``SystemExit`` naming provider and action.+ """+ handler = plugin_auth_handler(provider)+ if handler is None:+ return False+ try:+ return bool(handler(action, args))+ except SystemExit:+ raise+ except Exception as exc:+ raise SystemExit(f"{provider} auth handler failed for `{action}`: {type(exc).__name__}: {exc}") from exc+++def plugin_missing_auth_handler_error(provider: str, action: str) -> Optional[SystemExit]:+ """Fail loud for a registered non-api-key plugin that ships no ``auth_handler``.++ Its login is not something core can perform (there is no token endpoint to call), and silently+ running the api-key prompt or reporting "Unknown provider" both hide the plugin bug.+ """+ profile = plugin_profile(provider)+ if profile is None or profile.auth_type == "api_key" or plugin_auth_handler(provider) is not None:+ return None+ return SystemExit(+ f"Provider '{provider}' declares auth_type '{profile.auth_type}' but its plugin ships no "+ f"auth_handler, so `hermes auth {action} {provider}` cannot be handled. Add "+ "`auth_handler=` to its ProviderProfile (see the model-provider plugin guide).")diff --git a/providers/base.py b/providers/base.pyindex 6e5f23ff4a9..9a275fc0dee 100644--- a/providers/base.py+++ b/providers/base.py@@ -13,7 +13,7 @@ from __future__ import annotationsimport loggingfrom dataclasses import dataclass, field-from typing import Any+from typing import Any, Callablelogger = logging.getLogger(__name__)@@ -58,15 +58,14 @@ class ProviderProfile:# False → fetch_models returns None without a network call (catalog comes from an SDK/subprocess).supports_model_listing: bool = True- # ── Provider-owned interactive auth (optional) ────────────- # Lets a `kind: model-provider` plugin own its own login flow instead of- # shipping a second command plugin. When set, `hermes auth <action> <name>`- # (action ∈ add|status|logout|refresh) calls it FIRST as- # ``auth_handler(action, args)`` — ``args`` is the parsed CLI namespace — and- # only falls back to the built-in credential-pool flow when the handler- # returns falsy. Sync or async (a returned awaitable is awaited). The- # handler owns its own credential storage; Hermes passes no secrets to it.- auth_handler: Any = None+ # ── Provider-owned auth (optional; non-api-key plugins) ──────────+ # ``auth_handler(action, args) -> bool``: ``hermes auth add|status|logout|refresh <name>`` calls it+ # FIRST with the parsed CLI namespace; truthy = the plugin owned the action, falsy = built-in path.+ # ``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.+ auth_handler: Callable[[str, Any], Any] | None = None+ refresh_credential: Callable[[Any], Any] | None = None# ── Vision support ────────────────────────────────────────# True when the provider's API accepts image content insidediff --git a/website/docs/developer-guide/model-provider-plugin.md b/website/docs/developer-guide/model-provider-plugin.mdindex bc7e6522455..bf257cea7ac 100644--- a/website/docs/developer-guide/model-provider-plugin.md+++ b/website/docs/developer-guide/model-provider-plugin.md@@ -100,7 +100,8 @@ Full definition in `providers/base.py`. The most useful ones:| `base_url` | str | Default inference endpoint || `models_url` | str | Explicit catalog URL (falls back to `{base_url}/models`) || `auth_type` | str | `api_key` \| `oauth_device_code` \| `oauth_external` \| `copilot` \| `aws_sdk` \| `external_process` |-| `auth_handler` | `Callable \| None` | Optional provider-owned interactive auth for `hermes auth add/status/logout/refresh <name>` — see [Provider-owned interactive auth](#provider-owned-interactive-auth-auth_handler) |+| `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 || `fallback_models` | `tuple[str, ...]` | Curated list shown when live catalog fetch fails || `default_headers` | `dict[str, str]` | Sent on every request (e.g. Copilot's `Editor-Version`) || `fixed_temperature` | Any | `None` = use caller's value; `OMIT_TEMPERATURE` sentinel = don't send temperature at all (Kimi) |@@ -220,60 +221,76 @@ Set `profile.api_mode` to match the default your provider ships — it acts as a| `auth_type` | Meaning | Who uses it ||---|---|---|| `api_key` | Single env var carries a static API key | Most providers |-| `oauth_device_code` | Device-code OAuth flow | — |+| `oauth_device_code` | Device-code OAuth flow | Nous Portal; out-of-tree plugins via `auth_handler` || `oauth_external` | User signs in elsewhere, tokens land in `auth.json` | Anthropic OAuth, MiniMax OAuth, Qwen Portal, Nous Portal || `copilot` | GitHub Copilot token refresh cycle | `copilot` plugin only || `aws_sdk` | AWS SDK credential chain (IAM role, profile, env) | `bedrock` plugin only || `external_process` | Auth handled by a subprocess the agent spawns (see [External-process providers](#external-process-acp-providers)) | `copilot-acp` plugin, out-of-tree ACP plugins |-`auth_type` gates which codepaths treat your provider as a "simple api-key provider" — if it's not `api_key`, the PluginManager still records the manifest but Hermes' CLI-level automation (doctor checks, `--provider` flag, setup wizard delegation) may skip over it.+Every profile is mirrored into Hermes' auth registry under the `auth_type` it declares, so `hermes auth`,+`--provider <name>` and runtime resolution accept it whatever its shape. What differs is who performs the+login: `api_key` profiles get the built-in key prompt / env-var resolution; every other `auth_type` is+**provider-owned** — the plugin ships the two hooks below, and a non-api-key profile without an+`auth_handler` makes `hermes auth add <name>` fail with a clear "ships no auth_handler" error instead of+silently doing nothing.-## Provider-owned interactive auth (`auth_handler`)+## Provider-owned auth (`auth_handler`, `refresh_credential`)-`auth_type` describes *what kind* of credential a provider needs; `auth_handler` is how the-plugin **acquires** it — its own device-code / OIDC / IdC flow inside the existing `hermes auth`-command family, with no second standalone command plugin (model-provider manifests are skipped by-the generic command-plugin loader, so `register(ctx)` is not the way to add commands).+`auth_type` describes *what kind* of credential a provider needs; `auth_handler` is how the plugin+**acquires** it — its own device-code / OIDC / IdC flow inside the existing `hermes auth` command family+(model-provider manifests are skipped by the generic command-plugin loader, so `register(ctx)` is not the+way to add commands). `refresh_credential` is how the credential pool **rotates** a pooled token the plugin+stored.```python+import uuidfrom providers import register_providerfrom providers.base import ProviderProfile-def kiro_auth(action: str, args) -> bool:+def example_auth(action: str, args) -> bool:"""action: "add" | "status" | "logout" | "refresh"; args: parsed CLI namespace."""if action == "add":- start_url = input("IdC start URL: ").strip() # provider-specific inputs- creds = run_device_code_flow(start_url)- save_my_credentials(creds) # the plugin owns its own storage- print("Signed in to Kiro.")+ from agent.credential_pool import AUTH_TYPE_OAUTH, PooledCredential, load_pool+ tokens = run_device_code_flow() # provider-specific+ load_pool("example-oauth").add_entry(PooledCredential(+ provider="example-oauth", id=uuid.uuid4().hex[:6], label=tokens["account"],+ auth_type=AUTH_TYPE_OAUTH, priority=0, source="manual:example_device",+ access_token=tokens["access_token"], refresh_token=tokens["refresh_token"],+ extra={"tenant": tokens["tenant"]})) # any extra keys round-trip through auth.json+ print("Signed in to Example.")return Trueif action == "status":- print("kiro: " + ("logged in" if load_my_credentials() else "logged out"))+ print("example-oauth: " + ("logged in" if load_pool("example-oauth").entries() else "logged out"))return Truereturn False # decline → this action stays with the built-in credential-pool handling+def example_refresh(entry):+ """Called by the credential pool with the pooled row; return the rotated fields or raise."""+ tokens = post_refresh(entry.refresh_token)+ return {"access_token": tokens["access_token"], "refresh_token": tokens["refresh_token"],+ "expires_at_ms": tokens["expires_at_ms"]}++register_provider(ProviderProfile(- name="kiro", auth_type="oauth_device_code", auth_handler=kiro_auth))+ name="example-oauth", auth_type="oauth_external", base_url="https://api.example.com/v1",+ auth_handler=example_auth, refresh_credential=example_refresh))```| Contract | ||---|---|-| Signature | `auth_handler(action, args)` — `args` is the parsed `hermes auth` namespace |-| Return | truthy = handled (Hermes prints nothing more, exit 0); falsy = fall back to the built-in path **for that action** |-| Async | a returned awaitable is awaited, so `async def` handlers work |-| Failure | an exception becomes `SystemExit("<provider> auth handler failed for `<action>`: ValueError: …")` |-| No handler | `hermes auth <action> <provider>` behaves exactly as it did before the seam |+| `auth_handler(action, args)` | `args` is the parsed `hermes auth` namespace. 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 `<action>`: …")`. |+| `refresh_credential(entry)` | Receives the `PooledCredential`; returns a mapping of rotated fields (`access_token`, `refresh_token`, `expires_at_ms`, …) applied to the row, or raises (the pool benches the row). Its presence is what makes the provider *refreshable* — `hermes auth refresh <name>` and the 401 recovery paths (main loop and auxiliary client) call it; no core name list is involved. |+| No hooks | `api_key` profiles behave exactly as before. Any other `auth_type` without `auth_handler` fails loud on `hermes auth add`. |-`hermes auth add|status|logout|refresh <provider>` consults the handler **first** — before the-known-provider gate and before the credential pool — so a provider Hermes does not otherwise-recognize (`oauth_device_code`, `oauth_external`) is fully drivable. Registering the same name-twice is last-writer-wins, so a user plugin can replace a bundled provider's flow.+`hermes auth add|status|logout|refresh <provider>` consults the handler **first** — before the built-in+credential-pool flow. Registering the same name twice is last-writer-wins, so a user plugin can replace a+bundled provider's flow.Hermes passes the parsed namespace, not provider-declared flags: ask for provider-specific values-interactively (or read your own config/env). Credentials stay provider-owned — Hermes hands your-handler no secrets and reads none back.+interactively (or read your own config/env). Rows the plugin stores in the pool are its own — extra keys+survive `load → save → load`, and Hermes passes no secrets beyond that pooled row to `refresh_credential`.## Discovery timing