The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(credits): warm the pricing catalog before the session-open notice policy
Robin Fernandesa728c5545569
diff --git a/agent/credits_tracker.py b/agent/credits_tracker.pyindex 91f3114b7d8..705172ec4a8 100644--- a/agent/credits_tracker.py+++ b/agent/credits_tracker.py@@ -393,6 +393,19 @@ def _hydrate_seed_state(agent, state) -> None:emit()+def _warm_nous_pricing_cache() -> None:+ """Fill the in-process Nous pricing catalog so :func:`is_free_tier_model`'s peek can answer.+ The peek never fetches and nothing else warms it during session start, so a cold process reads+ an EMPTY catalog and a subscription-billed model — which spends no credits — still draws the+ depleted banner. Fail-open: a miss leaves the peek exactly as it was."""+ try:+ from hermes_cli.models_pricing import get_pricing_for_provider++ get_pricing_for_provider("nous")+ except Exception:+ logger.debug("credits ▸ nous pricing warm failed", exc_info=True)++def seed_credits_at_session_start(agent) -> bool:"""Hydrate agent._credits_state from the portal account (or a dev fixture) and fire the notice policy sowarnings show at session OPEN (TUI/desktop "ready" and plain-CLI first-turn setup). Idempotent once a seed@@ -411,9 +424,18 @@ def seed_credits_at_session_start(agent) -> bool:def _bg_seed() -> None: # FIRE-AND-FORGET: a slow portal must never delay "ready"try:from hermes_cli.nous_account import get_nous_portal_account_info+ # BEFORE the policy runs (either branch below): the free-model gate only PEEKS the+ # pricing cache, and this thread is the first thing a chat session runs that can+ # afford to fill it.+ _warm_nous_pricing_cache()info = get_nous_portal_account_info(force_fresh=True)if getattr(agent, "_credits_state", None) is not None:- return # a live inference header beat us — don't clobber it+ # A live inference header beat us — don't clobber it, but DO re-run the policy:+ # it evaluated against the cold cache and may be showing a banner the warm+ # catalog now suppresses.+ if callable(emit := getattr(agent, "_emit_credits_notices", None)):+ emit()+ returnif (state := _credits_state_from_account(info)) is not None:_hydrate_seed_state(agent, state)except Exception:diff --git a/tests/agent/test_credits_cold_start.py b/tests/agent/test_credits_cold_start.pyindex 9d7e2c3cc4f..74c2ce87e91 100644--- a/tests/agent/test_credits_cold_start.py+++ b/tests/agent/test_credits_cold_start.py@@ -78,11 +78,12 @@ class _FakeAgent:the real policy against the latch (mirroring run_agent._emit_credits_notices,including the free-model suppression flag)."""- def __init__(self, provider="nous", model=""):+ def __init__(self, provider="nous", model="", base_url=""):from agent.credits_tracker import evaluate_credits_notices, is_free_tier_modelself.provider = providerself.model = model+ self.base_url = base_urlself._credits_state = Noneself._credits_session_start_micros = Noneself._credits_latch = {"active": set(), "seen_below_90": False, "usage_band": None}@@ -96,7 +97,7 @@ class _FakeAgent:show, clear = self._eval(self._credits_state,self._credits_latch,- model_is_free=self._is_free(self.model),+ model_is_free=self._is_free(self.model, self.base_url),)self.emitted.append(([n.key for n in show], clear))@@ -157,3 +158,99 @@ def test_seed_skips_non_nous():a = _FakeAgent(provider="openrouter")assert seed_credits_at_session_start(a) is Falseassert a._credits_state is None+++# ── background seed: the pricing warm the free-model gate depends on ─────────++_NOUS_BASE = "https://inference-api.nousresearch.com/v1"+# One subscription-billed row, keyed on the pre-/v1 root the picker caches under.+_SUBSCRIPTION_CATALOG = {+ "https://inference-api.nousresearch.com": {+ "openai/gpt-5.6-luna": {+ "prompt": "0.0000002000", "completion": "0.0000012000", "billing_mode": "subscription",+ },+ }+}+++class _DepletedAccount:+ """The /api/oauth/account shape _credits_state_from_account reads: access off, no money."""++ class _Info:+ total_usable_credits = 0.0+ subscription_credits_remaining = 0.0+ purchased_credits_remaining = 0.0++ paid_service_access = False+ paid_service_access_info = _Info()+ subscription = None+++def _cold_pricing_cache(monkeypatch):+ """Empty the process-wide pricing cache (and its expiry map) so the peek starts cold."""+ from hermes_cli import models_pricing++ monkeypatch.setattr(models_pricing, "_pricing_cache", {})+ monkeypatch.setattr(models_pricing, "_pricing_cache_retry_after", {})+ return models_pricing+++def _run_bg_seed(monkeypatch, agent, *, warm):+ """Drive the seed down its BACKGROUND branch (no dev fixture) and join the thread. *warm* stands+ in for the real pricing fetch, so a test controls what the catalog holds and when."""+ import threading++ import hermes_cli.nous_account as nous_account+ from agent import credits_tracker++ monkeypatch.delenv("HERMES_DEV_CREDITS", raising=False) # fixtures would take the sync path+ monkeypatch.setattr(credits_tracker, "_warm_nous_pricing_cache", warm)+ monkeypatch.setattr(nous_account, "get_nous_portal_account_info", lambda *a, **kw: _DepletedAccount())+ existing = set(threading.enumerate())+ result = credits_tracker.seed_credits_at_session_start(agent)+ for thread in set(threading.enumerate()) - existing:+ if thread.name == "credits-seed":+ thread.join(timeout=10)+ assert not thread.is_alive(), "seed thread hung"+ return result+++def test_bg_seed_warms_pricing_so_a_subscription_model_escapes_the_banner(monkeypatch):+ """The regression: a cold process peeks an EMPTY catalog, so a subscription-billed model — which+ spends no credits — drew the depleted banner at session open. The seed fills the catalog first."""+ models_pricing = _cold_pricing_cache(monkeypatch)+ agent = _FakeAgent(model="openai/gpt-5.6-luna", base_url=_NOUS_BASE)++ assert _run_bg_seed(+ monkeypatch, agent, warm=lambda: models_pricing._pricing_cache.update(_SUBSCRIPTION_CATALOG)+ ) is True+ assert agent._credits_state.depleted is True # the account really is out of credits...+ assert agent.emitted == [([], [])] # ...and the session says nothing about it+++def test_bg_seed_without_the_warm_still_warns(monkeypatch):+ """Guard rail for the test above: the same account and model DO warn while the catalog stays+ cold, so the suppression is the warm's doing and not the model id's."""+ _cold_pricing_cache(monkeypatch)+ agent = _FakeAgent(model="openai/gpt-5.6-luna", base_url=_NOUS_BASE)++ _run_bg_seed(monkeypatch, agent, warm=lambda: None)+ assert agent.emitted == [(["credits.depleted"], [])]+++def test_bg_seed_reruns_the_policy_when_a_header_beat_it(monkeypatch):+ """A live inference header can land while the warm is still in flight; it evaluates against the+ cold catalog and shows the banner. The seed must keep that state but re-run the policy."""+ models_pricing = _cold_pricing_cache(monkeypatch)+ agent = _FakeAgent(model="openai/gpt-5.6-luna", base_url=_NOUS_BASE)+ header_state = _state(paid_access=False)++ def _warm():+ agent._credits_state = header_state # the header lands mid-fetch...+ agent._emit_credits_notices() # ...and evaluates against the cold catalog+ models_pricing._pricing_cache.update(_SUBSCRIPTION_CATALOG)++ _run_bg_seed(monkeypatch, agent, warm=_warm)+ assert agent._credits_state is header_state # the seed never clobbers a live header+ assert agent.emitted[0] == (["credits.depleted"], []) # cold: shown+ assert agent.emitted[-1] == ([], ["credits.depleted"]) # warm re-run: cleared, no "restored"