The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(usage): report credential-pool usage per account
Brooklyn Nicholsond0e40fff3c34
diff --git a/agent/account_usage.py b/agent/account_usage.pyindex ad6f49dbda6..f1ae4fa74c5 100644--- a/agent/account_usage.py+++ b/agent/account_usage.py@@ -32,6 +32,10 @@ class AccountUsageWindow:used_percent: Optional[float] = Nonereset_at: Optional[datetime] = Nonedetail: Optional[str] = None+ # ``account``: exhausting this window exhausts the whole login (Codex session/weekly).+ # ``model``: the window caps only one model family (Anthropic Opus/Sonnet weekly) and can+ # never imply the account itself is out of quota.+ scope: str = "account"@dataclass(frozen=True)@@ -44,6 +48,10 @@ class AccountUsageSnapshot:windows: tuple[AccountUsageWindow, ...] = ()details: tuple[str, ...] = ()unavailable_reason: Optional[str] = None+ # Stable account identity of the credential the snapshot was fetched with (e.g. a decoded+ # Codex JWT principal), when the provider supports one. Never a secret; ``None`` = the+ # fetcher cannot tell accounts apart, so the snapshot belongs to the provider's legacy slot.+ identity: Optional[str] = None# Exact decoded provider response body (no headers/credentials) for integrations that need# fields Hermes does not normalize yet. Only populated by providers that fetch a JSON body.raw: Optional[dict] = None@@ -387,9 +395,11 @@ def _get_json(url: str, headers: dict[str, str], *, timeout: float) -> dict:def _usage_windows(- source: dict, mapping: tuple[tuple[str, str], ...], used_key: str, reset_key: str, *, fraction: bool = False+ source: dict, mapping: tuple[tuple[str, str], ...], used_key: str, reset_key: str, *, fraction: bool = False,+ model_scoped: frozenset[str] | set[str] = frozenset(),) -> list[AccountUsageWindow]:- """Build windows from ``source[key][used_key]``; ``fraction`` scales values <= 1 to percent."""+ """Build windows from ``source[key][used_key]``; ``fraction`` scales values <= 1 to percent.+ ``model_scoped`` keys build windows that cap only a model family, never the account."""windows: list[AccountUsageWindow] = []for key, label in mapping:window = source.get(key) or {}@@ -399,7 +409,10 @@ def _usage_windows(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))))+ windows.append(AccountUsageWindow(+ label=label, used_percent=used, reset_at=_parse_dt(window.get(reset_key)),+ scope="model" if key in model_scoped else "account",+ ))return windows@@ -431,6 +444,22 @@ def _plural(count: int) -> str:def _fetch_codex_account_usage(base_url: Optional[str] = None, api_key: Optional[str] = None,+) -> Optional[AccountUsageSnapshot]:+ return _fetch_codex_account_usage_impl(base_url, api_key, read_only=False)+++def _fetch_codex_account_usage_read_only(+ base_url: Optional[str] = None, api_key: Optional[str] = None,+) -> Optional[AccountUsageSnapshot]:+ """Picker-cache variant: a 401 is reported, never repaired. The live-agent path+ (``_fetch_codex_account_usage``) retries via a forced credential refresh because the+ session it serves owns that credential; a per-credential read of the pool must NOT+ rotate, refresh or mutate anything — it just marks that account unknown."""+ return _fetch_codex_account_usage_impl(base_url, api_key, read_only=True)+++def _fetch_codex_account_usage_impl(+ base_url: Optional[str] = None, api_key: Optional[str] = None, *, read_only: bool = False,) -> Optional[AccountUsageSnapshot]:token, resolved_base_url, account_id = _resolve_codex_usage_credentials(base_url, api_key)try:@@ -440,6 +469,9 @@ def _fetch_codex_account_usage(except httpx.HTTPStatusError as exc:if exc.response.status_code != 401:raise+ if read_only:+ # Never refresh/rotate on the picker's read-only path — surface the failure.+ raisetoken, resolved_base_url, account_id = _resolve_codex_usage_credentials(base_url, api_key, force_refresh=True,)@@ -458,7 +490,17 @@ def _fetch_codex_account_usage(elif credits.get("has_credits") and credits.get("unlimited"):details.append("Credits balance: unlimited")return _snapshot("openai-codex", "usage_api", windows, details, plan=_title_case_slug(payload.get("plan_type")),- raw=payload)+ identity=_codex_snapshot_identity(token), raw=payload)+++def _codex_snapshot_identity(token: str) -> Optional[str]:+ """Trusted per-account identity of a Codex credential: the decoded JWT principal+ (``chatgpt_account_id`` + ``sub``), never the token itself. Two credentials for one+ workspace member share it, so pool accounts are counted once, honestly."""+ from agent.credential_pool import _codex_principal_identity++ principal = _codex_principal_identity(token)+ return f"codex:{principal[0]}:{principal[1]}" if principal else None@dataclass(frozen=True)@@ -589,7 +631,12 @@ def redeem_codex_reset_credit(def _fetch_anthropic_account_usage(base_url: Optional[str] = None, api_key: Optional[str] = None) -> Optional[AccountUsageSnapshot]:- token = (resolve_anthropic_token() or "").strip()+ # An explicit api_key (live agent / per-credential pool read) must not be shadowed by+ # the ambient OAuth singleton: fetch_account_usage(base_url, api_key) promises to+ # report THAT credential's usage. An API key answers the OAuth usage endpoint with+ # 401, so only an OAuth-shaped token reaches the fetch.+ explicit = str(api_key or "").strip()+ token = explicit or (resolve_anthropic_token() or "").strip()if not token:return Noneif not _is_oauth_token(token):@@ -601,6 +648,7 @@ def _fetch_anthropic_account_usage(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,+ model_scoped={"seven_day_opus", "seven_day_sonnet"},)details: list[str] = []extra = payload.get("extra_usage") or {}@@ -652,6 +700,12 @@ _USAGE_FETCHERS: dict[str, Callable[[Optional[str], Optional[str]], Optional[Acc"openrouter": _fetch_openrouter_account_usage,}+# Picker per-credential variants: same parsers/fetch shape, but a failure is never repaired by+# rotating/refreshing a credential (see ``fetch_account_usage(read_only=True)``).+_READ_ONLY_USAGE_FETCHERS: dict[str, Callable[[Optional[str], Optional[str]], Optional[AccountUsageSnapshot]]] = {+ "openai-codex": _fetch_codex_account_usage_read_only,+}+# Wall-clock bound on a plugin profile's ``fetch_account_usage`` hook. The built-in fetchers above carry# their own httpx timeouts; a plugin hook is arbitrary code, and the gateway/TUI ``/usage`` paths await@@ -676,20 +730,33 @@ def _call_plugin_usage_hook(profile, base_url: Optional[str], api_key: Optional[def fetch_account_usage(provider: Optional[str], *, base_url: Optional[str] = None, api_key: Optional[str] = None,+ read_only: bool = False, identity_id: Optional[str] = None,) -> Optional[AccountUsageSnapshot]:from agent.account_usage_cache import remember_account_usage- fetcher = _USAGE_FETCHERS.get(str(provider or "").strip().lower())+ slug = str(provider or "").strip().lower()+ # The picker's per-credential path resolves variants that never rotate/refresh a credential+ # on failure (Codex 401), so a read cannot repair or bench a pool entry it does not own.+ fetcher = _READ_ONLY_USAGE_FETCHERS.get(slug) if read_only else None+ if fetcher is None:+ fetcher = _USAGE_FETCHERS.get(slug)+ import time as _time++ started = _time.monotonic()try:if fetcher:snapshot = fetcher(base_url, api_key)else:from providers import get_provider_profile- profile = get_provider_profile(str(provider or "").strip().lower())+ profile = get_provider_profile(slug)snapshot = _call_plugin_usage_hook(profile, base_url, api_key) if profile else Noneexcept Exception:return None# Every fetch (``/usage``, the per-turn ``session.usage``) keeps the picker's cache current.- remember_account_usage(provider, snapshot)+ # A per-credential fetch is remembered under its account slot only; the provider-wide fetch+ # keeps both the legacy gauge slot and (when the fetcher identifies the account) that+ # account's slot current.+ remember_account_usage(provider, snapshot, identity_id=identity_id, base_url=base_url,+ started_monotonic=started)return snapshotdiff --git a/agent/account_usage_cache.py b/agent/account_usage_cache.pyindex 1b57aaa5711..0358fd5c58b 100644--- a/agent/account_usage_cache.py+++ b/agent/account_usage_cache.py@@ -3,7 +3,14 @@Usage windows come from a provider API (:func:`agent.account_usage.fetch_account_usage`), so apicker reads this cache and asks for a background refresh instead of fetching inline. Every fetchlands here, including the one ``session.usage`` runs after each turn, so a picker is at most one-turn or one refresh interval behind. Keyed per profile home: one process may serve many profiles.+turn or one refresh interval behind.++Slots are keyed per profile home AND per account: one process may serve many profiles, and a+provider may have a pool of credentials whose usage must not contaminate each other. A fetcher+that can identify its account (a decoded Codex JWT principal) dedupes several credentials of one+account onto a single slot; fetchers that cannot get one slot per credential, never a+provider-wide singleton. The legacy provider slot (``identity_id=None``) remains the single-account+gauge: a per-turn or ``/usage`` fetch still lands there, so non-pooled chips are unchanged."""from __future__ import annotations@@ -11,24 +18,37 @@ from __future__ import annotationsimport threadingimport timefrom contextvars import copy_context-from typing import TYPE_CHECKING, Iterable, Optional+from typing import TYPE_CHECKING, Any, Iterable, Optionalif TYPE_CHECKING:from agent.account_usage import AccountUsageSnapshot# A picker opened again within this long reuses what it has; usage windows move in minutes, not seconds.REFRESH_AFTER_S = 120.0+# A snapshot older than this renders as state ``unknown`` instead of a confident gauge: a benched+# credential's windows stop updating, and reporting stale numbers as live would mislabel an+# account that may have recovered (or worsened) in the meantime.+SNAPSHOT_STALE_AFTER_S = 15 * 60.0_lock = threading.Lock()-_snapshots: dict[tuple[str, str], "AccountUsageSnapshot"] = {}-_last_try: dict[tuple[str, str], float] = {}-_inflight: set[tuple[str, str]] = set()+# slot key (home, provider, identity_id, base_url) → snapshot+_snapshots: dict[tuple[str, str, str, str], "AccountUsageSnapshot"] = {}+# slot key → monotonic time the stored snapshot's fetch STARTED (late-fetch guard)+_started: dict[tuple[str, str, str, str], float] = {}+# slot key → monotonic time of the last refresh try (success or failure)+_last_try: dict[tuple[str, str, str, str], float] = {}+_inflight: set[tuple[str, str, str, str]] = set()-def _key(provider: str) -> tuple[str, str]:+def _key(provider: str, identity_id: Optional[str] = None, base_url: Optional[str] = None) -> tuple[str, str, str, str]:from hermes_constants import hermes_home_key- return hermes_home_key(), str(provider or "").strip().lower()+ return (+ hermes_home_key(),+ str(provider or "").strip().lower(),+ str(identity_id or "").strip(),+ str(base_url or "").strip().rstrip("/"),+ )def has_account_usage(provider: str) -> bool:@@ -44,41 +64,168 @@ def has_account_usage(provider: str) -> bool:return profile is not None and type(profile).fetch_account_usage is not ProviderProfile.fetch_account_usage-def remember_account_usage(provider: Optional[str], snapshot: Optional["AccountUsageSnapshot"]) -> None:- if provider and snapshot is not None and snapshot.windows:- with _lock:- _snapshots[_key(provider)] = snapshot+def _identity_id_for(provider: str, entry: Any) -> str:+ """Stable non-secret account id of one pool entry, for slot keys and wire ``accounts[].id``.++ A trusted decoded identity (Codex JWT principal) wins: several credentials of one account+ share a slot, so the account is counted once. Without one, the entry's token fingerprint+ stands in — same token ⇒ same account, and a replaced token never reuses the old quota.+ A metadata-only row (no token) falls back to the entry id: nothing better is knowable.+ """+ token = str(getattr(entry, "runtime_api_key", "") or "").strip()+ if not token:+ return f"entry:{getattr(entry, 'id', '')}"+ if provider == "openai-codex":+ from agent.credential_pool import _codex_principal_identity++ principal = _codex_principal_identity(token)+ if principal:+ return f"codex:{principal[0]}:{principal[1]}"+ import hashlib++ return f"fp:{hashlib.sha256(token.encode('utf-8')).hexdigest()[:16]}"+++def remember_account_usage(+ provider: Optional[str], snapshot: Optional["AccountUsageSnapshot"],+ *, identity_id: Optional[str] = None, base_url: Optional[str] = None,+ started_monotonic: Optional[float] = None,+) -> None:+ """Land one fetch result.++ ``identity_id`` given (per-credential fetch): the snapshot is stored under that account's+ slot only — one pool entry's usage must never pose as the provider-wide gauge. The snapshot's+ own trusted ``identity`` (decoded from the very token it was fetched with) wins over the+ caller's id, so a replaced credential cannot repopulate its old account's slot.++ ``identity_id`` absent (per-turn / ``/usage`` fetch): stored in the provider's legacy slot —+ the single-account gauge — and additionally in the account's identity slot when the fetcher+ identified it, so a pooled picker sees per-turn data without waiting on its own refresh.++ A snapshot without windows is never stored: a failed or empty fetch must not erase a fresher+ snapshot. A fetch that STARTED before the freshest stored one cannot replace it either+ (``started_monotonic``), however late its response arrives.+ """+ if not provider or snapshot is None or not snapshot.windows:+ return+ started = time.monotonic() if started_monotonic is None else started_monotonic+ with _lock:+ targets = []+ snapshot_identity = getattr(snapshot, "identity", None)+ if identity_id is None:+ targets.append(_key(provider, None, base_url))+ if snapshot_identity:+ targets.append(_key(provider, snapshot_identity, None))+ else:+ targets.append(_key(provider, snapshot_identity or identity_id, None))+ for key in targets:+ if key in _started and _started[key] > started:+ continue # a fresher fetch already landed; this late result must not replace it+ _snapshots[key] = snapshot+ _started[key] = started+++def cached_account_usage(+ provider: str, *, identity_id: Optional[str] = None, base_url: Optional[str] = None,+) -> Optional["AccountUsageSnapshot"]:+ with _lock:+ return _snapshots.get(_key(provider, identity_id, base_url))+++def snapshot_is_stale(snapshot: Optional["AccountUsageSnapshot"]) -> bool:+ """True when the snapshot is too old to render as a live gauge (the picker shows state+ ``unknown`` instead of trusting its percentages)."""+ from agent.account_usage import AccountUsageSnapshot as _Snapshot++ if not isinstance(snapshot, _Snapshot):+ return True+ try:+ age = time.time() - snapshot.fetched_at.timestamp()+ except (AttributeError, TypeError, ValueError, OSError, OverflowError):+ return True+ return age < 0 or age > SNAPSHOT_STALE_AFTER_S-def cached_account_usage(provider: str) -> Optional["AccountUsageSnapshot"]:+def _claim_refresh(key: tuple[str, str, str, str], now: float) -> bool:+ """Take the refresh right for *key* unless one is inflight or tried too recently.++ A failed or empty fetch still counts as a try, so a dead credential (or a provider with no+ usage API) isn't re-asked on every picker open."""with _lock:- return _snapshots.get(_key(provider))+ if key in _inflight or now - _last_try.get(key, float("-inf")) < REFRESH_AFTER_S:+ return False+ _inflight.add(key)+ _last_try[key] = now+ return True+++def _release_refresh(key: tuple[str, str, str, str]) -> None:+ with _lock:+ _inflight.discard(key)def refresh_account_usage_async(providers: Iterable[str]) -> list[threading.Thread]:- """Fetch usage in the background for each provider not tried within ``REFRESH_AFTER_S``. A failed- or empty fetch still counts as a try, so a provider with no usage API isn't re-asked every open."""+ """Background-refresh the provider-wide (legacy) slot for each provider not tried within+ ``REFRESH_AFTER_S``. Returns the started threads (daemon; callers never join them)."""started: list[threading.Thread] = []now = time.monotonic()for provider in dict.fromkeys(providers):key = _key(provider)- with _lock:- if key in _inflight or now - _last_try.get(key, float("-inf")) < REFRESH_AFTER_S:- continue- _inflight.add(key)- _last_try[key] = now- thread = threading.Thread(target=copy_context().run, args=(_refresh, provider, key),- name="hermes-account-usage-refresh", daemon=True)+ if not _claim_refresh(key, now):+ continue+ thread = threading.Thread(+ target=copy_context().run, args=(_refresh_legacy, provider, key),+ name="hermes-account-usage-refresh", daemon=True)thread.start()started.append(thread)return started-def _refresh(provider: str, key: tuple[str, str]) -> None:+def _refresh_legacy(provider: str, key: tuple[str, str, str, str]) -> None:from agent.account_usage import fetch_account_usagetry:fetch_account_usage(provider) # remembers its own resultfinally:- with _lock:- _inflight.discard(key)+ _release_refresh(key)+++def refresh_account_usage_entries_async(requests: Iterable[dict]) -> list[threading.Thread]:+ """Background-refresh per-credential usage slots. *requests* entries are+ ``{"provider", "identity_id", "base_url", "api_key"}`` — the live credentials to read.++ One worker thread fetches all due entries serially (no thread storm for a 10-credential+ pool), read-only: a 401 or any other failure is reported, never repaired by rotating or+ refreshing the credential. Throttled per account slot, failures included."""+ due: list[dict] = []+ now = time.monotonic()+ for request in requests:+ provider = str(request.get("provider") or "").strip().lower()+ identity_id = str(request.get("identity_id") or "").strip()+ if not provider or not identity_id or not str(request.get("api_key") or "").strip():+ continue+ if not _claim_refresh(_key(provider, identity_id), now):+ continue+ due.append(request)+ if not due:+ return []+ thread = threading.Thread(+ target=copy_context().run, args=(_refresh_entries, list(due)),+ name="hermes-account-usage-refresh", daemon=True)+ thread.start()+ return [thread]+++def _refresh_entries(requests: list[dict]) -> None:+ from agent.account_usage import fetch_account_usage++ for request in requests:+ provider = request["provider"]+ key = _key(provider, request["identity_id"])+ try:+ fetch_account_usage(+ provider, base_url=request.get("base_url"), api_key=request.get("api_key"),+ read_only=True, identity_id=request["identity_id"],+ )+ finally:+ _release_refresh(key)diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 75bf5c449e0..35936a91c83 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -808,15 +808,25 @@ export interface ProviderLimit {resets_at?: string | nullmodels?: Record<string, string> | null}-/** ``hermes_cli/inventory.py::_apply_usage`` — the provider's account usage windows, from cache. */+/** ``hermes_cli/inventory.py::_apply_usage`` — the provider's subscription usage, from cache. Multi-entry credential pools carry ``accounts`` (one row per account; the legacy ``windows`` stays EMPTY there — a provider-wide percentage across different logins would be fabricated). Single-account providers keep the legacy ``windows`` gauge. */export interface ProviderUsage {- windows: ProviderUsageWindow[]+ windows?: ProviderUsageWindow[]+ accounts?: ProviderUsageAccount[] | null}-/** One subscription usage window (``agent/account_usage.py::AccountUsageWindow``): e.g. the 5-hour session or the weekly cap, with how much of it is spent and when it rolls over (ISO). */+/** One subscription usage window (``agent/account_usage.py::AccountUsageWindow``): e.g. the 5-hour session or the weekly cap, with how much of it is spent and when it rolls over (ISO). ``scope``: ``account`` — exhausting the window exhausts the whole login (Codex session/weekly, so a limited account's resets_at must wait for it); ``model`` — the window caps only one model family (Anthropic Opus/Sonnet weekly) and can never imply the account itself is out of quota. */export interface ProviderUsageWindow {label: stringused_percent: numberresets_at?: string | null+ scope?: 'account' | 'model'+}+/** One account of a provider's credential pool (``hermes_cli/inventory.py::_pool_usage_accounts``). ``id`` is a stable non-secret account identity (never a key or URL); ``label`` may be empty (UI falls back to a localized "Account N"). ``windows`` is empty while the account's usage is not yet known — state carries the meaning, never a fabricated gauge. ``state``: ``ready`` — live quota below the cap (numeric windows present); ``limited`` — a live credential-wide cooldown or exhausted account-scoped quota windows; ``unknown`` — no live numeric windows (failed/empty fetch, stale snapshot, provider without a usage API); ``unavailable`` — DEAD auth row (kept visible, never a quota row). ``resets_at``: for a limited account, the LATEST of its exhausted account-scoped windows (or a live cooldown when later); ``None`` when unknown (the frontend renders its own advisory, e.g. the earliest limited sibling). */+export interface ProviderUsageAccount {+ id: string+ label?: string+ windows?: ProviderUsageWindow[]+ state: 'ready' | 'limited' | 'unknown' | 'unavailable'+ resets_at?: string | null}export interface ImageGenerateParams {prompt?: string | nulldiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 767807dab45..37350051b64 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -26539,7 +26539,7 @@},"ProviderUsage": {"additionalProperties": false,- "description": "``hermes_cli/inventory.py::_apply_usage`` \u2014 the provider's account usage windows, from cache.",+ "description": "``hermes_cli/inventory.py::_apply_usage`` \u2014 the provider's subscription usage, from cache.\n\nMulti-entry credential pools carry ``accounts`` (one row per account; the legacy ``windows``\nstays EMPTY there \u2014 a provider-wide percentage across different logins would be fabricated).\nSingle-account providers keep the legacy ``windows`` gauge.","properties": {"windows": {"items": {@@ -26547,17 +26547,79 @@},"title": "Windows","type": "array"+ },+ "accounts": {+ "anyOf": [+ {+ "items": {+ "$ref": "#/components/schemas/ProviderUsageAccount"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Accounts"+ }+ },+ "title": "ProviderUsage",+ "type": "object"+ },+ "ProviderUsageAccount": {+ "additionalProperties": false,+ "description": "One account of a provider's credential pool (``hermes_cli/inventory.py::_pool_usage_accounts``).\n``id`` is a stable non-secret account identity (never a key or URL); ``label`` may be empty (UI\nfalls back to a localized \"Account N\"). ``windows`` is empty while the account's usage is not\nyet known \u2014 state carries the meaning, never a fabricated gauge.\n\n``state``: ``ready`` \u2014 live quota below the cap (numeric windows present); ``limited`` \u2014 a live\ncredential-wide cooldown or exhausted account-scoped quota windows; ``unknown`` \u2014 no live\nnumeric windows (failed/empty fetch, stale snapshot, provider without a usage API);\n``unavailable`` \u2014 DEAD auth row (kept visible, never a quota row).\n\n``resets_at``: for a limited account, the LATEST of its exhausted account-scoped windows (or a\nlive cooldown when later); ``None`` when unknown (the frontend renders its own advisory, e.g.\nthe earliest limited sibling).",+ "properties": {+ "id": {+ "title": "Id",+ "type": "string"+ },+ "label": {+ "default": "",+ "title": "Label",+ "type": "string"+ },+ "windows": {+ "items": {+ "$ref": "#/components/schemas/ProviderUsageWindow"+ },+ "title": "Windows",+ "type": "array"+ },+ "state": {+ "enum": [+ "ready",+ "limited",+ "unknown",+ "unavailable"+ ],+ "title": "State",+ "type": "string"+ },+ "resets_at": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Resets At"}},"required": [- "windows"+ "id",+ "state"],- "title": "ProviderUsage",+ "title": "ProviderUsageAccount","type": "object"},"ProviderUsageWindow": {"additionalProperties": false,- "description": "One subscription usage window (``agent/account_usage.py::AccountUsageWindow``): e.g. the 5-hour\nsession or the weekly cap, with how much of it is spent and when it rolls over (ISO).",+ "description": "One subscription usage window (``agent/account_usage.py::AccountUsageWindow``): e.g. the 5-hour\nsession or the weekly cap, with how much of it is spent and when it rolls over (ISO).\n\n``scope``: ``account`` \u2014 exhausting the window exhausts the whole login (Codex session/weekly,\nso a limited account's resets_at must wait for it); ``model`` \u2014 the window caps only one model\nfamily (Anthropic Opus/Sonnet weekly) and can never imply the account itself is out of quota.","properties": {"label": {"title": "Label",@@ -26578,6 +26640,15 @@],"default": null,"title": "Resets At"+ },+ "scope": {+ "default": "account",+ "enum": [+ "account",+ "model"+ ],+ "title": "Scope",+ "type": "string"}},"required": [diff --git a/hermes_cli/inventory.py b/hermes_cli/inventory.pyindex ea13fbf4647..ff0dd526d98 100644--- a/hermes_cli/inventory.py+++ b/hermes_cli/inventory.py@@ -288,24 +288,180 @@ def _apply_limits(rows: list[dict]) -> None:def _apply_usage(rows: list[dict]) -> None:"""Attach ``usage`` (subscription windows: % spent + reset) to signed-in rows that can report it,from the cache only, and ask for a background refresh, so the picker never waits on a usage API- and a chip can warn before the wall instead of at it."""- from agent.account_usage_cache import cached_account_usage, has_account_usage, refresh_account_usage_async+ and a chip can warn before the wall instead of at it.++ Single-account providers keep the legacy gauge (``usage.windows``). A provider with a+ MULTI-ENTRY credential pool reports ``usage.accounts`` instead — one row per account, each with+ its own windows/state/resets_at — because one account's quota says nothing about its siblings;+ a provider-wide percentage there would be a fabricated average. A snapshot older than the+ staleness bound renders ``unknown``/``unavailable``, never a confident stale gauge. Nothing here+ mutates the pool or disables routing: telemetry never benches a credential."""+ from agent.account_usage_cache import (+ cached_account_usage, has_account_usage, refresh_account_usage_async,+ refresh_account_usage_entries_async, snapshot_is_stale,+ )+ from hermes_cli.auth import read_credential_pool++ def _wire_windows(snapshot) -> list[dict]:+ return [+ {"label": w.label, "used_percent": float(w.used_percent),+ "resets_at": w.reset_at.isoformat() if w.reset_at else None,+ "scope": w.scope}+ for w in (snapshot.windows if snapshot else ()) if w.used_percent is not None+ ]++ def _account_resets_at(snapshot, live_cooldown_until: float | None) -> str | None:+ """A quota-exhausted account recovers at the LATEST of its exhausted account-scoped+ windows (all of them must reopen before the account is whole again); a live+ credential-wide cooldown wins when later. Model-scoped windows never reset an account.+ Unknown stays None — the frontend renders its own advisory (e.g. the earliest sibling)."""+ resets: list[str] = []+ if live_cooldown_until:+ resets.append(_iso_from_epoch(live_cooldown_until))+ for window in (snapshot.windows if snapshot else ()):+ if window.scope != "account" or window.used_percent is None or window.reset_at is None:+ continue+ if float(window.used_percent) >= _EXHAUSTED_WINDOW_PERCENT:+ resets.append(window.reset_at.isoformat())+ return max(resets) if resets else Nonewanted: list[str] = []+ entry_requests: list[dict] = []+ pooled_sizes = {slug: len(entries) for slug, entries in read_credential_pool().items() if entries}for row in rows:slug = str(row.get("slug") or "")- if not slug or row.get("is_user_defined") or row.get("authenticated") is False or not has_account_usage(slug):+ if not slug or row.get("is_user_defined") or row.get("authenticated") is False:continue- wanted.append(slug)- snapshot = cached_account_usage(slug)- windows = [- {"label": w.label, "used_percent": float(w.used_percent),- "resets_at": w.reset_at.isoformat() if w.reset_at else None}- for w in (snapshot.windows if snapshot else ()) if w.used_percent is not None- ]- if windows:- row["usage"] = {"windows": windows}+ supports_usage = has_account_usage(slug)+ # A single-entry pool (or no pool) is the single-account case: the legacy gauge stays+ # (chip contract unchanged). Only a genuinely multi-entry pool gets per-account rows —+ # there, a provider-wide percentage would be a fabricated average across logins.+ if pooled_sizes.get(slug, 0) < 2:+ if not supports_usage:+ continue+ wanted.append(slug)+ snapshot = cached_account_usage(slug)+ windows = _wire_windows(snapshot)+ if windows and not snapshot_is_stale(snapshot):+ row["usage"] = {"windows": windows}+ continue+ if supports_usage:+ wanted.append(slug)+ accounts = _pool_usage_accounts(slug, _wire_windows, _account_resets_at, entry_requests)+ if accounts is not None:+ row["usage"] = {"accounts": accounts}refresh_account_usage_async(wanted)+ refresh_account_usage_entries_async(entry_requests)+++# A window this spent counts as exhausted when computing an account's recovery time.+_EXHAUSTED_WINDOW_PERCENT = 100.0+++def _iso_from_epoch(epoch: float) -> str:+ from datetime import datetime, timezone++ return datetime.fromtimestamp(float(epoch), timezone.utc).isoformat()+++def _pool_usage_accounts(slug: str, wire_windows, account_resets_at,+ entry_requests: list[dict]) -> Optional[list[dict]]:+ """Per-account usage rows for one pooled provider, or None when the pool cannot be read.++ Read-only: entries are inspected via ``load_pool(slug)`` properties (no select/rotate/refresh).+ Dedupe is scoped to provider+host+trusted decoded account id where supported (several+ credentials of one Codex account are ONE account), else per-credential token identity — never+ a provider-wide singleton. Providers without a usage fetcher still get one metadata row per+ account with state unknown/limited/unavailable, so the chip can count honestly without bogus+ fetches. DEAD auth rows stay visible as ``unavailable`` (never a quota row). No secrets, raw+ payloads or base URLs ride the wire."""+ import logging+ import time++ from agent.account_usage_cache import _identity_id_for, cached_account_usage, has_account_usage, snapshot_is_stale+ from agent.credential_pool import STATUS_DEAD, _exhausted_until, load_pool++ try:+ pool = load_pool(slug)+ entries = list(pool.entries())+ except Exception: # an unreadable pool must not fail the whole catalog+ logging.getLogger(__name__).debug("Pool usage read failed for %s", slug, exc_info=True)+ return None+ if not entries:+ return None+ live = [e for e in entries if e.last_status != STATUS_DEAD]+ sole = len(live) <= 1+ supports_usage = has_account_usage(slug)+ now = time.time()+ accounts: list[dict] = []+ seen: dict[tuple[str, str, str], dict] = {}+ for entry in entries:+ identity_id = _identity_id_for(slug, entry)+ host = _pool_entry_host(slug, entry)+ dedupe_key = (slug, host, identity_id)+ is_dead = entry.last_status == STATUS_DEAD+ snapshot = (cached_account_usage(slug, identity_id=identity_id)+ if supports_usage and not is_dead else None)+ stale = snapshot_is_stale(snapshot)+ windows = wire_windows(snapshot) if not stale else []+ # 'limited' only when a live credential-wide cooldown benches this account or its+ # account-scoped quota windows are exhausted — telemetry alone never benches anything.+ cooldown_until = None if is_dead else _exhausted_until(entry, sole_credential=sole)+ live_cooldown = cooldown_until if cooldown_until and cooldown_until > now else None+ quota_exhausted = bool(windows) and any(+ w.get("scope") == "account" and w.get("used_percent") is not None+ and float(w["used_percent"]) >= _EXHAUSTED_WINDOW_PERCENT for w in windows)+ if is_dead:+ state = "unavailable"+ elif live_cooldown is not None or quota_exhausted:+ state = "limited"+ elif snapshot is None or stale or not windows:+ # No numeric live windows (failed/empty fetch, stale snapshot, non-supporting+ # provider): unknown — including a "ready-looking" account with nothing to show.+ state = "unknown"+ else:+ state = "ready"+ account_row = {+ "id": identity_id, "label": str(entry.label or ""), "windows": windows,+ "state": state, "resets_at": account_resets_at(snapshot, live_cooldown),+ }+ if dedupe_key in seen:+ # Same account under a second credential: keep the row that says more (state rank+ # limited > ready > unknown > unavailable), but never duplicate the account.+ existing = seen[dedupe_key]+ rank = {"limited": 3, "ready": 2, "unknown": 1, "unavailable": 0}+ if rank.get(account_row["state"], 0) > rank.get(existing["state"], 0):+ accounts[accounts.index(existing)] = account_row+ seen[dedupe_key] = account_row+ continue+ seen[dedupe_key] = account_row+ accounts.append(account_row)+ if supports_usage and not is_dead:+ entry_requests.append({+ "provider": slug, "identity_id": identity_id,+ "base_url": _pool_entry_route_base_url(slug, entry), "api_key": entry.runtime_api_key,+ })+ return accounts or None+++def _pool_entry_host(slug: str, entry) -> str:+ """Normalized route host of one entry, for account dedupe scoping. Never serialized."""+ from agent.credential_pool import _norm_url++ if slug == "openai-codex":+ from hermes_cli.auth_codex import _codex_pool_route_base_url++ return _norm_url(_codex_pool_route_base_url(entry.runtime_base_url))+ return _norm_url(getattr(entry, "runtime_base_url", None))+++def _pool_entry_route_base_url(slug: str, entry) -> Optional[str]:+ """The base URL a usage fetch for *entry* must target (its own route, never a sibling's)."""+ if slug == "openai-codex":+ from hermes_cli.auth_codex import _codex_pool_route_base_url++ return _codex_pool_route_base_url(entry.runtime_base_url)+ return getattr(entry, "runtime_base_url", None) or None# ─── Public: auxiliary-task pickers ─────────────────────────────────────diff --git a/tests/agent/test_account_usage_pool_fetch.py b/tests/agent/test_account_usage_pool_fetch.pynew file mode 100644index 00000000000..d3d1a2a96d2--- /dev/null+++ b/tests/agent/test_account_usage_pool_fetch.py@@ -0,0 +1,186 @@+"""Real-path source parsing and routing for per-credential usage fetches.++Loopback HTTP + actual auth stores: the Codex read-only fetcher hits the entry's own route,+parses real payloads, marks Opus/Sonnet windows model-scoped, and a 401 raises (never a+rotation/refresh) — while the live fetcher's repair path stays intact.+"""++from __future__ import annotations++import base64+import json+import threading+from datetime import datetime, timedelta, timezone+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer++import httpx+import pytest++from agent import account_usage+from agent.account_usage import fetch_account_usage+++def _b64(part: dict) -> str:+ return base64.urlsafe_b64encode(json.dumps(part).encode()).decode().rstrip("=")+++def _codex_jwt(account_id: str, sub: str) -> str:+ return (f"{_b64({'alg': 'none'})}."+ f"{_b64({'sub': sub, 'https://api.openai.com/auth': {'chatgpt_account_id': account_id}})}.sig")+++class _LoopbackUsageServer:+ """Loopback Codex usage API: one handler per token, keyed by Authorization bearer."""++ def __init__(self):+ self.requests: list[dict] = []+ self.responses: dict[str, tuple[int, dict]] = {}+ self.lock = threading.Lock()+ handler = self++ class _Handler(BaseHTTPRequestHandler):+ def do_GET(self):+ with handler.lock:+ handler.requests.append({"path": self.path, "token": self.headers.get("Authorization", "")})+ token = (self.headers.get("Authorization") or "").removeprefix("Bearer ").strip()+ status, payload = handler.responses.get(token, (200, {}))+ body = json.dumps(payload).encode()+ self.send_response(status)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, format, *args):+ pass++ self.server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler)+ self.url = f"http://127.0.0.1:{self.server.server_address[1]}/backend-api/codex"++ def __enter__(self):+ threading.Thread(target=self.server.serve_forever, daemon=True).start()+ return self++ def __exit__(self, *exc):+ self.server.shutdown()+ return False+++def _usage_payload(session_used: float = 20.0, weekly_used: float = 5.0) -> dict:+ now = datetime.now(timezone.utc)+ return {+ "plan_type": "pro",+ "rate_limit": {+ "primary_window": {"used_percent": session_used, "reset_at": int((now + timedelta(hours=1)).timestamp()),+ "limit_window_seconds": 18000},+ "secondary_window": {"used_percent": weekly_used, "reset_at": int((now + timedelta(days=3)).timestamp()),+ "limit_window_seconds": 604800},+ },+ "credits": {"has_credits": False},+ }+++def test_read_only_fetch_routes_to_entries_own_host_and_parses(monkeypatch, tmp_path):+ """The per-credential read-only fetch hits the entry's own route host with its own token and+ parses the payload: duration-labeled windows, identity from the JWT, no refresh attempted."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)+ from hermes_cli import auth as auth_mod++ rotations: list = []+ monkeypatch.setattr(auth_mod, "resolve_codex_runtime_credentials",+ lambda **kw: rotations.append(kw) or (_ for _ in ()).throw(AssertionError(+ "read-only per-credential fetch must never consult the singleton resolver")))+ token = _codex_jwt("acct-9", "user-9")+ with _LoopbackUsageServer() as server:+ server.responses[token] = (200, _usage_payload(session_used=44.0))+ snapshot = fetch_account_usage(+ "openai-codex", base_url=server.url, api_key=token, read_only=True, identity_id="codex:acct-9:user-9")++ assert snapshot is not None+ assert [(w.label, w.used_percent, w.scope) for w in snapshot.windows] == [+ ("Session", 44.0, "account"), ("Weekly", 5.0, "account")]+ assert snapshot.identity == "codex:acct-9:user-9"+ assert server.requests[0]["path"].endswith("/wham/usage"), \+ "a /backend-api base routes to the ChatGPT wham usage path"+ assert server.requests[0]["token"] == f"Bearer {token}"+++def test_read_only_401_raises_and_never_retries_with_rotation(monkeypatch, tmp_path):+ """A 401 on the read-only path is reported (snapshot None → unknown), never repaired via a+ forced refresh that could rotate a pooled credential; the live (non-read-only) fetch keeps its+ retry path for the session's own credential."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ monkeypatch.delenv("OPENAI_API_KEY", raising=False)+ from hermes_cli import auth as auth_mod++ def _forbidden_refresh(**kw):+ raise AssertionError("read-only path must not force-refresh (would rotate a pool credential)")++ token = _codex_jwt("acct-1", "user-1")+ with _LoopbackUsageServer() as server:+ server.responses[token] = (401, {"error": "unauthorized"})+ monkeypatch.setattr(account_usage, "_resolve_codex_usage_credentials",+ lambda base_url, api_key, **kw: (api_key, base_url, None))+ monkeypatch.setattr(auth_mod, "resolve_codex_runtime_credentials", _forbidden_refresh)+ # The fetcher under test imports _resolve_codex_usage_credentials at module level, so the+ # 401 path must NOT re-enter it with force_refresh: patch it to blow up on force_refresh.+ original = account_usage._resolve_codex_usage_credentials++ def no_force_refresh(base_url, api_key, *, force_refresh=False):+ if force_refresh:+ raise AssertionError("read-only path must not force-refresh")+ return original(base_url, api_key)++ monkeypatch.setattr(account_usage, "_resolve_codex_usage_credentials", no_force_refresh)+ snapshot = fetch_account_usage(+ "openai-codex", base_url=server.url, api_key=token, read_only=True)++ assert snapshot is None, "401 → no snapshot (account renders unknown), no repair attempted"+ assert len(server.requests) == 1, "exactly one request — no retry on the read-only path"+++def test_anthropic_fetch_honors_explicit_api_key_and_marks_model_scoped_windows(monkeypatch):+ """An explicit Anthropic api_key must not be shadowed by the ambient OAuth singleton, and the+ Opus/Sonnet weekly windows parse as ``model`` scope (they can never imply the account is out)."""+ called: dict = {}++ def fake_get_json(url, headers, *, timeout):+ called["url"], called["headers"] = url, headers+ return {"five_hour": {"utilization": 0.3, "resets_at": "2026-10-05T12:00:00Z"},+ "seven_day": {"utilization": 0.2, "resets_at": "2026-10-08T12:00:00Z"},+ "seven_day_opus": {"utilization": 1.0, "resets_at": "2026-10-09T12:00:00Z"},+ "seven_day_sonnet": {"utilization": 0.4, "resets_at": "2026-10-09T12:00:00Z"}}++ monkeypatch.setattr(account_usage, "_get_json", fake_get_json)+ monkeypatch.setattr(account_usage, "resolve_anthropic_token",+ lambda **kw: (_ for _ in ()).throw(AssertionError("ambient token must not be consulted")))++ snapshot = fetch_account_usage("anthropic", api_key="sk-ant-oat-explicit-token")++ assert snapshot is not None+ assert called["headers"]["Authorization"] == "Bearer sk-ant-oat-explicit-token"+ scopes = {w.label: w.scope for w in snapshot.windows}+ assert scopes == {"Current session": "account", "Current week": "account",+ "Opus week": "model", "Sonnet week": "model"}+ percents = {w.label: w.used_percent for w in snapshot.windows}+ assert percents["Opus week"] == 100.0 and percents["Current session"] == 30.0+++def test_read_only_fetch_remembered_under_identity_slot(monkeypatch, tmp_path):+ """A per-credential fetch's result lands in THAT account's cache slot (readable by+ ``cached_account_usage(identity_id=...)``) and never in the provider-wide legacy slot."""+ from agent.account_usage_cache import _snapshots, cached_account_usage++ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "home"))+ _snapshots.clear()+ token = _codex_jwt("acct-7", "user-7")+ with _LoopbackUsageServer() as server:+ server.responses[token] = (200, _usage_payload(session_used=66.0))+ fetch_account_usage("openai-codex", base_url=server.url, api_key=token,+ read_only=True, identity_id="codex:acct-7:user-7")++ snapshot = cached_account_usage("openai-codex", identity_id="codex:acct-7:user-7")+ assert snapshot is not None and snapshot.windows[0].used_percent == 66.0+ assert cached_account_usage("openai-codex") is None, \+ "a per-credential snapshot must never pose as the provider-wide gauge"diff --git a/tests/hermes_cli/test_model_options_pool_usage.py b/tests/hermes_cli/test_model_options_pool_usage.pynew file mode 100644index 00000000000..602d644d7cc--- /dev/null+++ b/tests/hermes_cli/test_model_options_pool_usage.py@@ -0,0 +1,393 @@+"""Pool-aware model-picker usage: per-account rows, cache isolation, honest failures.++Real-path regression tests for ``hermes_cli/inventory.py::_apply_usage`` and+``agent/account_usage_cache`` against actual auth stores on disk (no pool mocks): a+multi-entry pool must report per-account windows/state, one profile's snapshot must+never leak into another's picker, a failed/401 fetch must not hide or mutate its+siblings, and a late background fetch must not replace fresher per-turn data.+"""++from __future__ import annotations++import json+import threading+import time+from datetime import datetime, timedelta, timezone++import pytest++from agent import account_usage+from agent.account_usage import AccountUsageSnapshot, AccountUsageWindow+from agent.account_usage_cache import _snapshots, remember_account_usage+from hermes_cli.inventory import _apply_usage++pytestmark = pytest.mark.usefixtures("_join_refresh_workers_autouse")+++def _write_pool(home, provider: str, entries: list[dict]) -> None:+ home.mkdir(parents=True, exist_ok=True)+ (home / "auth.json").write_text(+ json.dumps({"version": 1, "credential_pool": {provider: entries}}, indent=2), encoding="utf-8")+++def _entry(cred_id: str, token: str, **over) -> dict:+ entry = {+ "id": cred_id, "label": cred_id, "auth_type": "api_key", "priority": 0,+ "source": "manual", "access_token": token,+ }+ entry.update(over)+ return entry+++def _fp(token: str) -> str:+ """The stable non-secret identity the cache assigns to an opaque API-key token."""+ import hashlib++ return f"fp:{hashlib.sha256(token.encode('utf-8')).hexdigest()[:16]}"+++def _snapshot(used: float, *, resets_in_hours: float = 2.0, scope: str = "account") -> AccountUsageSnapshot:+ return AccountUsageSnapshot(+ provider="openrouter", source="test", fetched_at=datetime.now(timezone.utc),+ windows=(AccountUsageWindow(label="API key quota", used_percent=used,+ reset_at=datetime.now(timezone.utc) + timedelta(hours=resets_in_hours),+ scope=scope),))+++def _clear_cache() -> None:+ _snapshots.clear()+++def _join_refresh_workers() -> None:+ """Wait out any account-usage refresh daemon this test spawned (bounded): a straggler+ worker re-resolves the pool under whatever HERMES_HOME is current when it runs — after+ monkeypatch teardown that is the NEXT test's home, and its load_pool persist would merge+ this test's in-memory entries into that store (cross-test auth.json contamination)."""+ import threading++ for worker in [t for t in threading.enumerate() if "hermes-account-usage-refresh" in t.name]:+ worker.join(10)++[email protected](autouse=True)+def _join_refresh_workers_autouse():+ """Every test in this file: join refresh workers AFTER the test body (teardown ordering —+ monkeypatch restores HERMES_HOME after the body, so joining must happen after it)."""+ yield+ _join_refresh_workers()+++def _install_fetcher(monkeypatch, answers: dict) -> dict:+ """Loopback-free deterministic fetcher: token → snapshot (or exception). Records calls."""+ calls: dict = {"tokens": [], "lock": threading.Lock()}++ def fake(base_url, api_key):+ with calls["lock"]:+ calls["tokens"].append(api_key)+ answer = answers.get(api_key)+ if isinstance(answer, Exception):+ raise answer+ return answer++ monkeypatch.setitem(account_usage._USAGE_FETCHERS, "openrouter", fake)+ return calls+++def _openrouter_row(usage_rows: list[dict]) -> dict:+ row = {"slug": "openrouter", "name": "OpenRouter", "models": ["m"], "authenticated": True}+ _apply_usage([row])+ return row+++# ── per-account rows for a multi-entry pool ──────────────────────────────────+++def test_multi_entry_pool_reports_per_account_rows(monkeypatch, tmp_path):+ """>=2 pool entries → ``usage.accounts`` (never a provider-wide ``windows`` gauge), one row+ per credential with its own cached windows, plus a background refresh per account."""+ from hermes_constants import hermes_home_key++ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "a"))+ _write_pool(tmp_path / "a", "openrouter", [+ _entry("c1", "tok-1"), _entry("c2", "tok-2"), _entry("c3", "tok-3")])+ _clear_cache()+ remember_account_usage("openrouter", _snapshot(10.0), identity_id=_fp("tok-1"))+ remember_account_usage("openrouter", _snapshot(80.0), identity_id=_fp("tok-2"))+ # c3 has no snapshot yet → state unknown, still visible.+ _install_fetcher(monkeypatch, {})++ row = _openrouter_row([])++ usage = row["usage"]+ assert "windows" not in usage or not usage["windows"], "multi-entry pool must not fabricate a provider-wide gauge"+ accounts = {a["id"]: a for a in usage["accounts"]}+ assert len(accounts) == 3, "every pool entry stays visible, including the unmeasured one"+ assert accounts[_fp("tok-1")]["state"] == "ready"+ assert accounts[_fp("tok-1")]["windows"][0]["used_percent"] == 10.0+ assert accounts[_fp("tok-2")]["state"] == "ready"+ assert accounts[_fp("tok-2")]["windows"][0]["used_percent"] == 80.0+ assert accounts[_fp("tok-3")]["state"] == "unknown"+ assert accounts[_fp("tok-3")]["windows"] == []+ # identity ids are non-secret (fingerprint/decoded-principal shaped, never the token)+ assert all("tok-" not in a_id for a_id in accounts)+++def test_same_codex_account_two_credentials_counts_one_account(monkeypatch, tmp_path):+ """Two credentials of one Codex account (same decoded JWT principal) dedupe to ONE account+ row; an anonymous third credential stays its own row."""+ import base64++ def _codex_jwt(account_id: str, sub: str) -> str:+ def b64(part: dict) -> str:+ return base64.urlsafe_b64encode(json.dumps(part).encode()).decode().rstrip("=")++ return f"{b64({'alg': 'none'})}.{b64({'sub': sub, 'https://api.openai.com/auth': {'chatgpt_account_id': account_id}})}.sig"++ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "a"))+ _write_pool(tmp_path / "a", "openai-codex", [+ _entry("c1", _codex_jwt("acct-1", "user-1"), auth_type="oauth"),+ _entry("c2", _codex_jwt("acct-1", "user-1"), auth_type="oauth"),+ _entry("c3", _codex_jwt("acct-2", "user-2"), auth_type="oauth"),+ ])+ _clear_cache()+ _install_fetcher(monkeypatch, {})++ row = {"slug": "openai-codex", "name": "Codex", "models": ["m"], "authenticated": True}+ _apply_usage([row])++ accounts = row["usage"]["accounts"]+ ids = [a["id"] for a in accounts]+ assert len(accounts) == 2, f"same-account credentials dedupe: {ids}"+ assert ids.count("codex:acct-1:user-1") == 1+ assert "codex:acct-2:user-2" in ids+++def test_single_entry_pool_keeps_legacy_gauge(monkeypatch, tmp_path):+ """A one-entry pool is the single-account case: the legacy ``usage.windows`` chip contract."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "a"))+ _write_pool(tmp_path / "a", "openrouter", [_entry("c1", "tok-1")])+ _clear_cache()+ remember_account_usage("openrouter", _snapshot(50.0))++ row = _openrouter_row([])++ assert row["usage"]["windows"][0]["used_percent"] == 50.0+ assert "accounts" not in row["usage"] or row["usage"]["accounts"] is None+++def test_limited_account_resets_at_is_latest_exhausted_window(monkeypatch, tmp_path):+ """A quota-exhausted account recovers at the LATEST of its exhausted account-scoped windows;+ an exhausted model-scoped window (Opus) never sets an account's resets_at nor limits it."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "a"))+ _write_pool(tmp_path / "a", "openrouter", [_entry("c1", "tok-1"), _entry("c2", "tok-2")])+ _clear_cache()+ now = datetime.now(timezone.utc)+ snapshot = AccountUsageSnapshot(+ provider="openrouter", source="test", fetched_at=now,+ windows=(+ AccountUsageWindow(label="Session", used_percent=100.0, reset_at=now + timedelta(hours=1)),+ AccountUsageWindow(label="Weekly", used_percent=100.0, reset_at=now + timedelta(hours=5)),+ AccountUsageWindow(label="Opus week", used_percent=100.0, reset_at=now + timedelta(hours=9),+ scope="model"),+ ))+ remember_account_usage("openrouter", snapshot, identity_id=_fp("tok-1"))+ remember_account_usage("openrouter", _snapshot(30.0), identity_id=_fp("tok-2"))++ row = _openrouter_row([])+ accounts = {a["id"]: a for a in row["usage"]["accounts"]}++ assert accounts[_fp("tok-1")]["state"] == "limited"+ assert accounts[_fp("tok-1")]["resets_at"] == (now + timedelta(hours=5)).isoformat(), \+ "latest EXHAUSTED account window wins; the exhausted model window must not extend it"+ assert accounts[_fp("tok-2")]["state"] == "ready"+++def test_live_cooldown_marks_account_limited_without_mutating_pool(monkeypatch, tmp_path):+ """A persisted credential-wide cooldown (live) renders ``limited`` + resets_at; reading usage+ never writes the pool back (auth.json unchanged)."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "a"))+ reset_at = time.time() + 3600+ _write_pool(tmp_path / "a", "openrouter", [+ _entry("c1", "tok-1", last_status="exhausted", last_status_at=time.time() - 60,+ last_error_code=429, last_error_reset_at=reset_at),+ _entry("c2", "tok-2")])+ _clear_cache()+ remember_account_usage("openrouter", _snapshot(5.0), identity_id=_fp("tok-2"))+ _install_fetcher(monkeypatch, {})++ row = _openrouter_row([])+ accounts = {a["id"]: a for a in row["usage"]["accounts"]}++ from datetime import datetime as _dt++ assert accounts[_fp("tok-1")]["state"] == "limited"+ assert accounts[_fp("tok-1")]["resets_at"] == _dt.fromtimestamp(reset_at, timezone.utc).isoformat()+ assert accounts[_fp("tok-2")]["state"] == "ready", "a benched sibling never hides a healthy account"+ disk = json.loads((tmp_path / "a" / "auth.json").read_text())+ assert len(disk["credential_pool"]["openrouter"]) == 2, "read path must not prune or rewrite the pool"+++def test_dead_row_stays_visible_as_unavailable(monkeypatch, tmp_path):+ """A DEAD auth row renders ``unavailable`` (visible, never a quota row) and is never fetched."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "a"))+ _write_pool(tmp_path / "a", "openrouter", [+ _entry("c1", "tok-1", last_status="dead", last_status_at=time.time() - 60),+ _entry("c2", "tok-2")])+ _clear_cache()+ remember_account_usage("openrouter", _snapshot(7.0), identity_id=_fp("tok-2"))+ _install_fetcher(monkeypatch, {})++ row = _openrouter_row([])+ states = {a["id"]: a["state"] for a in row["usage"]["accounts"]}++ assert states[_fp("tok-1")] == "unavailable"+ assert states[_fp("tok-2")] == "ready"+++# ── failure isolation: a 401/failed fetch must not hide or mutate siblings ────+++def test_failed_fetch_keeps_sibling_visible_and_does_not_repair(monkeypatch, tmp_path):+ """A per-credential 401 (read-only path: never retried via rotation/refresh) renders that+ account unknown, and the sibling with cached data stays ready; the failed token is never+ re-resolved through the pool (no rotation)."""+ from hermes_cli import auth as auth_mod++ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "a"))+ _write_pool(tmp_path / "a", "openai-codex", [+ _entry("c1", "tok-1", auth_type="oauth"), _entry("c2", "tok-2", auth_type="oauth")])+ _clear_cache()+ # Read-only Codex fetcher: 401 on tok-1; the resolver must NOT be consulted again.++ class _Unauthorized(Exception):+ pass++ def fake_read_only(base_url, api_key):+ if api_key == "tok-1":+ raise _Unauthorized()+ return _snapshot(11.0)++ monkeypatch.setitem(account_usage._READ_ONLY_USAGE_FETCHERS, "openai-codex", fake_read_only)+ monkeypatch.setattr(auth_mod, "resolve_codex_runtime_credentials",+ lambda **kw: (_ for _ in ()).throw(AssertionError("read-only path must not rotate")))++ row = {"slug": "openai-codex", "name": "Codex", "models": ["m"], "authenticated": True}+ _apply_usage([row])+ # populate c2's slot the way the background refresh would, then re-open the picker+ remember_account_usage("openai-codex", _snapshot(11.0), identity_id=_fp("tok-2"))+ _apply_usage([row])++ accounts = {a["id"]: a for a in row["usage"]["accounts"]}+ assert accounts[_fp("tok-1")]["state"] == "unknown", "401 → unknown, no fabricated windows"+ assert accounts[_fp("tok-2")]["state"] == "ready", "the failed sibling stays visible with its data"+ disk = json.loads((tmp_path / "a" / "auth.json").read_text())+ assert disk["credential_pool"]["openai-codex"][0]["access_token"] == "tok-1", \+ "a read-only usage fetch must never rotate or mutate a pool entry"+++# ── cache scope: A→B→A profile isolation ────────────────────────────────────+++def test_cache_isolation_a_to_b_to_a(monkeypatch, tmp_path):+ """Snapshots are scoped per profile home: B's open must not read A's snapshot, and back on A+ the original data is intact (no cross-profile contamination in either direction)."""+ home_a, home_b = tmp_path / "a", tmp_path / "b"+ monkeypatch.setenv("HERMES_HOME", str(home_a))+ _write_pool(home_a, "openrouter", [_entry("c1", "tok-1"), _entry("c2", "tok-2")])+ monkeypatch.setenv("HERMES_HOME", str(home_b))+ _write_pool(home_b, "openrouter", [_entry("b1", "tok-b1"), _entry("b2", "tok-b2")])+ _clear_cache()++ monkeypatch.setenv("HERMES_HOME", str(home_a))+ remember_account_usage("openrouter", _snapshot(10.0), identity_id=_fp("tok-1"))+ remember_account_usage("openrouter", _snapshot(20.0), identity_id=_fp("tok-2"))++ monkeypatch.setenv("HERMES_HOME", str(home_b))+ row_b = _openrouter_row([])+ assert row_b["usage"]["accounts"], "B sees its own pool"+ states_b = {a["id"]: a["state"] for a in row_b["usage"]["accounts"]}+ assert all(state == "unknown" for state in states_b.values()), \+ f"B's accounts must be unknown, not A's cached numbers: {states_b}"+ windows_b = [w for a in row_b["usage"]["accounts"] for w in a["windows"]]+ assert windows_b == [], "A's snapshot must not leak into B's picker"++ monkeypatch.setenv("HERMES_HOME", str(home_a))+ row_a = _openrouter_row([])+ accounts_a = {a["id"]: a for a in row_a["usage"]["accounts"]}+ assert accounts_a[_fp("tok-1")]["state"] == "ready"+ assert accounts_a[_fp("tok-1")]["windows"][0]["used_percent"] == 10.0, "A→B→A keeps A's data intact"+++def test_replaced_credential_never_reuses_stale_quota(monkeypatch, tmp_path):+ """A new token gets a NEW identity slot: the old account's snapshot cannot answer for it."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "a"))+ _write_pool(tmp_path / "a", "openrouter", [_entry("c1", "tok-new"), _entry("c2", "tok-2")])+ _clear_cache()+ remember_account_usage("openrouter", _snapshot(99.0), identity_id=_fp("tok-old"))++ row = _openrouter_row([])+ states = {a["id"]: a["state"] for a in row["usage"]["accounts"]}++ assert _fp("tok-old") not in states, "a replaced credential's slot is not reused"+ assert all(state == "unknown" for state in states.values())+++def test_late_background_fetch_cannot_replace_fresher_data(monkeypatch, tmp_path):+ """A background refresh started before a fresher per-turn fetch cannot overwrite it, however+ late its response lands."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "a"))+ _write_pool(tmp_path / "a", "openrouter", [_entry("c1", "tok-1"), _entry("c2", "tok-2")])+ _clear_cache()++ # Per-turn fetch (no identity) lands a fresh snapshot in fp:1's slot, "now".+ remember_account_usage("openrouter", _snapshot(42.0), identity_id=_fp("tok-1"))+ # A background fetch that STARTED earlier finishes later with older numbers.+ remember_account_usage("openrouter", _snapshot(90.0), identity_id=_fp("tok-1"), started_monotonic=-1000.0)++ row = _openrouter_row([])+ accounts = {a["id"]: a for a in row["usage"]["accounts"]}+ assert accounts[_fp("tok-1")]["windows"][0]["used_percent"] == 42.0, \+ "the late fetch must not replace the fresher per-turn snapshot"+++def test_model_scoped_window_exhaustion_does_not_limit_account(monkeypatch, tmp_path):+ """An exhausted MODEL-scoped window (Anthropic Opus/Sonnet) never marks the account limited+ nor contributes to its resets_at (model-scoped non-exhaustion is preserved)."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "a"))+ _write_pool(tmp_path / "a", "openrouter", [_entry("c1", "tok-1"), _entry("c2", "tok-2")])+ _clear_cache()+ now = datetime.now(timezone.utc)+ snapshot = AccountUsageSnapshot(+ provider="openrouter", source="test", fetched_at=now,+ windows=(AccountUsageWindow(label="Opus week", used_percent=100.0,+ reset_at=now + timedelta(hours=9), scope="model"),))+ remember_account_usage("openrouter", snapshot, identity_id=_fp("tok-1"))+ remember_account_usage("openrouter", _snapshot(30.0), identity_id=_fp("tok-2"))++ row = _openrouter_row([])+ accounts = {a["id"]: a for a in row["usage"]["accounts"]}++ assert accounts[_fp("tok-1")]["state"] == "ready", "an exhausted model window alone must not limit the account"+ assert accounts[_fp("tok-1")]["resets_at"] is None+++def test_non_supporting_pool_provider_reports_unknown_without_fetching(monkeypatch, tmp_path):+ """A pooled provider with NO usage fetcher still gets per-account metadata rows (state+ unknown), and no bogus fetch is attempted for it."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "a"))+ _write_pool(tmp_path / "a", "kimi", [_entry("c1", "tok-1"), _entry("c2", "tok-2")])+ _clear_cache()++ row = {"slug": "kimi", "name": "Kimi", "models": ["m"], "authenticated": True}+ with monkeypatch.context() as m:+ def fail_fetch(*a, **kw):+ raise AssertionError("no fetch may run for a non-supporting provider")++ # The background refresh worker must not fetch for this provider either.+ import agent.account_usage_cache as cache_mod+ m.setattr(cache_mod, "_refresh_entries", lambda requests: None)+ _apply_usage([row])++ accounts = row["usage"]["accounts"]+ assert len(accounts) == 2+ assert all(a["state"] == "unknown" and a["windows"] == [] for a in accounts)diff --git a/tui_gateway/contracts/config_free_tier_control.py b/tui_gateway/contracts/config_free_tier_control.pyindex 72a58c26591..b8831baa3b8 100644--- a/tui_gateway/contracts/config_free_tier_control.py+++ b/tui_gateway/contracts/config_free_tier_control.py@@ -446,17 +446,49 @@ class ProviderLimit(Result):class ProviderUsageWindow(Result):"""One subscription usage window (``agent/account_usage.py::AccountUsageWindow``): e.g. the 5-hour- session or the weekly cap, with how much of it is spent and when it rolls over (ISO)."""+ session or the weekly cap, with how much of it is spent and when it rolls over (ISO).++ ``scope``: ``account`` — exhausting the window exhausts the whole login (Codex session/weekly,+ so a limited account's resets_at must wait for it); ``model`` — the window caps only one model+ family (Anthropic Opus/Sonnet weekly) and can never imply the account itself is out of quota."""label: strused_percent: floatresets_at: str | None = None+ scope: Literal["account", "model"] = "account"+++class ProviderUsageAccount(Result):+ """One account of a provider's credential pool (``hermes_cli/inventory.py::_pool_usage_accounts``).+ ``id`` is a stable non-secret account identity (never a key or URL); ``label`` may be empty (UI+ falls back to a localized "Account N"). ``windows`` is empty while the account's usage is not+ yet known — state carries the meaning, never a fabricated gauge.++ ``state``: ``ready`` — live quota below the cap (numeric windows present); ``limited`` — a live+ credential-wide cooldown or exhausted account-scoped quota windows; ``unknown`` — no live+ numeric windows (failed/empty fetch, stale snapshot, provider without a usage API);+ ``unavailable`` — DEAD auth row (kept visible, never a quota row).++ ``resets_at``: for a limited account, the LATEST of its exhausted account-scoped windows (or a+ live cooldown when later); ``None`` when unknown (the frontend renders its own advisory, e.g.+ the earliest limited sibling)."""++ id: str+ label: str = ""+ windows: list[ProviderUsageWindow] = Field(default_factory=list)+ state: Literal["ready", "limited", "unknown", "unavailable"]+ resets_at: str | None = Noneclass ProviderUsage(Result):- """``hermes_cli/inventory.py::_apply_usage`` — the provider's account usage windows, from cache."""+ """``hermes_cli/inventory.py::_apply_usage`` — the provider's subscription usage, from cache.++ Multi-entry credential pools carry ``accounts`` (one row per account; the legacy ``windows``+ stays EMPTY there — a provider-wide percentage across different logins would be fabricated).+ Single-account providers keep the legacy ``windows`` gauge."""- windows: list[ProviderUsageWindow]+ windows: list[ProviderUsageWindow] = Field(default_factory=list)+ accounts: list[ProviderUsageAccount] | None = Noneclass ModelOptionProvider(OpenModel):