Skip to content

The agent that grows with you

fix(anthropic): key_cmd Claude Code OAuth identity survives on custom api.anthropic.com routes (main + aux)

teknium12b3bab0a5cc4
diff --git a/agent/agent_init.py b/agent/agent_init.py
index 5712731afd2..6d85e6eda2c 100644
--- a/agent/agent_init.py
+++ b/agent/agent_init.py
@@ -750,14 +750,13 @@ def _init_anthropic_client(agent, api_key, base_url, _provider_timeout):
agent.api_key = effective_key
agent._anthropic_api_key = effective_key
- # OAuth only for native Anthropic: third-party anthropic_messages providers must never
- # trip OAuth paths — those inject Claude-Code identity headers → 401/403.
- # Only mark the session as OAuth-authenticated when the token genuinely belongs to native Anthropic.
- # Third-party providers (MiniMax, Kimi, GLM, LiteLLM proxies) that accept the Anthropic protocol must
- # never trip OAuth code paths — doing so injects Claude-Code identity headers and system prompts that
+ # OAuth only for native Anthropic routes (the anthropic provider, or a custom provider whose host
+ # is exactly api.anthropic.com, incl. a key_cmd callable token — #114967). Third-party
+ # providers (MiniMax, Kimi, GLM, LiteLLM proxies) that accept the Anthropic protocol must never
+ # trip OAuth code paths — doing so injects Claude-Code identity headers and system prompts that
# cause 401/403 on their endpoints. See #1739.
- from agent.anthropic_credentials import _is_oauth_token as _is_oat
- agent._is_anthropic_oauth = _is_oat(effective_key) if (_is_native_anthropic and isinstance(effective_key, str)) else False
+ from agent.anthropic_credentials import anthropic_route_is_oauth
+ agent._is_anthropic_oauth = anthropic_route_is_oauth(base_url, effective_key, provider=agent.provider)
agent._anthropic_client = build_anthropic_client(effective_key, base_url, timeout=_provider_timeout)
if not agent.quiet_mode:
print(f"🤖 AI Agent initialized with model: {agent.model} (Anthropic native)")
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.py
index b3008920a5e..969c236bfc7 100644
--- a/agent/agent_runtime_helpers.py
+++ b/agent/agent_runtime_helpers.py
@@ -1983,7 +1983,7 @@ def _build_switched_client(agent, new_provider, api_key, base_url, api_mode, new
return
if api_mode == "anthropic_messages":
from agent.anthropic_adapter import build_anthropic_client
- from agent.anthropic_credentials import resolve_anthropic_token, _is_oauth_token
+ from agent.anthropic_credentials import resolve_anthropic_token, anthropic_route_is_oauth
# Only fall back to ANTHROPIC_TOKEN for native Anthropic; other anthropic_messages providers
# must never receive Anthropic credentials.
is_native_anthropic = new_provider == "anthropic"
@@ -2007,7 +2007,7 @@ def _build_switched_client(agent, new_provider, api_key, base_url, api_mode, new
effective_key, agent._anthropic_base_url,
timeout=get_provider_request_timeout(agent.provider, agent.model),
)
- agent._is_anthropic_oauth = bool(is_native_anthropic and isinstance(effective_key, str) and _is_oauth_token(effective_key))
+ agent._is_anthropic_oauth = anthropic_route_is_oauth(agent._anthropic_base_url, effective_key, provider=new_provider)
agent.client = None
agent._client_kwargs = {}
return
diff --git a/agent/anthropic_adapter.py b/agent/anthropic_adapter.py
index 876fc58389d..7137bce7237 100644
--- a/agent/anthropic_adapter.py
+++ b/agent/anthropic_adapter.py
@@ -375,7 +375,17 @@ def _build_anthropic_client_with_bearer_hook(
normalized_base_url, kwargs = _base_client_kwargs(base_url, timeout)
kwargs["http_client"] = build_bearer_http_client(token_provider, timeout=kwargs["timeout"])
kwargs["auth_token"] = "entra-id-bearer-via-http-hook"
- headers = _beta_header(_common_betas_for_base_url(normalized_base_url, drop_context_1m_beta=drop_context_1m_beta))
+ betas = _common_betas_for_base_url(normalized_base_url, drop_context_1m_beta=drop_context_1m_beta)
+ from agent.anthropic_credentials import anthropic_route_is_oauth
+ if anthropic_route_is_oauth(base_url, token_provider):
+ # key_cmd-sourced Claude Code OAuth on the native host: a bare bearer without the Claude Code
+ # identity is answered with 429 rate_limit_error "Error" (#114967) — same headers as the
+ # static "oauth" style in build_anthropic_client.
+ headers = _beta_header(betas + _OAUTH_ONLY_BETAS)
+ headers["user-agent"] = f"claude-code/{_get_claude_code_version()} (external, cli)"
+ headers["x-app"] = "cli"
+ else:
+ headers = _beta_header(betas)
return _new_sdk_client(sdk, kwargs, headers, route=base_url)
diff --git a/agent/anthropic_credentials.py b/agent/anthropic_credentials.py
index 424b9cfa255..43e0a89fa74 100644
--- a/agent/anthropic_credentials.py
+++ b/agent/anthropic_credentials.py
@@ -25,6 +25,7 @@ import time
from collections import OrderedDict
from pathlib import Path
from typing import Any, Dict, Optional
+from urllib.parse import urlparse
from hermes_constants import get_hermes_home
from utils import atomic_json_write
@@ -66,6 +67,29 @@ def _is_oauth_token(key: str) -> bool:
return key.startswith(("sk-ant-", "eyJ", "cc-"))
+def anthropic_route_is_oauth(base_url: Any, credential: Any, *, provider: Optional[str] = None) -> bool:
+ """Claude Code OAuth identity for one Anthropic Messages route (#114967).
+
+ The route qualifies when it is the ``anthropic`` provider itself or its host is exactly
+ ``api.anthropic.com`` (an empty base_url is the native default) — a named custom provider
+ pointed at the native host carries the same identity, while third-party Anthropic-protocol
+ endpoints never do (Claude Code headers and tool-name transforms 401/403 there). ``credential``
+ is a static string or a ``key_cmd``/per-request callable token source; a callable is
+ materialized once for the shape test (``CommandTokenSource`` caches, so this never double-mints)
+ and a mint failure classifies as non-OAuth — the wire client surfaces the real error.
+ """
+ text = str(base_url or "").strip()
+ native_host = not text or (urlparse(text).hostname or "").lower().rstrip(".") == "api.anthropic.com"
+ if not (native_host or (provider or "").strip().lower() == "anthropic"):
+ return False
+ if callable(credential) and not isinstance(credential, str):
+ try:
+ credential = credential()
+ except Exception: # noqa: BLE001 — classification must never raise
+ return False
+ return isinstance(credential, str) and _is_oauth_token(credential)
+
+
class CredentialPersistError(RuntimeError):
"""A rotated single-use credential could not be durably committed. The refresh POST already spent the old
refresh token, so a swallowed write failure leaves a consumed pair on disk that later replays as invalid_grant."""
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index bfb17906c40..12b16b164bb 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -2843,9 +2843,11 @@ def _try_custom_endpoint() -> Tuple[Optional[Any], Optional[str]]:
real_client = _create_openai_client(api_key=custom_key, base_url=_clean_base, **_extra)
return CodexAuxiliaryClient(real_client, model), model
if custom_mode == "anthropic_messages":
- # Third-party Anthropic-compatible gateway — never OAuth (that's api.anthropic.com only).
+ # OAuth identity only when the host is exactly api.anthropic.com (key_cmd callable included,
+ # #114967); third-party Anthropic-compatible gateways never get it.
try:
from agent.anthropic_adapter import build_anthropic_client
+ from agent.anthropic_credentials import anthropic_route_is_oauth
real_client = build_anthropic_client(custom_key, custom_base)
except ImportError:
logger.warning(
@@ -2853,7 +2855,8 @@ def _try_custom_endpoint() -> Tuple[Optional[Any], Optional[str]]:
"anthropic SDK is not installed — falling back to OpenAI-wire."
)
return _create_openai_client(api_key=custom_key, base_url=_clean_base, **_extra), model
- return AnthropicAuxiliaryClient(real_client, model, custom_key, custom_base, is_oauth=False), model
+ return AnthropicAuxiliaryClient(real_client, model, custom_key, custom_base,
+ is_oauth=anthropic_route_is_oauth(custom_base, custom_key)), model
# URL-based anthropic detection for custom endpoints without explicit api_mode.
_fallback_client = _create_openai_client(api_key=custom_key, base_url=_clean_base, **_extra)
return _maybe_wrap_anthropic(_fallback_client, model, custom_key, custom_base, custom_mode), model
@@ -5106,6 +5109,7 @@ def _resolve_named_custom_branch(req: _ResolveRequest) -> Optional[_ResolveResul
if entry_api_mode == "anthropic_messages":
try:
from agent.anthropic_adapter import build_anthropic_client
+ from agent.anthropic_credentials import anthropic_route_is_oauth
real_client = build_anthropic_client(custom_key, custom_base)
if entry_headers:
# Same entry headers as the two OpenAI-wire arms; ``with_options`` merges onto the
@@ -5116,7 +5120,8 @@ def _resolve_named_custom_branch(req: _ResolveRequest) -> Optional[_ResolveResul
"is not installed — falling back to OpenAI-wire.", provider)
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)
+ req, AnthropicAuxiliaryClient(real_client, final_model, custom_key, custom_base,
+ is_oauth=anthropic_route_is_oauth(custom_base, custom_key)), final_model)
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":
diff --git a/agent/client_lifecycle.py b/agent/client_lifecycle.py
index e2722dad251..753af3bd84b 100644
--- a/agent/client_lifecycle.py
+++ b/agent/client_lifecycle.py
@@ -77,16 +77,13 @@ def _swap_fallback_clients(agent, fb_client, fb_provider: str, fb_model: str, fb
credential = key_provider if callable(key_provider) else fb_client.api_key
if fb_api_mode == "anthropic_messages":
from agent.anthropic_adapter import build_anthropic_client
- from agent.anthropic_credentials import resolve_anthropic_token, _is_oauth_token
+ from agent.anthropic_credentials import resolve_anthropic_token, anthropic_route_is_oauth
is_anthropic = fb_provider == "anthropic"
effective_key = credential or (resolve_anthropic_token(model=getattr(agent, "model", None)) if is_anthropic else None) or ""
agent.api_key = agent._anthropic_api_key = effective_key
agent._anthropic_base_url = fb_base_url
agent._anthropic_client = build_anthropic_client(effective_key, fb_base_url, timeout=timeout)
- agent._is_anthropic_oauth = (
- _is_oauth_token(effective_key)
- if is_anthropic and isinstance(effective_key, str) else False
- )
+ agent._is_anthropic_oauth = anthropic_route_is_oauth(fb_base_url, effective_key, provider=fb_provider)
agent.client, agent._client_kwargs = None, {}
return
agent.api_key = credential
@@ -492,9 +489,9 @@ class ClientLifecycleMixin:
return build_anthropic_client(token, base_url, timeout=get_provider_request_timeout(self.provider, self.model))
def _anthropic_oauth_flag(self, token: str) -> bool:
- """OAuth flag only on native Anthropic; third-party Anthropic-protocol endpoints must not trip OAuth paths."""
- from agent.anthropic_credentials import _is_oauth_token
- return _is_oauth_token(token) if self.provider == "anthropic" else False
+ """OAuth flag only on native Anthropic routes; third-party Anthropic-protocol endpoints must not trip OAuth paths."""
+ from agent.anthropic_credentials import anthropic_route_is_oauth
+ return anthropic_route_is_oauth(getattr(self, "_anthropic_base_url", None), token, provider=self.provider)
def _build_anthropic_client_for_key(self, key: tuple) -> Any:
from agent.anthropic_adapter import build_anthropic_bedrock_client, build_anthropic_client
diff --git a/agent/model_metadata.py b/agent/model_metadata.py
index b47ebd21873..fe7e46018f9 100644
--- a/agent/model_metadata.py
+++ b/agent/model_metadata.py
@@ -1693,9 +1693,13 @@ def _normalize_model_version(model: str) -> str:
return model.replace(".", "-")
-def _query_anthropic_context_length(model: str, base_url: str, api_key: str) -> Optional[int]:
- """Anthropic /v1/models max_input_tokens; OAuth tokens (sk-ant-oat*) 401 and are skipped."""
- if not api_key or api_key.startswith("sk-ant-oat"):
+def _query_anthropic_context_length(model: str, base_url: str, api_key: Any) -> Optional[int]:
+ """Anthropic /v1/models max_input_tokens; OAuth tokens (sk-ant-oat*) 401 and are skipped.
+
+ ``api_key`` may be a ``key_cmd`` callable token source; the metadata probe never mints — a
+ callable is not a Console key, so the lookup is skipped like an OAuth token (#114967).
+ """
+ if not api_key or not isinstance(api_key, str) or api_key.startswith("sk-ant-oat"):
return None
try:
base = base_url.rstrip("/").removesuffix("/v1")
diff --git a/tests/agent/test_anthropic_route_oauth_identity.py b/tests/agent/test_anthropic_route_oauth_identity.py
new file mode 100644
index 00000000000..350c1c35e2d
--- /dev/null
+++ b/tests/agent/test_anthropic_route_oauth_identity.py
@@ -0,0 +1,71 @@
+"""A ``key_cmd`` Claude Code OAuth token keeps its OAuth identity on native api.anthropic.com routes (#114967).
+
+A named custom provider pointed at ``api.anthropic.com`` with ``api_mode: anthropic_messages`` and a
+``key_cmd`` callable used to be built with ``is_oauth=False`` / string-only OAuth detection, so the
+request carried a bare Bearer without the Claude Code identity and Anthropic answered
+``429 rate_limit_error: Error``. Third-party Anthropic-protocol hosts must stay non-OAuth.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from agent.anthropic_credentials import anthropic_route_is_oauth
+
+OAUTH = "sk-ant-oat01-keycmd-token"
+CONSOLE = "sk-ant-api03-console-key"
+
+
+def test_route_identity_requires_native_host_and_oauth_shape():
+ calls = []
+
+ def key_cmd():
+ calls.append(1)
+ return OAUTH
+
+ assert anthropic_route_is_oauth("https://api.anthropic.com", key_cmd) is True
+ assert anthropic_route_is_oauth("https://api.anthropic.com/v1", OAUTH) is True
+ assert anthropic_route_is_oauth("", OAUTH) is True # empty = native default route
+ # provider=anthropic behind a proxy keeps today's behaviour (identity travels with the provider).
+ assert anthropic_route_is_oauth("https://proxy.example.com", OAUTH, provider="anthropic") is True
+ # Third-party hosts and Console keys never qualify; a callable that cannot mint is non-OAuth.
+ assert anthropic_route_is_oauth("https://api.minimax.io/anthropic", key_cmd) is False
+ assert anthropic_route_is_oauth("https://api.anthropic.com", CONSOLE) is False
+ assert anthropic_route_is_oauth("https://notapi.anthropic.com.evil.example", key_cmd) is False
+ assert anthropic_route_is_oauth("https://api.anthropic.com", lambda: (_ for _ in ()).throw(RuntimeError("no token"))) is False
+ assert len(calls) == 1 # the third-party route never materialised the callable
+
+
+def test_key_cmd_oauth_route_builds_claude_code_identity_on_main_and_aux_clients(monkeypatch):
+ pytest.importorskip("anthropic")
+ from agent.agent_init import _init_anthropic_client
+ from agent.anthropic_adapter import _OAUTH_ONLY_BETAS, build_anthropic_client
+ from agent.auxiliary_client import AnthropicAuxiliaryClient
+
+ def key_cmd():
+ return OAUTH
+
+ # Main runtime: named custom provider -> api.anthropic.com with a callable token source.
+ agent = SimpleNamespace(provider="enterprise-anthropic", model="claude-opus-5", quiet_mode=True)
+ _init_anthropic_client(agent, key_cmd, "https://api.anthropic.com", None)
+ assert agent._is_anthropic_oauth is True
+ headers = agent._anthropic_client._custom_headers
+ assert headers["user-agent"].startswith("claude-code/") and headers["x-app"] == "cli"
+ assert all(beta in headers["anthropic-beta"] for beta in _OAUTH_ONLY_BETAS)
+
+ # Same token source at a third-party Anthropic-protocol host: no identity, no OAuth betas.
+ third_party = build_anthropic_client(key_cmd, "https://api.minimax.io/anthropic")
+ tp_headers = third_party._custom_headers
+ assert "user-agent" not in tp_headers and not any(beta in tp_headers.get("anthropic-beta", "") for beta in _OAUTH_ONLY_BETAS)
+
+ # Aux: the custom anthropic_messages route (production entry) carries the flag from the same rule.
+ import agent.auxiliary_client as aux
+ monkeypatch.setattr(aux, "_resolve_custom_runtime", lambda: ("https://api.anthropic.com", key_cmd, "anthropic_messages"))
+ monkeypatch.setattr(aux, "_read_main_model_for_aux", lambda: "claude-opus-5")
+ native_aux, _model = aux._try_custom_endpoint()
+ assert isinstance(native_aux, AnthropicAuxiliaryClient) and native_aux.chat.completions._is_oauth is True
+ monkeypatch.setattr(aux, "_resolve_custom_runtime", lambda: ("https://api.minimax.io/anthropic", key_cmd, "anthropic_messages"))
+ third_party_aux, _model = aux._try_custom_endpoint()
+ assert isinstance(third_party_aux, AnthropicAuxiliaryClient) and third_party_aux.chat.completions._is_oauth is False