The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(models): a curated fallback never pins itself in the provider models cache
teknium13fb8b3f65f3b
diff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex 8a5574fada0..b445198c9e0 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -1344,6 +1344,11 @@ def _copilot_acp_session_models(force_refresh: bool) -> Optional[list[str]]:return live+class CuratedFallbackModels(list[str]):+ """A curated list served because the provider's live catalog was unavailable. The disk cache+ treats it as a placeholder, never as the account's real catalog (#107391)."""++def _copilot_catalog(normalized: str, force_refresh: bool) -> Optional[list[str]]:if normalized == "copilot-acp" and (live := _copilot_acp_session_models(force_refresh)):return live@@ -1353,7 +1358,7 @@ def _copilot_catalog(normalized: str, force_refresh: bool) -> Optional[list[str]return liveexcept Exception:pass- return list(_PROVIDER_MODELS.get("copilot", [])) if normalized == "copilot-acp" else None+ return CuratedFallbackModels(_PROVIDER_MODELS.get("copilot", []))def _nous_catalog(normalized: str, force_refresh: bool) -> Optional[list[str]]:@@ -1576,7 +1581,7 @@ def merge_profile_catalog(normalized: str, profile, live: Optional[list[str]]) -first-time setup (``model_setup_flows._api_key_provider_model_list``) offers the same rows thepicker will later show. Empty live → ``fallback_models`` (None when the profile has none)."""if not live:- rows = list(profile.fallback_models) if profile.fallback_models else None+ rows = CuratedFallbackModels(profile.fallback_models) if profile.fallback_models else Noneelse:curated = list(_PROVIDER_MODELS.get(normalized, [])) or list(profile.fallback_models or ())if not curated:@@ -1593,7 +1598,7 @@ def _drop_delisted_opencode_models(normalized: str, rows: Optional[list[str]]) -FINAL rows for the live-first Zen/Go pickers so no path can offer a slug that 401s (#111749,#115496)."""if rows and normalized in _LIVE_FIRST_PICKER_PROVIDERS:- return [m for m in rows if str(m).lower() not in _OPENCODE_FREE_EXCLUDED_MODELS]+ return type(rows)(m for m in rows if str(m).lower() not in _OPENCODE_FREE_EXCLUDED_MODELS)return rows@@ -1625,7 +1630,9 @@ def provider_model_ids(provider: Optional[str], *, force_refresh: bool = False)# _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).- curated_static = list(_PROVIDER_MODELS.get(normalized, []))+ # 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.@@ -1646,6 +1653,9 @@ _PROVIDER_MODELS_CACHE_TTL = 3600 # 1h# daemon thread refreshes the disk cache; beyond this bound the caller blocks on a live fetch.# Catalogs change on release timescales, so hour-old data beats stalling every picker surface._PROVIDER_MODELS_STALE_SERVE_MAX = 7 * 24 * 3600 # 7d+# A curated fallback row is a placeholder for an outage, not a catalog: re-probe soon and never+# serve it through the stale window.+_PROVIDER_MODELS_FALLBACK_TTL = 60# Cache keys with a background SWR refresh in flight — dedupes concurrent refreshes._swr_refresh_inflight: set = set()@@ -1657,6 +1667,17 @@ def _cache_entry(fp: str, models: list[str], at: Optional[float] = None) -> dictreturn {"fp": fp, "at": time.time() if at is None else at, "models": list(models)}+def _live_result_entry(fp: str, live: list[str], existing: Any, at: Optional[float] = None) -> Optional[dict]:+ """Row to store for a ``provider_model_ids`` result, or ``None`` to keep *existing*: a curated+ fallback never replaces the account's real catalog for the same credentials, and when it is+ stored it is flagged so it expires on the short fallback TTL."""+ if not isinstance(live, CuratedFallbackModels):+ return _cache_entry(fp, live, at)+ if _cache_entry_valid(existing, fp) and not existing.get("fallback"):+ return None+ return {**_cache_entry(fp, live, at), "fallback": True}++def _ollama_native_probe_reachable() -> bool:"""Whether the configured local Ollama root answered the native ``/api/tags`` probe (an emptycatalog from a reachable server is authoritative; a failed probe is not)."""@@ -1684,7 +1705,8 @@ def _spawn_swr_refresh(cache_key: str, refresh_fn=None) -> None:def _default_refresh():live = provider_model_ids(cache_key, force_refresh=True)if live or (cache_key == "ollama" and _ollama_native_probe_reachable()):- return _cache_entry(_credential_fingerprint(cache_key), live or [])+ fp = _credential_fingerprint(cache_key)+ return _live_result_entry(fp, live or [], _load_provider_models_cache().get(cache_key))return Nonedef _refresh() -> None:@@ -1887,12 +1909,12 @@ def cached_provider_model_ids(if not force_refresh and _cache_entry_valid(entry, fp, allow_empty=is_ollama):age = now - entry["at"]- if age < ttl_seconds:+ if age < (_PROVIDER_MODELS_FALLBACK_TTL if entry.get("fallback") else ttl_seconds):return list(entry["models"])# Empty native catalogs are authoritative only for the short native TTL — never served# through the stale window. Non-empty stale rows are served immediately (SWR) so picker# opens never block on serial /v1/models round-trips.- if entry["models"] and age < _PROVIDER_MODELS_STALE_SERVE_MAX:+ if entry["models"] and not entry.get("fallback") and age < _PROVIDER_MODELS_STALE_SERVE_MAX:_spawn_swr_refresh(normalized)return list(entry["models"])@@ -1908,7 +1930,11 @@ def cached_provider_model_ids(live = provider_model_ids(normalized, force_refresh=force_refresh)if live:- _store_cache_entry(normalized, _cache_entry(fp, live, now), cache)+ fresh = _live_result_entry(fp, live, entry, now)+ if fresh is None:+ # The live fetch degraded to the curated list; the account's real catalog is on disk.+ return [model for model in entry["models"] if not _model_requires_account_discovery(normalized, model)]+ _store_cache_entry(normalized, fresh, cache)return list(live)if is_ollama:diff --git a/tests/hermes_cli/test_model_cache_fallback_rows.py b/tests/hermes_cli/test_model_cache_fallback_rows.pynew file mode 100644index 00000000000..c19133a6a51--- /dev/null+++ b/tests/hermes_cli/test_model_cache_fallback_rows.py@@ -0,0 +1,82 @@+"""A curated fallback served because the live catalog fetch failed must never be pinned in the+disk cache as if it were the account's real catalog (#107391): a transient Copilot outage wrote+the 17-model static list over the account's 10 live models with a fresh 1h TTL, and every picker+surface served the wrong list until the TTL lapsed.+"""++from __future__ import annotations++import time+from unittest.mock import patch++import pytest++import hermes_cli.models as mod++[email protected](autouse=True)+def _reset_swr_state():+ with mod._swr_refresh_lock:+ mod._swr_refresh_inflight.clear()+ yield+ with mod._swr_refresh_lock:+ mod._swr_refresh_inflight.clear()+++def _row(models, age_seconds, **extra):+ return {"fp": "fp", "at": time.time() - age_seconds, "models": list(models), **extra}+++LIVE = ["claude-opus-5", "kimi-k3", "gpt-5.6-sol"]+STATIC = ["gpt-5.4", "gpt-4o", "claude-sonnet-4.6"]+++def test_fallback_does_not_overwrite_the_same_credentials_live_row():+ # 2h-old live row (past the 1h TTL, inside the SWR window) + a live fetch that degrades to the+ # curated list: the account's real catalog must survive, in the cache AND in the return value.+ cache = {"copilot": _row(LIVE, age_seconds=7200)}+ with patch.object(mod, "_load_provider_models_cache", return_value=cache), \+ patch.object(mod, "_credential_fingerprint", return_value="fp"), \+ patch.object(mod, "_save_provider_models_cache") as save, \+ patch.object(mod, "provider_model_ids", return_value=mod.CuratedFallbackModels(STATIC)):+ out = mod.cached_provider_model_ids("copilot", force_refresh=True)++ assert out == LIVE+ assert cache["copilot"]["models"] == LIVE+ save.assert_not_called()+++def test_fallback_row_is_recorded_as_fallback_and_never_served_stale():+ # Cold cache: the curated list is served (the picker must not be empty) but recorded as a+ # fallback row, which the SWR stale window must not resurrect — a stale fallback re-probes.+ cache: dict = {}+ with patch.object(mod, "_load_provider_models_cache", return_value=cache), \+ patch.object(mod, "_credential_fingerprint", return_value="fp"), \+ patch.object(mod, "_save_provider_models_cache"), \+ patch.object(mod, "provider_model_ids", return_value=mod.CuratedFallbackModels(STATIC)):+ assert mod.cached_provider_model_ids("copilot") == STATIC+ assert cache["copilot"]["fallback"] is True++ # Same row, now past the fallback TTL: the live fetch runs instead of the stale-serve path,+ # and a real catalog replaces the fallback row.+ cache["copilot"]["at"] = time.time() - mod._PROVIDER_MODELS_FALLBACK_TTL - 1+ with patch.object(mod, "_load_provider_models_cache", return_value=cache), \+ patch.object(mod, "_credential_fingerprint", return_value="fp"), \+ patch.object(mod, "_save_provider_models_cache"), \+ patch.object(mod, "_spawn_swr_refresh") as spawn, \+ patch.object(mod, "provider_model_ids", return_value=list(LIVE)) as live:+ assert mod.cached_provider_model_ids("copilot") == LIVE+ live.assert_called_once()+ spawn.assert_not_called()+ assert cache["copilot"]["models"] == LIVE+ assert "fallback" not in cache["copilot"]+++def test_copilot_catalog_marks_the_static_list_as_fallback_on_a_failed_live_fetch():+ with patch.object(mod, "_copilot_acp_session_models", return_value=None), \+ patch.object(mod, "_resolve_copilot_catalog_api_key", return_value="tok"), \+ patch.object(mod, "_fetch_github_models", side_effect=OSError("503")):+ for slug in ("copilot", "copilot-acp"):+ rows = mod.provider_model_ids(slug)+ assert isinstance(rows, mod.CuratedFallbackModels), slug+ assert rows == list(mod._PROVIDER_MODELS["copilot"])