The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(agent/models): table-driven credits header parsing, unified account-usage fetchers
Teknium771045655bf4
diff --git a/agent/account_usage.py b/agent/account_usage.pyindex b7abb180176..a3ba6e52f7b 100644--- a/agent/account_usage.py+++ b/agent/account_usage.py@@ -4,7 +4,7 @@ import loggingimport mathfrom dataclasses import dataclassfrom datetime import datetime, timezone-from typing import TYPE_CHECKING, Any, Optional+from typing import TYPE_CHECKING, Any, Callable, Optionalimport httpx@@ -48,9 +48,7 @@ class AccountUsageSnapshot:def _title_case_slug(value: Optional[str]) -> Optional[str]:cleaned = str(value or "").strip()- if not cleaned:- return None- return cleaned.replace("_", " ").replace("-", " ").title()+ return cleaned.replace("_", " ").replace("-", " ").title() if cleaned else Nonedef _parse_dt(value: Any) -> Optional[datetime]:@@ -58,49 +56,39 @@ def _parse_dt(value: Any) -> Optional[datetime]:return Noneif isinstance(value, (int, float)):return datetime.fromtimestamp(float(value), tz=timezone.utc)- if isinstance(value, str):- text = value.strip()- if not text:- return None- if text.endswith("Z"):- text = text[:-1] + "+00:00"- try:- dt = datetime.fromisoformat(text)- return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)- except ValueError:- return None- return None+ if not isinstance(value, str) or not (text := value.strip()):+ return None+ if text.endswith("Z"):+ text = text[:-1] + "+00:00"+ try:+ dt = datetime.fromisoformat(text)+ return dt if dt.tzinfo else dt.replace(tzinfo=timezone.utc)+ except ValueError:+ return Nonedef _format_reset(dt: Optional[datetime]) -> str:if not dt:return "unknown"local_dt = dt.astimezone()- delta = dt - _utc_now()- total_seconds = int(delta.total_seconds())+ stamp = local_dt.strftime("%Y-%m-%d %H:%M %Z")+ total_seconds = int((dt - _utc_now()).total_seconds())if total_seconds <= 0:- return f"now ({local_dt.strftime('%Y-%m-%d %H:%M %Z')})"+ return f"now ({stamp})"hours, rem = divmod(total_seconds, 3600)minutes = rem // 60if hours >= 24:days, hours = divmod(hours, 24)- rel = f"in {days}d {hours}h"- elif hours > 0:- rel = f"in {hours}h {minutes}m"- else:- rel = f"in {minutes}m"- return f"{rel} ({local_dt.strftime('%Y-%m-%d %H:%M %Z')})"+ return f"in {days}d {hours}h ({stamp})"+ return f"in {hours}h {minutes}m ({stamp})" if hours > 0 else f"in {minutes}m ({stamp})"def render_account_usage_lines(snapshot: Optional[AccountUsageSnapshot], *, markdown: bool = False) -> list[str]:if not snapshot:return []- header = f"π {'**' if markdown else ''}{snapshot.title}{'**' if markdown else ''}"- lines = [header]- if snapshot.plan:- lines.append(f"Provider: {snapshot.provider} ({snapshot.plan})")- else:- lines.append(f"Provider: {snapshot.provider}")+ bold = "**" if markdown else ""+ plan = f" ({snapshot.plan})" if snapshot.plan else ""+ lines = [f"π {bold}{snapshot.title}{bold}", f"Provider: {snapshot.provider}{plan}"]for window in snapshot.windows:if window.used_percent is None:base = f"{window.label}: unavailable"@@ -113,8 +101,7 @@ def render_account_usage_lines(snapshot: Optional[AccountUsageSnapshot], *, markelif window.detail:base += f" β’ {window.detail}"lines.append(base)- for detail in snapshot.details:- lines.append(detail)+ lines.extend(snapshot.details)if snapshot.unavailable_reason:lines.append(f"Unavailable: {snapshot.unavailable_reason}")return lines@@ -125,79 +112,59 @@ def _fmt_usd(d: float) -> str:def _is_finite_num(v: Any) -> TypeGuard[float]:- """True iff v is a real numeric value (int or float, not bool, not NaN/Inf).-- Typed as a ``TypeGuard[float]`` so the type checker narrows ``v`` to a real- number in the positive branch β callers can then do arithmetic / pass it to- ``_fmt_usd`` without a None-operand warning.- """+ """True iff v is a real number (int/float, not bool, not NaN/Inf). ``TypeGuard``+ so callers can do arithmetic on the positive branch without a None warning."""return isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(v)+def _nous_snapshot(+ windows: list[AccountUsageWindow], details: list[str], *, source: str, plan: Optional[str] = None+) -> AccountUsageSnapshot:+ return AccountUsageSnapshot(+ provider="nous", source=source, fetched_at=_utc_now(), title="Nous credits", plan=plan,+ windows=tuple(windows), details=tuple(details),+ )++def build_nous_credits_snapshot(account_info) -> Optional[AccountUsageSnapshot]:- """Map a NousPortalAccountInfo into an AccountUsageSnapshot for /usage.-- Shows dollar magnitudes (subscription / top-up / total) + renewal date + a- portal CTA. When the portal supplies a subscription denominator- (``monthly_credits``), also emits a subscription-usage window so the renderer- shows a real ``% used`` gauge; when it's absent (older portals) the view- gracefully degrades to magnitudes-only. Returns None when there's no usable- account info to show (fail-open: caller just shows nothing).- """+ """Map a NousPortalAccountInfo into an AccountUsageSnapshot for /usage:+ dollar magnitudes + renewal date + portal CTA, plus a ``% used`` gauge when+ the portal supplies ``monthly_credits`` (older portals: magnitudes-only).+ Fail-open β None (caller shows nothing)."""try:from hermes_cli.nous_account import nous_portal_topup_url-if account_info is None or not getattr(account_info, "logged_in", False):return None-access = getattr(account_info, "paid_service_access_info", None)sub = getattr(account_info, "subscription", None)-windows: list[AccountUsageWindow] = []details: list[str] = []- # Subscription usage gauge β only when the portal supplies a positive- # monthly_credits denominator AND a finite remaining balance that does- # not exceed the cap. Money math is on float dollars (allowed: numeric- # account fields, NOT a server-provided *_usd string). used = cap -- # remaining; clamp [0,100] so a debt balance (remaining < 0) reads 100%.- # Excluded on purpose:- # - non-finite values (NaN/Infinity slip past isinstance and json.loads- # parses bare NaN/Infinity by default) β would render "$nan"/"$inf"- # and a falsely-confident gauge;- # - remaining > cap (rollover balance spanning the period) β monthly_credits- # is no longer a meaningful denominator, and "$X of $Y left" with X>Y- # reads as a contradiction. Both fall back to the magnitudes lines.+ # Gauge needs a positive cap AND a finite remaining <= cap (float math on+ # numeric account fields, NOT a server *_usd). used = cap - remaining,+ # clamped [0,100] so debt reads 100%. Excluded: NaN/Inf (json.loads+ # accepts bare NaN β "$nan") and remaining > cap (rollover makes the cap+ # a meaningless denominator). Both fall back to the magnitudes lines.if sub is not None:monthly_credits = getattr(sub, "monthly_credits", None)sub_remaining = getattr(sub, "credits_remaining", None)if (- _is_finite_num(monthly_credits)- and monthly_credits > 0- and _is_finite_num(sub_remaining)- and sub_remaining <= monthly_credits+ _is_finite_num(monthly_credits) and monthly_credits > 0+ and _is_finite_num(sub_remaining) and sub_remaining <= monthly_credits):used = monthly_credits - sub_remaining- used_pct = max(0.0, min(100.0, used / monthly_credits * 100.0))- windows.append(- AccountUsageWindow(- label="Subscription",- used_percent=used_pct,- detail=f"{_fmt_usd(sub_remaining)} of {_fmt_usd(monthly_credits)} left",- )- )-+ windows.append(AccountUsageWindow(+ label="Subscription", used_percent=max(0.0, min(100.0, used / monthly_credits * 100.0)),+ detail=f"{_fmt_usd(sub_remaining)} of {_fmt_usd(monthly_credits)} left",+ ))if access is not None:- sub_credits = getattr(access, "subscription_credits_remaining", None)- if _is_finite_num(sub_credits):- details.append(f"Subscription credits: {_fmt_usd(sub_credits)}")- purchased = getattr(access, "purchased_credits_remaining", None)- if _is_finite_num(purchased):- details.append(f"Top-up credits: {_fmt_usd(purchased)}")- total_usable = getattr(access, "total_usable_credits", None)- if _is_finite_num(total_usable):- details.append(f"Total usable: {_fmt_usd(total_usable)}")-+ for attr, label in (+ ("subscription_credits_remaining", "Subscription credits"),+ ("purchased_credits_remaining", "Top-up credits"), ("total_usable_credits", "Total usable"),+ ):+ value = getattr(access, attr, None)+ if _is_finite_num(value):+ details.append(f"{label}: {_fmt_usd(value)}")if sub is not None:rollover = getattr(sub, "rollover_credits", None)if _is_finite_num(rollover) and rollover > 0:@@ -205,148 +172,100 @@ def build_nous_credits_snapshot(account_info) -> Optional[AccountUsageSnapshot]:period_end = getattr(sub, "current_period_end", None)if period_end:details.append(f"Renews: {period_end}")-- paid = getattr(account_info, "paid_service_access", None)- if paid is False:+ if getattr(account_info, "paid_service_access", None) is False:details.append("Status: access depleted β top up to restore")-if not windows and not details:return None-details.append(f"Top up: {nous_portal_topup_url(account_info)}")details.append("(or run /topup)")-plan = getattr(sub, "plan", None) if sub is not None else None- return AccountUsageSnapshot(- provider="nous",- source="portal-account",- fetched_at=_utc_now(),- title="Nous credits",- plan=plan,- windows=tuple(windows),- details=tuple(details),- )+ return _nous_snapshot(windows, details, source="portal-account", plan=plan)except (AttributeError, TypeError):return None-def nous_credits_lines(*, markdown: bool = False, timeout: float = 10.0) -> list[str]:- """Return rendered Nous-credits /usage lines, or [] when there's nothing to show.+def _nous_logged_in() -> bool:+ """Cheap local auth-state check: a Nous access token is present. Fail-open False."""+ try:+ from hermes_cli.auth import get_provider_auth_state+ tok = (get_provider_auth_state("nous") or {}).get("access_token")+ return isinstance(tok, str) and bool(tok.strip())+ except Exception:+ return False+++def _fetch_portal_account(timeout: float):+ """Wall-clock-bounded fresh portal account fetch (raises on any failure/timeout)."""+ import concurrent.futures+ from hermes_cli.nous_account import get_nous_portal_account_info+ with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:+ return pool.submit(get_nous_portal_account_info, force_fresh=True).result(timeout=timeout)+- Account-independent of any live agent: gated on "a Nous account is logged in"- (a cheap local auth-state check), then a wall-clock-bounded portal fetch. Shared- by the CLI ``_show_usage`` and the TUI ``session.usage`` RPC so both surfaces show- the same block regardless of session API-call count or resume state. Fail-open:- any auth/portal hiccup or timeout returns [] (the caller shows nothing).+def nous_credits_lines(*, markdown: bool = False, timeout: float = 10.0) -> list[str]:+ """Rendered Nous-credits /usage lines, or [] when there's nothing to show.- Dev override: when HERMES_DEV_CREDITS_FIXTURE selects a fixture state, /usage- renders from that fixture instead of the real portal (so the block + gauge are- testable without a live account). Throwaway scaffolding.+ Independent of any live agent (logged-in gate, then a bounded portal fetch);+ shared by CLI ``_show_usage`` and the TUI ``session.usage`` RPC so both show+ the same block. Fail-open: any hiccup or timeout β []. Dev override:+ HERMES_DEV_CREDITS_FIXTURE renders from the fixture instead of the portal."""- # Dev fixture short-circuit β render /usage from the injected state, no portal.try:from agent.credits_tracker import dev_fixture_credits_state-fixture = dev_fixture_credits_state()except Exception:fixture = Noneif fixture is not None:- snapshot = _snapshot_from_credits_state(fixture)- return render_account_usage_lines(snapshot, markdown=markdown)-- try:- from hermes_cli.auth import get_provider_auth_state-- tok = (get_provider_auth_state("nous") or {}).get("access_token")- if not (isinstance(tok, str) and tok.strip()):- return []- except Exception:+ return render_account_usage_lines(_snapshot_from_credits_state(fixture), markdown=markdown)+ if not _nous_logged_in():return []try:- import concurrent.futures-- from hermes_cli.nous_account import get_nous_portal_account_info-- with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:- account = pool.submit(- get_nous_portal_account_info, force_fresh=True- ).result(timeout=timeout)- snapshot = build_nous_credits_snapshot(account)+ snapshot = build_nous_credits_snapshot(_fetch_portal_account(timeout))return render_account_usage_lines(snapshot, markdown=markdown)except Exception:- # Fail-open (caller shows nothing), but leave a breadcrumb so a dead- # /usage credits block is diagnosable in agent.log without a dev flag.+ # Fail-open; breadcrumb so a dead /usage credits block is diagnosable.logger.debug("credits βΈ /usage portal fetch/render failed (fail-open)", exc_info=True)return []def _snapshot_from_credits_state(state) -> Optional[AccountUsageSnapshot]:- """Map a header-shaped CreditsState (e.g. a dev fixture) to the /usage snapshot.-- Renders the same magnitudes + monthly-grant % window the portal path produces,- so HERMES_DEV_CREDITS_FIXTURE can exercise /usage without a live account. The- *_usd strings are mock display values here (not server balance to compute on);- the % comes from CreditsState.used_fraction (micros math). Fail-open β None.- """+ """Map a header-shaped CreditsState (dev fixture) to the /usage snapshot, same+ shape as the portal path. *_usd strings are display values only; the % comes+ from CreditsState.used_fraction (micros math). Fail-open β None."""try:if state is None:return None-windows: list[AccountUsageWindow] = []details: list[str] = []-uf = getattr(state, "used_fraction", None)- if isinstance(uf, (int, float)) and math.isfinite(uf):- cap_usd = getattr(state, "subscription_limit_usd", None)- sub_usd = getattr(state, "subscription_usd", None)- detail = None- if sub_usd and cap_usd:- detail = f"${sub_usd} of ${cap_usd} left"- windows.append(- AccountUsageWindow(- label="Subscription",- used_percent=max(0.0, min(100.0, uf * 100.0)),- detail=detail,- )- )-sub_usd = getattr(state, "subscription_usd", None)- if sub_usd:- details.append(f"Subscription credits: ${sub_usd}")- purchased_usd = getattr(state, "purchased_usd", None)- if purchased_usd:- details.append(f"Top-up credits: ${purchased_usd}")- remaining_usd = getattr(state, "remaining_usd", None)- if remaining_usd:- details.append(f"Total usable: ${remaining_usd}")+ cap_usd = getattr(state, "subscription_limit_usd", None)+ if isinstance(uf, (int, float)) and math.isfinite(uf):+ windows.append(AccountUsageWindow(+ label="Subscription", used_percent=max(0.0, min(100.0, uf * 100.0)),+ detail=f"${sub_usd} of ${cap_usd} left" if sub_usd and cap_usd else None,+ ))+ for value, label in (+ (sub_usd, "Subscription credits"), (getattr(state, "purchased_usd", None), "Top-up credits"),+ (getattr(state, "remaining_usd", None), "Total usable"),+ ):+ if value:+ details.append(f"{label}: ${value}")if getattr(state, "paid_access", True) is False:details.append("Status: access depleted β top up to restore")-if not windows and not details:return None-details.append("(dev fixture β HERMES_DEV_CREDITS_FIXTURE)")- return AccountUsageSnapshot(- provider="nous",- source="dev-fixture",- fetched_at=_utc_now(),- title="Nous credits",- windows=tuple(windows),- details=tuple(details),- )+ return _nous_snapshot(windows, details, source="dev-fixture")except (AttributeError, TypeError):return None@dataclass(frozen=True)class CreditsView:- """Surface-agnostic data for the ``/topup`` balance view.-- One portal fetch, one parse β consumed identically by the CLI panel, the- gateway button, and any other money surface. Fail-open: when not logged in- or the portal is unreachable, ``logged_in`` is False / ``topup_url`` is None- and callers degrade gracefully.- """+ """Surface-agnostic ``/topup`` balance view: one portal fetch, consumed+ identically by every money surface. Fail-open: not logged in / portal+ unreachable β ``logged_in`` False, ``topup_url`` None."""logged_in: boolbalance_lines: tuple[str, ...] = ()@@ -356,135 +275,75 @@ class CreditsView:def build_credits_view(*, markdown: bool = False, timeout: float = 10.0) -> CreditsView:- """Build the /topup balance view: balance block + identity line + top-up URL.-- Reuses the same account fetch + snapshot + URL builder as the /usage credits- block, so the numbers always match. The balance block is the rendered- snapshot MINUS its trailing top-up/command-hint lines (the /topup surface- supplies its own affordance). Fail-open β ``CreditsView(logged_in=False)``.- """+ """Build the /topup view: balance block + identity line + top-up URL. Reuses the+ /usage fetch + snapshot so numbers match; the balance block is the rendered+ snapshot MINUS its trailing top-up/hint lines (/topup has its own affordance).+ Fail-open β ``CreditsView(logged_in=False)``."""not_logged_in = CreditsView(logged_in=False)- try:- from hermes_cli.auth import get_provider_auth_state-- tok = (get_provider_auth_state("nous") or {}).get("access_token")- if not (isinstance(tok, str) and tok.strip()):- return not_logged_in- except Exception:+ if not _nous_logged_in():return not_logged_in-try:- import concurrent.futures-- from hermes_cli.nous_account import (- get_nous_portal_account_info,- nous_portal_topup_url,- )-- with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:- account = pool.submit(get_nous_portal_account_info, force_fresh=True).result(- timeout=timeout- )+ account = _fetch_portal_account(timeout)except Exception:logger.debug("credits βΈ /topup portal fetch failed (fail-open)", exc_info=True)return not_logged_in-if account is None or not getattr(account, "logged_in", False):return not_logged_in-+ from hermes_cli.nous_account import nous_portal_topup_urlsnapshot = build_nous_credits_snapshot(account)- # Balance lines = the snapshot block minus the two trailing affordance lines- # ("Top up: <url>" + "(or run /topup)") that build_nous_credits_snapshot- # appends for the /usage surface. /topup renders its own button/panel.balance_lines: list[str] = []if snapshot is not None:- rendered = render_account_usage_lines(snapshot, markdown=markdown)balance_lines = [line- for line in rendered- if not line.lstrip().startswith("Top up:")- and not line.lstrip().startswith("(or run")+ for line in render_account_usage_lines(snapshot, markdown=markdown)+ if not line.lstrip().startswith("Top up:") and not line.lstrip().startswith("(or run")]- # Identity line β shown before any open (roadmap Β§4.4).+ # Identity line β shown before any open.+ who: list[str] = []email = getattr(account, "email", None)org_name = getattr(account, "org_name", None)- who: list[str] = []if email:who.append(str(email))if org_name:who.append(f"org {org_name}")- identity_line = ("Topping up as " + " / ".join(who)) if who else None-return CreditsView(- logged_in=True,- balance_lines=tuple(balance_lines),- identity_line=identity_line,- topup_url=nous_portal_topup_url(account),+ logged_in=True, balance_lines=tuple(balance_lines),+ identity_line=("Topping up as " + " / ".join(who)) if who else None, topup_url=nous_portal_topup_url(account),depleted=getattr(account, "paid_service_access", None) is False,)def _codex_backend_urls(base_url: str) -> tuple[str, str, str]:- """Resolve the Codex backend endpoints (usage, reset-credits list, consume).-- Mirrors the Codex CLI's PathStyle split (codex-rs backend-client): base URLs- containing ``/backend-api`` use the ChatGPT ``/wham/...`` paths; everything- else uses ``/api/codex/...``.- """- normalized = (base_url or "").strip().rstrip("/")- if not normalized:- normalized = "https://chatgpt.com/backend-api/codex"+ """Codex backend endpoints (usage, reset-credits list, consume). Mirrors the+ Codex CLI's PathStyle split: ``/backend-api`` bases use the ChatGPT ``/wham/``+ paths; everything else ``/api/codex/``."""+ normalized = (base_url or "").strip().rstrip("/") or "https://chatgpt.com/backend-api/codex"if normalized.endswith("/codex"):normalized = normalized[: -len("/codex")]prefix = normalized + ("/wham" if "/backend-api" in normalized else "/api/codex")- return (- prefix + "/usage",- prefix + "/rate-limit-reset-credits",- prefix + "/rate-limit-reset-credits/consume",- )---def _resolve_codex_usage_url(base_url: str) -> str:- return _codex_backend_urls(base_url)[0]+ return (prefix + "/usage", prefix + "/rate-limit-reset-credits", prefix + "/rate-limit-reset-credits/consume")def _resolve_codex_usage_credentials(- base_url: Optional[str],- api_key: Optional[str],+ base_url: Optional[str], api_key: Optional[str],) -> tuple[str, str, Optional[str]]:- """Resolve Codex quota credentials from the native runtime path.-- Prefer explicit live-agent credentials, then the legacy singleton OAuth- state, then the credential pool. Hermes's native OAuth setup now stores- device-code logins in the pool, so quota diagnostics must not depend only- on the older singleton store.- """+ """Codex quota credentials: explicit live-agent creds β native runtime resolver+ (itself pool-aware) β direct pool select. Native OAuth stores device-code+ logins in the pool, so this must not depend only on the singleton store."""explicit_key = str(api_key or "").strip()if explicit_key:return explicit_key, str(base_url or "").strip(), None- # Tier 2: the native runtime resolver. It ALREADY falls back to the- # credential pool when the singleton is empty (see- # ``resolve_codex_runtime_credentials`` β issue #32992), so in a pool-only- # setup this returns a usable ``source="credential_pool"`` token.- #- # Only ``AuthError`` ("no creds" / rate-limited) is caught so tier 3 can- # run: a broad ``except Exception`` would (a) mask a transient refresh /- # network failure and silently hand back a DIFFERENT pool account's usage,- # and (b) hide genuine programming errors. A refresh/network error must- # propagate β the outer ``fetch_account_usage`` guard fails open (shows- # nothing this turn) rather than reporting the wrong account.- #- # The ``account_id`` (for the ``ChatGPT-Account-Id`` header) is read- # best-effort: a partial/missing singleton token store must not sink an- # otherwise-usable resolver credential and force a header-less pool fallback.+ # Only AuthError is caught so tier 3 can run: a broad except would mask a+ # transient refresh/network failure and hand back a DIFFERENT pool account's+ # usage; such errors must propagate to the fail-open outer guard. account_id+ # is best-effort: a partial singleton store must not sink a usable credential.try:creds = resolve_codex_runtime_credentials(refresh_if_expiring=True)account_id: Optional[str] = Nonetry:- token_data = _read_codex_tokens()- tokens = token_data.get("tokens") or {}+ tokens = _read_codex_tokens().get("tokens") or {}account_id = str(tokens.get("account_id", "") or "").strip() or Noneexcept AuthError:# Pool-only creds carry no singleton account_id; header is optional.@@ -493,73 +352,73 @@ def _resolve_codex_usage_credentials(except AuthError:logger.debug("codex βΈ /usage runtime resolver returned no creds; trying pool", exc_info=True)- # Tier 3: direct pool select. Reached only when the resolver itself raises- # AuthError (e.g. singleton missing AND its own pool read found nothing at- # resolve time, but a pool entry is usable now). Pool credentials have no- # account_id concept, so the ChatGPT-Account-Id header is intentionally- # omitted here.+ # Tier 3: pool credentials have no account_id concept β header omitted.from agent.credential_pool import load_pool-- pool = load_pool("openai-codex")- entry = pool.select()+ entry = load_pool("openai-codex").select()if entry is None:raise RuntimeError("No available openai-codex credential in credential pool")return entry.runtime_api_key, str(entry.runtime_base_url or base_url or "").strip(), None-def _fetch_codex_account_usage(- base_url: Optional[str] = None,- api_key: Optional[str] = None,-) -> Optional[AccountUsageSnapshot]:- token, resolved_base_url, account_id = _resolve_codex_usage_credentials(base_url, api_key)- headers = {- "Authorization": f"Bearer {token}",- "Accept": "application/json",- "User-Agent": "codex-cli",- }+def _codex_banked_resets(payload: dict) -> int:+ raw = (payload.get("rate_limit_reset_credits") or {}).get("available_count")+ return int(raw) if isinstance(raw, (int, float)) else 0+++def _codex_headers(token: str, account_id: Optional[str]) -> dict[str, str]:+ headers = {"Authorization": f"Bearer {token}", "Accept": "application/json", "User-Agent": "codex-cli"}if account_id:headers["ChatGPT-Account-Id"] = account_id- with httpx.Client(timeout=15.0) as client:- response = client.get(_resolve_codex_usage_url(resolved_base_url), headers=headers)+ return headers+++def _get_json(url: str, headers: dict[str, str], *, timeout: float) -> dict:+ with httpx.Client(timeout=timeout) as client:+ response = client.get(url, headers=headers)response.raise_for_status()- payload = response.json() or {}- rate_limit = payload.get("rate_limit") or {}+ return response.json() or {}+++def _usage_windows(+ source: dict, mapping: tuple[tuple[str, str], ...], used_key: str, reset_key: str, *, fraction: bool = False+) -> list[AccountUsageWindow]:+ """Build windows from ``source[key][used_key]``; ``fraction`` scales values <= 1 to percent."""windows: list[AccountUsageWindow] = []- for key, label in (("primary_window", "Session"), ("secondary_window", "Weekly")):- window = rate_limit.get(key) or {}- used = window.get("used_percent")+ for key, label in mapping:+ window = source.get(key) or {}+ used = window.get(used_key)if used is None:continue- windows.append(- AccountUsageWindow(- label=label,- used_percent=float(used),- reset_at=_parse_dt(window.get("reset_at")),- )- )+ used = float(used)+ if fraction and used <= 1:+ used *= 100+ windows.append(AccountUsageWindow(label=label, used_percent=used, reset_at=_parse_dt(window.get(reset_key))))+ return windows+++def _fetch_codex_account_usage(+ base_url: Optional[str] = None, api_key: Optional[str] = None,+) -> Optional[AccountUsageSnapshot]:+ token, resolved_base_url, account_id = _resolve_codex_usage_credentials(base_url, api_key)+ payload = _get_json(_codex_backend_urls(resolved_base_url)[0], _codex_headers(token, account_id), timeout=15.0)+ windows = _usage_windows(+ payload.get("rate_limit") or {}, (("primary_window", "Session"), ("secondary_window", "Weekly")),+ "used_percent", "reset_at",+ )details: list[str] = []- reset_credits = payload.get("rate_limit_reset_credits") or {}- banked = reset_credits.get("available_count")- if isinstance(banked, (int, float)) and int(banked) > 0:- count = int(banked)+ count = _codex_banked_resets(payload)+ if count > 0:plural = "s" if count != 1 else ""- details.append(- f"You have {count} reset{plural} banked - use /usage reset to activate"- )+ details.append(f"You have {count} reset{plural} banked - use /usage reset to activate")credits = payload.get("credits") or {}- if credits.get("has_credits"):- balance = credits.get("balance")- if isinstance(balance, (int, float)):- details.append(f"Credits balance: ${float(balance):.2f}")- elif credits.get("unlimited"):- details.append("Credits balance: unlimited")+ balance = credits.get("balance")+ if credits.get("has_credits") and isinstance(balance, (int, float)):+ details.append(f"Credits balance: ${float(balance):.2f}")+ elif credits.get("has_credits") and credits.get("unlimited"):+ details.append("Credits balance: unlimited")return AccountUsageSnapshot(- provider="openai-codex",- source="usage_api",- fetched_at=_utc_now(),- plan=_title_case_slug(payload.get("plan_type")),- windows=tuple(windows),- details=tuple(details),+ provider="openai-codex", source="usage_api", fetched_at=_utc_now(),+ plan=_title_case_slug(payload.get("plan_type")), windows=tuple(windows), details=tuple(details),)@@ -578,78 +437,48 @@ class CodexResetRedeemResult:return self.status == "reset"-# Client-side guard threshold: a rate-limit window only counts as exhausted-# when it is fully used. Below this, redeeming a banked reset wastes most of-# its value, so we block and point at --force instead.+# Client-side guard: a window only counts as exhausted when fully used. Below+# this, redeeming a banked reset wastes most of its value β block, point at --force._CODEX_WINDOW_EXHAUSTED_PERCENT = 100.0+def _unavailable(message: str) -> CodexResetRedeemResult:+ return CodexResetRedeemResult(status="unavailable", message=message)++def redeem_codex_reset_credit(- *,- base_url: Optional[str] = None,- api_key: Optional[str] = None,- force: bool = False,+ *, base_url: Optional[str] = None, api_key: Optional[str] = None, force: bool = False,) -> CodexResetRedeemResult:- """Redeem one banked Codex rate-limit reset credit (`/usage reset`).-- Flow (mirrors the Codex CLI's reset-credits picker, codex-rs- ``backend-client``):-- 1. ``GET .../usage`` β read the current windows + banked credit count.- 2. Guard: zero banked credits β refuse. No window fully used and not- ``force`` β refuse with a warning (a banked reset restores the WHOLE- 5h + weekly allowance; burning it early wastes it). The backend has- the same protection (``nothing_to_reset`` doesn't consume the- credit), but failing fast client-side gives a clearer message.- 3. ``POST .../rate-limit-reset-credits/consume`` with a fresh UUID- idempotency key (``redeem_request_id``). No ``credit_id`` β the- backend picks the next available credit, exactly like the CLI's- default "Full reset" option.-- Never raises: every failure mode returns a ``CodexResetRedeemResult``- with a user-renderable message.- """+ """Redeem one banked Codex rate-limit reset credit (`/usage reset`), mirroring+ the Codex CLI picker: GET usage β guard (no banked credits, or no window fully+ used and not ``force`` β refuse; a reset restores the WHOLE 5h + weekly+ allowance, and the backend's own ``nothing_to_reset`` guard is less clear) β+ POST consume with a fresh UUID ``redeem_request_id`` and no ``credit_id`` (the+ backend picks the next credit). Never raises: every failure returns a result."""import uuid-try:token, resolved_base_url, account_id = _resolve_codex_usage_credentials(base_url, api_key)except Exception:- return CodexResetRedeemResult(- status="unavailable",- message="No Codex credentials available. Run `hermes auth` to sign in with your ChatGPT account.",- )+ return _unavailable("No Codex credentials available. Run `hermes auth` to sign in with your ChatGPT account.")usage_url, _credits_url, consume_url = _codex_backend_urls(resolved_base_url)- headers = {- "Authorization": f"Bearer {token}",- "Accept": "application/json",- "User-Agent": "codex-cli",- }- if account_id:- headers["ChatGPT-Account-Id"] = account_id-+ headers = _codex_headers(token, account_id)try:with httpx.Client(timeout=15.0) as client:usage_resp = client.get(usage_url, headers=headers)usage_resp.raise_for_status()payload = usage_resp.json() or {}-- reset_credits = payload.get("rate_limit_reset_credits") or {}- raw_count = reset_credits.get("available_count")- available = int(raw_count) if isinstance(raw_count, (int, float)) else 0+ available = _codex_banked_resets(payload)if available <= 0:return CodexResetRedeemResult(- status="no_credits_banked",- message="No banked reset credits on this account β nothing to redeem.",+ status="no_credits_banked", message="No banked reset credits on this account β nothing to redeem.")-rate_limit = payload.get("rate_limit") or {}- worst_used: Optional[float] = None- for key in ("primary_window", "secondary_window"):- used = (rate_limit.get(key) or {}).get("used_percent")- if isinstance(used, (int, float)):- worst_used = max(worst_used or 0.0, float(used))- exhausted = worst_used is not None and worst_used >= _CODEX_WINDOW_EXHAUSTED_PERCENT- if not exhausted and not force:+ used_pcts = [+ float(u) for u in ((rate_limit.get(k) or {}).get("used_percent") for k in ("primary_window", "secondary_window"))+ if isinstance(u, (int, float))+ ]+ worst_used: Optional[float] = max(0.0, *used_pcts) if used_pcts else None+ if not force and not (worst_used is not None and worst_used >= _CODEX_WINDOW_EXHAUSTED_PERCENT):usage_note = (f"your busiest window is only {worst_used:.0f}% used"if worst_used is not None@@ -666,10 +495,8 @@ def redeem_codex_reset_credit(),available_count=available,)-consume_resp = client.post(- consume_url,- headers={**headers, "Content-Type": "application/json"},+ consume_url, headers={**headers, "Content-Type": "application/json"},json={"redeem_request_id": str(uuid.uuid4())},)consume_resp.raise_for_status()@@ -677,42 +504,26 @@ def redeem_codex_reset_credit(except httpx.HTTPStatusError as exc:code = exc.response.status_codeif code in (401, 403):- return CodexResetRedeemResult(- status="unavailable",- message=(- "Codex backend rejected the request (HTTP "- f"{code}). Reset credits require ChatGPT-account (OAuth) auth β "- "run `hermes auth` and sign in with your ChatGPT account."- ),+ return _unavailable(+ "Codex backend rejected the request (HTTP "+ f"{code}). Reset credits require ChatGPT-account (OAuth) auth β "+ "run `hermes auth` and sign in with your ChatGPT account.")- return CodexResetRedeemResult(- status="unavailable",- message=f"Codex backend error (HTTP {code}) β try again shortly.",- )+ return _unavailable(f"Codex backend error (HTTP {code}) β try again shortly.")except Exception as exc:- return CodexResetRedeemResult(- status="unavailable",- message=f"Could not reach the Codex backend: {exc}",- )-+ return _unavailable(f"Could not reach the Codex backend: {exc}")code = str(body.get("code", "") or "").strip().lower()windows_reset = body.get("windows_reset")- windows_reset = int(windows_reset) if isinstance(windows_reset, (int, float)) else 0remaining = max(0, available - 1)plural = "s" if remaining != 1 else ""if code == "reset":- # The redeemed reset restores the account's quota upstream β lift any- # persisted pool cooldowns so Hermes doesn't keep the credential- # frozen behind the now-stale ``last_error_reset_at`` (issue #43747).+ # Quota is restored upstream β lift persisted pool cooldowns so the+ # credential isn't frozen behind a stale ``last_error_reset_at``.try:from hermes_cli.auth import clear_codex_pool_quota_cooldowns-clear_codex_pool_quota_cooldowns()except Exception:- logger.debug(- "Failed to clear Codex pool cooldowns after reset redemption",- exc_info=True,- )+ logger.debug("Failed to clear Codex pool cooldowns after reset redemption", exc_info=True)return CodexResetRedeemResult(status="reset",message=(@@ -720,183 +531,115 @@ def redeem_codex_reset_credit(f"{remaining} banked reset{plural} remaining."),available_count=remaining,- windows_reset=windows_reset,- )- if code == "nothing_to_reset":- return CodexResetRedeemResult(- status="nothing_to_reset",- message=(- "Backend reports nothing to reset β your limits aren't exhausted. "- "The credit was NOT spent."- ),- available_count=available,- )- if code == "no_credit":- return CodexResetRedeemResult(- status="no_credit",- message="Backend reports no available reset credit on this account.",- )- if code == "already_redeemed":- return CodexResetRedeemResult(- status="already_redeemed",- message="This redemption was already processed β no additional credit was spent.",- available_count=remaining,+ windows_reset=int(windows_reset) if isinstance(windows_reset, (int, float)) else 0,)- return CodexResetRedeemResult(- status="unavailable",- message=f"Unexpected response from the Codex backend: {body!r}",- )+ outcomes: dict[str, tuple[str, int]] = {+ "nothing_to_reset": (+ "Backend reports nothing to reset β your limits aren't exhausted. The credit was NOT spent.", available,+ ),+ "no_credit": ("Backend reports no available reset credit on this account.", 0),+ "already_redeemed": ("This redemption was already processed β no additional credit was spent.", remaining),+ }+ if code in outcomes:+ message, count = outcomes[code]+ return CodexResetRedeemResult(status=code, message=message, available_count=count)+ return _unavailable(f"Unexpected response from the Codex backend: {body!r}")-def _fetch_anthropic_account_usage() -> Optional[AccountUsageSnapshot]:+def _fetch_anthropic_account_usage(+ base_url: Optional[str] = None, api_key: Optional[str] = None+) -> Optional[AccountUsageSnapshot]:token = (resolve_anthropic_token() or "").strip()if not token:return Noneif not _is_oauth_token(token):return AccountUsageSnapshot(- provider="anthropic",- source="oauth_usage_api",- fetched_at=_utc_now(),+ provider="anthropic", source="oauth_usage_api", fetched_at=_utc_now(),unavailable_reason="Anthropic account limits are only available for OAuth-backed Claude accounts.",)headers = {- "Authorization": f"Bearer {token}",- "Accept": "application/json",- "Content-Type": "application/json",- "anthropic-beta": "oauth-2025-04-20",- "User-Agent": "claude-code/2.1.0",+ "Authorization": f"Bearer {token}", "Accept": "application/json", "Content-Type": "application/json",+ "anthropic-beta": "oauth-2025-04-20", "User-Agent": "claude-code/2.1.0",}- with httpx.Client(timeout=15.0) as client:- response = client.get("https://api.anthropic.com/api/oauth/usage", headers=headers)- response.raise_for_status()- payload = response.json() or {}- windows: list[AccountUsageWindow] = []- mapping = (- ("five_hour", "Current session"),- ("seven_day", "Current week"),- ("seven_day_opus", "Opus week"),- ("seven_day_sonnet", "Sonnet week"),+ payload = _get_json("https://api.anthropic.com/api/oauth/usage", headers, timeout=15.0)+ windows = _usage_windows(+ payload,+ (("five_hour", "Current session"), ("seven_day", "Current week"), ("seven_day_opus", "Opus week"),+ ("seven_day_sonnet", "Sonnet week")),+ "utilization", "resets_at", fraction=True,)- for key, label in mapping:- window = payload.get(key) or {}- util = window.get("utilization")- if util is None:- continue- used = float(util) * 100 if float(util) <= 1 else float(util)- windows.append(- AccountUsageWindow(- label=label,- used_percent=used,- reset_at=_parse_dt(window.get("resets_at")),- )- )details: list[str] = []extra = payload.get("extra_usage") or {}- if extra.get("is_enabled"):- used_credits = extra.get("used_credits")- monthly_limit = extra.get("monthly_limit")- currency = extra.get("currency") or "USD"- if isinstance(used_credits, (int, float)) and isinstance(monthly_limit, (int, float)):- details.append(- f"Extra usage: {used_credits:.2f} / {monthly_limit:.2f} {currency}"- )+ used_credits, monthly_limit = extra.get("used_credits"), extra.get("monthly_limit")+ if extra.get("is_enabled") and isinstance(used_credits, (int, float)) and isinstance(monthly_limit, (int, float)):+ details.append(f"Extra usage: {used_credits:.2f} / {monthly_limit:.2f} {extra.get('currency') or 'USD'}")return AccountUsageSnapshot(- provider="anthropic",- source="oauth_usage_api",- fetched_at=_utc_now(),- windows=tuple(windows),+ provider="anthropic", source="oauth_usage_api", fetched_at=_utc_now(), windows=tuple(windows),details=tuple(details),)def _fetch_openrouter_account_usage(base_url: Optional[str], api_key: Optional[str]) -> Optional[AccountUsageSnapshot]:- runtime = resolve_runtime_provider(- requested="openrouter",- explicit_base_url=base_url,- explicit_api_key=api_key,- )+ runtime = resolve_runtime_provider(requested="openrouter", explicit_base_url=base_url, explicit_api_key=api_key)token = str(runtime.get("api_key", "") or "").strip()if not token:return Nonenormalized = str(runtime.get("base_url", "") or "").rstrip("/")- credits_url = f"{normalized}/credits"- key_url = f"{normalized}/key"- headers = {- "Authorization": f"Bearer {token}",- "Accept": "application/json",- }+ headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}with httpx.Client(timeout=10.0) as client:- credits_resp = client.get(credits_url, headers=headers)- credits_resp.raise_for_status()- credits = (credits_resp.json() or {}).get("data") or {}+ def _data(path: str) -> dict:+ resp = client.get(f"{normalized}/{path}", headers=headers)+ resp.raise_for_status()+ return (resp.json() or {}).get("data") or {}+ credits = _data("credits")try:- key_resp = client.get(key_url, headers=headers)- key_resp.raise_for_status()- key_data = (key_resp.json() or {}).get("data") or {}+ key_data = _data("key")except Exception:key_data = {}- total_credits = float(credits.get("total_credits") or 0.0)- total_usage = float(credits.get("total_usage") or 0.0)- details = [f"Credits balance: ${max(0.0, total_credits - total_usage):.2f}"]+ balance = float(credits.get("total_credits") or 0.0) - float(credits.get("total_usage") or 0.0)+ details = [f"Credits balance: ${max(0.0, balance):.2f}"]windows: list[AccountUsageWindow] = []limit = key_data.get("limit")limit_remaining = key_data.get("limit_remaining")limit_reset = str(key_data.get("limit_reset") or "").strip()usage = key_data.get("usage")if (- isinstance(limit, (int, float))- and float(limit) > 0- and isinstance(limit_remaining, (int, float))- and 0 <= float(limit_remaining) <= float(limit)+ isinstance(limit, (int, float)) and float(limit) > 0+ and isinstance(limit_remaining, (int, float)) and 0 <= float(limit_remaining) <= float(limit)):limit_value = float(limit)remaining_value = float(limit_remaining)- used_percent = ((limit_value - remaining_value) / limit_value) * 100detail_parts = [f"${remaining_value:.2f} of ${limit_value:.2f} remaining"]if limit_reset:detail_parts.append(f"resets {limit_reset}")- windows.append(- AccountUsageWindow(- label="API key quota",- used_percent=used_percent,- detail=" β’ ".join(detail_parts),- )- )+ windows.append(AccountUsageWindow(+ label="API key quota", used_percent=((limit_value - remaining_value) / limit_value) * 100,+ detail=" β’ ".join(detail_parts),+ ))if isinstance(usage, (int, float)):usage_parts = [f"API key usage: ${float(usage):.2f} total"]- for value, label in (- (key_data.get("usage_daily"), "today"),- (key_data.get("usage_weekly"), "this week"),- (key_data.get("usage_monthly"), "this month"),- ):+ for key, label in (("usage_daily", "today"), ("usage_weekly", "this week"), ("usage_monthly", "this month")):+ value = key_data.get(key)if isinstance(value, (int, float)) and float(value) > 0:usage_parts.append(f"${float(value):.2f} {label}")details.append(" β’ ".join(usage_parts))return AccountUsageSnapshot(- provider="openrouter",- source="credits_api",- fetched_at=_utc_now(),- windows=tuple(windows),+ provider="openrouter", source="credits_api", fetched_at=_utc_now(), windows=tuple(windows),details=tuple(details),)+_USAGE_FETCHERS: dict[str, Callable[[Optional[str], Optional[str]], Optional[AccountUsageSnapshot]]] = {+ "openai-codex": _fetch_codex_account_usage, "anthropic": _fetch_anthropic_account_usage,+ "openrouter": _fetch_openrouter_account_usage,+}++def fetch_account_usage(- provider: Optional[str],- *,- base_url: Optional[str] = None,- api_key: Optional[str] = None,+ provider: Optional[str], *, base_url: Optional[str] = None, api_key: Optional[str] = None,) -> Optional[AccountUsageSnapshot]:- normalized = str(provider or "").strip().lower()- if normalized in {"", "auto", "custom"}:- return None+ fetcher = _USAGE_FETCHERS.get(str(provider or "").strip().lower())try:- if normalized == "openai-codex":- return _fetch_codex_account_usage(base_url=base_url, api_key=api_key)- if normalized == "anthropic":- return _fetch_anthropic_account_usage()- if normalized == "openrouter":- return _fetch_openrouter_account_usage(base_url, api_key)+ return fetcher(base_url, api_key) if fetcher else Noneexcept Exception:return None- return Nonediff --git a/agent/billing_links.py b/agent/billing_links.pyindex 1e9320ebb45..d38cbc4bdd7 100644--- a/agent/billing_links.py+++ b/agent/billing_links.py@@ -1,11 +1,10 @@"""Provider-agnostic billing/credit recovery links.-Maps a billing-classified failure onto a recovery link + label. *Detection*-is not done here β that is :mod:`agent.error_classifier`-(``FailoverReason.billing``), the single source of truth for "credit wall vs.-rate limit / auth / transport". The resulting :class:`BillingBlock` rides the-turn result and the gateway ``message.complete`` event so every surface (CLI,-TUI, desktop) renders one structured signal instead of re-parsing error text.+Maps a billing-classified failure onto a recovery link + label. *Detection* is+:mod:`agent.error_classifier` (``FailoverReason.billing``), the single source of+truth for "credit wall vs. rate limit / auth / transport". The :class:`BillingBlock`+rides the turn result and the gateway ``message.complete`` event so every surface+renders one structured signal instead of re-parsing error text."""from __future__ import annotations@@ -20,10 +19,9 @@ from utils import base_url_host_matchesclass BillingBlock:"""Structured billing-wall descriptor shared across every surface.- ``is_nous`` is the routing bit: Nous has a first-class in-app billing surface- (desktop Settings β Billing, TUI/CLI ``/topup``), so surfaces prefer that over- ``billing_url``; third-party providers have no in-app flow, so ``billing_url``- is the deep link the user actually needs.+ ``is_nous`` is the routing bit: Nous has an in-app billing surface (desktop+ Settings β Billing, TUI/CLI ``/topup``) preferred over ``billing_url``;+ third-party providers have none, so ``billing_url`` is the deep link needed."""provider: str@@ -45,11 +43,10 @@ class _Provider:hosts: tuple[str, ...] = ()-# Single source of truth: internal slug(s) + base_url host(s) β billing page.-# Curated "add credits / manage billing" landing pages, not marketing homes.-# Hosts back the OpenAI-compatible fallback where the slug is a generic bucket-# (e.g. "openai_compatible") but base_url reveals the real upstream. An unknown-# provider degrades to a readable label with no invented URL.+# Single source of truth: slug(s) + base_url host(s) β curated "add credits"+# page (not marketing homes). Hosts back the OpenAI-compatible fallback where the+# slug is a generic bucket but base_url reveals the real upstream. Unknown+# providers degrade to a readable label with no invented URL._PROVIDERS: tuple[_Provider, ...] = (_Provider("OpenAI", "https://platform.openai.com/settings/organization/billing", ("openai",), ("api.openai.com",)),_Provider("Anthropic", "https://console.anthropic.com/settings/billing", ("anthropic",), ("api.anthropic.com",)),@@ -72,16 +69,15 @@ _BY_SLUG: dict[str, _Provider] = {slug: p for p in _PROVIDERS for slug in p.slugdef is_nous_inference_route(provider: str, base_url: str) -> bool:"""True when the failing route is the Nous-managed inference gateway."""- if (provider or "").strip().lower() == "nous":- return True- return base_url_host_matches(str(base_url or ""), "inference-api.nousresearch.com")+ return (provider or "").strip().lower() == "nous" or base_url_host_matches(+ str(base_url or ""), "inference-api.nousresearch.com"+ )def _nous_billing_url() -> Optional[str]:"""Best-effort Nous portal billing URL (text-surface fallback; Nous prefers the in-app flow)."""try:from hermes_cli.nous_account import nous_portal_billing_url-return nous_portal_billing_url(None)except Exception:return "https://portal.nousresearch.com/billing"@@ -92,22 +88,14 @@ def _resolve_provider_link(slug: str, base_url: str) -> tuple[str, Optional[str]hit = _BY_SLUG.get(slug)if hit:return hit.label, hit.url-base = str(base_url or "")for p in _PROVIDERS:if any(base_url_host_matches(base, host) for host in p.hosts):return p.label, p.url-return slug.replace("_", " ").replace("-", " ").strip().title() or "your provider", None-def build_billing_block(- *,- provider: str,- base_url: str,- model: str,- message: str = "",-) -> BillingBlock:+def build_billing_block(*, provider: str, base_url: str, model: str, message: str = "") -> BillingBlock:"""Build the billing descriptor for a billing-classified failure.``message`` is the guidance already assembled by the agent loop@@ -116,9 +104,7 @@ def build_billing_block("""slug = (provider or "").strip().lower()model = (model or "").strip()-if is_nous_inference_route(slug, base_url):return BillingBlock(slug or "nous", "Nous Portal", model, _nous_billing_url(), True, message or "")-label, url = _resolve_provider_link(slug, base_url)return BillingBlock(slug, label, model, url, False, message or "")diff --git a/agent/credits_tracker.py b/agent/credits_tracker.pyindex 82e2d53caa4..54f0de07953 100644--- a/agent/credits_tracker.py+++ b/agent/credits_tracker.py@@ -1,30 +1,22 @@-"""Credits tracking for Nous inference API responses.--Parses x-nous-credits-* (and optional x-nous-tool-pool-*) headers from-inference responses into a validated CreditsState dataclass. Provides-depletion detection (paid_access), subscription-cap used_fraction, and-warn-once schema-version gating. This is the hardened parser used by all-live consumers (run_agent, tui_gateway) β not a dev-only shim.--Header schema (x-nous-credits-* family):- x-nous-credits-version contract/schema version- x-nous-credits-remaining-micros total remaining balance (micros)- x-nous-credits-remaining-usd same, formatted USD string- x-nous-credits-subscription-micros subscription balance (SIGNED; may be negative/debt)- x-nous-credits-subscription-usd same, formatted USD string- x-nous-credits-subscription-limit-micros subscription cap (PAIRED/optional)- x-nous-credits-subscription-limit-usd same, formatted USD string (PAIRED/optional)- x-nous-credits-rollover-micros rolled-over balance (micros)- x-nous-credits-purchased-micros purchased balance (micros)- x-nous-credits-purchased-usd same, formatted USD string- x-nous-credits-denominator-kind "subscription_cap" | "none"- x-nous-credits-paid-access "true" | "false" (STRING!)- x-nous-credits-disabled-reason reason string (header omitted when null)- x-nous-credits-as-of-ms server-side timestamp (ms epoch)--Tool-pool headers use a SEPARATE prefix:- x-nous-tool-pool-micros tool-pool balance (micros)- x-nous-tool-pool-gated-off "true" | "false" (STRING!)+"""Credits tracking for Nous inference API responses: parses x-nous-credits-*+(and optional x-nous-tool-pool-*) headers into a validated CreditsState, with+depletion detection (paid_access), subscription-cap used_fraction, and warn-once+schema-version gating. The hardened parser used by all live consumers.++Header schema (x-nous-credits-*; each *-micros balance has a *-usd twin holding+the server's formatted USD string):+ version contract/schema version+ remaining-micros/-usd total remaining balance+ subscription-micros/-usd subscription balance (SIGNED; may be negative/debt)+ subscription-limit-* subscription cap (PAIRED/optional)+ rollover-micros rolled-over balance+ purchased-micros/-usd purchased balance+ denominator-kind "subscription_cap" | "none"+ paid-access "true" | "false" (STRING!)+ disabled-reason reason string (header omitted when null)+ as-of-ms server-side timestamp (ms epoch)+Tool-pool headers use a SEPARATE prefix: x-nous-tool-pool-micros (balance) and+x-nous-tool-pool-gated-off ("true" | "false" STRING!).Money is handled as micros ints only; *_usd values are preserved verbatim asthe raw strings the server sent (never re-parsed to float).@@ -52,25 +44,12 @@ _VALID_DENOMINATOR_KINDS = frozenset({"subscription_cap", "none"})# USD format: optional leading minus, one-or-more digits, dot, exactly 2 digits._USD_RE = re.compile(r"^-?\d+\.\d{2}$")--# ββ Internal helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ--_SENTINEL = object() # singleton sentinel for "parse failed"def _safe_int(value: Any) -> Any:- """Parse a header value to an exact int (money-safe).-- The contract guarantees every ``*_micros`` field is an integer string β- we parse with ``int()`` directly, NOT ``int(float(...))``, to avoid float-- precision loss above 2**53 that would silently corrupt large money values.-- Returns the parsed int, or ``_SENTINEL`` if the value is not a valid integer- string (including float-shaped strings like "1.5"). The sentinel lets callers- detect the failure and return None from the overall parse (fail-hard-on-bad-- input, not silently coerce).- """+ """Exact int (money-safe) or ``_SENTINEL``. ``int()`` directly, NOT ``int(float())``+ (precision loss above 2**53 corrupts money); float-shaped strings fail."""if value is None:return _SENTINELtry:@@ -79,15 +58,9 @@ def _safe_int(value: Any) -> Any:return _SENTINEL-def _validate_usd(value: Optional[str]) -> bool:"""Return True iff value is a non-None string matching ^-?\\d+\\.\\d{2}$."""- if value is None:- return False- return bool(_USD_RE.match(value))---# ββ CreditsState dataclass βββββββββββββββββββββββββββββββββββββββββββββββββββ+ return value is not None and bool(_USD_RE.match(value))@dataclass@@ -119,93 +92,55 @@ class CreditsState:@propertydef age_seconds(self) -> float:- if not self.has_data:- return float("inf")- return time.time() - self.captured_at+ return time.time() - self.captured_at if self.has_data else float("inf")@propertydef depleted(self) -> bool:- """True when the account has lost paid access.-- Keyed off ``paid_access == False`` ONLY β never ``remaining_micros == 0``,- which would give a false positive whenever the balance is zero but access- is still live (e.g. subscription renewal pending).- """+ """Keyed off ``paid_access == False`` ONLY β never ``remaining_micros == 0``,+ a false positive when the balance is zero but access is live (renewal pending)."""return not self.paid_access@propertydef used_fraction(self) -> Optional[float]:- """Fraction of the subscription cap consumed, in [0.0, 1.0].-- Computable only when ``subscription_limit_micros`` is a truthy (non-zero,- non-None) int. Guarded on the LIMIT FIELD, not ``denominator_kind`` β- the limit field is the real denominator; ``denominator_kind`` is metadata.- Returns None when there is no computable denominator (no limit, or limit==0).- """- if not isinstance(self.subscription_limit_micros, int):- return None- if self.subscription_limit_micros <= 0:+ """Fraction of the subscription cap consumed, in [0.0, 1.0]; None without a+ computable denominator. Guarded on the LIMIT FIELD (the real denominator),+ not ``denominator_kind`` (metadata)."""+ if not isinstance(self.subscription_limit_micros, int) or self.subscription_limit_micros <= 0:return Noneused = self.subscription_limit_micros - self.subscription_microsreturn max(0.0, min(1.0, used / self.subscription_limit_micros))-# ββ Credits policy constants βββββββββββββββββββββββββββββββββββββββββββββββββ-# Switching credits notices from stickyβTTL later would also require wiring a-# paired *_TTL_MS companion for each notice kind β the field exists on AgentNotice-# but is not yet plumbed through the policy loop.-+# ββ Credits policy constants. Switching notices stickyβTTL later also needs a+# paired *_TTL_MS per notice kind (AgentNotice has the field; not plumbed yet).CREDITS_NOTICE_KIND = "sticky" # v1: credits notices are stickyCREDITS_RESTORED_TTL_MS = 8000 # the only TTL notice in v1 (depletion-recovery confirmation)-# Usage-gauge bands (ascending). Each is (threshold_fraction, level, label_pct).-# The notice shows the HIGHEST band the current used_fraction has reached β a single-# escalating status-bar line (50 β 75 β 90), not three stacked notices. Crossing the-# next band up replaces the line; recovering below a band steps it back down. Edit-# this list to retune the bands; the policy derives everything from it.-CREDITS_USAGE_BANDS: tuple[tuple[float, str, int], ...] = (- (0.50, "info", 50),- (0.75, "warn", 75),- (0.90, "warn", 90),-)+# Usage-gauge bands (ascending): (threshold_fraction, level, label_pct). One+# escalating line showing the HIGHEST band reached (50 β 75 β 90); crossing up+# replaces it, recovering steps it down. The policy derives everything from it.+CREDITS_USAGE_BANDS: tuple[tuple[float, str, int], ...] = ((0.50, "info", 50), (0.75, "warn", 75), (0.90, "warn", 90))CREDITS_USAGE_KEY = "credits.usage" # single key for the escalating usage notice-# Minimum subscription balance that counts as "grant not yet spent" for the-# grant_spent crossing gate (see evaluate_credits_notices). 1Β’: portal-seeded-# states derive micros from float dollars and can carry sub-cent residue where-# the inference headers report exactly 0 β without this floor such a seed-# opens the gate and the first header re-creates the at-open nag.+# Min subscription balance counting as "grant not yet spent" for the grant_spent+# gate. 1Β’: portal-seeded states (float dollars β micros) can carry sub-cent+# residue where headers report 0 β without the floor such a seed opens the gate+# and the first header re-creates the at-open nag.GRANT_UNSPENT_MIN_MICROS = 10_000def new_credits_latch() -> dict:- """Fresh notice latch in the shape :func:`evaluate_credits_notices` expects.-- The policy owns this schema β every producer (agent build, lazy re-init,- tests) must build the latch through here so a new gate key lands everywhere- at once instead of drifting across hand-rolled literals."""- return {- "active": set(),- "seen_below_90": False,- "usage_band": None,- "seen_grant_unspent": False,- }---# ββ AgentNotice (out-of-band notice payload; driver-agnostic) ββββββββββββββββ+ """Fresh notice latch for :func:`evaluate_credits_notices`. Every producer must+ build it here so a new gate key lands everywhere at once."""+ return {"active": set(), "seen_below_90": False, "usage_band": None, "seen_grant_unspent": False}@dataclassclass AgentNotice:- """A structured, driver-agnostic out-of-band notice.-- The agent fires these via ``AIAgent.notice_callback`` (and clears them via- ``notice_clear_callback``); each driver renders it its own way β the TUI as a- status-bar override, the CLI as a console line, etc. v1 credits notices are all- ``kind="sticky"``; ``kind``/``ttl_ms`` are kept fully expressive so a future- config/slash-command can switch them to TTL without touching the policy (a- single default seam β see L4).- """+ """Driver-agnostic out-of-band notice, fired via ``AIAgent.notice_callback``+ (cleared via ``notice_clear_callback``); each driver renders its own way.+ ``kind``/``ttl_ms`` stay expressive so a future config can switch v1's+ sticky credits notices to TTL without touching the policy."""text: strlevel: str = "info" # info | warn | error | success@@ -215,39 +150,26 @@ class AgentNotice:id: Optional[str] = None-# ββ is_free_tier_model (local-data-only free-model check) ββββββββββββββββββββ+def _sticky_notice(text: str, level: str, key: str) -> AgentNotice:+ return AgentNotice(text=text, level=level, kind=CREDITS_NOTICE_KIND, key=key, id=key)def is_free_tier_model(model: str, base_url: str = "") -> bool:"""Return True when *model* is a Nous free-tier model, using ONLY local data.- Two signals, both zero-network:-- 1. The ``:free`` suffix β the canonical Nous free SKU marker (e.g.- ``nvidia/nemotron-3-ultra:free``). Free by construction on the API side- (spend is forced to 0 for ``:free`` ids).- 2. The ``stealth/`` prefix β Nous stealth-preview SKUs (e.g.- ``stealth/ox-alpha``) are free-tier but carry no ``:free`` suffix. Spend- is forced to zero server-side, so these are also free by construction.- 3. A peek into the in-process pricing cache in ``hermes_cli.models``- (populated when the model picker fetched ``/v1/models`` pricing for- *base_url*). PEEK ONLY β a cache miss never triggers a fetch. This is- CLI/TUI-session best-effort: gateway sessions never run the picker's- pricing fetch, so suppression there rests entirely on the ``:free``- suffix and ``stealth/`` prefix.-- Fail-open to False (the depleted notice still shows) on any error: wrongly- showing the warning is recoverable noise; wrongly hiding it on a paid model- would mask a real billing block.+ Zero-network signals: (1) ``:free`` suffix β canonical Nous free SKU marker;+ (2) ``stealth/`` prefix β stealth-preview SKUs are free without the suffix+ (naming-convention trust: a PAID ``stealth/`` model would wrongly suppress+ the banner); (3) a PEEK into ``hermes_cli.models``' pricing cache (filled by+ the model picker; a miss never fetches β gateway sessions never run the+ picker, so there only 1-2 apply).++ Fail-open to False (depleted notice still shows): a wrong warning is+ recoverable noise; hiding it on a paid model masks a real block."""if not model:return False- if model.endswith(":free"):- return True- # Stealth-preview SKUs are free-tier but carry no ``:free`` suffix (see- # docstring point 2). Naming-convention trust: if a PAID model ever shipped- # under ``stealth/`` this would wrongly suppress the banner on it.- if model.startswith("stealth/"):+ if model.endswith(":free") or model.startswith("stealth/"):return Trueif not base_url:return False@@ -263,140 +185,85 @@ def is_free_tier_model(model: str, base_url: str = "") -> bool:return False-# ββ evaluate_credits_notices (pure reconciliation function) ββββββββββββββββββ--def evaluate_credits_notices(- state: CreditsState,- latch: dict,- *,- model_is_free: bool = False,+ state: CreditsState, latch: dict, *, model_is_free: bool = False,) -> tuple[list[AgentNotice], list[str]]:- """Reconcile credits notices against the latch. Mutates ``latch`` IN PLACE.-- latch = {"active": set[str], "seen_below_90": bool, "usage_band": Optional[int],- "seen_grant_unspent": bool}.-- ``model_is_free``: True when the session's active model is a Nous free-tier- model (see :func:`is_free_tier_model`). Suppresses the ``credits.depleted``- notice β a depleted account on a free model can keep inferencing, so the- error banner is noise (and confuses free-tier users who never had credits).- Suppression does NOT emit the "restored" success notice; that fires only on- a genuine ``paid_access`` flip back to True.+ """Reconcile credits notices against the latch (see :func:`new_credits_latch`).+ Mutates ``latch`` IN PLACE. Pure β no I/O, no agent/run_agent imports.- Returns ``(to_show: list[AgentNotice], to_clear: list[str])``.- Caller emits to_clear FIRST, then to_show.+ ``model_is_free`` (see :func:`is_free_tier_model`) suppresses+ ``credits.depleted`` β a depleted account on a free model keeps inferencing,+ so the banner is noise. Suppression does NOT emit "restored"; that fires+ only on a genuine ``paid_access`` flip back to True.- Pure function β no I/O, no agent/run_agent imports.+ Returns ``(to_show, to_clear)``; caller emits to_clear FIRST, then to_show."""to_show: list[AgentNotice] = []to_clear: list[str] = []-uf = state.used_fraction- # Crossing latch: once we've observed uf below the LOWEST band, escalating- # usage notices may fire. This prevents a brand-new session that opens- # mid-range from firing spuriously on the first observation (the cold-start- # seed primes this explicitly when it WANTS an open-high warning).- _lowest_band = CREDITS_USAGE_BANDS[0][0]- if uf is not None and uf < _lowest_band:- latch["seen_below_90"] = True # gate opened: usage-band notices may now fire-- # Grant-spent crossing gate: grant_spent may fire only after this session- # has OBSERVED the grant meaningfully unspent (β₯1Β’ left β see- # GRANT_UNSPENT_MIN_MICROS). Opening at grant-spent is a steady STATE, not- # an event β /usage carries it; only a live in-session crossing announces.- # Unlike seen_below_90, seeds must NOT prime this gate.- if (- uf is not None- and uf < 1.0- and state.subscription_micros >= GRANT_UNSPENT_MIN_MICROS- ):- latch["seen_grant_unspent"] = True+ # Crossing latch: band notices fire only once uf was observed below the LOWEST+ # band, so a session opening mid-range doesn't fire on its first observation+ # (the cold-start seed primes this when it WANTS an open-high warning).+ if uf is not None and uf < CREDITS_USAGE_BANDS[0][0]:+ latch["seen_below_90"] = True+ # Grant-spent gate: fires only after this session OBSERVED the grant unspent+ # (β₯1Β’). Opening at grant-spent is a steady STATE (/usage carries it), not an+ # event. Unlike seen_below_90, seeds must NOT prime this gate.+ if uf is not None and uf < 1.0 and state.subscription_micros >= GRANT_UNSPENT_MIN_MICROS:+ latch["seen_grant_unspent"] = Trueactive = latch["active"]- # ββ Conditions βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ- # Highest band whose threshold the current usage has reached (None below all).+ # Highest band reached (ascending β last match wins); None below all.current_band: Optional[tuple[float, str, int]] = Noneif uf is not None:- for band in CREDITS_USAGE_BANDS: # ascending β last match wins = highest+ for band in CREDITS_USAGE_BANDS:if uf >= band[0]:current_band = band- # Top-up suppression: when the account holds purchased (top-up) credits,- # the subscription-cap gauge is the wrong denominator β warning "90% used"- # at a user sitting on $50 of top-up is noise (and it previously stuck- # PERMANENTLY alongside grant_spent at >=100%). Suppress the usage band- # entirely; the cap-reached case is covered by the grant_spent info notice- # below, which already names the remaining top-up balance. A top-up landing- # mid-session flips current_band β None and the clear path below removes- # any showing band line.+ # Top-up suppression: with purchased credits the cap gauge is the wrong+ # denominator ("90% used" on $50 of top-up is noise; it used to stick+ # PERMANENTLY beside grant_spent at >=100%). grant_spent below covers the+ # cap-reached case; a mid-session top-up flips current_band β None and the+ # clear path removes the band line.if state.purchased_micros > 0:current_band = Nonegrant_cond = (- state.denominator_kind == "subscription_cap"- and uf is not None- and uf >= 1.0- and state.purchased_micros > 0+ state.denominator_kind == "subscription_cap" and uf is not None and uf >= 1.0 and state.purchased_micros > 0)depleted_cond = not state.paid_access- # ββ usage gauge (escalating single notice: 50 β 75 β 90) ββββββββββββββββββ- # Show only the highest crossed band; replace the line when the band changes- # (climb or step-down on recovery); clear entirely when usage drops below the- # lowest band or the denominator disappears (uf is None).- shown_band = latch.get("usage_band") # the pct label currently displayed, or None+ # ββ usage gauge: highest crossed band only; replace on band change (climb or+ # step-down); clear below the lowest band or when the denominator vanishes.+ shown_band = latch.get("usage_band")target_band = current_band[2] if (current_band and latch["seen_below_90"]) else Noneif target_band != shown_band:if CREDITS_USAGE_KEY in active:to_clear.append(CREDITS_USAGE_KEY)active.discard(CREDITS_USAGE_KEY)if target_band is not None:- # Belt-and-suspenders: a producer could set subscription_limit_micros- # without subscription_limit_usd. Render "$?" rather than "$None".+ # Absolute dollars used (a bare "N%" is only meaningful against a Nous+ # cap): cap β remaining in micros, clamped [0, cap]; "$?" if a producer+ # set the limit without its *_usd. Re-emits on band change only._cap_usd = state.subscription_limit_usd or "?"_level = current_band[1] # type: ignore[index] (current_band set when target_band set)- # Report absolute dollars used, not a bare "N% used": the percentage is- # only meaningful against a Nous subscription cap (no cap β never fires),- # so dollars are clearer and don't imply a universal %. Used = cap β- # remaining (micros, money-safe), clamped to [0, cap]. Re-emits on band- # change (50 β 75 β 90), not every turn β a snapshot, not a live ticker._lim = state.subscription_limit_micros or 0_used_micros = max(0, min(_lim, _lim - state.subscription_micros))_used_usd = f"{_used_micros / 1_000_000:.2f}" if _lim else "?"_glyph = "β " if _level == "warn" else "β’"to_show.append(- AgentNotice(- text=f"{_glyph} You've used ${_used_usd} of your ${_cap_usd} cap",- level=_level,- kind=CREDITS_NOTICE_KIND,- key=CREDITS_USAGE_KEY,- id=CREDITS_USAGE_KEY,- )+ _sticky_notice(f"{_glyph} You've used ${_used_usd} of your ${_cap_usd} cap", _level, CREDITS_USAGE_KEY))active.add(CREDITS_USAGE_KEY)latch["usage_band"] = target_band- # ββ grant_spent ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ- # The crossing gate guards only the SHOW and is CONSUMED by it β one- # announcement per crossing. A header flicker (uf β None β back to 1.0)- # clears the sticky line via grant_cond but cannot re-announce; only a- # renewal that re-opens the gate (a fresh β₯1Β’ observation) arms the next- # announcement. .get(): default closed for any hand-built latch missing- # the key, so a first observation can never fire this notice.- if (- grant_cond- and "credits.grant_spent" not in active- and latch.get("seen_grant_unspent", False)- ):+ # ββ grant_spent: the gate guards only the SHOW and is CONSUMED by it β one+ # announcement per crossing. A header flicker (uf β None β 1.0) clears the+ # line but cannot re-announce; only a renewal re-opening the gate (fresh β₯1Β’+ # observation) arms the next. .get(): default closed for hand-built latches.+ if grant_cond and "credits.grant_spent" not in active and latch.get("seen_grant_unspent", False):to_show.append(- AgentNotice(- text=f"β’ Grant spent Β· ${state.purchased_usd} top-up left",- level="info",- kind=CREDITS_NOTICE_KIND,- key="credits.grant_spent",- id="credits.grant_spent",- )+ _sticky_notice(f"β’ Grant spent Β· ${state.purchased_usd} top-up left", "info", "credits.grant_spent"))active.add("credits.grant_spent")latch["seen_grant_unspent"] = False@@ -404,313 +271,166 @@ def evaluate_credits_notices(to_clear.append("credits.grant_spent")active.discard("credits.grant_spent")- # ββ depleted βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ- # Suppressed while the active model is free: inference still works there,- # so the error banner would just alarm users (free-tier users especially,- # who never had paid credits to "lose").+ # ββ depleted: suppressed while the model is free (inference still works).show_depleted = depleted_cond and not model_is_freeif show_depleted and "credits.depleted" not in active:- to_show.append(- AgentNotice(- text="β Credit access paused Β· run /topup to top up",- level="error",- kind=CREDITS_NOTICE_KIND,- key="credits.depleted",- id="credits.depleted",- )- )+ to_show.append(_sticky_notice("β Credit access paused Β· run /topup to top up", "error", "credits.depleted"))active.add("credits.depleted")elif "credits.depleted" in active and not show_depleted:to_clear.append("credits.depleted")active.discard("credits.depleted")if not depleted_cond:- # Genuine recovery (paid_access flipped back True): also emit the- # success notice. A clear caused by switching to a free model while- # still depleted must NOT claim access was restored.- to_show.append(- AgentNotice(- text="β Credit access restored",- level="success",- kind="ttl",- ttl_ms=CREDITS_RESTORED_TTL_MS,- key="credits.restored",- id="credits.restored",- )- )-+ # Genuine recovery only β switching to a free model while still+ # depleted must NOT claim access was restored.+ to_show.append(AgentNotice(+ text="β Credit access restored", level="success", kind="ttl",+ ttl_ms=CREDITS_RESTORED_TTL_MS, key="credits.restored", id="credits.restored",+ ))return (to_show, to_clear)-# ββ parse_credits_headers ββββββββββββββββββββββββββββββββββββββββββββββββββββ+# (field, header, signed) β required micros fields; only subscription may be negative.+_MICROS_FIELDS: tuple[tuple[str, str, bool], ...] = (+ ("remaining_micros", "x-nous-credits-remaining-micros", False),+ ("subscription_micros", "x-nous-credits-subscription-micros", True),+ ("rollover_micros", "x-nous-credits-rollover-micros", False),+ ("purchased_micros", "x-nous-credits-purchased-micros", False), ("as_of_ms", "x-nous-credits-as-of-ms", False),+)+_USD_FIELDS: tuple[tuple[str, str], ...] = (+ ("remaining_usd", "x-nous-credits-remaining-usd"), ("subscription_usd", "x-nous-credits-subscription-usd"),+ ("purchased_usd", "x-nous-credits-purchased-usd"),+)+# (field, header, default-when-absent) β "true"/"false" (case-insensitive) STRING flags.+_BOOL_FIELDS: tuple[tuple[str, str, bool], ...] = (+ ("paid_access", "x-nous-credits-paid-access", True), # absent β fail-open (assume access)+ ("tool_pool_gated_off", "x-nous-tool-pool-gated-off", False),+)-def parse_credits_headers(- headers: Mapping[str, str],- provider: str = "",-) -> Optional[CreditsState]:+def parse_credits_headers(headers: Mapping[str, str], provider: str = "") -> Optional[CreditsState]:"""Parse x-nous-credits-* (and x-nous-tool-pool-*) headers into a CreditsState.- Returns None (miss) on ANY of:- - No ``x-nous-credits-version`` header present.- - Version != 1 (> 1 also emits a one-time logger.warning).- - Any ``*_micros`` field is non-integer, or negative for a non-subscription field.- - Any ``*_usd`` field doesn't match ``^-?\\d+\\.\\d{2}$``.- - ``denominator_kind`` is not in {"subscription_cap", "none"}.- - ``paid_access`` / ``tool_pool_gated_off`` is not exactly "true"/"false".- - ``as_of_ms`` is not a valid integer.- - Any unexpected exception.+ Returns None (miss) on ANY of: no ``x-nous-credits-version`` header; version+ != 1 (> 1 also warns once); a ``*_micros``/``as_of_ms`` field non-integer or+ negative (subscription excepted); a ``*_usd`` not matching+ ``^-?\\d+\\.\\d{2}$``; ``denominator_kind`` outside {"subscription_cap",+ "none"}; ``paid_access``/``tool_pool_gated_off`` not exactly "true"/"false";+ any unexpected exception.Fail-open on the subscription_limit pair: a half-pair (only -micros or only- -usd present) is treated as both-absent; the overall parse STILL SUCCEEDS- but with subscription_limit_micros/usd both None.+ -usd) is treated as both-absent β the parse STILL SUCCEEDS with both None."""global _version_warning_emitted-try:- # Cheap probe before the full lowercase copy: bail when the version- # sentinel header is absent (the common case for non-Nous providers, on- # every API call) β skips allocating a dict over the whole response's- # headers on the hot path, while preserving case-insensitivity. Behaviour- # is identical: a missing version header was already a None return below.+ # Cheap probe before the lowercase copy (header names are case-insensitive):+ # bail when the version header is absent β the hot path for non-Nous providers.if not any(k.lower() == "x-nous-credits-version" for k in headers):return None- # Normalize to lowercase so lookups work regardless of how the server- # capitalises headers (HTTP header names are case-insensitive per RFC 7230).lowered = {k.lower(): v for k, v in headers.items()}-- # ββ Version check ββββββββββββββββββββββββββββββββββββββββββββββββββββ- # Must be present and exactly 1; > 1 warns once then returns None.- version_raw = lowered.get("x-nous-credits-version")- if version_raw is None:- return None- version_val = _safe_int(version_raw)+ version_val = _safe_int(lowered.get("x-nous-credits-version"))if version_val is _SENTINEL:return Noneif version_val != 1:if version_val > 1 and not _version_warning_emitted:_version_warning_emitted = True- logger.warning(- "credits header version %d unsupported, ignoring β update Hermes",- version_val,- )- return None-- # ββ Helper: parse a required non-negative int field (fail β None) βββ- def _req_nonneg(key: str) -> Any:- raw = lowered.get(key)- val = _safe_int(raw)- if val is _SENTINEL:- return _SENTINEL- if val < 0:- return _SENTINEL- return val-- # ββ Helper: parse a required int field that may be negative (subscription only) β- def _req_int(key: str) -> Any:- raw = lowered.get(key)- val = _safe_int(raw)- if val is _SENTINEL:- return _SENTINEL- return val-- # ββ Parse micros fields ββββββββββββββββββββββββββββββββββββββββββββββ- remaining_micros = _req_nonneg("x-nous-credits-remaining-micros")- if remaining_micros is _SENTINEL:- return None-- subscription_micros = _req_int("x-nous-credits-subscription-micros")- if subscription_micros is _SENTINEL:+ logger.warning("credits header version %d unsupported, ignoring β update Hermes", version_val)return None-- rollover_micros = _req_nonneg("x-nous-credits-rollover-micros")- if rollover_micros is _SENTINEL:- return None-- purchased_micros = _req_nonneg("x-nous-credits-purchased-micros")- if purchased_micros is _SENTINEL:- return None-- # tool_pool_micros is OPTIONAL: absent β 0 (default); present-but-invalid β None (miss).- _tp_raw = lowered.get("x-nous-tool-pool-micros")- if _tp_raw is None:- tool_pool_micros = 0- else:- _tp_val = _safe_int(_tp_raw)- if _tp_val is _SENTINEL or _tp_val < 0:+ fields: dict[str, Any] = {}+ for name, key, signed in _MICROS_FIELDS:+ val = _safe_int(lowered.get(key))+ if val is _SENTINEL or (not signed and val < 0):return None- tool_pool_micros = _tp_val-- as_of_ms = _req_nonneg("x-nous-credits-as-of-ms")- if as_of_ms is _SENTINEL:- return None-- # ββ Validate USD strings βββββββββββββββββββββββββββββββββββββββββββββ- remaining_usd = lowered.get("x-nous-credits-remaining-usd", "")- if not _validate_usd(remaining_usd):- return None+ fields[name] = val- subscription_usd = lowered.get("x-nous-credits-subscription-usd", "")- if not _validate_usd(subscription_usd):- return None-- purchased_usd = lowered.get("x-nous-credits-purchased-usd", "")- if not _validate_usd(purchased_usd):+ # tool_pool_micros is OPTIONAL: absent β 0; present-but-invalid β miss.+ _tp_raw = lowered.get("x-nous-tool-pool-micros")+ _tp_val = 0 if _tp_raw is None else _safe_int(_tp_raw)+ if _tp_val is _SENTINEL or _tp_val < 0:return None+ fields["tool_pool_micros"] = _tp_val+ for name, key in _USD_FIELDS:+ val = lowered.get(key, "")+ if not _validate_usd(val):+ return None+ fields[name] = val- # ββ subscription_limit_* PAIRED + OPTIONAL βββββββββββββββββββββββββββ- # Both present β validate both; half-pair β treat BOTH as absent (parse- # still succeeds, just with no limit pair).+ # subscription_limit_* PAIRED + OPTIONAL: both present β validate both+ # (any invalid β miss); half-pair or both absent β both None, parse continues.sub_limit_micros_raw = lowered.get("x-nous-credits-subscription-limit-micros")sub_limit_usd_raw = lowered.get("x-nous-credits-subscription-limit-usd")-- subscription_limit_micros: Optional[int] = None- subscription_limit_usd: Optional[str] = None-if sub_limit_micros_raw is not None and sub_limit_usd_raw is not None:- # Both present β validate both; any invalid β return None (bad data)lm = _safe_int(sub_limit_micros_raw)- if lm is _SENTINEL:- return None- if lm < 0:- return None- if not _validate_usd(sub_limit_usd_raw):+ if lm is _SENTINEL or lm < 0 or not _validate_usd(sub_limit_usd_raw):return None- subscription_limit_micros = lm- subscription_limit_usd = sub_limit_usd_raw- # else: half-pair or both absent β leave both None, parse continues-- # ββ denominator_kind βββββββββββββββββββββββββββββββββββββββββββββββββ+ fields["subscription_limit_micros"] = lm+ fields["subscription_limit_usd"] = sub_limit_usd_rawdenominator_kind = lowered.get("x-nous-credits-denominator-kind", "none")if denominator_kind not in _VALID_DENOMINATOR_KINDS:return None-- # ββ paid_access / tool_pool_gated_off ββββββββββββββββββββββββββββββββ- # Both must be exactly "true" or "false" (case-insensitive). An absent- # paid_access header β fail-open (assume access); absent tool_pool_gated_off- # β default False. Present but invalid β return None.- if "x-nous-credits-paid-access" in lowered:- pa_raw = lowered["x-nous-credits-paid-access"].strip().lower()- if pa_raw not in ("true", "false"):+ for name, key, default in _BOOL_FIELDS:+ if key not in lowered:+ fields[name] = default+ continue+ raw = lowered[key].strip().lower()+ if raw not in ("true", "false"):return None- paid_access = pa_raw == "true"- else:- paid_access = True # fail-open-- if "x-nous-tool-pool-gated-off" in lowered:- tpgo_raw = lowered["x-nous-tool-pool-gated-off"].strip().lower()- if tpgo_raw not in ("true", "false"):- return None- tool_pool_gated_off = tpgo_raw == "true"- else:- tool_pool_gated_off = False-- # ββ disabled_reason: header omitted when null ββββββββββββββββββββββββ- disabled_reason = lowered.get("x-nous-credits-disabled-reason") # None if absent-+ fields[name] = raw == "true"return CreditsState(version=version_val,- remaining_micros=remaining_micros,- remaining_usd=remaining_usd,- subscription_micros=subscription_micros,- subscription_usd=subscription_usd,- subscription_limit_micros=subscription_limit_micros,- subscription_limit_usd=subscription_limit_usd,- rollover_micros=rollover_micros,- purchased_micros=purchased_micros,- purchased_usd=purchased_usd,- tool_pool_micros=tool_pool_micros,- tool_pool_gated_off=tool_pool_gated_off,denominator_kind=denominator_kind,- paid_access=paid_access,- disabled_reason=disabled_reason,- as_of_ms=as_of_ms,+ disabled_reason=lowered.get("x-nous-credits-disabled-reason"), # None if absent (omitted when null)captured_at=time.time(),from_header=True,+ **fields,)-except Exception:- # Fail-open β miss, but leave a breadcrumb so a parser/import regression- # (feature silently dead) is distinguishable from a legitimate no-headers- # response in agent.log, without needing a dev flag.+ # Fail-open β miss; breadcrumb distinguishes a parser regression from a+ # legitimate no-headers response.logger.debug("credits βΈ parse_credits_headers raised (fail-open miss)", exc_info=True)return None-# ββ Dev test fixtures (HERMES_DEV_CREDITS_FIXTURE) βββββββββββββββββββββββββββ-# Throwaway dev scaffolding: trigger any notice state on demand for testing,-# without real spend or Redis seeding. Set HERMES_DEV_CREDITS_FIXTURE to either a-# state NAME (fixed for the session) or a FILE PATH whose contents are a state-# name (re-read every turn β flip states live: `echo depleted > /tmp/cf`, take a-# turn; `echo healthy > /tmp/cf`, take a turn β recovery).-#-# A fixture drives THREE surfaces uniformly, so the whole credits UX is testable-# offline: (1) the per-turn capture/notice path (_capture_credits), (2) the-# cold-start seed at session open (conversation_loop β depletion/warn90 hydrate-# immediately), and (3) the /usage view (nous_credits_lines renders the fixture).-# `clear` / `none` / unset β real behaviour. Delete with the rest of the-# HERMES_DEV_CREDITS scaffolding.+# ββ Dev fixtures (HERMES_DEV_CREDITS_FIXTURE): throwaway scaffolding to trigger+# any notice state without real spend. Value is a state NAME or a FILE PATH whose+# contents are a name (re-read every turn β `echo depleted > /tmp/cf` flips live).+# Drives the per-turn capture/notice path, the cold-start seed, and /usage.+def _fixture(remaining: str, subscription: str, limit: Optional[str] = None, purchased: Optional[str] = None,+ *, paid: bool = True, reason: Optional[str] = None) -> dict:+ """Fixture spec from *_usd strings; micros derived exactly (Decimal)."""+ from decimal import Decimal+ d: dict = {}+ for field, usd in (("remaining", remaining), ("subscription", subscription),+ ("subscription_limit", limit), ("purchased", purchased)):+ if usd is not None:+ d[f"{field}_micros"], d[f"{field}_usd"] = int(Decimal(usd) * 1_000_000), usd+ if limit is not None:+ d["denominator_kind"] = "subscription_cap"+ d["paid_access"] = paid+ if reason is not None:+ d["disabled_reason"] = reason+ return d++_DEV_FIXTURES: dict[str, dict] = {- "healthy": dict( # used_fraction ~0.1, paid β no notice (recovery target)- remaining_micros=30_340_000, remaining_usd="30.34",- subscription_micros=18_000_000, subscription_usd="18.00",- subscription_limit_micros=20_000_000, subscription_limit_usd="20.00",- purchased_micros=12_340_000, purchased_usd="12.34",- denominator_kind="subscription_cap", paid_access=True,- ),- "sub_50pct": dict( # used_fraction == 0.5 β credits.usage band 50 (info)- remaining_micros=10_000_000, remaining_usd="10.00",- subscription_micros=10_000_000, subscription_usd="10.00",- subscription_limit_micros=20_000_000, subscription_limit_usd="20.00",- denominator_kind="subscription_cap", paid_access=True,- ),- "sub_75pct": dict( # used_fraction == 0.75 β credits.usage band 75 (warn)- remaining_micros=5_000_000, remaining_usd="5.00",- subscription_micros=5_000_000, subscription_usd="5.00",- subscription_limit_micros=20_000_000, subscription_limit_usd="20.00",- denominator_kind="subscription_cap", paid_access=True,- ),- "sub_90pct": dict( # used_fraction == 0.9 β credits.usage band 90 (warn)- remaining_micros=2_000_000, remaining_usd="2.00",- subscription_micros=2_000_000, subscription_usd="2.00",- subscription_limit_micros=20_000_000, subscription_limit_usd="20.00",- denominator_kind="subscription_cap", paid_access=True,- ),- "grant_exhausted": dict( # uf == 1.0 + purchased>0 β SILENT at open (crossing-gated);- # flip healthy β grant_exhausted via the fixture-file path to see credits.grant_spent- remaining_micros=12_340_000, remaining_usd="12.34",- subscription_micros=0, subscription_usd="0.00",- subscription_limit_micros=20_000_000, subscription_limit_usd="20.00",- purchased_micros=12_340_000, purchased_usd="12.34",- denominator_kind="subscription_cap", paid_access=True,- ),- "depleted": dict( # paid_access False β credits.depleted (sticky)- remaining_micros=0, remaining_usd="0.00",- subscription_micros=0, subscription_usd="0.00",- purchased_micros=0, purchased_usd="0.00",- paid_access=False, disabled_reason="out_of_credits",- ),- "debt": dict( # subscription in debt (negative, the only signed field) β depleted- remaining_micros=0, remaining_usd="0.00",- subscription_micros=-5_000_000, subscription_usd="-5.00",- subscription_limit_micros=20_000_000, subscription_limit_usd="20.00",- purchased_micros=0, purchased_usd="0.00",- denominator_kind="subscription_cap", paid_access=False,- disabled_reason="out_of_credits",- ),+ "healthy": _fixture("30.34", "18.00", "20.00", "12.34"), # used_fraction ~0.1, paid β no notice (recovery target)+ "sub_50pct": _fixture("10.00", "10.00", "20.00"), # used_fraction == 0.5 β credits.usage band 50 (info)+ "sub_75pct": _fixture("5.00", "5.00", "20.00"), # used_fraction == 0.75 β band 75 (warn)+ "sub_90pct": _fixture("2.00", "2.00", "20.00"), # used_fraction == 0.9 β band 90 (warn)+ # uf == 1.0 + purchased>0 β SILENT at open (crossing-gated); flip healthy β+ # grant_exhausted via the fixture-file path to see credits.grant_spent+ "grant_exhausted": _fixture("12.34", "0.00", "20.00", "12.34"),+ "depleted": _fixture("0.00", "0.00", None, "0.00", paid=False, reason="out_of_credits"), # β credits.depleted+ # subscription in debt (negative, the only signed field) β depleted+ "debt": _fixture("0.00", "-5.00", "20.00", "0.00", paid=False, reason="out_of_credits"),}def dev_fixture_credits_state() -> Optional[CreditsState]:- """Return a fixture CreditsState for HERMES_DEV_CREDITS_FIXTURE, or None.-- The env value is a state name, OR a path to a file whose contents are a state- name (re-read each call β flip states live without a restart). Unknown name /- "clear" / "none" / unset β None (normal behaviour). Throwaway test scaffolding.+ """Return a fixture CreditsState for HERMES_DEV_CREDITS_FIXTURE, or None+ (unknown name / "clear" / "none" / unset β None).- Hard prod-leak guard: a fixture applies ONLY when the dev flag HERMES_DEV_CREDITS- is also on, so a stray HERMES_DEV_CREDITS_FIXTURE (leaked into a shell profile, a- container env, a launch plist, β¦) can never surface fabricated balances/notices- on a real account.+ Hard prod-leak guard: applies ONLY when HERMES_DEV_CREDITS is also on, so a+ stray fixture env var can never surface fabricated balances on a real account."""if not is_truthy_value(os.environ.get("HERMES_DEV_CREDITS")):return None@@ -727,50 +447,38 @@ def dev_fixture_credits_state() -> Optional[CreditsState]:spec = _DEV_FIXTURES.get(name.lower())if not spec:return None- # Stamp the fields the REAL parser always guarantees, so a fixture state is- # field-identical to a parse_credits_headers() result from equivalent headers- # (verified by the differential test): version is always 1, and purchased_usd- # is always a valid usd string (the parser rejects a missing/empty one, so a- # real zero-top-up account still carries "0.00"). Specs may override these.+ # Stamp what the REAL parser always guarantees so a fixture is field-identical+ # to a parse_credits_headers() result (differential test): version 1, and a+ # valid purchased_usd (a zero-top-up account still carries "0.00").merged = {"version": 1, "purchased_usd": "0.00", **spec}return CreditsState(**merged, from_header=True, captured_at=time.time())def _credits_state_from_account(info) -> Optional[CreditsState]:"""Map a NousPortalAccountInfo into a header-shaped CreditsState for the seed.-- Float account dollars β micros (plus a DISPLAY *_usd string β allowed, since- we're formatting account floats, NOT parsing a server-provided *_usd). Returns- None if the account can't yield a usable state (fail-open)."""+ Float account dollars β micros plus a DISPLAY *_usd (formatting account floats+ is allowed; parsing a server *_usd is not). Fail-open β None."""try:_acc = getattr(info, "paid_service_access_info", None)_sub = getattr(info, "subscription", None)- def _to_micros(dollars):- return int(round(dollars * 1_000_000)) if isinstance(dollars, (int, float)) else 0-- def _to_usd(dollars):- # DISPLAY formatting of an account float (not a server *_usd string);- # "" when absent so render/notice copy falls back gracefully.- return f"{dollars:.2f}" if isinstance(dollars, (int, float)) else ""-+ def _money(dollars) -> tuple[int, str]: # (micros, display usd); (0, "") when absent+ if isinstance(dollars, (int, float)):+ return int(round(dollars * 1_000_000)), f"{dollars:.2f}"+ return 0, ""+ _remaining = _money(getattr(_acc, "total_usable_credits", None))+ _sub_rem = _money(getattr(_acc, "subscription_credits_remaining", None))+ _purchased = _money(getattr(_acc, "purchased_credits_remaining", None))_monthly = getattr(_sub, "monthly_credits", None)- _has_cap = isinstance(_monthly, (int, float)) and _monthly > 0+ _cap = _money(_monthly) if isinstance(_monthly, (int, float)) and _monthly > 0 else (None, None)_paid = getattr(info, "paid_service_access", None)return CreditsState(- remaining_micros=_to_micros(getattr(_acc, "total_usable_credits", None)),- remaining_usd=_to_usd(getattr(_acc, "total_usable_credits", None)),- subscription_micros=_to_micros(getattr(_acc, "subscription_credits_remaining", None)),- subscription_usd=_to_usd(getattr(_acc, "subscription_credits_remaining", None)),- subscription_limit_micros=_to_micros(_monthly) if _has_cap else None,- subscription_limit_usd=_to_usd(_monthly) if _has_cap else None,- purchased_micros=_to_micros(getattr(_acc, "purchased_credits_remaining", None)),- purchased_usd=_to_usd(getattr(_acc, "purchased_credits_remaining", None)),- rollover_micros=_to_micros(getattr(_sub, "rollover_credits", None)),- denominator_kind="subscription_cap" if _has_cap else "none",- paid_access=_paid if isinstance(_paid, bool) else True,- from_header=False,- captured_at=time.time(),+ remaining_micros=_remaining[0], remaining_usd=_remaining[1], subscription_micros=_sub_rem[0],+ subscription_usd=_sub_rem[1], subscription_limit_micros=_cap[0], subscription_limit_usd=_cap[1],+ purchased_micros=_purchased[0], purchased_usd=_purchased[1],+ rollover_micros=_money(getattr(_sub, "rollover_credits", None))[0],+ denominator_kind="subscription_cap" if _cap[0] is not None else "none",+ paid_access=_paid if isinstance(_paid, bool) else True, from_header=False, captured_at=time.time(),)except Exception:logger.debug("credits βΈ seed accountβstate mapping failed", exc_info=True)@@ -779,20 +487,15 @@ def _credits_state_from_account(info) -> Optional[CreditsState]:def _hydrate_seed_state(agent, state) -> None:"""Install a seed CreditsState on the agent and fire the notice policy once.-- Sets _credits_state, latches session-start remaining, and primes the crossing- gate (the cold-start snapshot IS the first observation, so a session that opens- already in a band warns immediately β the live header path keeps true crossing- semantics), then emits. Safe to call from a worker thread: emit already runs- off-thread in the TUI build path."""+ Primes the crossing gate: the cold-start snapshot IS the first observation, so+ a session opening in a band warns immediately. Safe from a worker thread."""agent._credits_state = stateif getattr(agent, "_credits_session_start_micros", None) is None:agent._credits_session_start_micros = state.remaining_micros_latch = getattr(agent, "_credits_latch", None)if isinstance(_latch, dict) and state.used_fraction is not None:- # Prime ONLY seen_below_90 (open-high band warnings are wanted at open).- # Never prime seen_grant_unspent here: a seed observing grant-spent is a- # steady state, and priming it would revive the every-session nag.+ # Prime ONLY seen_below_90. Never prime seen_grant_unspent: a seed+ # observing grant-spent is a steady state; priming revives the nag._latch["seen_below_90"] = Trueemit = getattr(agent, "_emit_credits_notices", None)if callable(emit):@@ -800,37 +503,30 @@ def _hydrate_seed_state(agent, state) -> None:def seed_credits_at_session_start(agent) -> bool:- """Hydrate agent._credits_state from /api/oauth/account (or a dev fixture) and- fire the notice policy, so depletion / usage-band warnings show at session OPEN.+ """Hydrate agent._credits_state from the portal account (or a dev fixture) and+ fire the notice policy so warnings show at session OPEN. Shared by the+ TUI/desktop build ("ready") and first-turn setup (plain-CLI fallback).+ Idempotent once a seed or real header populated _credits_state.- Shared by (a) the TUI/desktop agent build (fires at "ready", before any message)- and (b) the first-turn conversation setup (fallback for plain CLI / when the- build path didn't seed). Idempotent: a second call is a no-op once a seed or a- real header has already populated _credits_state.-- Returns True if it seeded this call, False otherwise (not nous / already seeded /- fail-open error). Never raises β credits must never block session startup.+ Returns True iff it seeded this call. Never raises β credits must never block startup."""try:if getattr(agent, "provider", "") != "nous":return False- # Idempotent: don't re-seed if state already exists (seed or live header).if getattr(agent, "_credits_state", None) is not None:return False- fixture = Nonetry:fixture = dev_fixture_credits_state()except Exception:fixture = Noneif fixture is not None:- # Synchronous: a fixture is instant (no network), and tests rely on the- # state + notice landing before this returns.+ # Synchronous: a fixture is instant, and tests rely on the state ++ # notice landing before this returns._hydrate_seed_state(agent, fixture)return True- # Real portal fetch is FIRE-AND-FORGET: a slow/unreachable portal must never- # delay session "ready". A daemon thread hydrates + emits when it resolves,- # re-checking idempotency first (a live inference header may land before it).+ # FIRE-AND-FORGET: a slow portal must never delay "ready". The daemon+ # thread re-checks idempotency (a live header may land first).import threadingdef _bg_seed() -> None:@@ -844,12 +540,9 @@ def seed_credits_at_session_start(agent) -> bool:_hydrate_seed_state(agent, state)except Exception:logger.debug("credits βΈ session-start seed (background) failed", exc_info=True)-threading.Thread(target=_bg_seed, name="credits-seed", daemon=True).start()return Trueexcept Exception:- # Fail-open: any auth/portal hiccup leaves _credits_state as-is, never blocks.- # Innermost log across all four call sites (TUI build / CLI build / first- # turn / desktop), so a dead session-open seed is diagnosable in agent.log.+ # Innermost log across all call sites so a dead seed is diagnosable.logger.debug("credits βΈ session-start seed failed (fail-open)", exc_info=True)return Falsediff --git a/agent/fast_mode.py b/agent/fast_mode.pyindex b8121f6295f..b258b00d896 100644--- a/agent/fast_mode.py+++ b/agent/fast_mode.py@@ -1,17 +1,12 @@"""Bounded fast-mode windows (``/fast auto`` and ``/fast cold``).-``agent.service_tier`` is ``None`` (normal), ``"priority"`` (static fast),-``"auto"`` or ``"cold"``. The static value is pinned into-``agent.request_overrides`` at agent build time; the two bounded modes-instead open a wall-clock window at each user-turn boundary and layer the-provider's fast override onto the request kwargs only while it is open:--- ``auto`` β every user turn opens a window of ``agent.fast_auto_seconds``.-- ``cold`` β only the first turn of a session (no prior history) opens it.--Only per-request params (``service_tier`` / ``speed``) vary between requests;-the system prompt, tools, and messages are untouched, so the prompt cache is-preserved across the window boundary.+``agent.service_tier`` is ``None`` (normal), ``"priority"`` (static fast, pinned+into ``agent.request_overrides`` at build time), ``"auto"`` (every user turn opens+a window of ``agent.fast_auto_seconds``) or ``"cold"`` (only a session's first+turn, no prior history, opens it). The provider's fast override is layered onto+the request kwargs only while the window is open. Only per-request params+(``service_tier`` / ``speed``) vary β system prompt, tools, and messages are+untouched, so the prompt cache survives the boundary."""from __future__ import annotations@@ -44,19 +39,16 @@ def begin_turn(agent: Any, conversation_history: Any) -> None:def effective_request_overrides(agent: Any) -> dict[str, Any]:"""``agent.request_overrides`` plus the fast override while the window is open."""overrides = dict(getattr(agent, "request_overrides", None) or {})- if getattr(agent, "service_tier", None) not in BOUNDED_MODES:- return overrides- if time.monotonic() >= getattr(agent, "_fast_until", 0.0):+ if getattr(agent, "service_tier", None) not in BOUNDED_MODES or time.monotonic() >= getattr(+ agent, "_fast_until", 0.0+ ):return overridesfrom hermes_cli.models import resolve_fast_mode_overrides-base_url = getattr(agent, "base_url", None)if getattr(agent, "api_mode", None) == "anthropic_messages":base_url = getattr(agent, "_anthropic_base_url", None) or base_urlfast = resolve_fast_mode_overrides(- getattr(agent, "model", None),- provider=getattr(agent, "provider", None),- base_url=base_url,+ getattr(agent, "model", None), provider=getattr(agent, "provider", None), base_url=base_url)if fast:overrides.update(fast)diff --git a/agent/model_metadata.py b/agent/model_metadata.pyindex 7a2e344c772..7c7865c2119 100644--- a/agent/model_metadata.py+++ b/agent/model_metadata.py@@ -2714,11 +2714,8 @@ def get_model_context_length(# model has different limits per provider (claude-opus-4.6: 1M on# Anthropic, 128K on Copilot). Generic providers are inferred from the URL.effective_provider = provider- if not effective_provider or effective_provider in {"openrouter", "custom"}:- if base_url:- inferred = _infer_provider_from_url(base_url)- if inferred:- effective_provider = inferred+ if base_url and (not effective_provider or effective_provider in {"openrouter", "custom"}):+ effective_provider = _infer_provider_from_url(base_url) or effective_provider# 5a. Copilot live /models β account-specific models (claude-opus-4.6-1m)# absent from models.dev, and the provider-enforced limit for the rest.