The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): /model listing also skips the OpenRouter catalog GET and saved-endpoint /models probes
kshitijk4poor4243abd6335b
diff --git a/gateway/slash_commands_model.py b/gateway/slash_commands_model.pyindex 7ae52e7274c..83fc4484dd2 100644--- a/gateway/slash_commands_model.py+++ b/gateway/slash_commands_model.py@@ -423,8 +423,9 @@ class GatewayModelCommandsMixin:current_model=ctx.current_model, user_providers=ctx.user_provs,custom_providers=ctx.custom_provs, excluded_providers=ctx.excluded_provs,# Chat `/model` is a read path: catalogs come from the disk cache and stale ones warm- # in the background, so one degraded provider can't stall the reply (#74003).- non_blocking_catalogs=True,+ # in the background, and only the selected custom endpoint is probed live, so one+ # degraded provider can't stall the reply (#74003). Mirrors the GUI read path.+ non_blocking_catalogs=True, probe_custom_providers=False, probe_current_custom_provider=True,)adapter = self._delivery_adapter_for(ctx.source)if adapter is not None and getattr(type(adapter), "send_model_picker", None) is not None:diff --git a/hermes_cli/model_switch_providers.py b/hermes_cli/model_switch_providers.pyindex 8164ec91a68..4d2ab8e2dd8 100644--- a/hermes_cli/model_switch_providers.py+++ b/hermes_cli/model_switch_providers.py@@ -1302,20 +1302,23 @@ def list_picker_providers(current_provider: str = "", current_base_url: str = "", user_providers: dict = None,custom_providers: list | None = None, max_models: int | None = None, current_model: str = "",include_moa: bool = False, excluded_providers: list | None = None,- non_blocking_catalogs: bool = False) -> List[dict]:+ non_blocking_catalogs: bool = False, probe_custom_providers: bool = True,+ probe_current_custom_provider: bool = False) -> List[dict]:"""Interactive-picker variant of :func:`list_authenticated_providers`.OpenRouter's list is replaced with :func:`hermes_cli.models.fetch_openrouter_models` (curatedsnapshot filtered against the live catalog) and rows left with no models are dropped — exceptcustom endpoints, where the user may supply their own model set through config.- ``non_blocking_catalogs`` is forwarded unchanged (cache-only catalogs, background warm)."""+ ``non_blocking_catalogs`` makes every catalog read cache-only (OpenRouter's included, stale disk+ copy over a live GET) with a background warm; the ``probe_*`` flags are forwarded unchanged."""from hermes_cli.model_switch import list_authenticated_providersfrom hermes_cli.models import fetch_openrouter_modelsproviders = list_authenticated_providers(current_provider=current_provider, current_base_url=current_base_url,user_providers=user_providers, custom_providers=custom_providers, max_models=max_models,current_model=current_model, for_picker=True, excluded_providers=excluded_providers,- non_blocking_catalogs=non_blocking_catalogs)+ non_blocking_catalogs=non_blocking_catalogs, probe_custom_providers=probe_custom_providers,+ probe_current_custom_provider=probe_current_custom_provider)if include_moa:providers = _prepend_moa_picker_provider(providers, current_provider=current_provider)@@ -1323,7 +1326,7 @@ def list_picker_providers(for p in providers:if str(p.get("slug", "")).lower() == "openrouter":try:- live_ids = [mid for mid, _ in fetch_openrouter_models()]+ live_ids = [mid for mid, _ in fetch_openrouter_models(cache_only=non_blocking_catalogs)]except Exception:live_ids = list(p.get("models", []))p = dict(p)diff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex 21b463122ab..32b575dbb38 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -171,13 +171,15 @@ def _openrouter_catalog_disk_path() -> Path:return get_hermes_home() / "cache" / "openrouter_curated_catalog.json"-def _read_openrouter_catalog_disk() -> list[tuple[str, str]] | None:- """Fresh curated catalog from disk, or None (missing, corrupt, expired, or empty)."""+def _read_openrouter_catalog_disk(*, allow_stale: bool = False) -> list[tuple[str, str]] | None:+ """Fresh curated catalog from disk, or None (missing, corrupt, expired, or empty).++ ``allow_stale`` ignores the TTL — the cache-only read path prefers a stale copy over a live GET."""obj = _read_json_cache(_openrouter_catalog_disk_path())if obj is None:return Nonetry:- if time.time() - float(obj.get("fetched_at", 0)) > _openrouter_catalog_disk_ttl():+ if not allow_stale and time.time() - float(obj.get("fetched_at", 0)) > _openrouter_catalog_disk_ttl():return Noneexcept (TypeError, ValueError):return None@@ -567,8 +569,10 @@ def _fetch_live_catalog_index(url: str, timeout: float, opener) -> Optional[tupldef fetch_openrouter_models(- timeout: float = 8.0, *, force_refresh: bool = False) -> list[tuple[str, str]]:- """Return the curated OpenRouter picker list, refreshed from the live catalog when possible."""+ timeout: float = 8.0, *, force_refresh: bool = False, cache_only: bool = False) -> list[tuple[str, str]]:+ """Return the curated OpenRouter picker list, refreshed from the live catalog when possible.++ ``cache_only`` never opens a socket: memory, then disk (stale accepted), then the in-repo snapshot."""# The curated list is filtered from this profile's manifest (``model_catalog.*`` config, its# ``<home>/cache`` copy), so a routed profile keeps its own slot instead of the module one.from hermes_cli.models_profile_cache import profile_slot_get, profile_slot_set@@ -585,6 +589,8 @@ def fetch_openrouter_models(if disk:profile_slot_set(_me, "_openrouter_catalog_cache", disk)return list(disk)+ if cache_only:+ return list(_read_openrouter_catalog_disk(allow_stale=True) or OPENROUTER_MODELS)# Remote catalog manifest first, in-repo snapshot when unreachable; the live /v1/models filter# (tool support, free pricing) is applied on top either way.diff --git a/tests/gateway/test_model_command_async_offload.py b/tests/gateway/test_model_command_async_offload.pyindex ed973d86191..da7a337aa8c 100644--- a/tests/gateway/test_model_command_async_offload.py+++ b/tests/gateway/test_model_command_async_offload.py@@ -140,3 +140,27 @@ async def test_picker_path_offloads_list_picker_providers(_isolated_config, monk)+++async def test_picker_path_lists_cache_only_and_probes_only_the_current_custom_endpoint(_isolated_config, monkeypatch):+ """#74003: the chat ``/model`` reply is a read path. The listing must ask for cache-only catalogs+ and must not live-probe every saved custom endpoint (only the selected one), matching the GUI."""+ seen: list[dict] = []++ def _fake_list_picker_providers(**kwargs):+ seen.append(kwargs)+ return [{"slug": "openrouter", "name": "OpenRouter", "is_current": True,+ "models": ["gpt-x"], "total_models": 1}]++ monkeypatch.setattr("hermes_cli.model_switch_providers.list_picker_providers", _fake_list_picker_providers)+ runner = _make_runner()+ runner.adapters = {Platform.TELEGRAM: _FakePickerAdapter()}+ monkeypatch.setattr(runner, "_thread_metadata_for_source", lambda *a, **k: None, raising=False)+ monkeypatch.setattr(runner, "_reply_anchor_for_event", lambda *a, **k: None, raising=False)++ assert await runner._handle_model_command(_make_event()) is None+ assert seen, "listing never ran"+ flags = {k: seen[0].get(k) for k in ("non_blocking_catalogs", "probe_custom_providers", "probe_current_custom_provider")}+ assert flags == {"non_blocking_catalogs": True, "probe_custom_providers": False,+ "probe_current_custom_provider": True}, flagsdiff --git a/tests/gateway/test_model_command_nonblocking_catalogs.py b/tests/gateway/test_model_command_nonblocking_catalogs.pydeleted file mode 100644index d5324c29594..00000000000--- a/tests/gateway/test_model_command_nonblocking_catalogs.py+++ /dev/null@@ -1,92 +0,0 @@-"""#74003: the chat ``/model`` listing must never join live catalog probes.--``list_authenticated_providers(non_blocking_catalogs=True)`` is the cache-only read path (rows read-the disk cache, stale ones warm in the background). The gateway listing has to opt in, and-``list_picker_providers`` has to forward the flag — otherwise a cold cache with several credentialed-providers force-refreshes every catalog in the request path."""--import json--import pytest--from gateway.config import Platform-from gateway.platforms.event import MessageEvent, MessageType-from gateway.run import GatewayRunner-from gateway.session import SessionSource--_PROVIDER_KEYS = ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "DEEPSEEK_API_KEY", "GROQ_API_KEY",- "MISTRAL_API_KEY", "XAI_API_KEY")---def test_picker_listing_with_non_blocking_catalogs_never_forces_a_refresh(tmp_path, monkeypatch):- import hermes_cli.models as models- from hermes_cli.model_switch_providers import list_picker_providers-- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- for key in _PROVIDER_KEYS:- monkeypatch.setenv(key, "dummy")- (tmp_path / "provider_models_cache.json").write_text(json.dumps({}), encoding="utf-8")- monkeypatch.setattr("agent.models_dev.fetch_models_dev", lambda *a, **k: {})- monkeypatch.setattr(models, "fetch_api_models", lambda *a, **k: [])-- forced: list[str] = []- real_cached = models.cached_provider_model_ids-- def counting_cached(slug, *args, **kwargs):- if kwargs.get("force_refresh"):- forced.append(slug)- return real_cached(slug, *args, **kwargs)-- monkeypatch.setattr(models, "cached_provider_model_ids", counting_cached)-- list_picker_providers(max_models=50, include_moa=True, current_provider="deepseek",- user_providers={}, custom_providers=[], excluded_providers=[],- non_blocking_catalogs=True)-- assert forced == [], f"cache-only listing force-refreshed catalogs in the request path: {forced}"---class _PickerResult:- success = True---class _PickerAdapter:- async def send_model_picker(self, **kwargs):- return _PickerResult()---async def test_gateway_model_listing_passes_non_blocking_catalogs(tmp_path, monkeypatch):- import gateway.run as gateway_run-- hermes_home = tmp_path / ".hermes"- hermes_home.mkdir()- (hermes_home / "config.yaml").write_text(- "model:\n default: gpt-x\n provider: openrouter\nproviders: {}\n", encoding="utf-8")- monkeypatch.setattr(gateway_run, "_hermes_home", hermes_home)- monkeypatch.setattr("agent.models_dev.fetch_models_dev", lambda: {})-- seen: list[dict] = []-- def fake_list_picker_providers(**kwargs):- seen.append(kwargs)- return [{"slug": "openrouter", "name": "OpenRouter", "is_current": True,- "models": ["gpt-x"], "total_models": 1}]-- monkeypatch.setattr("hermes_cli.model_switch_providers.list_picker_providers",- fake_list_picker_providers)-- runner = object.__new__(GatewayRunner)- runner.adapters = {Platform.TELEGRAM: _PickerAdapter()}- runner._voice_mode = {}- runner._session_model_overrides = {}- runner._running_agents = {}- monkeypatch.setattr(runner, "_thread_metadata_for_source", lambda *a, **k: None, raising=False)- monkeypatch.setattr(runner, "_reply_anchor_for_event", lambda *a, **k: None, raising=False)-- event = MessageEvent(text="/model", message_type=MessageType.TEXT,- source=SessionSource(platform=Platform.TELEGRAM, chat_id="12345", chat_type="dm"))- assert await runner._handle_model_command(event) is None- assert seen and seen[0].get("non_blocking_catalogs") is True, (- f"gateway /model listing must pass non_blocking_catalogs=True, got {seen}")-diff --git a/tests/hermes_cli/test_list_picker_providers.py b/tests/hermes_cli/test_list_picker_providers.pyindex 21581fd2046..5e03d3dfd6d 100644--- a/tests/hermes_cli/test_list_picker_providers.py+++ b/tests/hermes_cli/test_list_picker_providers.py@@ -240,3 +240,37 @@ def test_distinct_kimi_china_credential_still_listed(monkeypatch):assert slugs.count("kimi-coding") == 1assert "kimi" not in slugs # alias collapsed into the canonical rowassert "kimi-coding-cn" in slugs # distinct China endpoint preserved+++def test_non_blocking_listing_opens_no_socket(monkeypatch, tmp_path):+ """#74003: ``non_blocking_catalogs=True`` must not run a single live catalog probe in the calling+ thread — not the per-provider ``/models`` prefetch and not OpenRouter's curated-catalog GET —+ even with several credentialed providers and an empty on-disk cache."""+ import json++ import hermes_cli.models as models_mod++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ for key in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "DEEPSEEK_API_KEY", "GROQ_API_KEY",+ "MISTRAL_API_KEY", "XAI_API_KEY", "OPENROUTER_API_KEY"):+ monkeypatch.setenv(key, "dummy")+ (tmp_path / "provider_models_cache.json").write_text(json.dumps({}), encoding="utf-8")+ monkeypatch.setattr("agent.models_dev.fetch_models_dev", lambda *a, **k: {})++ live: list[str] = []++ def _live_probe(*args, **kwargs):+ live.append(str(args[0]) if args else "openrouter-catalog")+ return []++ monkeypatch.setattr(models_mod, "provider_model_ids", _live_probe)+ monkeypatch.setattr(models_mod, "fetch_api_models", _live_probe)+ monkeypatch.setattr(models_mod, "_fetch_live_catalog_index", _live_probe)+ monkeypatch.setattr(models_mod, "_spawn_swr_refresh", lambda *a, **k: None) # background warm is not "live"++ rows = model_switch_providers.list_picker_providers(+ max_models=50, include_moa=True, current_provider="openrouter", user_providers={},+ custom_providers=[], excluded_providers=[], non_blocking_catalogs=True)++ assert live == [], f"cache-only listing ran live probes in the request path: {live}"+ assert any(r.get("slug") == "openrouter" and r.get("models") for r in rows), "OpenRouter row lost its curated snapshot"