The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): keep first model picker open responsive on cold pricing cache
fangliquanflq401ac7e1f8da
diff --git a/hermes_cli/inventory.py b/hermes_cli/inventory.pyindex f9b0de4d90c..03964dbc20e 100644--- a/hermes_cli/inventory.py+++ b/hermes_cli/inventory.py@@ -33,10 +33,16 @@ Substrate facts (verified May 2026):from __future__ import annotations+from contextvars import copy_contextfrom dataclasses import dataclass, replace+from threading import Lock, Thread, current_threadfrom typing import Any, Optional+_pricing_prewarm_lock = Lock()+_pricing_prewarm_threads: dict[tuple[str, tuple[tuple[str, str], ...]], Thread] = {}++# ─── Public types ───────────────────────────────────────────────────────@@ -125,6 +131,7 @@ def build_models_payload(picker_hints: bool = False,canonical_order: bool = False,pricing: bool = False,+ pricing_cache_only: bool = False,capabilities: bool = False,featured: bool = False,force_fresh_nous_tier: bool = False,@@ -155,6 +162,9 @@ def build_models_payload(show $/Mtok columns and gate paid models on free accounts —mirroring the ``hermes model`` CLI picker. Adds network calls(pricing fetch + Nous tier check); only set for interactive pickers.+ - ``pricing_cache_only``: when pricing is enabled, use only values already+ resident in process caches. Normal picker opens use this while a+ background worker warms cold pricing endpoints.- ``capabilities``: add a per-row ``capabilities`` map``{model: {fast, reasoning}}`` so pickers can gate the model-optionscontrols (fast toggle / reasoning) to what each model actually@@ -304,7 +314,11 @@ def build_models_payload(if canonical_order:rows = _reorder_canonical(rows)if pricing:- _apply_pricing(rows, force_fresh_nous_tier=force_fresh_nous_tier)+ _apply_pricing(+ rows,+ force_fresh_nous_tier=force_fresh_nous_tier,+ cached_only=pricing_cache_only,+ )if capabilities:_apply_capabilities(rows)if featured:@@ -336,19 +350,27 @@ def build_model_options_payload(cache so live catalogs repopulate fully"""refresh = bool(refresh)- return build_models_payload(+ payload = build_models_payload(ctx,explicit_only=bool(explicit_only),include_unconfigured=bool(include_unconfigured),picker_hints=True,canonical_order=True,pricing=True,+ pricing_cache_only=not refresh,capabilities=True,featured=True,refresh=refresh,probe_custom_providers=refresh,probe_current_custom_provider=not refresh,)+ if not refresh:+ _prewarm_pricing_async(+ payload["providers"],+ current_provider=ctx.current_provider,+ current_base_url=ctx.current_base_url,+ )+ return payload# ─── Public: auxiliary-task pickers ─────────────────────────────────────@@ -944,6 +966,7 @@ def _apply_pricing(rows: list[dict],*,force_fresh_nous_tier: bool = False,+ cached_only: bool = False,) -> None:"""Enrich each provider row with per-model pricing + Nous tier gating.@@ -966,6 +989,7 @@ def _apply_pricing(_format_price_per_mtok,check_nous_free_tier,compute_sale_discount,+ get_cached_nous_free_tier,get_pricing_for_provider,partition_nous_models_by_tier,)@@ -979,10 +1003,28 @@ def _apply_pricing(if not models:continuetry:- raw_pricing = get_pricing_for_provider(slug) or {}+ pricing_kwargs = {"cached_only": True} if cached_only else {}+ raw_pricing = get_pricing_for_provider(slug, **pricing_kwargs) or {}except Exception:raw_pricing = {}+ cached_nous_tier: Optional[bool] = None+ if slug == "nous" and cached_only:+ cached_nous_tier = get_cached_nous_free_tier()+ if cached_nous_tier is None:+ # Entitlement is not yet known. Keep the response nonblocking,+ # but fail closed until this profile's prewarm has populated+ # both caches; otherwise a free account can briefly select+ # paid models on its first picker open.+ row["free_tier_pending"] = True+ row["unavailable_models"] = list(models)+ continueif not raw_pricing:+ if slug == "nous":+ row["free_tier"] = bool(cached_nous_tier)+ row["pricing_pending"] = True+ row["unavailable_models"] = (+ list(models) if cached_nous_tier else []+ )continueformatted: dict[str, dict] = {}@@ -1032,9 +1074,12 @@ def _apply_pricing(if slug == "nous":try:if nous_free_tier is None:- nous_free_tier = check_nous_free_tier(- force_fresh=force_fresh_nous_tier- )+ if cached_only:+ nous_free_tier = cached_nous_tier+ else:+ nous_free_tier = check_nous_free_tier(+ force_fresh=force_fresh_nous_tier+ )row["free_tier"] = bool(nous_free_tier)if nous_free_tier:_selectable, unavailable = partition_nous_models_by_tier(@@ -1100,6 +1145,68 @@ def _local_runtime_row(ctx: "ConfigContext") -> dict | None:return None+def _prewarm_pricing_async(+ rows: list[dict],+ *,+ current_provider: str = "",+ current_base_url: str = "",+) -> Optional[Thread]:+ """Warm picker pricing caches without delaying the current payload."""+ from hermes_constants import hermes_home_key+ from hermes_cli.models import pricing_cache_scope++ profile_key = hermes_home_key()+ endpoint_scope = tuple(+ sorted(+ (+ slug,+ pricing_cache_scope(+ slug,+ current_provider=current_provider,+ current_base_url=current_base_url,+ ),+ )+ for slug in {+ str(row.get("slug") or "").lower()+ for row in rows+ if row.get("slug")+ }+ )+ )+ prewarm_key = (profile_key, endpoint_scope)++ with _pricing_prewarm_lock:+ current = _pricing_prewarm_threads.get(prewarm_key)+ if current is not None and current.is_alive():+ return current++ # The worker mutates only private copies while the pricing helpers+ # populate their shared process caches.+ worker_rows = [+ {**row, "models": list(row.get("models") or [])}+ for row in rows+ ]++ def _worker() -> None:+ try:+ _apply_pricing(worker_rows)+ finally:+ with _pricing_prewarm_lock:+ if _pricing_prewarm_threads.get(prewarm_key) is current_thread():+ _pricing_prewarm_threads.pop(prewarm_key, None)++ worker_context = copy_context()+ thread = Thread(+ target=worker_context.run,+ args=(_worker,),+ name="hermes-picker-pricing-prewarm",+ daemon=True,+ )+ _pricing_prewarm_threads[prewarm_key] = thread+ thread.start()+ return thread++def _moa_provider_row(current_provider: str = "") -> dict | None:"""Build the virtual ``moa`` provider row for model pickers.diff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex 6d1a88e6aa0..14799782cc6 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -1031,35 +1031,61 @@ def union_with_portal_paid_recommendations(# session while still picking up upgrades quickly.# ---------------------------------------------------------------------------_FREE_TIER_CACHE_TTL: int = 180 # seconds (3 minutes)-_free_tier_cache: tuple[bool, float] | None = None # (result, timestamp)+_free_tier_cache: dict[str, tuple[bool, float]] = {}-def check_nous_free_tier(*, force_fresh: bool = False) -> bool:+def _pricing_profile_key() -> str:+ """Return the stable profile identity for process-local pricing caches."""+ from hermes_constants import hermes_home_key++ return hermes_home_key()+++def get_cached_nous_free_tier() -> Optional[bool]:+ """Return this profile's live cached entitlement, or ``None`` if unknown."""+ cached = _free_tier_cache.get(_pricing_profile_key())+ if cached is None:+ return None+ result, cached_at = cached+ if time.monotonic() - cached_at >= _FREE_TIER_CACHE_TTL:+ return None+ return result+++def check_nous_free_tier(+ *, force_fresh: bool = False, cached_only: bool = False+) -> bool:"""Check if the current Nous Portal user is on a free (unpaid) tier.Results are cached for ``_FREE_TIER_CACHE_TTL`` seconds to avoidhitting the Portal API on every call. The cache is short-lived sothat an account upgrade is reflected within a few minutes.+ ``cached_only`` returns a live cached answer or the fail-open ``False``+ default without contacting Portal.+Returns True only when entitlement is known to be free. Unknown/errorstates return False so this compatibility wrapper does not block users."""- global _free_tier_cachenow = time.monotonic()- if not force_fresh and _free_tier_cache is not None:- cached_result, cached_at = _free_tier_cache- if now - cached_at < _FREE_TIER_CACHE_TTL:+ profile_key = _pricing_profile_key()+ if not force_fresh:+ cached_result = get_cached_nous_free_tier()+ if cached_result is not None:return cached_result+ if cached_only:+ return False+try:from hermes_cli.nous_account import get_nous_portal_account_infoaccount_info = get_nous_portal_account_info(force_fresh=force_fresh)result = account_info.is_free_tier- _free_tier_cache = (result, now)+ _free_tier_cache[profile_key] = (result, now)return resultexcept Exception:- _free_tier_cache = (False, now)+ _free_tier_cache[profile_key] = (False, now)return False # default to paid on error — don't block users@@ -2321,6 +2347,7 @@ def ai_gateway_model_ids(*, force_refresh: bool = False) -> list[str]:# Cache: maps model_id → {"prompt": str, "completion": str} per endpoint_pricing_cache: dict[str, dict[str, dict[str, str]]] = {}+_pricing_provider_cache_keys: dict[tuple[str, str], str] = {}# A failed fetch caches its empty result too, so an unreachable endpoint isn't# re-dialed on every call — but only until this deadline. Cached forever, one@@ -2807,26 +2834,145 @@ def restrict_to_nous_policy(return kept-def get_pricing_for_provider(provider: str, *, force_refresh: bool = False) -> dict[str, dict[str, str]]:- """Return live pricing for providers that support it (openrouter, nous, ai-gateway, novita)."""+def get_cached_nous_inference_base_url() -> str:+ """Return the profile's persisted Nous endpoint without refreshing auth."""+ try:+ from hermes_cli.auth import (+ _load_auth_store,+ _load_provider_state,+ _optional_base_url,+ _validate_nous_inference_url_from_network,+ )++ state = _load_provider_state(_load_auth_store(), "nous") or {}+ return (+ _validate_nous_inference_url_from_network(+ _optional_base_url(state.get("inference_base_url"))+ )+ or ""+ ).rstrip("/").removesuffix("/v1")+ except Exception:+ return ""+++def pricing_cache_scope(+ provider: str,+ *,+ current_provider: str = "",+ current_base_url: str = "",+) -> str:+ """Return the current endpoint identity used by a provider's pricing cache.++ This only resolves local configuration; it never fetches a catalog. Picker+ prewarm single-flight uses the result to let an endpoint rotation start a+ new worker while the previous endpoint is still slow or unreachable.+ """normalized = normalize_provider(provider)if normalized == "openrouter":+ return "https://openrouter.ai/api"+ if normalized == "ai-gateway":+ from hermes_constants import AI_GATEWAY_BASE_URL++ return AI_GATEWAY_BASE_URL.rstrip("/")+ if normalized == "novita":+ return (+ os.getenv("NOVITA_BASE_URL", "").strip()+ or "https://api.novita.ai/openai/v1"+ ).rstrip("/")+ if normalized == "deepinfra":+ cache_key, _url = _deepinfra_catalog_url()+ return cache_key+ if normalized == "fireworks":+ return "models.dev/fireworks"+ if normalized == "nous":+ try:+ from hermes_cli.auth import _nous_inference_env_override++ env_base = _nous_inference_env_override()+ except Exception:+ env_base = None+ if env_base:+ return env_base.rstrip("/").removesuffix("/v1")+ if normalize_provider(current_provider) == "nous" and current_base_url:+ return current_base_url.rstrip("/").removesuffix("/v1")+ persisted_base = get_cached_nous_inference_base_url()+ if persisted_base:+ return persisted_base+ return _pricing_provider_cache_keys.get(+ (_pricing_profile_key(), normalized), _DEFAULT_NOUS_INFERENCE_BASE+ )+ return ""+++def get_pricing_for_provider(+ provider: str,+ *,+ force_refresh: bool = False,+ cached_only: bool = False,+) -> dict[str, dict[str, str]]:+ """Return pricing for providers that publish it.++ ``cached_only`` never starts provider I/O. Normal picker opens use it so+ cold endpoints cannot hold the response path; a background prewarm fills+ the same caches for later opens.+ """+ normalized = normalize_provider(provider)+ if cached_only:+ if normalized == "deepinfra":+ cache_key, _url = _deepinfra_catalog_url()+ if cache_key not in _deepinfra_catalog_cache:+ return {}+ return _fetch_deepinfra_pricing()++ cache_key = _pricing_provider_cache_keys.get(+ (_pricing_profile_key(), normalized)+ )+ if cache_key is None:+ if normalized == "openrouter":+ cache_key = "https://openrouter.ai/api"+ elif normalized == "ai-gateway":+ from hermes_constants import AI_GATEWAY_BASE_URL++ cache_key = AI_GATEWAY_BASE_URL.rstrip("/")+ elif normalized == "fireworks":+ cache_key = "models.dev/fireworks"+ return (_cached_catalog(cache_key) or {}) if cache_key else {}++ if normalized == "openrouter":+ _pricing_provider_cache_keys[+ (_pricing_profile_key(), normalized)+ ] = "https://openrouter.ai/api"return fetch_models_with_pricing(api_key=_resolve_openrouter_api_key(),base_url="https://openrouter.ai/api",force_refresh=force_refresh,)if normalized == "ai-gateway":+ from hermes_constants import AI_GATEWAY_BASE_URL++ _pricing_provider_cache_keys[+ (_pricing_profile_key(), normalized)+ ] = AI_GATEWAY_BASE_URL.rstrip("/")return fetch_ai_gateway_pricing(force_refresh=force_refresh)if normalized == "novita":+ base_url = os.getenv("NOVITA_BASE_URL", "").strip() or "https://api.novita.ai/openai/v1"+ _pricing_provider_cache_keys[+ (_pricing_profile_key(), normalized)+ ] = base_url.rstrip("/")return _fetch_novita_pricing(force_refresh=force_refresh)if normalized == "deepinfra":return _fetch_deepinfra_pricing(force_refresh=force_refresh)if normalized == "fireworks":+ _pricing_provider_cache_keys[+ (_pricing_profile_key(), normalized)+ ] = "models.dev/fireworks"return _fireworks_pricing_from_models_dev(force_refresh=force_refresh)if normalized == "nous":api_key, base_url = _resolve_nous_pricing_credentials()if base_url:+ _pricing_provider_cache_keys[+ (_pricing_profile_key(), normalized)+ ] = base_url.rstrip("/")return fetch_models_with_pricing(api_key=api_key,base_url=base_url,diff --git a/tests/hermes_cli/test_inventory_pricing.py b/tests/hermes_cli/test_inventory_pricing.pyindex 5fb7c39490d..0309ff82851 100644--- a/tests/hermes_cli/test_inventory_pricing.py+++ b/tests/hermes_cli/test_inventory_pricing.py@@ -5,6 +5,9 @@ columns + Free/Pro badges and gate paid models on free Nous accounts, thesame way the `hermes model` CLI picker does."""+from threading import Event+from time import monotonic+import hermes_cli.inventory as invimport hermes_cli.models as models_mod@@ -101,3 +104,382 @@ def test_apply_pricing_omits_sale_when_original_not_cheaper(monkeypatch):assert "discount_percent" not in rows[0]["pricing"]["a/eq"]+def test_model_options_cold_pricing_fetch_runs_off_the_request_path(monkeypatch):+ """A cold pricing endpoint must not delay the first picker payload."""+ fetch_started = Event()+ release_fetch = Event()++ def fake_pricing(_slug, *, force_refresh=False, cached_only=False):+ if cached_only:+ return {}+ fetch_started.set()+ release_fetch.wait(timeout=5)+ return {}++ row = {+ "slug": "openrouter",+ "name": "OpenRouter",+ "models": ["vendor/model"],+ "total_models": 1,+ "is_current": True,+ "is_user_defined": False,+ "source": "built-in",+ }+ monkeypatch.setattr(models_mod, "get_pricing_for_provider", fake_pricing)+ monkeypatch.setattr(+ "hermes_cli.model_switch.list_authenticated_providers",+ lambda **_kwargs: [row],+ )+ monkeypatch.setattr(inv, "_moa_provider_row", lambda *_args, **_kwargs: None)+ monkeypatch.setattr(inv, "_apply_capabilities", lambda _rows: None)+ monkeypatch.setattr(inv, "_apply_featured", lambda _rows: None)+ monkeypatch.setattr(inv, "_pricing_prewarm_threads", {})++ try:+ started_at = monotonic()+ payload = inv.build_model_options_payload(+ inv.ConfigContext(+ current_provider="openrouter",+ current_model="vendor/model",+ current_base_url="",+ user_providers={},+ custom_providers=[],+ )+ )+ elapsed = monotonic() - started_at+ assert payload["providers"][0]["slug"] == "openrouter"+ assert "pricing" not in payload["providers"][0]+ assert elapsed < 2.0, f"cold picker blocked for {elapsed:.2f}s"+ assert fetch_started.wait(timeout=1), "pricing should prewarm in the background"+ finally:+ threads = list(inv._pricing_prewarm_threads.values())+ release_fetch.set()+ for thread in threads:+ thread.join(timeout=2)+++def test_cold_nous_entitlement_keeps_models_unselectable(monkeypatch):+ """A cold nonblocking response must not expose paid models fail-open."""+ monkeypatch.setattr(+ models_mod, "get_pricing_for_provider", lambda *_args, **_kwargs: {}+ )+ monkeypatch.setattr(models_mod, "get_cached_nous_free_tier", lambda: None)+ rows = [{"slug": "nous", "models": ["free/model", "paid/model"]}]++ inv._apply_pricing(rows, cached_only=True)++ assert rows[0]["free_tier_pending"] is True+ assert rows[0]["unavailable_models"] == ["free/model", "paid/model"]+++def test_prewarm_preserves_context_and_runs_once_per_profile(tmp_path, monkeypatch):+ """Concurrent multiplex profiles retain their own home and secret scope."""+ from agent.secret_scope import (+ current_secret_scope,+ reset_secret_scope,+ set_secret_scope,+ )+ from hermes_constants import (+ hermes_home_key,+ reset_hermes_home_override,+ set_hermes_home_override,+ )++ monkeypatch.setattr(inv, "_pricing_prewarm_threads", {})+ release = Event()+ started = {"a": Event(), "b": Event()}+ observed = {}++ def capture_context(_rows):+ scope = current_secret_scope()+ label = scope["PROFILE_MARKER"]+ observed[label] = (hermes_home_key(), dict(scope))+ started[label].set()+ release.wait(timeout=5)++ monkeypatch.setattr(inv, "_apply_pricing", capture_context)++ threads = []+ try:+ for label in ("a", "b"):+ home = tmp_path / label+ home_token = set_hermes_home_override(str(home))+ secret_token = set_secret_scope({"PROFILE_MARKER": label})+ try:+ threads.append(inv._prewarm_pricing_async([{"models": []}]))+ finally:+ reset_secret_scope(secret_token)+ reset_hermes_home_override(home_token)++ assert threads[0] is not threads[1]+ assert started["a"].wait(timeout=1)+ assert started["b"].wait(timeout=1)+ assert observed["a"] == (+ hermes_home_key(tmp_path / "a"),+ {"PROFILE_MARKER": "a"},+ )+ assert observed["b"] == (+ hermes_home_key(tmp_path / "b"),+ {"PROFILE_MARKER": "b"},+ )+ finally:+ release.set()+ for thread in threads:+ if thread is not None:+ thread.join(timeout=2)+++def test_prewarm_deduplicates_inflight_scope_and_cleans_up(monkeypatch):+ """Rapid opens share one worker, then a completed scope can run again."""+ monkeypatch.setattr(inv, "_pricing_prewarm_threads", {})+ started = Event()+ release = Event()+ calls = []++ def blocked_prewarm(_rows):+ calls.append(None)+ started.set()+ release.wait(timeout=5)++ monkeypatch.setattr(inv, "_apply_pricing", blocked_prewarm)+ rows = [{"slug": "openrouter", "models": ["vendor/model"]}]++ first = inv._prewarm_pricing_async(rows)+ try:+ assert started.wait(timeout=1)+ second = inv._prewarm_pricing_async(rows)+ assert second is first+ assert len(calls) == 1+ finally:+ release.set()+ first.join(timeout=2)++ assert not first.is_alive()+ assert inv._pricing_prewarm_threads == {}++ retry = inv._prewarm_pricing_async(rows)+ retry.join(timeout=2)+ assert retry is not first+ assert len(calls) == 2+ assert inv._pricing_prewarm_threads == {}+++def test_prewarm_endpoint_rotation_starts_a_new_worker(tmp_path, monkeypatch):+ """A live endpoint-A worker must not suppress endpoint B for its profile."""+ from hermes_constants import (+ reset_hermes_home_override,+ set_hermes_home_override,+ )++ endpoint_a = "https://endpoint-a.example"+ endpoint_b = "https://endpoint-b.example"+ active_endpoint = {"value": endpoint_a}+ started = {endpoint_a: Event(), endpoint_b: Event()}+ release_a = Event()+ expected = {+ endpoint_a: {"a/model": {"prompt": "1", "completion": "2"}},+ endpoint_b: {"b/model": {"prompt": "3", "completion": "4"}},+ }+ monkeypatch.setattr(inv, "_pricing_prewarm_threads", {})+ monkeypatch.setattr(models_mod, "_pricing_cache", {})+ monkeypatch.setattr(models_mod, "_pricing_cache_retry_after", {})+ monkeypatch.setattr(models_mod, "_pricing_provider_cache_keys", {})+ monkeypatch.setattr(+ models_mod,+ "_resolve_nous_pricing_credentials",+ lambda: ("", active_endpoint["value"]),+ )++ def fetch_pricing(*, base_url, **_kwargs):+ started[base_url].set()+ if base_url == endpoint_a:+ release_a.wait(timeout=5)+ return models_mod._cache_catalog(base_url, expected[base_url])++ monkeypatch.setattr(models_mod, "fetch_models_with_pricing", fetch_pricing)+ monkeypatch.setattr(+ inv,+ "_apply_pricing",+ lambda _rows: models_mod.get_pricing_for_provider("nous"),+ )++ token = set_hermes_home_override(str(tmp_path / "profile"))+ threads = []+ try:+ threads.append(+ inv._prewarm_pricing_async(+ [{"slug": "nous", "models": ["a/model"]}],+ current_provider="nous",+ current_base_url=endpoint_a,+ )+ )+ assert started[endpoint_a].wait(timeout=1)++ active_endpoint["value"] = endpoint_b+ threads.append(+ inv._prewarm_pricing_async(+ [{"slug": "nous", "models": ["b/model"]}],+ current_provider="nous",+ current_base_url=endpoint_b,+ )+ )++ assert threads[0] is not threads[1]+ assert started[endpoint_b].wait(timeout=1)+ threads[1].join(timeout=2)+ assert not threads[1].is_alive()+ assert models_mod.get_pricing_for_provider(+ "nous", cached_only=True+ ) == expected[endpoint_b]+ finally:+ release_a.set()+ for thread in threads:+ if thread is not None:+ thread.join(timeout=2)+ reset_hermes_home_override(token)+++def test_prewarm_nous_rotation_when_another_provider_is_current(tmp_path, monkeypatch):+ """Nous endpoint identity must not depend on Nous being selected."""+ from hermes_constants import (+ reset_hermes_home_override,+ set_hermes_home_override,+ )++ endpoint_a = "https://endpoint-a.example"+ endpoint_b = "https://endpoint-b.example"+ active_endpoint = {"value": endpoint_a}+ started = {endpoint_a: Event(), endpoint_b: Event()}+ release_a = Event()+ expected = {+ endpoint_a: {"a/model": {"prompt": "1", "completion": "2"}},+ endpoint_b: {"b/model": {"prompt": "3", "completion": "4"}},+ }+ monkeypatch.setattr(inv, "_pricing_prewarm_threads", {})+ monkeypatch.setattr(models_mod, "_pricing_cache", {})+ monkeypatch.setattr(models_mod, "_pricing_cache_retry_after", {})+ monkeypatch.setattr(models_mod, "_pricing_provider_cache_keys", {})+ monkeypatch.setattr(+ models_mod,+ "get_cached_nous_inference_base_url",+ lambda: active_endpoint["value"],+ )+ monkeypatch.setattr(+ models_mod,+ "_resolve_nous_pricing_credentials",+ lambda: ("", active_endpoint["value"]),+ )++ def fetch_pricing(*, base_url, **_kwargs):+ started[base_url].set()+ if base_url == endpoint_a:+ release_a.wait(timeout=5)+ return models_mod._cache_catalog(base_url, expected[base_url])++ monkeypatch.setattr(models_mod, "fetch_models_with_pricing", fetch_pricing)+ monkeypatch.setattr(+ inv,+ "_apply_pricing",+ lambda _rows: models_mod.get_pricing_for_provider("nous"),+ )++ token = set_hermes_home_override(str(tmp_path / "profile"))+ threads = []+ try:+ threads.append(+ inv._prewarm_pricing_async(+ [{"slug": "nous", "models": ["a/model"]}],+ current_provider="openrouter",+ current_base_url="https://openrouter.ai/api/v1",+ )+ )+ assert started[endpoint_a].wait(timeout=1)++ active_endpoint["value"] = endpoint_b+ threads.append(+ inv._prewarm_pricing_async(+ [{"slug": "nous", "models": ["b/model"]}],+ current_provider="openrouter",+ current_base_url="https://openrouter.ai/api/v1",+ )+ )++ assert threads[0] is not threads[1]+ assert started[endpoint_b].wait(timeout=1)+ threads[1].join(timeout=2)+ assert not threads[1].is_alive()+ assert models_mod.get_pricing_for_provider(+ "nous", cached_only=True+ ) == expected[endpoint_b]+ finally:+ release_a.set()+ for thread in threads:+ if thread is not None:+ thread.join(timeout=2)+ reset_hermes_home_override(token)+++def test_cached_only_pricing_returns_a_warm_value_without_fetching(monkeypatch):+ """Cache-only picker reads preserve pricing once the prewarm completes."""+ cache_key = "https://openrouter.ai/api"+ expected = {"vendor/model": {"prompt": "0.000001", "completion": "0.000002"}}+ monkeypatch.setattr(models_mod, "_pricing_cache", {cache_key: expected})+ monkeypatch.setattr(models_mod, "_pricing_cache_retry_after", {})+ monkeypatch.setattr(models_mod, "_pricing_provider_cache_keys", {})+ monkeypatch.setattr(+ models_mod,+ "fetch_models_with_pricing",+ lambda **_kwargs: (_ for _ in ()).throw(AssertionError("network fetch started")),+ )++ assert models_mod.get_pricing_for_provider(+ "openrouter", cached_only=True+ ) == expected+++def test_cached_only_dynamic_pricing_is_profile_scoped(tmp_path, monkeypatch):+ """Alternating profiles read the endpoint each profile warmed."""+ from hermes_constants import (+ reset_hermes_home_override,+ set_hermes_home_override,+ )++ endpoint_a = "https://profile-a.example"+ endpoint_b = "https://profile-b.example"+ expected_a = {"a/model": {"prompt": "1", "completion": "2"}}+ expected_b = {"b/model": {"prompt": "3", "completion": "4"}}+ monkeypatch.setattr(+ models_mod,+ "_pricing_cache",+ {endpoint_a: expected_a, endpoint_b: expected_b},+ )+ monkeypatch.setattr(models_mod, "_pricing_cache_retry_after", {})+ monkeypatch.setattr(models_mod, "_pricing_provider_cache_keys", {})+ active_endpoint = {"value": endpoint_a}+ monkeypatch.setattr(+ models_mod,+ "_resolve_nous_pricing_credentials",+ lambda: ("", active_endpoint["value"]),+ )+ monkeypatch.setattr(+ models_mod,+ "fetch_models_with_pricing",+ lambda **kwargs: models_mod._pricing_cache[kwargs["base_url"]],+ )++ def in_profile(home, endpoint, *, cached_only):+ token = set_hermes_home_override(str(home))+ active_endpoint["value"] = endpoint+ try:+ return models_mod.get_pricing_for_provider(+ "nous", cached_only=cached_only+ )+ finally:+ reset_hermes_home_override(token)++ assert in_profile(tmp_path / "a", endpoint_a, cached_only=False) == expected_a+ assert in_profile(tmp_path / "b", endpoint_b, cached_only=False) == expected_b+ assert in_profile(tmp_path / "a", endpoint_b, cached_only=True) == expected_a+ assert in_profile(tmp_path / "b", endpoint_a, cached_only=True) == expected_b++diff --git a/tests/hermes_cli/test_models.py b/tests/hermes_cli/test_models.pyindex bba81a9eccd..855bc248a58 100644--- a/tests/hermes_cli/test_models.py+++ b/tests/hermes_cli/test_models.py@@ -299,10 +299,10 @@ class TestCheckNousFreeTierCache:"""Tests for the TTL cache on check_nous_free_tier()."""def setup_method(self):- _models_mod._free_tier_cache = None+ _models_mod._free_tier_cache.clear()def teardown_method(self):- _models_mod._free_tier_cache = None+ _models_mod._free_tier_cache.clear()@patch("hermes_cli.nous_account.get_nous_portal_account_info")def test_result_is_cached(self, mock_account):@@ -320,6 +320,42 @@ class TestCheckNousFreeTierCache:assert result2 is Trueassert mock_account.call_count == 1+ @patch("hermes_cli.nous_account.get_nous_portal_account_info")+ def test_cache_only_cold_lookup_does_not_call_portal(self, mock_account):+ assert check_nous_free_tier(cached_only=True) is False+ mock_account.assert_not_called()++ @patch("hermes_cli.nous_account.get_nous_portal_account_info")+ def test_entitlement_cache_is_profile_scoped(self, mock_account, tmp_path):+ from hermes_constants import (+ hermes_home_key,+ reset_hermes_home_override,+ set_hermes_home_override,+ )++ def account_for_active_profile(*, force_fresh=False):+ is_free = hermes_home_key() == hermes_home_key(tmp_path / "free")+ return NousPortalAccountInfo(+ logged_in=True,+ source="jwt",+ fresh=force_fresh,+ paid_service_access=not is_free,+ )++ mock_account.side_effect = account_for_active_profile++ def check_in(home):+ token = set_hermes_home_override(str(home))+ try:+ return check_nous_free_tier()+ finally:+ reset_hermes_home_override(token)++ assert check_in(tmp_path / "free") is True+ assert check_in(tmp_path / "paid") is False+ assert check_in(tmp_path / "free") is True+ assert mock_account.call_count == 2+@patch("hermes_cli.nous_account.get_nous_portal_account_info")def test_force_fresh_bypasses_cache(self, mock_account):