Skip to content

The agent that grows with you

feat(auth): add key_cmd credential source for custom providers

LordMelkor6efab2872626
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index d49a797ed8a..d1a513c7ec1 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -6483,6 +6483,17 @@ def resolve_provider_client(
custom_key_env = (custom_entry.get("key_env") or custom_entry.get("api_key_env") or "").strip()
if not custom_key and custom_key_env:
custom_key = _scoped_key_env(custom_key_env)
+ # Auxiliary tasks resolve named custom providers here rather than
+ # through _resolve_named_custom_runtime, so key_cmd has to be
+ # honoured on both paths at matching precedence: otherwise the main
+ # agent turn works while every auxiliary call (title generation,
+ # compression, vision, embedding) 401s on the placeholder below.
+ custom_key_cmd = str(custom_entry.get("key_cmd", "") or "").strip()
+ if custom_key_cmd:
+ from agent.command_token_source import build_command_token_provider
+ custom_key = build_command_token_provider(
+ custom_key_cmd, custom_entry.get("name") or provider
+ ) or custom_key
custom_key = custom_key or "no-key-required"
if custom_key == "no-key-required":
logger.warning(
diff --git a/agent/command_token_source.py b/agent/command_token_source.py
new file mode 100644
index 00000000000..e12cb2e7e86
--- /dev/null
+++ b/agent/command_token_source.py
@@ -0,0 +1,186 @@
+"""Mint a provider API key by running a command (``key_cmd``).
+
+Static API keys are the exception at enterprise gateways: SSO/OIDC brokers,
+cloud IAM, and internal auth proxies all issue SHORT-LIVED bearers instead.
+A key copied into ``.env`` (``key_env``) is stale within the hour, so every
+request after that 401s and the user has to restart the session.
+
+``key_cmd`` names a command that PRINTS a token, so the credential is derived
+rather than stored::
+
+ providers:
+ my-gateway:
+ base_url: https://gateway.internal.example.com/v1
+ api_mode: chat_completions
+ key_cmd: my-auth-cli print-token --profile prod
+
+This is the established pattern for agent tooling — Claude Code's
+``apiKeyHelper``, the ``gcloud auth print-access-token`` / ``aws ecr
+get-login-password`` idiom, and vendor helpers such as ``databricks auth
+token`` all expose exactly this contract. Hermes already accepts a callable
+API key on both wire clients (the Entra ID / Azure identity path) and invokes
+it per request, so nothing downstream changes: the token is simply always
+fresh. It is cached until shortly before expiry, so the command runs about
+once per token lifetime rather than once per request.
+
+Output contract: print ONLY the token on stdout, either bare or as JSON with
+an ``access_token`` field (``expires_in`` is honoured when present) — the
+shape OAuth 2.0 token endpoints and the helpers above already emit.
+
+Precedence: an explicit ``--api-key`` still wins (the one-off recovery escape
+hatch); otherwise ``key_cmd`` is preferred over a static ``api_key`` /
+``key_env`` on the same entry.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+import subprocess
+import threading
+import time
+from typing import Callable, Optional
+
+logger = logging.getLogger(__name__)
+
+# Treat a cached token as spent slightly before its stated expiry, so a request
+# can't be signed with a token that dies in flight. 60s matches the leeway used
+# by comparable OAuth token caches.
+_TOKEN_REFRESH_LEEWAY_SECONDS = 60.0
+# A token helper reads a local credential cache and should answer in
+# milliseconds; anything approaching this budget is hung, not slow.
+_MINT_TIMEOUT_SECONDS = 15
+
+
+class CommandTokenError(RuntimeError):
+ """A ``key_cmd`` failed to produce a usable token."""
+
+
+def _mint(command: str, label: str) -> tuple[str, Optional[float]]:
+ """Run *command*, returning ``(token, ttl_seconds_or_None)``."""
+ try:
+ completed = subprocess.run(
+ command,
+ shell=True,
+ capture_output=True,
+ text=True,
+ timeout=_MINT_TIMEOUT_SECONDS,
+ )
+ except subprocess.TimeoutExpired as exc:
+ raise CommandTokenError(
+ f"key_cmd for provider {label!r} timed out after "
+ f"{_MINT_TIMEOUT_SECONDS}s"
+ ) from exc
+ except OSError as exc:
+ raise CommandTokenError(
+ f"key_cmd for provider {label!r} could not be executed: {exc}"
+ ) from exc
+
+ if completed.returncode != 0:
+ # NEVER include stdout/stderr: a partially-successful auth helper can
+ # print a token or refresh secret there. The command STRING is also
+ # withheld — a key_cmd can legitimately embed a secret
+ # (`print-token --client-secret=…`), so echoing it back would leak the
+ # very credential this module exists to protect. Name the provider so
+ # the user knows which config entry to run by hand.
+ raise CommandTokenError(
+ f"key_cmd for provider {label!r} exited {completed.returncode}. "
+ f"Run that provider's key_cmd manually to see why "
+ f"(e.g. `databricks auth login` if its OAuth session expired)."
+ )
+
+ stdout = completed.stdout or ""
+ if not stdout.strip():
+ raise CommandTokenError(f"key_cmd for provider {label!r} produced no output")
+
+ # JSON payload — the shape `databricks auth token --output json` prints.
+ # Token extraction mirrors databricks/ucode's get_databricks_token:
+ # json.loads(result.stdout or "{}").get("access_token", "")
+ if stdout.lstrip().startswith("{"):
+ try:
+ payload = json.loads(stdout)
+ except json.JSONDecodeError:
+ payload = None
+ if isinstance(payload, dict):
+ token = str(payload.get("access_token") or "").strip()
+ if not token:
+ raise CommandTokenError(
+ f"key_cmd for provider {label!r} returned JSON without an "
+ "'access_token' field"
+ )
+ ttl = payload.get("expires_in")
+ if isinstance(ttl, (int, float)) and ttl > 0:
+ return token, float(ttl)
+ # A relative lifetime is the OAuth 2.0 field, but CLI token helpers
+ # commonly print an absolute ISO 8601 deadline instead. Treating
+ # that as "no TTL advertised" caches the token for the life of the
+ # process, so every request 401s once the deadline passes.
+ # Imported lazily: hermes_cli.auth imports from agent.* at module
+ # level, so a top-level import here would risk a cycle.
+ from hermes_cli.auth import _parse_iso_timestamp
+
+ for field in ("expiry", "expiresOn"):
+ deadline = _parse_iso_timestamp(payload.get(field))
+ if deadline is not None:
+ remaining = deadline - time.time()
+ if remaining > 0:
+ return token, remaining
+ return token, None
+
+ # Bare token. The contract every comparable helper documents is "stdout
+ # carries the token and nothing else" — extra output would be consumed as
+ # part of the credential. Strip surrounding whitespace and take the rest
+ # verbatim; do NOT silently keep one line of several, which converts a
+ # misconfigured helper (banner, warning, two tokens) into a corrupt-key 401
+ # that is far harder to diagnose than an explicit refusal.
+ token = stdout.strip()
+ if "\n" in token:
+ raise CommandTokenError(
+ f"key_cmd for provider {label!r} printed multiple lines; it must "
+ "print only the token (or JSON with an 'access_token' field)"
+ )
+ return token, None
+
+
+class CommandTokenSource:
+ """Callable returning a bearer token, cached until shortly before expiry."""
+
+ def __init__(self, command: str, label: str = "custom") -> None:
+ self._command = command
+ self._label = label or "custom"
+ self._lock = threading.Lock()
+ self._token = ""
+ self._expires_at: Optional[float] = None
+
+ def __call__(self) -> str:
+ with self._lock:
+ # ``expires_at is None`` means the command advertised no TTL: use
+ # the token and rely on the caller's 401 handling, rather than
+ # inventing an expiry. Same contract as buzz's is_expired().
+ if self._token and (
+ self._expires_at is None or time.monotonic() < self._expires_at
+ ):
+ return self._token
+ token, ttl = _mint(self._command, self._label)
+ self._token = token
+ self._expires_at = (
+ time.monotonic() + max(ttl - _TOKEN_REFRESH_LEEWAY_SECONDS, 5.0)
+ if ttl
+ else None
+ )
+ logger.debug(
+ "Minted key_cmd token for provider %s (ttl=%s)",
+ self._label, f"{int(ttl)}s" if ttl else "unknown",
+ )
+ return token
+
+
+def build_command_token_provider(
+ key_cmd: str,
+ provider_label: str = "custom",
+) -> Optional[Callable[[], str]]:
+ """A per-request token provider for *key_cmd*, or ``None`` when unset."""
+ command = str(key_cmd or "").strip()
+ if not command:
+ return None
+ return CommandTokenSource(command, provider_label)
diff --git a/cli-config.yaml.example b/cli-config.yaml.example
index 4dee7a61f3b..f23783e6f55 100644
--- a/cli-config.yaml.example
+++ b/cli-config.yaml.example
@@ -133,6 +133,59 @@ model:
# CF-Access-Client-Secret: "${CF_ACCESS_SECRET}"
# X-Client-Name: "hermes-agent"
+# Command-minted credentials (optional): key_cmd
+# ------------------------------------------------------------------
+# Enterprise gateways often issue SHORT-LIVED bearers (SSO/OIDC brokers, cloud
+# IAM, internal auth proxies) rather than static API keys, so a value copied
+# into .env via `key_env` is stale within the hour and every later request 401s.
+# `key_cmd` names a command that PRINTS a token instead: Hermes runs it per
+# request (cached until shortly before expiry), so long sessions keep working
+# with no restart.
+#
+# Contract: print ONLY the token on stdout, either bare or as JSON with an
+# "access_token" field ("expires_in" is honoured). Same shape as OAuth 2.0
+# token endpoints, Claude Code's `apiKeyHelper`, `gcloud auth
+# print-access-token`, and `aws ecr get-login-password`.
+#
+# Precedence: an explicit --api-key still wins; otherwise key_cmd is preferred
+# over inline api_key / key_env on that entry.
+#
+# Applies to the main agent turn and to auxiliary tasks (title generation,
+# context compression, vision, embedding) alike.
+#
+# Not to be confused with `secrets.command`, which is a different mechanism:
+# that one runs a helper ONCE at startup to populate env vars for many secrets
+# at the process level. Use it for a vault or keychain helper that hands back a
+# KEY=VALUE blob. Use `key_cmd` when ONE provider needs a credential refreshed
+# DURING a session, because a startup-time env var cannot be re-minted after it
+# expires.
+#
+# providers:
+# my-gateway:
+# base_url: "https://gateway.internal.example.com/v1"
+# api_mode: chat_completions
+# key_cmd: "my-auth-cli print-token --profile prod"
+#
+# Worked example — an AI gateway that routes by model family, so one entry per
+# wire format shares the same credential helper:
+#
+# providers:
+# dbx: # OpenAI-compatible (MLflow) route
+# base_url: "https://<workspace>.cloud.databricks.com/ai-gateway/mlflow/v1"
+# api_mode: chat_completions
+# model: databricks-claude-sonnet-4-6
+# key_cmd: "databricks auth token -p MY-PROFILE"
+# dbx-gpt: # OpenAI Responses route
+# base_url: "https://<workspace>.cloud.databricks.com/ai-gateway/openai/v1"
+# api_mode: codex_responses
+# model: databricks-gpt-5-5
+# key_cmd: "databricks auth token -p MY-PROFILE"
+# dbx-claude: # Anthropic Messages route
+# base_url: "https://<workspace>.cloud.databricks.com/ai-gateway/anthropic"
+# api_mode: anthropic_messages
+# model: databricks-claude-fable-5
+# key_cmd: "databricks auth token -p MY-PROFILE"
+
# Named provider overrides (optional)
# Use this for per-provider request timeouts, non-stream stale timeouts,
# and per-model exceptions.
@@ -1832,3 +1885,6 @@ updates:
# command: "cat /run/user/1000/hermes-secrets.env"
# helper_timeout_seconds: 3
# override_existing: false # .env/shell win by default
+# # This runs ONCE per process at startup, so it cannot replace a credential
+# # that expires mid-session. For a single provider whose token needs
+# # re-minting during a session, use `providers.<name>.key_cmd` instead.
diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]
new file mode 100644
index 00000000000..a2862ad8f8b
--- /dev/null
+++ b/contributors/emails/[email protected]
@@ -0,0 +1,2 @@
+LordMelkor
+# key_cmd credential source
diff --git a/hermes_cli/config.py b/hermes_cli/config.py
index bca802d0752..cd226a92ad3 100644
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@ -1360,6 +1360,7 @@ def _normalize_custom_provider_entry(
# configs don't warn on every load.
"provider",
"name", "api", "url", "base_url", "api_key", "key_env", "api_key_env",
+ "key_cmd",
"api_mode", "transport", "model", "default_model", "models",
"context_length", "rate_limit_delay",
"request_timeout_seconds", "stale_timeout_seconds",
diff --git a/hermes_cli/runtime_provider.py b/hermes_cli/runtime_provider.py
index 92cb28c8455..a7da0ae7f1c 100644
--- a/hermes_cli/runtime_provider.py
+++ b/hermes_cli/runtime_provider.py
@@ -763,6 +763,13 @@ def _get_named_custom_provider(requested_provider: str) -> Optional[Dict[str, An
if isinstance(extra_body, dict):
result["extra_body"] = dict(extra_body)
_lift_extra_headers(entry, result)
+ # Command that PRINTS a credential, for gateways issuing
+ # short-lived bearers instead of static keys. Propagated
+ # raw; wrapped in a per-request token provider at
+ # resolution.
+ key_cmd = str(entry.get("key_cmd", "") or "").strip()
+ if key_cmd:
+ result["key_cmd"] = key_cmd
# The v11→v12 migration writes the API mode under the new
# ``transport`` field, but hand-edited configs may still
# use the legacy ``api_mode`` spelling. Accept both —
@@ -1171,6 +1178,22 @@ def _resolve_named_custom_runtime(
]
api_key = next((candidate for candidate in api_key_candidates if has_usable_secret(candidate)), "")
+ # A ``key_cmd`` credential is minted per request rather than resolved once:
+ # gateways that issue short-lived bearers would otherwise go stale
+ # mid-session and 401. Both wire clients already accept a callable api_key
+ # (the Entra ID contract) and invoke it per request. An explicit --api-key
+ # still wins — it is the one-off recovery escape hatch.
+ key_cmd = str(custom_provider.get("key_cmd", "") or "").strip()
+ if key_cmd and not has_usable_secret((explicit_api_key or "").strip()):
+ from agent.command_token_source import build_command_token_provider
+
+ token_provider = build_command_token_provider(
+ key_cmd,
+ str(custom_provider.get("name", requested_provider) or "custom"),
+ )
+ if token_provider is not None:
+ api_key = token_provider
+
result = {
"provider": "custom",
"api_mode": custom_provider.get("api_mode")
diff --git a/tests/agent/test_command_token_source.py b/tests/agent/test_command_token_source.py
new file mode 100644
index 00000000000..b66278f2222
--- /dev/null
+++ b/tests/agent/test_command_token_source.py
@@ -0,0 +1,340 @@
+"""``key_cmd``: derive a provider API key by running a command.
+
+Gateways that issue short-lived bearers (SSO/OIDC brokers, cloud IAM, internal
+auth proxies) make a stored key go stale mid-session. These tests pin the three
+behaviours that make the feature work:
+
+* resolution yields a CALLABLE (invoked per request) rather than a resolved
+ string, so a long session never sends a stale token;
+* the token is cached until shortly before expiry, so the command is not run
+ once per request;
+* a failure never leaks the helper's output or the command string, either of
+ which can contain a credential.
+"""
+
+from __future__ import annotations
+
+import time
+from types import SimpleNamespace
+
+import pytest
+
+from agent.command_token_source import (
+ CommandTokenError,
+ CommandTokenSource,
+ _mint,
+ build_command_token_provider,
+)
+
+
+class TestMinting:
+ def test_bare_token_stdout(self):
+ source = CommandTokenSource("printf 'tok-abc'", "dbx")
+ assert source() == "tok-abc"
+
+ def test_json_access_token(self):
+ """The OAuth 2.0 token-endpoint response shape."""
+ source = CommandTokenSource(
+ """printf '{"access_token":"tok-json","expires_in":3600}'""", "dbx"
+ )
+ assert source() == "tok-json"
+
+ def test_trailing_newline_is_stripped(self):
+ """A raw newline in the credential would corrupt the auth header."""
+ assert CommandTokenSource("echo tok-nl", "dbx")() == "tok-nl"
+
+ def test_multiline_output_is_rejected_not_guessed(self):
+ """Only the token may land on stdout.
+
+ Silently taking the first line turns a misconfigured helper (banner,
+ warning, two tokens) into a corrupt-credential 401 that is much harder
+ to diagnose than an explicit refusal.
+ """
+ source = CommandTokenSource("printf 'banner\\ntok-real'", "dbx")
+ with pytest.raises(CommandTokenError, match="multiple lines"):
+ source()
+
+ def test_json_without_access_token_is_an_error(self):
+ source = CommandTokenSource("""printf '{"nope":1}'""", "dbx")
+ with pytest.raises(CommandTokenError, match="access_token"):
+ source()
+
+ def test_empty_output_is_an_error(self):
+ with pytest.raises(CommandTokenError, match="no output"):
+ CommandTokenSource("true", "dbx")()
+
+ def test_nonzero_exit_is_an_error(self):
+ with pytest.raises(CommandTokenError, match="exited 3"):
+ CommandTokenSource("exit 3", "dbx")()
+
+ def test_failure_message_is_actionable_without_echoing_the_command(self):
+ """Actionable, but never echoes the command (it may embed a secret)."""
+ secret_cmd = "print-token --client-secret=SENTINEL-SECRET; exit 1"
+ with pytest.raises(CommandTokenError) as excinfo:
+ CommandTokenSource(secret_cmd, "dbx")()
+ message = str(excinfo.value)
+ assert "SENTINEL-SECRET" not in message
+ assert "dbx" in message # names the provider to fix
+ assert "exited" in message # states what happened
+
+
+class TestNoCredentialLeak:
+ def test_failure_message_excludes_command_output(self):
+ """A failing auth helper may print a token — it must not be surfaced."""
+ source = CommandTokenSource(
+ "printf 'SENTINEL-SECRET'; printf 'stderr-SENTINEL' >&2; exit 1",
+ "dbx",
+ )
+ with pytest.raises(CommandTokenError) as excinfo:
+ source()
+ assert "SENTINEL" not in str(excinfo.value)
+
+
+class TestCaching:
+ def test_token_is_cached_between_calls(self):
+ """Without caching the command would run on every request."""
+ # A command whose output changes each run: equal results prove caching.
+ source = CommandTokenSource("date +%s%N", "dbx")
+ assert source() == source()
+
+ def test_expired_token_is_reminted(self):
+ source = CommandTokenSource(
+ """printf '{"access_token":"tok-%s","expires_in":3600}' $RANDOM""", "dbx"
+ )
+ first = source()
+ # Force the cache past its expiry.
+ source._expires_at = 0.0
+ assert source() != first
+
+ def test_no_advertised_ttl_caches_indefinitely(self):
+ """No TTL means trust the token and refresh on 401.
+
+ Inventing a synthetic expiry would re-run the command on a schedule
+ the issuer never asked for.
+ """
+ source = CommandTokenSource("date +%s%N", "dbx")
+ source()
+ assert source._expires_at is None
+ assert source() == source()
+
+ def test_advertised_ttl_sets_an_expiry(self):
+ source = CommandTokenSource(
+ """printf '{"access_token":"tok","expires_in":3600}'""", "dbx"
+ )
+ source()
+ assert source._expires_at is not None
+
+ def test_ttl_shorter_than_the_leeway_still_caches_briefly(self):
+ """A leeway larger than the TTL must not disable caching entirely."""
+ source = CommandTokenSource(
+ """printf '{"access_token":"tok","expires_in":1}'""", "dbx"
+ )
+ source()
+ assert source._expires_at is not None
+ assert source._expires_at > 0.0
+
+
+class TestBuilder:
+ def test_returns_none_when_unset(self):
+ assert build_command_token_provider("") is None
+ assert build_command_token_provider(" ") is None
+
+ def test_returns_callable_when_set(self):
+ provider = build_command_token_provider("printf tok", "dbx")
+ assert callable(provider)
+ assert provider() == "tok"
+
+
+class TestResolutionYieldsACallable:
+ """The integration contract: a callable reaches the wire client."""
+
+ def test_key_cmd_entry_resolves_to_a_callable(self, monkeypatch):
+ from hermes_cli import runtime_provider as rp
+
+ config = {
+ "providers": {
+ "dbx": {
+ "base_url": "https://example.invalid/v1",
+ "api_mode": "chat_completions",
+ "model": "m1",
+ "key_cmd": "printf minted-token",
+ }
+ }
+ }
+ monkeypatch.setattr(rp, "load_config", lambda *a, **k: config)
+ monkeypatch.setattr("hermes_cli.config.load_config", lambda *a, **k: config)
+
+ runtime = rp.resolve_runtime_provider(requested="custom:dbx")
+ api_key = runtime["api_key"]
+ assert callable(api_key), "key_cmd must resolve to a per-request callable"
+ assert api_key() == "minted-token"
+
+ def test_explicit_api_key_still_wins(self, monkeypatch):
+ """``--api-key`` stays the one-off recovery escape hatch."""
+ from hermes_cli import runtime_provider as rp
+
+ config = {
+ "providers": {
+ "dbx": {
+ "base_url": "https://example.invalid/v1",
+ "api_mode": "chat_completions",
+ "model": "m1",
+ "key_cmd": "printf minted-token",
+ }
+ }
+ }
+ monkeypatch.setattr(rp, "load_config", lambda *a, **k: config)
+ monkeypatch.setattr("hermes_cli.config.load_config", lambda *a, **k: config)
+
+ runtime = rp.resolve_runtime_provider(
+ requested="custom:dbx", explicit_api_key="sk-explicit-override"
+ )
+ assert runtime["api_key"] == "sk-explicit-override"
+
+
+class TestCallableKeyGetsBearerAuth:
+ """A callable api_key must reach the Anthropic bearer-hook client path.
+
+ This is why key_cmd needs no per-vendor auth wiring: a static string is
+ sent as ``x-api-key`` (which OAuth-gated gateways reject with 401), while a
+ callable routes through the per-request ``Authorization: Bearer`` hook the
+ Entra ID path already established. Verified against a live gateway with the
+ SAME token value: static -> 401, callable -> 200.
+ """
+
+ def test_callable_takes_the_bearer_hook_path(self, monkeypatch):
+ import agent.anthropic_adapter as aa
+
+ seen = {}
+
+ def _fake_hook(api_key, base_url, timeout, **kw):
+ seen["callable"] = callable(api_key)
+ return object()
+
+ monkeypatch.setattr(
+ aa, "_build_anthropic_client_with_bearer_hook", _fake_hook
+ )
+ aa.build_anthropic_client(
+ lambda: "minted-token", "https://gateway.invalid/anthropic"
+ )
+ assert seen.get("callable") is True
+
+
+class TestAbsoluteExpiry:
+ """Helpers that advertise a deadline instead of a lifetime.
+
+ OAuth 2.0 token endpoints send a relative ``expires_in``, but CLI token
+ helpers commonly print an absolute ISO 8601 timestamp instead (Databricks
+ ``expiry``, older Azure ``expiresOn``). Reading only ``expires_in`` treats
+ those as "no TTL advertised", caches the token for the life of the process,
+ and every request 401s once the real deadline passes.
+ """
+
+ @staticmethod
+ def _iso(seconds_from_now: float) -> str:
+ from datetime import datetime, timedelta, timezone
+
+ return (
+ datetime.now(timezone.utc) + timedelta(seconds=seconds_from_now)
+ ).isoformat()
+
+ def test_iso_expiry_yields_a_ttl(self):
+ deadline = self._iso(3600)
+ _, ttl = _mint(f"printf '%s' '{{\"access_token\":\"t\",\"expiry\":\"{deadline}\"}}'", "p")
+ assert ttl is not None, "an advertised deadline must produce a TTL"
+ assert 3500 < ttl <= 3600
+
+ def test_azure_expires_on_spelling(self):
+ deadline = self._iso(1800)
+ _, ttl = _mint(f"printf '%s' '{{\"access_token\":\"t\",\"expiresOn\":\"{deadline}\"}}'", "p")
+ assert ttl is not None and 1700 < ttl <= 1800
+
+ def test_expires_in_still_wins_when_both_present(self):
+ """The RFC 6749 field is authoritative where a helper sends both."""
+ deadline = self._iso(3600)
+ _, ttl = _mint(
+ f"printf '%s' '{{\"access_token\":\"t\",\"expires_in\":120,\"expiry\":\"{deadline}\"}}'",
+ "p",
+ )
+ assert ttl == 120.0
+
+ def test_unparseable_expiry_is_not_a_ttl(self):
+ """Junk must fall back to refresh-on-401, never to a guessed deadline."""
+ _, ttl = _mint('printf \'%s\' \'{"access_token":"t","expiry":"whenever"}\'', "p")
+ assert ttl is None
+
+ def test_already_past_expiry_is_not_a_ttl(self):
+ """A stale deadline must not become a negative or zero TTL."""
+ _, ttl = _mint(
+ f"printf '%s' '{{\"access_token\":\"t\",\"expiry\":\"{self._iso(-60)}\"}}'", "p"
+ )
+ assert ttl is None
+
+ def test_the_token_actually_gets_re_minted(self, tmp_path):
+ """The regression that mattered: a deadline must expire the cache."""
+ counter = tmp_path / "calls"
+ cmd = (
+ f"printf x >> {counter}; "
+ f"printf '%s' '{{\"access_token\":\"t\",\"expiry\":\"{self._iso(1)}\"}}'"
+ )
+ src = CommandTokenSource(cmd, "p")
+ src()
+ assert src._expires_at is not None, "cache must carry a deadline"
+ src._expires_at = time.monotonic() - 1 # simulate crossing it
+ src()
+ assert len(counter.read_text()) == 2, "expired cache must re-run the helper"
+
+
+class TestAuxiliaryResolverHonoursKeyCmd:
+ """Auxiliary tasks resolve credentials on their own path.
+
+ ``agent.auxiliary_client.resolve_provider_client`` does not go through
+ ``_resolve_named_custom_runtime``, so a key_cmd honoured only there leaves
+ title generation, compression, vision and embedding falling back to the
+ ``no-key-required`` placeholder — the main agent turn succeeds while every
+ auxiliary call 401s.
+ """
+
+ @staticmethod
+ def _resolve(monkeypatch, entry):
+ """Resolve *entry* as a named custom provider; return the api_key seen."""
+ import agent.auxiliary_client as ac
+ from hermes_cli import runtime_provider as rp
+
+ monkeypatch.setattr(
+ rp, "_get_named_custom_provider",
+ lambda name: dict(entry, name="dbx") if name == "dbx" else None,
+ )
+ seen = {}
+
+ def _spy(*, api_key, base_url, **kw):
+ seen["api_key"] = api_key
+ return SimpleNamespace(api_key=api_key, base_url=base_url)
+
+ monkeypatch.setattr(ac, "_create_openai_client", _spy)
+ ac.resolve_provider_client("dbx")
+ return seen.get("api_key")
+
+ BASE = {"base_url": "https://example.invalid/v1", "model": "m1"}
+
+ def test_key_cmd_resolves_to_a_callable(self, monkeypatch):
+ api_key = self._resolve(monkeypatch, {**self.BASE, "key_cmd": "printf minted-token"})
+ assert callable(api_key), "auxiliary tasks must mint per request too"
+ assert api_key() == "minted-token"
+
+ def test_key_cmd_beats_static_credentials(self, monkeypatch):
+ """Precedence matches the runtime resolver, so both agree on one entry."""
+ api_key = self._resolve(
+ monkeypatch,
+ {**self.BASE, "api_key": "stale-static", "key_cmd": "printf minted-token"},
+ )
+ assert callable(api_key) and api_key() == "minted-token"
+
+ def test_static_credentials_still_resolve(self, monkeypatch):
+ assert self._resolve(monkeypatch, {**self.BASE, "api_key": "static"}) == "static"
+
+ def test_blank_key_cmd_keeps_the_placeholder(self, monkeypatch):
+ """A blank command must not become a callable that mints nothing."""
+ assert self._resolve(
+ monkeypatch, {**self.BASE, "key_cmd": " "}
+ ) == "no-key-required"