The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(providers): make a configured relay terminal for catalog egress; refuse a foreign Anthropic endpoint
Austin Pickett6926997f059c
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.pyindex 46d6c6050d9..867bc6879d2 100644--- a/agent/auxiliary_client.py+++ b/agent/auxiliary_client.py@@ -3044,9 +3044,18 @@ def _try_anthropic(explicit_api_key: Optional[Union[str, Callable[[], str]]] = Nbase_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).+ # primary path applies. A foreign host is REFUSED outright rather than silently demoted to+ # the canonical host: continuing would send the explicit credential to a target the caller+ # did not ask for (#121359).override_url = (explicit_base_url or "").strip().rstrip("/")- if override_url and _is_anthropic_compatible_host(override_url):+ if override_url:+ if not _is_anthropic_compatible_host(override_url):+ logger.warning(+ "Auxiliary client: refusing anthropic explicit base_url %r — not an "+ "Anthropic-compatible host; no client built and no request sent.",+ override_url,+ )+ return None, Nonebase_url = override_urlfrom agent.anthropic_credentials import _is_oauth_tokenis_oauth = _is_oauth_token(token)diff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex 015e87e49c8..62892c1c2ec 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -1638,6 +1638,42 @@ def _relay_model_catalog(normalized: str, relay: str) -> Optional[list[str]]:return None++# Canonical fetchers that already resolve `model.base_url` themselves for the configured+# provider AND degrade to their curated list when that relay fails — `_anthropic_catalog`,+# `_custom_catalog`, `_openai_catalog` (via `_openai_discovery_base_url`) and the simple+# api-key fetchers (via `resolve_api_key_provider_credentials`). They already satisfy the+# "no vendor egress when a relay is configured" invariant, so intercepting them would only+# override correct, better-merged behaviour. Everything else is vendor-pinned (#121387).+_RELAY_AWARE_CATALOG_FETCHERS = frozenset(+ {"anthropic", "custom", "openai", "openai-api", "stepfun", "gmi"}+)+++def _static_catalog(normalized: str, fetcher: Any) -> list[str]:+ """The local, no-egress catalog tail: curated static list (+ models.dev merge where preferred).++ Shared by the normal path's final fallback and by the configured-relay degrade path, which+ must never reach a live vendor fetcher (#121387).+ """+ # Merge static curated list with live API results so models that the live endpoint omits (stale cache,+ # partial rollout) still appear in the picker. Single providers (kimi, zai) use curated-first (commit+ # 658ac1d86) to surface newest models even when live API lags (#46309). OpenCode Zen / Go are different:+ # their live API is the authoritative catalog, so they merge live-first — live entries lead and stale+ # curated entries no longer pollute the top of the picker. (#49129) Plugin providers with no static+ # _PROVIDER_MODELS entry fall back to the profile's curated fallback_models so their agentic picks lead+ # the picker instead of whatever the live catalog happens to return first (e.g. Fireworks lists an image+ # model, flux-*, ahead of its chat models).+ # A provider with a live fetcher that declined is serving a placeholder; one without any live+ # source is serving its authoritative catalog.+ curated_static = (CuratedFallbackModels if fetcher is not None else list)(_PROVIDER_MODELS.get(normalized, []))+ if normalized not in _MODELS_DEV_PREFERRED:+ return _drop_delisted_opencode_models(normalized, curated_static)+ # models.dev keeps listing retired Zen ids too: filter after the merge, not before.+ merged = _drop_delisted_opencode_models(normalized, _merge_with_models_dev(normalized, curated_static))+ return _xai_finalize_catalog(merged) if normalized in {"xai", "xai-oauth"} else merged++def provider_model_ids(provider: Optional[str], *, force_refresh: bool = False) -> list[str]:"""Best known model catalog for a provider: per-provider live fetchers, then the generic profilefetch, then the static list (merged with models.dev for ``_MODELS_DEV_PREFERRED`` providers)."""@@ -1646,14 +1682,17 @@ def provider_model_ids(provider: Optional[str], *, force_refresh: bool = False)return _ollama_local_catalog(force_refresh)normalized = normalize_provider(provider)- # A configured `model.base_url` relay wins over the canonical per-provider fetchers: the- # picker must list what the configured endpoint serves and must not touch the vendor- # host (#121387). Any probe failure falls through to the existing canonical path.+ # A configured `model.base_url` relay is TERMINAL for live catalog egress: the picker must+ # list what the configured endpoint serves and must never touch the vendor host (#121387).+ # A failed or empty probe degrades to the local curated list — falling through to the+ # canonical fetchers would send the provider credential to exactly the host the user+ # deliberately routed away from, recreating the bug on the failure path.relay = _configured_relay_base_url(provider)- if relay:+ if relay and normalized not in _RELAY_AWARE_CATALOG_FETCHERS:relayed = _relay_model_catalog(normalized, relay)if relayed:return relayed+ return _static_catalog(normalized, _PROVIDER_CATALOG_FETCHERS.get(normalized))fetcher = _PROVIDER_CATALOG_FETCHERS.get(normalized)if fetcher is not None:models = fetcher(normalized, force_refresh)@@ -1666,22 +1705,7 @@ def provider_model_ids(provider: Optional[str], *, force_refresh: bool = False)if models is not None:return models- # Merge static curated list with live API results so models that the live endpoint omits (stale cache,- # partial rollout) still appear in the picker. Single providers (kimi, zai) use curated-first (commit- # 658ac1d86) to surface newest models even when live API lags (#46309). OpenCode Zen / Go are different:- # their live API is the authoritative catalog, so they merge live-first — live entries lead and stale- # curated entries no longer pollute the top of the picker. (#49129) Plugin providers with no static- # _PROVIDER_MODELS entry fall back to the profile's curated fallback_models so their agentic picks lead- # the picker instead of whatever the live catalog happens to return first (e.g. Fireworks lists an image- # model, flux-*, ahead of its chat models).- # A provider with a live fetcher that declined is serving a placeholder; one without any live- # source is serving its authoritative catalog.- curated_static = (CuratedFallbackModels if fetcher is not None else list)(_PROVIDER_MODELS.get(normalized, []))- if normalized not in _MODELS_DEV_PREFERRED:- return _drop_delisted_opencode_models(normalized, curated_static)- # models.dev keeps listing retired Zen ids too: filter after the merge, not before.- merged = _drop_delisted_opencode_models(normalized, _merge_with_models_dev(normalized, curated_static))- return _xai_finalize_catalog(merged) if normalized in {"xai", "xai-oauth"} else merged+ return _static_catalog(normalized, fetcher)# ---------------------------------------------------------------------------diff --git a/tests/agent/test_fallback_entry_base_url.py b/tests/agent/test_fallback_entry_base_url.pyindex 57991a5c3b9..41a8825a3db 100644--- a/tests/agent/test_fallback_entry_base_url.py+++ b/tests/agent/test_fallback_entry_base_url.py@@ -55,8 +55,13 @@ def test_anthropic_fallback_entry_base_url_is_the_resolved_endpoint():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."""+def test_anthropic_fallback_entry_refuses_a_non_anthropic_endpoint():+ """An explicit target mismatch is REFUSED — never silently demoted to the canonical host.++ Continuing with `base_url` reset to api.anthropic.com would send the caller's explicit+ credential to a host the caller did not ask for. No client is produced and the SDK+ builder is never reached.+ """from agent.auxiliary_client import resolve_provider_clientwith patch("agent.anthropic_adapter.build_anthropic_client", return_value=MagicMock()) as mock_build:@@ -64,8 +69,8 @@ def test_anthropic_fallback_entry_ignores_a_non_anthropic_endpoint():"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"+ assert client is None, "an incompatible explicit endpoint must not yield a client"+ assert mock_build.call_count == 0, "no canonical client may be constructed on refusal"def test_openrouter_fallback_entry_base_url_is_the_resolved_endpoint():diff --git a/tests/hermes_cli/test_models_relay_base_url.py b/tests/hermes_cli/test_models_relay_base_url.pyindex 134a3f6e1fe..8c14b35c9a5 100644--- a/tests/hermes_cli/test_models_relay_base_url.py+++ b/tests/hermes_cli/test_models_relay_base_url.py@@ -2,6 +2,8 @@from types import SimpleNamespace+import pytest+import hermes_cli.models as models@@ -59,7 +61,20 @@ def test_base_url_for_a_different_provider_is_ignored(monkeypatch):assert models._configured_relay_base_url("openai") == ""-def test_failed_relay_probe_falls_through_to_canonical_fetchers(monkeypatch):+ "probe_result",+ [+ pytest.param("raise", id="relay-hangs-or-errors"),+ pytest.param([], id="relay-404-empty-catalog"),+ ],+)+def test_a_failed_relay_probe_never_falls_back_to_the_vendor_host(monkeypatch, probe_result):+ """Egress sentinel: a configured relay is TERMINAL for live catalog egress.++ A relay that 404s, hangs or returns nothing must degrade to the LOCAL curated list.+ Falling through to the canonical fetcher would send the provider credential to exactly+ the vendor host the user routed away from, recreating #121387 on the failure path.+ """monkeypatch.setattr(models,"_get_model_config_dict",@@ -69,8 +84,10 @@ def test_failed_relay_probe_falls_through_to_canonical_fetchers(monkeypatch):},)- def _boom(**kwargs):- raise RuntimeError("relay down")+ def _probe(**kwargs):+ if probe_result == "raise":+ raise RuntimeError("relay down")+ return probe_resultimport providers@@ -78,14 +95,19 @@ def test_failed_relay_probe_falls_through_to_canonical_fetchers(monkeypatch):providers,"get_provider_profile",lambda name: SimpleNamespace(- auth_type="api_key", fetch_models=_boom, fallback_models=[]+ auth_type="api_key", fetch_models=_probe, fallback_models=[]),)monkeypatch.setattr(models, "_api_key_credentials", lambda name: (None, None))- monkeypatch.setattr(- models,- "_PROVIDER_CATALOG_FETCHERS",- {"deepseek": lambda n, f: ["canonical-model"]},- )- assert models.provider_model_ids("deepseek") == ["canonical-model"]+ # Sentinels on EVERY live-egress seam below the relay probe.+ def _egress(*a, **k):+ raise AssertionError("vendor host touched after a failed relay probe")++ monkeypatch.setattr(models, "_PROVIDER_CATALOG_FETCHERS", {"deepseek": _egress})+ monkeypatch.setattr(models, "_profile_live_catalog", _egress)+ monkeypatch.setattr(models, "_merge_with_models_dev", _egress)+ monkeypatch.setattr(models, "_PROVIDER_MODELS", {"deepseek": ["curated-local"]})++ # Degrades locally to the curated list, with no vendor egress at all.+ assert models.provider_model_ids("deepseek") == ["curated-local"]