The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(model-providers): fetch_models stubs drop to the ABC; commandcode and AI Gateway catalog GETs go through open_credentialed_url
teknium1d3644736207d
diff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex d70dc09fcd6..0c662667b39 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -637,7 +637,7 @@ def fetch_ai_gateway_models(from hermes_constants import AI_GATEWAY_BASE_URLfallback = list(VERCEL_AI_GATEWAY_MODELS)- live = _fetch_live_catalog_index(f"{AI_GATEWAY_BASE_URL.rstrip('/')}/models", timeout, urllib.request.urlopen)+ live = _fetch_live_catalog_index(f"{AI_GATEWAY_BASE_URL.rstrip('/')}/models", timeout, _urlopen_model_catalog_request)if live is None:return list(_ai_gateway_catalog_cache or fallback)_, live_by_id = live@@ -2481,7 +2481,7 @@ def _fetch_ai_gateway_models(timeout: float = 5.0) -> Optional[list[str]]:headers = {"Authorization": f"Bearer {api_key}", "User-Agent": _HERMES_USER_AGENT}try:url = base_url.rstrip("/") + "/models"- data = _get_json(url, timeout=timeout, headers=headers, opener=urllib.request.urlopen)+ data = _get_json(url, timeout=timeout, headers=headers)return [m["id"] for m in data.get("data", [])if m.get("id") and m.get("type") == "language" and "tool-use" in (m.get("tags") or [])]diff --git a/plugins/model-providers/bedrock/__init__.py b/plugins/model-providers/bedrock/__init__.pyindex f1d31949019..e461307b004 100644--- a/plugins/model-providers/bedrock/__init__.py+++ b/plugins/model-providers/bedrock/__init__.py@@ -7,17 +7,12 @@ from providers.base import ProviderProfileclass BedrockProfile(ProviderProfile):"""AWS Bedrock — no REST /v1/models endpoint; uses AWS SDK."""- def fetch_models(- self, *, api_key: str | None = None, base_url: str | None = None, timeout: float = 8.0- ) -> list[str] | None:- """Bedrock model listing requires AWS SDK, not a REST call."""- return None-bedrock = BedrockProfile(name="bedrock", aliases=("aws", "aws-bedrock", "amazon-bedrock", "amazon"), api_mode="bedrock_converse",env_vars=(), # AWS SDK credentials — not env varsbase_url="https://bedrock-runtime.us-east-1.amazonaws.com", auth_type="aws_sdk",+ supports_model_listing=False, # listing goes through the AWS SDK, not a REST call)register_provider(bedrock)diff --git a/plugins/model-providers/commandcode/__init__.py b/plugins/model-providers/commandcode/__init__.pyindex 37bfff5b2f9..0f57962c251 100644--- a/plugins/model-providers/commandcode/__init__.py+++ b/plugins/model-providers/commandcode/__init__.py@@ -6,6 +6,7 @@ import jsonimport loggingimport urllib.request+from hermes_cli.urllib_security import open_credentialed_urlfrom providers import register_providerfrom providers.base import ProviderProfile, _profile_user_agent@@ -30,7 +31,7 @@ class CommandCodeProfile(ProviderProfile):req = urllib.request.Request(models_url)req.add_header("Accept", "application/json")req.add_header("User-Agent", _profile_user_agent())- with urllib.request.urlopen(req, timeout=timeout) as resp:+ with open_credentialed_url(req, timeout=timeout) as resp:data = json.loads(resp.read().decode())return [m["id"] for m in data.get("data", []) if isinstance(m, dict) and "id" in m]except Exception as exc:diff --git a/plugins/model-providers/copilot-acp/__init__.py b/plugins/model-providers/copilot-acp/__init__.pyindex 0f3b87ca1df..1be440c4d1a 100644--- a/plugins/model-providers/copilot-acp/__init__.py+++ b/plugins/model-providers/copilot-acp/__init__.py@@ -21,12 +21,6 @@ class CopilotACPProfile(ProviderProfile):return CopilotACPClient(**client_kwargs)- def fetch_models(- self, *, api_key: str | None = None, base_url: str | None = None, timeout: float = 8.0- ) -> list[str] | None:- """Model listing is handled by the ACP subprocess."""- return None-copilot_acp = CopilotACPProfile(name="copilot-acp", aliases=("github-copilot-acp", "copilot-acp-agent"),@@ -34,6 +28,7 @@ copilot_acp = CopilotACPProfile(env_vars=(), # Managed by ACP subprocessbase_url="acp://copilot", # ACP internal schemeauth_type="external_process",+ supports_model_listing=False, # model listing is handled by the ACP subprocess# How to launch the CLI; env var names predate this profile (formerly hardcoded in# hermes_cli/auth.py), so existing setups keep working.process_command="copilot",diff --git a/plugins/model-providers/vertex/__init__.py b/plugins/model-providers/vertex/__init__.pyindex 51fe68ca418..5227f6bf842 100644--- a/plugins/model-providers/vertex/__init__.py+++ b/plugins/model-providers/vertex/__init__.py@@ -22,18 +22,13 @@ class VertexProfile(ProviderProfile):thinking_config = _snake_case_gemini_thinking_config(raw) if raw else Nonereturn {"extra_body": {"google": {"thinking_config": thinking_config}}} if thinking_config else {}- def fetch_models(- self, *, api_key: str | None = None, base_url: str | None = None, timeout: float = 8.0- ) -> list[str] | None:- """No ``/models`` route on the OpenAI-compat endpoint; setup ships a curated list."""- return None-vertex = VertexProfile(name="vertex", aliases=("google-vertex", "vertex-ai", "gcp-vertex"), api_mode="chat_completions",env_vars=(), # OAuth2 via service account / ADC — not a static key env varbase_url="https://aiplatform.googleapis.com", # real base_url computed at runtimeauth_type="vertex", default_aux_model="google/gemini-3.6-flash",+ supports_model_listing=False, # no /models route on the OpenAI-compat endpoint; setup ships a curated list)register_provider(vertex)diff --git a/providers/base.py b/providers/base.pyindex b509d36f5a9..0941c5d8d7c 100644--- a/providers/base.py+++ b/providers/base.py@@ -55,6 +55,8 @@ class ProviderProfile:models_url: str = "" # explicit models endpoint; falls back to {base_url}/modelsauth_type: str = "api_key" # api_key|oauth_device_code|oauth_external|copilot|aws_sdksupports_health_check: bool = True # False → doctor skips /models probe for this provider+ # False → fetch_models returns None without a network call (catalog comes from an SDK/subprocess).+ supports_model_listing: bool = True# ── Vision support ────────────────────────────────────────# True when the provider's API accepts image content inside@@ -300,6 +302,8 @@ class ProviderProfile:Callers must always fall back to the static _PROVIDER_MODELS listwhen this returns None."""+ if not self.supports_model_listing:+ return Nonecaller_base = (base_url or "").strip()effective_base = caller_base or self.base_urlcustom_base = bool(caller_base) and (diff --git a/tests/hermes_cli/test_ai_gateway_models.py b/tests/hermes_cli/test_ai_gateway_models.pyindex b08c98d1926..7c16f5ce56c 100644--- a/tests/hermes_cli/test_ai_gateway_models.py+++ b/tests/hermes_cli/test_ai_gateway_models.py@@ -94,7 +94,7 @@ def test_fetch_ai_gateway_models_filters_against_live_catalog():for mid in live_ids]}- with patch("urllib.request.urlopen", return_value=_mock_urlopen(payload)):+ with patch("hermes_cli.models._urlopen_model_catalog_request", return_value=_mock_urlopen(payload)):result = fetch_ai_gateway_models(force_refresh=True)assert [mid for mid, _ in result] == live_ids@@ -111,7 +111,7 @@ def test_fetch_ai_gateway_models_tags_free_models():{"id": second_id, "pricing": {"input": "0", "output": "0"}},]}- with patch("urllib.request.urlopen", return_value=_mock_urlopen(payload)):+ with patch("hermes_cli.models._urlopen_model_catalog_request", return_value=_mock_urlopen(payload)):result = fetch_ai_gateway_models(force_refresh=True)by_id = dict(result)@@ -129,7 +129,7 @@ def test_free_moonshot_model_auto_promoted_to_top_even_if_not_curated():{"id": unlisted_free_moonshot, "pricing": {"input": "0", "output": "0"}},]}- with patch("urllib.request.urlopen", return_value=_mock_urlopen(payload)):+ with patch("hermes_cli.models._urlopen_model_catalog_request", return_value=_mock_urlopen(payload)):result = fetch_ai_gateway_models(force_refresh=True)assert result[0] == (unlisted_free_moonshot, "recommended")@@ -145,7 +145,7 @@ def test_paid_moonshot_does_not_get_auto_promoted():{"id": "moonshotai/some-paid-variant", "pricing": {"input": "0.001", "output": "0.002"}},]}- with patch("urllib.request.urlopen", return_value=_mock_urlopen(payload)):+ with patch("hermes_cli.models._urlopen_model_catalog_request", return_value=_mock_urlopen(payload)):result = fetch_ai_gateway_models(force_refresh=True)assert result[0][0] == first_curated@@ -153,6 +153,16 @@ def test_paid_moonshot_does_not_get_auto_promoted():def test_fetch_ai_gateway_models_falls_back_on_error():_reset_caches()- with patch("urllib.request.urlopen", side_effect=OSError("network")):+ with patch("hermes_cli.models._urlopen_model_catalog_request", side_effect=OSError("network")):result = fetch_ai_gateway_models(force_refresh=True)assert result == list(VERCEL_AI_GATEWAY_MODELS)+++def test_fetch_ai_gateway_models_routes_bearer_through_catalog_opener(monkeypatch):+ """The keyed catalog GET carries the AI Gateway bearer, so it must go through the+ redirect-safe catalog opener rather than bare urlopen (which forwards headers cross-origin)."""+ monkeypatch.setenv("AI_GATEWAY_API_KEY", "gw-secret")+ with patch("hermes_cli.models._urlopen_model_catalog_request", return_value=_mock_urlopen({"data": []})) as opener:+ assert models_module._fetch_ai_gateway_models() == []+ req = opener.call_args.args[0]+ assert req.get_header("Authorization") == "Bearer gw-secret"diff --git a/tests/plugins/model_providers/test_commandcode_profile.py b/tests/plugins/model_providers/test_commandcode_profile.pyindex 7ae3f2953e7..dd7537e19f9 100644--- a/tests/plugins/model_providers/test_commandcode_profile.py+++ b/tests/plugins/model_providers/test_commandcode_profile.py@@ -353,9 +353,7 @@ class TestCommandCodeBaseUrlOverride:captured["url"] = req.full_urlreturn _FakeResp()- with mock_patch.object(- cc_mod.urllib.request, "urlopen", side_effect=fake_urlopen- ):+ with mock_patch.object(cc_mod, "open_credentialed_url", side_effect=fake_urlopen):result = commandcode_profile.fetch_models(api_key="k", base_url=cc_mod._COMMANDCODE_BASE + "/")diff --git a/tests/providers/test_fetch_models_base_url.py b/tests/providers/test_fetch_models_base_url.pyindex 59f11fecb5e..edbd5ed3015 100644--- a/tests/providers/test_fetch_models_base_url.py+++ b/tests/providers/test_fetch_models_base_url.py@@ -210,3 +210,16 @@ class TestModelPickerBaseUrlIntegration:mock_profile.fetch_models.assert_called_once()call_kwargs = mock_profile.fetch_models.call_argsassert call_kwargs.kwargs.get("base_url") == "https://custom.proxy.com"+++def test_profiles_without_model_listing_never_hit_the_network():+ """SDK/subprocess-backed profiles (bedrock, vertex, copilot-acp) still carry a base_url the+ generic fetch_models would happily GET ``/models`` against; the flag must short-circuit first."""+ from providers import list_providers++ flagged = [p for p in list_providers() if not p.supports_model_listing]+ assert {p.name for p in flagged} >= {"bedrock", "vertex", "copilot-acp"}+ with patch("hermes_cli.urllib_security.open_credentialed_url") as opener:+ for profile in flagged:+ assert profile.fetch_models(api_key="k", base_url=profile.base_url) is None, profile.name+ opener.assert_not_called()