Skip to content

The agent that grows with you

fix: capability probes send minted credentials instead of callable representations

Teknium7d44fe9c74f6
diff --git a/agent/command_token_source.py b/agent/command_token_source.py
index 6c7d5cdb5b2..c790f0dd8ac 100644
--- a/agent/command_token_source.py
+++ b/agent/command_token_source.py
@@ -34,6 +34,15 @@ class CommandTokenError(RuntimeError):
"""A ``key_cmd`` failed to produce a usable token."""
+def materialize_probe_api_key(api_key: object) -> str:
+ """Best-effort probe credential; never send a callable's repr or log mint errors."""
+ try:
+ token = api_key() if callable(api_key) else api_key
+ except Exception:
+ return ""
+ return token.strip() if isinstance(token, str) else ""
+
+
def _mint(command: str, label: str) -> tuple[str, Optional[float]]:
"""Run *command*, returning ``(token, ttl_seconds_or_None)``."""
try:
diff --git a/agent/image_routing.py b/agent/image_routing.py
index 19004139f65..5eb962bfdf8 100644
--- a/agent/image_routing.py
+++ b/agent/image_routing.py
@@ -104,7 +104,9 @@ def _runtime_main(key: str) -> str:
try:
from agent.auxiliary_client import _runtime_main_value
- return _clean_str(_runtime_main_value(key))
+ from agent.command_token_source import materialize_probe_api_key
+ value = _runtime_main_value(key)
+ return materialize_probe_api_key(value) if key == "api_key" else _clean_str(value)
except Exception:
return ""
diff --git a/agent/model_metadata.py b/agent/model_metadata.py
index d24df995f1b..6dabad25481 100644
--- a/agent/model_metadata.py
+++ b/agent/model_metadata.py
@@ -416,8 +416,9 @@ def _normalize_base_url(base_url: str) -> str:
return (base_url or "").strip().rstrip("/")
-def _auth_headers(api_key: str = "") -> Dict[str, str]:
- token = str(api_key or "").strip()
+def _auth_headers(api_key: object = "") -> Dict[str, str]:
+ from agent.command_token_source import materialize_probe_api_key
+ token = materialize_probe_api_key(api_key)
return {"Authorization": f"Bearer {token}"} if token else {}
@@ -919,7 +920,7 @@ def fetch_endpoint_model_metadata(base_url: str, api_key: str = "", force_refres
return {}
alternate = normalized[:-3].rstrip("/") if normalized.endswith("/v1") else normalized + "/v1"
candidates = [normalized] + ([alternate] if alternate != normalized else [])
- headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
+ headers = _auth_headers(api_key)
verify = _resolve_requests_verify(normalized)
last_error: Optional[Exception] = None
if local:
diff --git a/hermes_cli/models_local.py b/hermes_cli/models_local.py
index 2ffc968e204..3944e85f202 100644
--- a/hermes_cli/models_local.py
+++ b/hermes_cli/models_local.py
@@ -152,7 +152,8 @@ def _get_ollama_native_headers(base_url: Optional[str], *, api_key: Optional[str
*base_url* shares the configured Ollama root; an explicit *api_key* replaces any configured
Authorization variant rather than inheriting it."""
configured_base = _configured_ollama_base_url()
- explicit_key = str(api_key or "").strip()
+ from agent.command_token_source import materialize_probe_api_key
+ explicit_key = materialize_probe_api_key(api_key)
configured_matches = bool(configured_base and base_url and _same_ollama_native_root(base_url, configured_base))
if not configured_matches and not explicit_key:
return {}
@@ -366,7 +367,8 @@ def _lmstudio_server_root(base_url: Optional[str]) -> Optional[str]:
def _lmstudio_request_headers(api_key: Optional[str] = None) -> dict:
"""HTTP headers for LM Studio native API requests."""
from hermes_cli.models import _HERMES_USER_AGENT
- token = str(api_key or "").strip()
+ from agent.command_token_source import materialize_probe_api_key
+ token = materialize_probe_api_key(api_key)
return {"User-Agent": _HERMES_USER_AGENT, **({"Authorization": f"Bearer {token}"} if token else {})}
@@ -591,7 +593,8 @@ def ollama_model_supports_thinking(
if not server_url or not bare_model:
return None
- token = str(api_key or "").strip()
+ from agent.command_token_source import materialize_probe_api_key
+ token = materialize_probe_api_key(api_key)
try:
with httpx.Client(timeout=timeout, headers={"Authorization": f"Bearer {token}"} if token else {}) as client:
resp = client.post(f"{server_url}/api/show", json={"name": bare_model})
diff --git a/tests/agent/test_capability_probe_credentials.py b/tests/agent/test_capability_probe_credentials.py
new file mode 100644
index 00000000000..cac7ad56e77
--- /dev/null
+++ b/tests/agent/test_capability_probe_credentials.py
@@ -0,0 +1,38 @@
+"""Capability probes materialize credentials without consuming the chat source."""
+from unittest.mock import patch
+
+import httpx
+import pytest
+
+from agent import auxiliary_client, image_routing, model_metadata
+from hermes_cli import models_local
+
+
[email protected]("credential,expected", [(lambda: "minted", "minted"), ("static", "static")])
+def test_capability_paths_share_concrete_bearer(credential, expected):
+ auxiliary_client.set_runtime_main("custom", "fixture", api_key=credential)
+ try:
+ assert image_routing._resolve_inference_api_key({}, "custom") == expected
+ assert model_metadata._auth_headers(credential) == {"Authorization": f"Bearer {expected}"}
+ assert models_local._lmstudio_request_headers(credential)["Authorization"] == f"Bearer {expected}"
+ requests = []
+ def capture(req):
+ requests.append(req)
+ return httpx.Response(200, json={"capabilities": ["thinking"]})
+ client_type = httpx.Client
+ with patch("httpx.Client", lambda **kwargs: client_type(
+ **kwargs, transport=httpx.MockTransport(capture)
+ )):
+ models_local.ollama_model_supports_thinking("fixture", "http://localhost:11434/v1", credential)
+ assert requests and requests[0].headers["Authorization"] == f"Bearer {expected}"
+ assert auxiliary_client._runtime_main_value("api_key") is credential
+ finally:
+ auxiliary_client.clear_runtime_main()
+
+
+def test_failed_callable_never_becomes_a_bearer():
+ def failed():
+ raise RuntimeError("secret-bearing command failure")
+ for value in (failed, lambda: object(), object(), None):
+ assert model_metadata._auth_headers(value) == {}
+ assert "Authorization" not in models_local._lmstudio_request_headers(value)
diff --git a/website/docs/integrations/providers.md b/website/docs/integrations/providers.md
index 293f3c34914..1007319612c 100644
--- a/website/docs/integrations/providers.md
+++ b/website/docs/integrations/providers.md
@@ -1323,6 +1323,12 @@ Each entry accepts: `api` (the endpoint base URL — `base_url`/`url` are accept
#### Command-minted credentials (`key_cmd`)
+Vision, thinking, and native local-model capability probes materialize the same
+callable credential used by chat before building authentication headers. They
+reuse the command token cache without replacing the chat client's callable.
+If a command cannot mint a string token, these best-effort probes send no bearer
+rather than an object representation; chat retains its normal error handling.
+
Enterprise gateways often issue short-lived bearer tokens (SSO/OIDC brokers, cloud IAM, internal auth proxies) rather than static API keys, so a token copied into `.env` goes stale mid-session and requests start returning 401. `key_cmd` names a command that *prints* a token; Hermes runs it and caches the result until shortly before expiry, so long sessions keep working with no restart:
```yaml