Skip to content

The agent that grows with you

fix(agent): honor a fallback entry's base_url for anthropic and openrouter

Austin Pickett3112afeaff26
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index c075858bb20..faa0f2ad72d 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -2282,7 +2282,8 @@ def _warn_paid_lane_once(model: str) -> None:
)
-def _try_openrouter(explicit_api_key: Optional[Union[str, Callable[[], str]]] = None, model: str = None) -> Tuple[Optional[OpenAI], Optional[str]]:
+def _try_openrouter(explicit_api_key: Optional[Union[str, Callable[[], str]]] = None, model: str = None,
+ explicit_base_url: Optional[str] = None) -> Tuple[Optional[OpenAI], Optional[str]]:
free_only, cfg_model = _aux_openrouter_settings()
or_model = model or cfg_model
if free_only and not _is_free_model(or_model):
@@ -2295,11 +2296,14 @@ def _try_openrouter(explicit_api_key: Optional[Union[str, Callable[[], str]]] =
return None, None
if not _is_free_model(or_model):
_warn_paid_lane_once(or_model)
+ # A caller-supplied endpoint (fallback_providers entry, custom_providers entry) is
+ # authoritative over both the pool row and the canonical host (#121359).
+ override_url = (explicit_base_url or "").strip().rstrip("/")
pool_present, entry = _select_pool_entry("openrouter")
if pool_present:
or_key = explicit_api_key or _pool_runtime_api_key(entry)
if or_key:
- base_url = _pool_runtime_base_url(entry, OPENROUTER_BASE_URL) or OPENROUTER_BASE_URL
+ base_url = override_url or _pool_runtime_base_url(entry, OPENROUTER_BASE_URL) or OPENROUTER_BASE_URL
logger.debug("Auxiliary client: OpenRouter via pool")
return _create_openai_client(
api_key=or_key, base_url=base_url, default_headers=build_or_headers()
@@ -2313,7 +2317,7 @@ def _try_openrouter(explicit_api_key: Optional[Union[str, Callable[[], str]]] =
return None, None
logger.debug("Auxiliary client: OpenRouter")
return _create_openai_client(
- api_key=or_key, base_url=OPENROUTER_BASE_URL, default_headers=build_or_headers()
+ api_key=or_key, base_url=override_url or OPENROUTER_BASE_URL, default_headers=build_or_headers()
), or_model
@@ -3002,7 +3006,8 @@ def _try_azure_foundry(
return client, final_model
-def _try_anthropic(explicit_api_key: Optional[Union[str, Callable[[], str]]] = None) -> Tuple[Optional[Any], Optional[str]]:
+def _try_anthropic(explicit_api_key: Optional[Union[str, Callable[[], str]]] = None,
+ explicit_base_url: Optional[str] = None) -> Tuple[Optional[Any], Optional[str]]:
try:
from agent.anthropic_adapter import build_anthropic_client
from agent.anthropic_credentials import resolve_anthropic_token
@@ -3030,6 +3035,12 @@ def _try_anthropic(explicit_api_key: Optional[Union[str, Callable[[], str]]] = N
cfg_base_url = (model_cfg.get("base_url") or "").strip().rstrip("/")
if cfg_base_url and _is_anthropic_compatible_host(cfg_base_url):
base_url = cfg_base_url
+ # A caller-supplied endpoint (fallback_providers entry, custom_providers entry) wins over
+ # both the pool row and config.yaml, under the same Anthropic-compatible host rule the
+ # primary path applies — a foreign host would 401 every call (#121359).
+ override_url = (explicit_base_url or "").strip().rstrip("/")
+ if override_url and _is_anthropic_compatible_host(override_url):
+ base_url = override_url
from agent.anthropic_credentials import _is_oauth_token
is_oauth = _is_oauth_token(token)
model = _get_aux_model_for_provider("anthropic") or "claude-haiku-4-5-20251001"
@@ -4937,7 +4948,8 @@ def _resolve_auto_branch(req: _ResolveRequest) -> _ResolveResult:
def _resolve_openrouter_branch(req: _ResolveRequest) -> _ResolveResult:
"""OpenRouter."""
- client, default = _try_openrouter(explicit_api_key=req.explicit_api_key, model=req.model)
+ client, default = _try_openrouter(explicit_api_key=req.explicit_api_key, model=req.model,
+ explicit_base_url=req.explicit_base_url)
if client is None:
logger.warning("resolve_provider_client: openrouter requested but %s",
_describe_openrouter_unavailable(model=req.model))
@@ -5200,7 +5212,8 @@ def _resolve_api_key_branch(req: _ResolveRequest, pconfig: Any, resolve_creds: C
"""PROVIDER_REGISTRY ``api_key`` providers (Anthropic via its own resolver), honouring explicit overrides."""
provider = req.provider
if provider == "anthropic":
- client, default_model = _try_anthropic(explicit_api_key=req.explicit_api_key)
+ client, default_model = _try_anthropic(explicit_api_key=req.explicit_api_key,
+ explicit_base_url=req.explicit_base_url)
return _route_or_warn(req, client, default_model,
"resolve_provider_client: anthropic requested but no Anthropic credentials found")
creds = resolve_creds(provider)
diff --git a/tests/agent/test_fallback_entry_base_url.py b/tests/agent/test_fallback_entry_base_url.py
new file mode 100644
index 00000000000..57991a5c3b9
--- /dev/null
+++ b/tests/agent/test_fallback_entry_base_url.py
@@ -0,0 +1,91 @@
+"""A ``fallback_providers`` entry's ``base_url`` must reach the client (#121359).
+
+``try_activate_fallback`` forwards the entry's ``base_url`` to
+``resolve_provider_client(explicit_base_url=...)``. Every registry API-key provider honours
+that override, but the two providers with their own resolver branches — ``anthropic`` and
+``openrouter`` — dropped it and built the client on the vendor's canonical host, sending the
+fallback turn (and the key) somewhere the user never configured.
+
+These assert the RELATIONSHIP: given an explicit endpoint, the resolved client's base URL is
+that endpoint. No live request is made; all hosts here are loopback/``.invalid``.
+"""
+
+from __future__ import annotations
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+
[email protected](autouse=True)
+def _clean_env(monkeypatch):
+ for key in ("OPENAI_API_KEY", "OPENAI_BASE_URL", "ANTHROPIC_API_KEY", "ANTHROPIC_TOKEN",
+ "ANTHROPIC_BASE_URL", "OPENROUTER_API_KEY", "OPENROUTER_BASE_URL"):
+ monkeypatch.delenv(key, raising=False)
+
+
+_RELAY_ANTHROPIC = "http://127.0.0.1:9002/anthropic"
+_RELAY_OPENROUTER = "http://127.0.0.1:9002/openrouter/v1"
+
+
+def _client_base_url(client) -> str:
+ for chain in (("base_url",), ("_real_client", "base_url"), ("_client", "base_url")):
+ obj = client
+ try:
+ for attr in chain:
+ obj = getattr(obj, attr)
+ return str(obj)
+ except AttributeError:
+ continue
+ return ""
+
+
+def test_anthropic_fallback_entry_base_url_is_the_resolved_endpoint():
+ """A fallback entry pointing anthropic at an Anthropic-protocol relay must be honoured."""
+ from agent.auxiliary_client import resolve_provider_client
+
+ fake_anthropic = MagicMock(name="anthropic_sdk_client")
+ with patch("agent.anthropic_adapter.build_anthropic_client", return_value=fake_anthropic) as mock_build:
+ client, _model = resolve_provider_client(
+ "anthropic", model="claude-haiku-4-5-20251001", raw_codex=True,
+ explicit_base_url=_RELAY_ANTHROPIC, explicit_api_key="sk-test-not-a-real-key")
+
+ assert client is not None
+ assert mock_build.call_args[0][1] == _RELAY_ANTHROPIC
+ assert client.base_url == _RELAY_ANTHROPIC
+
+
+def test_anthropic_fallback_entry_ignores_a_non_anthropic_endpoint():
+ """A foreign host would 401 every call: the canonical host stays, same rule as the primary path."""
+ from agent.auxiliary_client import resolve_provider_client
+
+ with patch("agent.anthropic_adapter.build_anthropic_client", return_value=MagicMock()) as mock_build:
+ client, _model = resolve_provider_client(
+ "anthropic", model="claude-haiku-4-5-20251001", raw_codex=True,
+ explicit_base_url="http://127.0.0.1:9002/openai/v1", explicit_api_key="sk-test-not-a-real-key")
+
+ assert client is not None
+ assert mock_build.call_args[0][1] != "http://127.0.0.1:9002/openai/v1"
+
+
+def test_openrouter_fallback_entry_base_url_is_the_resolved_endpoint():
+ """A fallback entry pointing openrouter at a relay must not resolve to openrouter.ai."""
+ from agent.auxiliary_client import resolve_provider_client
+
+ client, _model = resolve_provider_client(
+ "openrouter", model="some/model", raw_codex=True,
+ explicit_base_url=_RELAY_OPENROUTER, explicit_api_key="sk-test-not-a-real-key")
+
+ assert client is not None
+ assert _client_base_url(client).rstrip("/") == _RELAY_OPENROUTER
+
+
+def test_openrouter_without_an_entry_base_url_keeps_the_configured_default():
+ """No override: resolution is unchanged (no relay invented)."""
+ from agent.auxiliary_client import OPENROUTER_BASE_URL, resolve_provider_client
+
+ client, _model = resolve_provider_client(
+ "openrouter", model="some/model", raw_codex=True, explicit_api_key="sk-test-not-a-real-key")
+
+ assert client is not None
+ assert _client_base_url(client).rstrip("/") == OPENROUTER_BASE_URL.rstrip("/")