The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(aux): keep key_cmd bearer and extra_headers on async aux calls to named custom providers
teknium1b1db026f3abc
diff --git a/agent/auxiliary_async_rebuild.py b/agent/auxiliary_async_rebuild.pynew file mode 100644index 00000000000..a9dec33ebb7--- /dev/null+++ b/agent/auxiliary_async_rebuild.py@@ -0,0 +1,42 @@+"""Carry a sync OpenAI client's credential and configured headers onto its async rebuild.++``_to_async_client`` recreates ``AsyncOpenAI`` from a resolved sync client. Two things do not+live on ``.api_key`` / the header set it recomputes: a per-request token provider (``key_cmd``,+Entra ID — the SDK parks the callable in ``_api_key_provider`` and leaves ``.api_key`` empty, so+an ``auth_headers`` built from the snapshot is ``{}`` and the request carries NO Authorization at+all) and the ``default_headers`` the client was constructed with (a named provider's+``extra_headers``). See #109595.+"""++from __future__ import annotations++import asyncio+from collections.abc import Mapping+from typing import Any, Dict++from openai import OpenAI+++def async_api_key(sync_client: Any) -> Any:+ """Credential for the async twin: the sync token provider wrapped for ``await``, else the static key.++ The sync provider is ``Callable[[], str]``; ``AsyncOpenAI`` awaits its provider before every request,+ so the callable is run off-loop (it may shell out to a ``key_cmd``).+ """+ provider = getattr(sync_client, "_api_key_provider", None) if isinstance(sync_client, OpenAI) else None+ if not callable(provider):+ return sync_client.api_key++ async def _provide() -> str:+ return str(await asyncio.to_thread(provider))++ return _provide+++def configured_default_headers(sync_client: Any) -> Dict[str, str]:+ """The ``default_headers`` mapping the sync client was constructed with (SDK ``_custom_headers``).++ SECURITY: values may carry credentials — never log them.+ """+ configured = getattr(sync_client, "_custom_headers", None) if isinstance(sync_client, OpenAI) else None+ return dict(configured) if isinstance(configured, Mapping) else {}diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex 4d8ac341b4b..6ad1b4442f7 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -4503,7 +4503,12 @@ def _to_async_client(sync_client, model: str, is_vision: bool = False):if _client_declares(sync_client, "HERMES_SKIP_ASYNC_WRAP"):return sync_client, modelsync_base_url = str(sync_client.base_url)- async_kwargs = {"api_key": sync_client.api_key, "base_url": sync_base_url}+ # A key_cmd/Entra client keeps its credential in the SDK's per-request provider slot, not in+ # ``.api_key`` (which stays ""); rebuilding from the snapshot alone ships NO Authorization+ # header. Configured default_headers (a named entry's extra_headers) are likewise carried over,+ # merged last exactly as the SDK merges them on the sync client. See #109595.+ from agent.auxiliary_async_rebuild import async_api_key, configured_default_headers+ async_kwargs = {"api_key": async_api_key(sync_client), "base_url": sync_base_url}if base_url_host_matches(sync_base_url, "openrouter.ai"):headers = _apply_user_default_headers(build_or_headers())elif _is_official_codex_base_url(sync_base_url):@@ -4522,6 +4527,7 @@ def _to_async_client(sync_client, model: str, is_vision: bool = False):from hermes_cli.models import OPENCODE_ZEN_FREE_KEYLESS_PLACEHOLDER, opencode_zen_free_headersif sync_client.api_key == OPENCODE_ZEN_FREE_KEYLESS_PLACEHOLDER:headers = {**(headers or {}), **opencode_zen_free_headers()}+ headers = {**(headers or {}), **configured_default_headers(sync_client)}if headers:async_kwargs["default_headers"] = headers_apply_required_codex_headers(async_kwargs, access_token=sync_client.api_key, base_url=sync_base_url)@@ -4895,11 +4901,16 @@ def _resolve_custom_branch(req: _ResolveRequest) -> _ResolveResult:return None, None-def _named_custom_openai_wire_client(custom_base: str, custom_key: Any):- """Plain OpenAI client on the /v1 equivalent of a named custom entry's base URL."""+def _named_custom_openai_wire_client(custom_base: str, custom_key: Any, extra_headers: Optional[Dict[str, str]] = None):+ """Plain OpenAI client on the /v1 equivalent of a named custom entry's base URL.++ ``extra_headers`` is the entry's own header block (gateway routing tags, proxy auth): the main+ runtime lifts it onto every request, so aux must too (#109595). SECURITY: never log the values."""_clean_base, _dq = _extract_url_query_params(_to_openai_base_url(custom_base))_extra = {"default_query": _dq} if _dq else {}_headers = _apply_user_default_headers(None)+ if extra_headers:+ _headers = {**(_headers or {}), **extra_headers}if _headers:_extra["default_headers"] = _headersreturn _create_openai_client(api_key=custom_key, base_url=_clean_base, **_extra)@@ -4937,6 +4948,8 @@ def _resolve_named_custom_branch(req: _ResolveRequest) -> Optional[_ResolveResulif not custom_base:logger.warning("resolve_provider_client: named custom provider %r has no base_url", provider)return None, None+ from hermes_cli.config import normalize_extra_headers+ entry_headers = normalize_extra_headers(custom_entry.get("extra_headers"))final_model = _normalize_resolved_model(req.modelor custom_entry.get("model")@@ -4957,10 +4970,10 @@ def _resolve_named_custom_branch(req: _ResolveRequest) -> Optional[_ResolveResulexcept ImportError:logger.warning("Named custom provider %r declares api_mode=anthropic_messages but the anthropic SDK ""is not installed — falling back to OpenAI-wire.", provider)- return _route_client(req, _named_custom_openai_wire_client(custom_base, custom_key), final_model)+ return _route_client(req, _named_custom_openai_wire_client(custom_base, custom_key, entry_headers), final_model)return _route_client(req, AnthropicAuxiliaryClient(real_client, final_model, custom_key, custom_base, is_oauth=False), final_model)- client = _named_custom_openai_wire_client(custom_base, custom_key)+ client = _named_custom_openai_wire_client(custom_base, custom_key, entry_headers)# codex_responses, or auto-detect via _wrap_transport (which reads the task-level api_mode).if entry_api_mode == "codex_responses":client = CodexAuxiliaryClient(client, final_model)diff --git a/tests/agent/test_auxiliary_named_custom_providers.py b/tests/agent/test_auxiliary_named_custom_providers.pyindex b66f25c59f5..6d5ef93d73a 100644--- a/tests/agent/test_auxiliary_named_custom_providers.py+++ b/tests/agent/test_auxiliary_named_custom_providers.py@@ -478,3 +478,56 @@ class TestResolveProviderClientMainRuntimeCustom:assert model == "explicit-model"assert "explicit.example.com" in str(client.base_url)assert client.api_key == "sk-explicit"+++class TestBareNamedAuxCredentialSurvivesAsyncRebuild:+ """#109595: a bare-named ``providers:`` entry pinned by ``auxiliary.<task>`` must reach the wire+ with its key_cmd bearer AND its extra_headers on the async path too. The SDK parks a callable+ key in ``_api_key_provider`` and leaves ``.api_key`` empty, so a rebuild from the snapshot+ alone sends no Authorization header at all."""++ def _cfg(self):+ import sys+ return {+ "model": {"provider": "hermes-gw", "default": "main-model"},+ "providers": {+ "hermes-gw": {+ "base_url": "http://127.0.0.1:1/openai/v1",+ "api_mode": "chat_completions",+ "key_cmd": f'"{sys.executable}" -c "print(\'vk-test-1234\')"',+ "extra_headers": {"x-gw-session": "aux-session-tag"},+ },+ },+ "auxiliary": {"compression": {"provider": "hermes-gw", "model": "aux-model"}},+ }++ @staticmethod+ def _wire_headers(client):+ """Headers the SDK would put on a request (after its own auth refresh), not the config view."""+ from openai._models import FinalRequestOptions+ return client._build_headers(FinalRequestOptions(method="post", url="/chat/completions"))++ def test_async_task_client_carries_key_cmd_bearer_and_extra_headers(self, tmp_path):+ import asyncio+ _write_config(tmp_path, self._cfg())+ from agent.auxiliary_client import resolve_provider_client+ client, _model = resolve_provider_client("hermes-gw", "aux-model", async_mode=True, task="compression")+ assert client is not None+ asyncio.run(client._refresh_api_key())+ headers = self._wire_headers(client)+ assert headers["authorization"] == "Bearer vk-test-1234"+ assert headers["x-gw-session"] == "aux-session-tag"++ def test_sync_to_async_rebuild_keeps_credential_and_headers(self, tmp_path):+ """The fallback-candidate ladder rebuilds a resolved sync client through ``_to_async_client``."""+ import asyncio+ _write_config(tmp_path, self._cfg())+ from agent.auxiliary_client import _to_async_client, resolve_provider_client+ sync_client, model = resolve_provider_client("hermes-gw", "aux-model", task="compression")+ sync_client._refresh_api_key() # what the SDK does in _prepare_options before each request+ assert self._wire_headers(sync_client)["authorization"] == "Bearer vk-test-1234"+ async_client, _ = _to_async_client(sync_client, model)+ asyncio.run(async_client._refresh_api_key())+ headers = self._wire_headers(async_client)+ assert headers["authorization"] == "Bearer vk-test-1234"+ assert headers["x-gw-session"] == "aux-session-tag"