The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(picker): curated fallback for cold OAuth rows; Z.AI failed-probe negative cache; trim salvage
teknium18669e47a60c7
diff --git a/hermes_cli/auth_zai_kimi.py b/hermes_cli/auth_zai_kimi.pyindex 1985bb44ab4..8649eee20b1 100644--- a/hermes_cli/auth_zai_kimi.py+++ b/hermes_cli/auth_zai_kimi.py@@ -8,11 +8,17 @@ from __future__ import annotationsimport loggingimport hashlib+import timefrom typing import Dict, Optionalfrom hermes_cli.auth_constants import httpxlogger = logging.getLogger("hermes_cli.auth")+# In-process negative cache for Z.AI endpoint detection, keyed by key hash: a failed probe is not+# retried for this long (a success persists to auth.json instead).+_ZAI_PROBE_FAILURE_TTL_SECONDS = 300+_zai_probe_failed_until: Dict[str, float] = {}+# "sk-kimi-" keys only work on api.kimi.com/coding; legacy moonshot keys use the old default.# NO /v1 suffix: the anthropic SDK appends "/v1/messages" itself ("/coding/v1" would 404).KIMI_CODE_BASE_URL = "https://api.kimi.com/coding"@@ -114,11 +120,16 @@ def _resolve_zai_base_url(api_key: str, default_url: str, env_override: str) ->if isinstance(cached, dict) and cached.get("base_url") and cached.get("key_hash", "") == key_hash:logger.debug("Z.AI: using cached endpoint %s", cached["base_url"])return cached["base_url"]+ # Only a success is persisted, so a failing key (429/401 on every endpoint) would re-run the+ # four chat-completion probes on every credential-pool load — dozens of times per picker open.+ if _zai_probe_failed_until.get(key_hash, 0.0) > time.time():+ return default_url# Probe — may take up to ~8s per endpoint.detected = detect_zai_endpoint(api_key)if not (detected and detected.get("base_url")):logger.debug("Z.AI: probe failed, falling back to default %s", default_url)+ _zai_probe_failed_until[key_hash] = time.time() + _ZAI_PROBE_FAILURE_TTL_SECONDSreturn default_urldetected_endpoint = {diff --git a/hermes_cli/inventory.py b/hermes_cli/inventory.pyindex febe74f1ba0..80c338c1a7c 100644--- a/hermes_cli/inventory.py+++ b/hermes_cli/inventory.py@@ -190,9 +190,8 @@ def build_model_options_payload(offline saved endpoints don't block the picker; explicit refresh probes all and busts the cache.A normal open (``refresh=False``) is a READ path: provider catalogs come from the disk cache- only, stale/missing ones warm in the background, and rows still waiting carry ``catalog_pending``.- A degraded provider (hanging endpoint, failed auth probe) can therefore delay neither the other- providers' rows nor the response (#114215)."""+ only and stale/missing ones warm in the background, so a degraded provider (hanging endpoint,+ failed auth probe) delays neither the other providers' rows nor the response (#114215)."""refresh = bool(refresh)payload = build_models_payload(ctx, explicit_only=bool(explicit_only), include_unconfigured=bool(include_unconfigured),diff --git a/hermes_cli/model_switch_providers.py b/hermes_cli/model_switch_providers.pyindex cae355b524e..a039213542e 100644--- a/hermes_cli/model_switch_providers.py+++ b/hermes_cli/model_switch_providers.py@@ -208,21 +208,6 @@ def prewarm_picker_cache_async() -> Optional["_threading.Thread"]:return t-def _spawn_background_warm(target, *args, cache_key: str = "", **kwargs) -> None:- """Run a cache-warming probe in a daemon thread (fire-and-forget, exception-isolated).-- The GUI read path never waits on a probe; the warm thread makes the NEXT open cheap. Named by- ``cache_key`` so a stack dump says which catalog is being fetched."""- def _warm() -> None:- try:- target(*args, **kwargs)- except Exception:- logger.debug("background catalog warm failed (%s)", cache_key or target, exc_info=True)-- _threading.Thread(target=_warm, daemon=True,- name=f"catalog-warm-{cache_key or 'anon'}").start()--def _prefetch_provider_models_parallel(provider_slugs: list[str]) -> None:"""Fetch stale/missing provider catalogs in parallel before the serial picker loop.@@ -891,9 +876,9 @@ def _lap_overlay_rows(b: _PickerBuild, data: dict) -> None:continueif hermes_slug in {"openai-codex", "copilot", "copilot-acp"}:# Live OAuth-backed discovery so Pro-only Codex slugs not in the static catalog- # appear; falls back to curated when unreachable.- from hermes_cli.models import cached_provider_model_ids- model_ids = cached_provider_model_ids(hermes_slug, non_blocking=b.non_blocking_catalogs)+ # appear; falls back to curated when unreachable (or not yet cached on the read path).+ model_ids = _live_or_curated_ids(hermes_slug, b.curated, merge_models_dev=False,+ non_blocking=b.non_blocking_catalogs)elif overlay.auth_type == "aws_sdk":model_ids = _aws_live_or_curated_ids(hermes_slug, b.curated, hermes_slug, pid,non_blocking=b.non_blocking_catalogs)@@ -1123,12 +1108,8 @@ def _build_curated_lists(current_provider: str, current_base_url: str, current_mcurated["nous"] = get_curated_nous_model_ids()if "ollama-cloud" not in curated:from hermes_cli.models import fetch_ollama_cloud_models- if non_blocking:- curated["ollama-cloud"] = fetch_ollama_cloud_models(cache_only=True)- if not curated["ollama-cloud"]: # nothing cached: warm for the next open, return now- _spawn_background_warm(fetch_ollama_cloud_models, cache_key="ollama-cloud")- else:- curated["ollama-cloud"] = fetch_ollama_cloud_models()+ # Read path: cache only; the row's own SWR refresh (cached_provider_model_ids) warms it.+ curated["ollama-cloud"] = fetch_ollama_cloud_models(cache_only=non_blocking)# LM Studio has no static catalog: probe its native endpoint live. Base URL precedence:# LM_BASE_URL > active config base_url (when current) > default. On auth rejection /# unreachable, fall back to the current model so the picker still shows something offline.@@ -1169,9 +1150,8 @@ def list_authenticated_providers(``probe_custom_providers`` enables live ``/models`` discovery for saved custom endpoints (CLItrue, GUI false); ``probe_current_custom_provider`` probes only the selected custom endpoint.``non_blocking_catalogs`` is the GUI read path (``model.options``): provider catalogs come from- the disk cache only, stale/missing ones warm in the background, and rows still waiting on a- warm-up carry ``catalog_pending``. A degraded provider therefore never stalls the picker- (#114215)."""+ the disk cache only and stale/missing ones warm in the background, so a degraded provider+ never stalls the picker (#114215)."""from agent.models_dev import fetch_models_devfrom hermes_cli.config import coerce_provider_id, stringify_provider_map@@ -1231,28 +1211,9 @@ def list_authenticated_providers(if custom_providers and isinstance(custom_providers, list):_lap_custom_provider_rows(b, custom_providers)- if non_blocking_catalogs:- _mark_catalogs_pending(b.results)-return _finalize_picker_rows(b.results, user_providers, current_model)-def _mark_catalogs_pending(rows: list) -> None:- """Flag rows whose catalog is still being warmed in the background (``catalog_pending``), so a- GUI knows an empty/short row is a not-yet-resolved state rather than that provider's catalog."""- try:- from hermes_cli.models import normalize_provider, provider_catalogs_refreshing- refreshing = provider_catalogs_refreshing()- except Exception:- return- if not refreshing:- return- for row in rows:- slug = str(row.get("slug") or "").strip().lower()- if slug and (normalize_provider(slug) or slug) in refreshing:- row["catalog_pending"] = True--def _finalize_picker_rows(results: list, user_providers, current_model: str) -> list:"""Post-passes: drop ``providers.<name>.enabled: false`` rows, inject the current model, sort."""# The enabled post-filter covers built-in rows (sections 1-2) that bypass the per-sectiondiff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex ff410e1ffde..61ca444e6fa 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -1577,14 +1577,6 @@ def _spawn_swr_refresh(cache_key: str, refresh_fn=None) -> None:threading.Thread(target=lambda: ctx.run(_refresh), daemon=True, name=f"model-cache-swr-{cache_key}").start()-def provider_catalogs_refreshing() -> set[str]:- """Slugs with a background catalog refresh in flight, for read paths that must mark which rows- are still warming (``catalog_pending``). Unscoped keys only — a routed profile's inflight key is- a (home, slug) tuple and reports nothing rather than the wrong slug."""- with _swr_refresh_lock:- return {key for key in _swr_refresh_inflight if isinstance(key, str)}--def _provider_models_cache_path() -> Path:from hermes_constants import get_hermes_homereturn get_hermes_home() / "provider_models_cache.json"diff --git a/tests/hermes_cli/test_api_key_providers.py b/tests/hermes_cli/test_api_key_providers.pyindex eb227457c87..af3c741bafd 100644--- a/tests/hermes_cli/test_api_key_providers.py+++ b/tests/hermes_cli/test_api_key_providers.py@@ -741,6 +741,18 @@ class TestZaiEndpointAutoDetect:creds = resolve_api_key_provider_credentials("zai")assert creds["api_key"] == ""+ def test_failed_probe_is_not_repeated_within_ttl(self, monkeypatch):+ """A key whose detection fails (429 on every endpoint) is probed once, not on every+ credential resolution — the picker resolves Z.AI dozens of times per open (#114215)."""+ from hermes_cli import auth_zai_kimi+ monkeypatch.setenv("GLM_API_KEY", "glm-key-that-429s")+ monkeypatch.setattr(auth_zai_kimi, "_zai_probe_failed_until", {})+ calls = []+ monkeypatch.setattr("hermes_cli.auth.detect_zai_endpoint", lambda *a, **kw: calls.append(1))+ for _ in range(3):+ assert resolve_api_key_provider_credentials("zai")["base_url"] == "https://api.z.ai/api/paas/v4"+ assert len(calls) == 1+class TestZaiParallelProbe:"""detect_zai_endpoint probes endpoints in parallel workers.diff --git a/tests/hermes_cli/test_model_options_read_path_catalogs.py b/tests/hermes_cli/test_model_options_read_path_catalogs.pyindex 8841dc6f322..f3c417aad9c 100644--- a/tests/hermes_cli/test_model_options_read_path_catalogs.py+++ b/tests/hermes_cli/test_model_options_read_path_catalogs.py@@ -3,8 +3,8 @@A normal open (``refresh=False``) used to run live ``/v1/models`` fetches inline — a cold cacheserialized every authed provider and one degraded provider (hanging endpoint, failed auth probe)held the whole picker for as long as its probe took (#114215). The open now serves cached/curated-rows, marks the ones still warming (``catalog_pending``) and refreshes them off-thread; only an-explicit refresh (``refresh=True``, the "Refresh Models" action) is allowed to block on probes.+rows and refreshes them off-thread; only an explicit refresh (``refresh=True``, the "Refresh+Models" action) is allowed to block on probes."""import threading@@ -20,16 +20,15 @@ def _picker_env(monkeypatch, tmp_path, *, hung=None):"""One authed provider visible to the picker, no real network, isolated model-id cache.``hung`` is a slug whose probe blocks on the returned event — a stand-in for a degraded- provider. Returns ``(live_calls, release_event)``; ``live_calls`` records- ``(provider, thread_name)`` for every live probe.+ provider. Returns ``(live_calls, release_event)``; ``live_calls`` records every live probe."""monkeypatch.setenv("HERMES_HOME", str(tmp_path))monkeypatch.setenv("DEEPSEEK_API_KEY", "test-key")release = threading.Event()- live_calls: list[tuple[str, str]] = []+ live_calls: list[str] = []def fake_provider_model_ids(provider, *, force_refresh=False):- live_calls.append((provider, threading.current_thread().name))+ live_calls.append(provider)if provider == hung:release.wait(30)return ["live-model"]@@ -46,12 +45,8 @@ def _picker_env(monkeypatch, tmp_path, *, hung=None):def _drain_background_warms(timeout=10.0) -> None:"""Let spawned catalog warms finish so a tmp HERMES_HOME can be torn down with no writers left."""- refreshing = getattr(models_mod, "provider_catalogs_refreshing", None)- if refreshing is None: # pre-fix builds have no inflight registry to consult- time.sleep(0.3)- returndeadline = time.time() + timeout- while time.time() < deadline and refreshing():+ while time.time() < deadline and models_mod._swr_refresh_inflight:time.sleep(0.02)@@ -59,26 +54,11 @@ def _row(payload, slug):return next((row for row in payload["providers"] if row["slug"] == slug), None)-def test_normal_open_never_probes_in_the_calling_thread(monkeypatch, tmp_path):- """The open returns without running one live catalog fetch on the caller: rows come from the- disk cache / curated list and rows still warming say so."""- live_calls, _ = _picker_env(monkeypatch, tmp_path)-- payload = build_model_options_payload(load_picker_context())-- caller_thread = threading.current_thread().name- assert [call for call in live_calls if call[1] == caller_thread] == []- row = _row(payload, _DEAD_PROVIDER)- assert row is not None, "the provider must still be offered from its cached/curated list"- assert "live-model" not in row["models"]- _drain_background_warms()--def test_degraded_provider_cannot_stall_the_open(monkeypatch, tmp_path):"""One provider whose probe hangs must not hold the picker: the payload comes back while the- probe is still in flight. (Pre-fix this assertion only ever ran after the probe returned.)"""+ probe is still in flight, the row still renders from its curated list, and the probe runs+ off the read path. (Pre-fix this assertion only ever ran after the probe returned.)"""live_calls, release = _picker_env(monkeypatch, tmp_path, hung=_DEAD_PROVIDER)-box: dict = {}def _open():@@ -94,10 +74,9 @@ def test_degraded_provider_cannot_stall_the_open(monkeypatch, tmp_path):assert returned_while_hung, "the open waited on a degraded provider's catalog probe"row = _row(box["payload"], _DEAD_PROVIDER)- assert isinstance(row, dict), "the degraded row must still render"- assert row.get("catalog_pending") is True, "a row whose catalog is still warming must say so"- assert live_calls, "the degraded provider is still probed — off the read path"- _drain_background_warms()+ assert row is not None and row["models"], "the degraded row must still render from curated"+ assert "live-model" not in row["models"]+ assert _DEAD_PROVIDER in live_calls, "the degraded provider is still probed — off the read path"def test_explicit_refresh_still_probes_providers(monkeypatch, tmp_path):@@ -106,55 +85,6 @@ def test_explicit_refresh_still_probes_providers(monkeypatch, tmp_path):payload = build_model_options_payload(load_picker_context(), refresh=True)- assert live_calls, "an explicit refresh must still probe provider catalogs"- row = _row(payload, _DEAD_PROVIDER)- assert row is not None- assert "live-model" in row["models"]- assert not row.get("catalog_pending")+ assert _DEAD_PROVIDER in live_calls, "an explicit refresh must still probe provider catalogs"+ assert "live-model" in _row(payload, _DEAD_PROVIDER)["models"]_drain_background_warms()---def test_non_blocking_cache_read_serves_stale_entry_and_warms(monkeypatch, tmp_path):- """Beyond the stale-serve window a non-blocking read still returns the cached row (rather than- blocking on a probe) and kicks off the off-thread refresh."""- monkeypatch.setenv("HERMES_HOME", str(tmp_path))- started = threading.Event()- release = threading.Event()-- def fake_provider_model_ids(provider, *, force_refresh=False):- started.set()- release.wait(15)- return ["live-model"]-- monkeypatch.setattr(models_mod, "provider_model_ids", fake_provider_model_ids)- models_mod._store_cache_entry(- _DEAD_PROVIDER,- {"fp": models_mod._credential_fingerprint(_DEAD_PROVIDER),- "at": time.time() - (models_mod._PROVIDER_MODELS_STALE_SERVE_MAX + 60),- "models": ["cached-model"]},- )-- try:- served = models_mod.cached_provider_model_ids(_DEAD_PROVIDER, non_blocking=True)- assert served == ["cached-model"]- assert started.wait(10), "the stale row must be refreshed off-thread"- finally:- release.set()- _drain_background_warms()---def test_warm_cache_open_is_served_from_disk_without_probing(monkeypatch, tmp_path):- """A fresh cache entry means the next open runs no probe at all and marks nothing pending.-- ``_credential_fingerprint`` is pinned: any write to ``auth.json`` during a build (credential-pool- seeding) legitimately changes it, which would make this test race its own background warms."""- live_calls, _ = _picker_env(monkeypatch, tmp_path)- monkeypatch.setattr(models_mod, "_credential_fingerprint", lambda provider: "pinned")- build_model_options_payload(load_picker_context())- _drain_background_warms() # first open warmed the disk cache- live_calls.clear()-- payload = build_model_options_payload(load_picker_context())-- assert live_calls == []- assert not _row(payload, _DEAD_PROVIDER).get("catalog_pending")diff --git a/tests/hermes_cli/test_opencode_zen_model_limit.py b/tests/hermes_cli/test_opencode_zen_model_limit.pyindex d766b04a160..8f0bdad39e9 100644--- a/tests/hermes_cli/test_opencode_zen_model_limit.py+++ b/tests/hermes_cli/test_opencode_zen_model_limit.py@@ -26,7 +26,7 @@ def test_opencode_zen_lists_all_models_while_other_providers_remain_capped(monkemonkeypatch.setattr(providers_mod, "HERMES_OVERLAYS", {})monkeypatch.setattr("hermes_cli.models.cached_provider_model_ids",- lambda provider: {+ lambda provider, **_: {"opencode-zen": zen_models,"deepseek": deepseek_models,}.get(provider, []),diff --git a/tui_gateway/contracts/config_free_tier_control.py b/tui_gateway/contracts/config_free_tier_control.pyindex 1a7c2cef085..afe5a22cb65 100644--- a/tui_gateway/contracts/config_free_tier_control.py+++ b/tui_gateway/contracts/config_free_tier_control.py@@ -269,8 +269,6 @@ class ModelOptionProvider(OpenModel):free_tier_pending: bool | None = Nonefree_tier_row: bool | None = Noneunavailable_models: list[str] | None = None- # Set on a normal picker open while this row's catalog is still warming in the background.- catalog_pending: bool | None = Noneclass ModelOptionsResult(Result):diff --git a/website/docs/reference/model-catalog.md b/website/docs/reference/model-catalog.mdindex 740404a5a17..e0b98a3ed70 100644--- a/website/docs/reference/model-catalog.md+++ b/website/docs/reference/model-catalog.md@@ -67,6 +67,10 @@ Field notes:Cache location: `~/.hermes/cache/model_catalog.json`.+### Per-provider model lists in the GUI picker++The Desktop, TUI and dashboard pickers (`model.options`) build each provider's row from the disk-cached live catalog (`~/.hermes/provider_models_cache.json`) or, when nothing is cached yet, the curated list. Opening the picker never waits on a provider's `/v1/models` probe or on an auth probe: stale or missing catalogs are refreshed in a background thread and land on the next open, so one slow, rate-limited or unreachable provider cannot hold the whole picker on its loading state. **Refresh models** (or `/model --refresh`) is the explicit action that busts the cache and probes every provider live.+## Config```yaml