Skip to content

The agent that grows with you

fix: keep the Entra token provider intact when auxiliary tasks re-resolve Azure Foundry

Tudor Pastorfc9f40ac2cbe
diff --git a/contributors/emails/[email protected] b/contributors/emails/[email protected]
new file mode 100644
index 00000000000..5e960d61b99
--- /dev/null
+++ b/contributors/emails/[email protected]
@@ -0,0 +1 @@
+tudorpastorglencore
diff --git a/hermes_cli/runtime_provider_backends.py b/hermes_cli/runtime_provider_backends.py
index 6f786ca3f20..993140c45b9 100644
--- a/hermes_cli/runtime_provider_backends.py
+++ b/hermes_cli/runtime_provider_backends.py
@@ -10,6 +10,7 @@ import os
import re
from typing import Any, Dict, Optional
+from agent.azure_identity_adapter import is_token_provider
from agent.secret_scope import get_secret_str
from hermes_constants import OPENROUTER_BASE_URL
from utils import base_url_host_matches
@@ -69,7 +70,10 @@ def _resolve_azure_foundry_runtime(*, requested_provider: str, model_cfg: Dict[s
``.env``/env or a per-request Entra ID token, trailing ``/v1`` stripped for Anthropic-style
endpoints (the Anthropic SDK appends /v1/messages itself)."""
rp = _rp()
- explicit_api_key = str(explicit_api_key or "").strip()
+ # Aux ``provider: auto`` forwards the main runtime's api_key — under entra_id that is the token
+ # provider callable; str() would turn it into a function repr sent as a static key (401, #72421).
+ forwarded_token_provider = explicit_api_key if is_token_provider(explicit_api_key) else None
+ explicit_api_key = "" if forwarded_token_provider else str(explicit_api_key or "").strip()
explicit_base_url_clean = str(explicit_base_url or "").strip().rstrip("/")
cfg_base_url, cfg_api_mode, cfg_auth_mode, cfg_entra = "", "chat_completions", "api_key", {}
if rp._cfg_provider(model_cfg) == "azure-foundry":
@@ -97,9 +101,8 @@ def _resolve_azure_foundry_runtime(*, requested_provider: str, model_cfg: Dict[s
api_key, source, auth_mode, entra = explicit_api_key, "explicit", "api_key", {}
else:
scope = str(cfg_entra.get("scope") or "").strip()
- api_key, source, auth_mode, entra = _azure_entra_credentials(cfg_entra), "entra_id", "entra_id", (
- {"scope": scope} if scope else {}
- )
+ api_key = forwarded_token_provider or _azure_entra_credentials(cfg_entra)
+ source, auth_mode, entra = "entra_id", "entra_id", ({"scope": scope} if scope else {})
return rp._runtime("azure-foundry", cfg_api_mode, base_url, api_key, auth_mode=auth_mode, entra=entra, source=source,
requested_provider=requested_provider)
return rp._runtime("azure-foundry", cfg_api_mode, base_url, _azure_foundry_api_key(rp, explicit_api_key),
diff --git a/tests/agent/test_auxiliary_client_azure_foundry.py b/tests/agent/test_auxiliary_client_azure_foundry.py
index 79ced884f76..332be471d55 100644
--- a/tests/agent/test_auxiliary_client_azure_foundry.py
+++ b/tests/agent/test_auxiliary_client_azure_foundry.py
@@ -299,6 +299,43 @@ class TestResolveProviderClientAzureFoundry:
# → OpenAI(api_key=...).
assert callable(received["api_key"])
+ def test_auto_route_forwards_main_runtime_entra_callable_intact(
+ self, monkeypatch, fake_azure_identity, patch_load_config,
+ ):
+ """#72421: ``provider: auto`` aux tasks (title generation, compression, smart approval)
+ re-resolve the main azure-foundry runtime with its api_key forwarded as
+ ``explicit_api_key``. That api_key is the Entra token-provider callable — it must reach
+ ``OpenAI(api_key=...)`` as the same object, never stringified into a function repr that
+ Azure rejects with 401."""
+ from agent import auxiliary_client as _aux
+
+ received = {}
+
+ class _FakeOpenAI:
+ def __init__(self, **kwargs):
+ received.update(kwargs)
+ self.api_key = kwargs.get("api_key", "")
+ self.base_url = kwargs.get("base_url", "")
+
+ monkeypatch.setattr(_aux, "OpenAI", _FakeOpenAI)
+ monkeypatch.setattr(_aux, "_is_provider_unhealthy", lambda *a, **k: False)
+ patch_load_config({
+ "provider": "azure-foundry",
+ "base_url": "https://r.openai.azure.com/openai/v1",
+ "api_mode": "chat_completions",
+ "auth_mode": "entra_id",
+ "default": "gpt-4o",
+ })
+ main_token_provider = lambda: "main-session-jwt" # noqa: E731
+ client, resolved, effective = _aux._resolve_auto_route(main_runtime={
+ "provider": "azure-foundry", "model": "gpt-4o", "api_mode": "chat_completions",
+ "base_url": "https://r.openai.azure.com/openai/v1", "api_key": main_token_provider,
+ })
+ assert client is not None
+ assert (resolved, effective) == ("gpt-4o", "azure-foundry")
+ assert received["api_key"] is main_token_provider
+ assert received["api_key"]() == "main-session-jwt"
+
def test_warns_and_returns_none_on_failure(
self, monkeypatch, patch_load_config, caplog,
):
diff --git a/tests/hermes_cli/test_azure_foundry_entra.py b/tests/hermes_cli/test_azure_foundry_entra.py
index 2205a66cbdd..20786e8ba24 100644
--- a/tests/hermes_cli/test_azure_foundry_entra.py
+++ b/tests/hermes_cli/test_azure_foundry_entra.py
@@ -143,6 +143,30 @@ class TestResolveAzureFoundryRuntimeEntra:
assert runtime["auth_mode"] == "api_key"
assert runtime["source"] == "explicit"
+ def test_forwarded_entra_callable_preserves_identity_and_metadata(self, fake_azure_identity):
+ """A live provider re-resolution must not stringify its token source or
+ relabel Entra authentication as a static-key override."""
+ from hermes_cli.runtime_provider import _resolve_azure_foundry_runtime
+
+ token_provider = lambda: "forwarded-jwt"
+ runtime = _resolve_azure_foundry_runtime(
+ requested_provider="azure-foundry",
+ model_cfg={
+ "provider": "azure-foundry",
+ "base_url": "https://r.services.ai.azure.com/openai/v1",
+ "api_mode": "chat_completions",
+ "auth_mode": "entra_id",
+ "entra": {"scope": "https://ai.azure.com/.default"},
+ "default": "gpt-4o",
+ },
+ explicit_api_key=token_provider,
+ )
+
+ assert runtime["api_key"] is token_provider
+ assert runtime["auth_mode"] == "entra_id"
+ assert runtime["source"] == "entra_id"
+ assert runtime["entra"] == {"scope": "https://ai.azure.com/.default"}
+
# ---------------------------------------------------------------------------
# _resolve_azure_foundry_runtime: legacy api_key branch (regression)
diff --git a/website/docs/guides/azure-foundry.md b/website/docs/guides/azure-foundry.md
index baff0a9950e..63fb8125b77 100644
--- a/website/docs/guides/azure-foundry.md
+++ b/website/docs/guides/azure-foundry.md
@@ -186,6 +186,8 @@ azure-foundry (Microsoft Entra ID):
Status: configured; live token probe is skipped here
```
+Auxiliary tasks that follow the main model (`provider: auto` — session titles, context compression, smart approval) reuse the main session's Entra token provider instead of re-authenticating; a `--api-key` string on the CLI still overrides it for one-off testing.
+
### Limitations
- **Anthropic-style endpoints use an httpx event hook.** The Anthropic Python SDK does not accept a callable `auth_token` natively (≤ 0.86.0). Hermes installs a request event hook on a custom `httpx.Client` that mints a fresh JWT per outbound request and rewrites `Authorization: Bearer <jwt>`. This is functionally equivalent to the OpenAI SDK's native `Callable[[], str]` contract but adds one indirection layer. If the Anthropic SDK adds first-class callable-auth support in a future release, Hermes will switch to it transparently.