diff --git a/agent/account_usage.py b/agent/account_usage.py index b7abb18017..a3ba6e52f7 100644 --- a/agent/account_usage.py +++ b/agent/account_usage.py @@ -4,7 +4,7 @@ import logging import math from dataclasses import dataclass from datetime import datetime, timezone -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any, Callable, Optional import 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 None def _parse_dt(value: Any) -> Optional[datetime]: @@ -58,49 +56,39 @@ def _parse_dt(value: Any) -> Optional[datetime]: return None if 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 None def _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 // 60 if 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], *, mark elif 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 build_nous_credits_snapshot(account_info) -> Optional[AccountUsageSnapshot]: - """Map a NousPortalAccountInfo into an AccountUsageSnapshot for /usage. +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), + ) - 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). - """ + +def build_nous_credits_snapshot(account_info) -> Optional[AccountUsageSnapshot]: + """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_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) + + 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. + """Rendered Nous-credits /usage lines, or [] when there's nothing to show. - 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). - - 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 = None if 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: bool balance_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_url snapshot = build_nous_credits_snapshot(account) - # Balance lines = the snapshot block minus the two trailing affordance lines - # ("Top up: " + "(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] = None try: - 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 None except 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_code if 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 0 remaining = 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, + windows_reset=int(windows_reset) if isinstance(windows_reset, (int, float)) else 0, ) - 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, - ) - 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 None if 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 None normalized = 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) * 100 detail_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 None except Exception: return None - return None diff --git a/agent/billing_links.py b/agent/billing_links.py index 1e9320ebb4..d38cbc4bdd 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_matches class 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.slug def 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/billing_usage.py b/agent/billing_usage.py index c3ab6203e3..2722429fc2 100644 --- a/agent/billing_usage.py +++ b/agent/billing_usage.py @@ -1,32 +1,18 @@ -"""Shared dollar-denominated usage model for the billing/subscription surfaces. +"""Shared dollar-denominated usage model for the ``/usage`` and ``/subscription`` bars. -The single source of truth behind the ``/usage`` and ``/subscription`` usage -bars (TUI + CLI). User feedback (Jun 2026): the terminal surfaces show -**dollars**, never "credits", and every usage bar must make the monthly -subscription allowance and separately-purchased top-up dollars distinctly -visible. +Terminal surfaces show **dollars**, never "credits"; the monthly subscription +allowance and separately-purchased top-up dollars must stay distinctly visible. -Data source: the NAS account-info fetch (``NousPortalAccountInfo``), whose -``paid_service_access_info`` carries the three dollar magnitudes we render -(despite the legacy ``*_credits`` field names, these are USD floats): +Data source: ``NousPortalAccountInfo.paid_service_access_info`` (USD floats despite +the legacy ``*_credits`` names): ``subscription_credits_remaining`` (plan $ left), +``purchased_credits_remaining`` (top-up $, rolls over), ``total_usable_credits``; +plus ``subscription.monthly_credits`` (plan bar denominator) and ``current_period_end``. - - ``subscription_credits_remaining`` -> plan dollars left this month - - ``purchased_credits_remaining`` -> top-up dollars left (rolls over) - - ``total_usable_credits`` -> total spendable - -plus ``subscription.monthly_credits`` (the plan's monthly $ allowance, the -denominator for the "% used" plan bar) and ``current_period_end`` (renewal). - -Design: two SEPARATE bars (decided with the user) rather than one crammed -three-segment bar โ€” at terminal widths three same-glyph density segments are -unreadable. The plan bar is "spent vs allowance this month" (carries % used); -the top-up bar is "money you bought, doesn't expire". Each gets full -resolution and a single fill glyph, so the bar is never ambiguous and never -relies on color. - -Fail-open everywhere: any missing/non-finite field degrades to fewer bars or a -magnitudes-only view; a logged-out / unreachable portal yields -``available=False`` and the surface shows nothing. +Design: two SEPARATE bars rather than one three-segment bar โ€” at terminal widths +three same-glyph density segments are unreadable. Plan bar = spent vs allowance +(carries % used); top-up bar = purchased money that doesn't expire. Fail-open: +missing/non-finite fields degrade to fewer bars; logged-out / unreachable portal +yields ``available=False`` and the surface shows nothing. """ from __future__ import annotations @@ -39,14 +25,17 @@ from typing import Any, Optional logger = logging.getLogger(__name__) -# Below this TOTAL spendable ($), a paid account is flagged "low" โ€” the alert -# state that nudges top-up/upgrade before a mid-run cutoff. Product threshold -# (user feedback): "any amount below $5 should be an alert status." +# Below this TOTAL spendable ($) a paid account is flagged "low" โ€” the alert state +# that nudges top-up/upgrade before a mid-run cutoff (product: "below $5 is an alert"). LOW_BALANCE_THRESHOLD_USD = 5.0 def _finite(value: Any) -> Optional[float]: - """Return value as a float iff it's a real finite number (not bool/NaN/Inf).""" + """Return value as a float iff it's a real finite number (not bool/NaN/Inf). + + NaN/Infinity slip past isinstance (json.loads parses bare NaN by default) and + would otherwise render as ``$nan`` with a falsely-confident gauge. + """ if isinstance(value, bool) or not isinstance(value, (int, float)): return None f = float(value) @@ -54,17 +43,33 @@ def _finite(value: Any) -> Optional[float]: def _fmt_usd(value: Optional[float]) -> str: - """``$X.YY`` for display. ``None`` -> ``$0.00`` (callers gate on presence).""" + """``$X,XXX.YY`` for display. ``None`` -> ``$0.00`` (callers gate on presence).""" return f"${(value or 0.0):,.2f}" -def format_renews(value: Optional[str]) -> Optional[str]: - """Format an ISO date/timestamp as a human date, e.g. ``Jul 24, 2026``. +def nous_logged_in() -> bool: + """Cheap local auth-state check: a Nous access token is present. Fail-closed.""" + try: + from hermes_cli.auth import get_provider_auth_state - Accepts ``2026-07-24``, ``2026-07-24T11:05:01.000Z``, etc. Returns the raw - string unchanged if it can't be parsed (never raises), and ``None`` for - empty input. - """ + tok = (get_provider_auth_state("nous") or {}).get("access_token") + return isinstance(tok, str) and bool(tok.strip()) + except Exception: + return False + + +def fetch_nous_account(timeout: float): + """Wall-clock-bounded fresh portal account fetch. Raises on 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) + + +def format_renews(value: Optional[str]) -> Optional[str]: + """ISO date/timestamp -> ``Jul 24, 2026``; unparseable input is returned unchanged.""" if not value: return None from datetime import datetime @@ -76,7 +81,6 @@ def format_renews(value: Optional[str]) -> Optional[str]: try: dt = datetime.fromisoformat(iso) except ValueError: - # Fall back to a bare date prefix (YYYY-MM-DD) if present. try: dt = datetime.strptime(text[:10], "%Y-%m-%d") except ValueError: @@ -89,9 +93,8 @@ def format_renews(value: Optional[str]) -> Optional[str]: class UsageBar: """One full-resolution bar: ``spent`` of ``total``, plus a remaining figure. - ``kind`` is ``"plan"`` (monthly allowance, shows % used) or ``"topup"`` - (purchased dollars, no denominator โ€” ``spent`` is 0 and ``total`` == - ``remaining`` so it renders as a full bar of available balance). + ``kind`` is ``"plan"`` (monthly allowance, shows % used) or ``"topup"`` (no + denominator โ€” ``spent`` is 0 and ``total == remaining`` so it renders full). """ kind: str # "plan" | "topup" @@ -117,11 +120,8 @@ class UsageBar: class UsageModel: """Surface-agnostic dollar usage model shared by /usage and /subscription. - ``status`` classifies the account for copy selection: - - ``"free"`` : no paid access / no subscription (free models only) - - ``"low"`` : paid, but total spendable < $5 (ALERT) - - ``"healthy"`` : paid, total spendable >= $5 - - ``"depleted"`` : paid access lost (balance exhausted) + ``status``: ``free`` (no paid access / no plan), ``low`` (paid, spendable < $5, + ALERT), ``healthy`` (paid, spendable >= $5), ``depleted`` (paid access lost). """ available: bool @@ -141,11 +141,7 @@ class UsageModel: def usage_model_from_account(account_info: Any) -> UsageModel: - """Build a :class:`UsageModel` from a ``NousPortalAccountInfo``. Fail-open. - - Returns ``UsageModel(available=False)`` when there's no usable account info - (logged out, no entitlement block). Never raises. - """ + """Build a :class:`UsageModel` from a ``NousPortalAccountInfo``. Never raises.""" try: if account_info is None or not getattr(account_info, "logged_in", False): return UsageModel(available=False) @@ -163,48 +159,39 @@ def usage_model_from_account(account_info: Any) -> UsageModel: monthly = _finite(getattr(sub, "monthly_credits", None)) if sub is not None else None has_subscription = bool(plan_name) or (monthly is not None and monthly > 0) + has_topup = bool(topup_remaining and topup_remaining > 0) - # Total spendable: prefer the server's total; else sum the parts we have. + # Prefer the server's total; else sum the parts we have. if total_usable is not None: total_spendable = total_usable else: parts = [v for v in (sub_remaining, topup_remaining) if v is not None] total_spendable = sum(parts) if parts else None - # Status classification. if paid is False: status = "depleted" - elif not has_subscription and not (topup_remaining and topup_remaining > 0): - # No plan and no purchased balance -> free-models-only. - status = "free" + elif not has_subscription and not has_topup: + status = "free" # no plan and no purchased balance -> free-models-only elif total_spendable is not None and total_spendable < LOW_BALANCE_THRESHOLD_USD: status = "low" else: status = "healthy" - # Plan bar โ€” only with a positive monthly allowance AND a remaining we - # can place on it. spent = cap - remaining, clamped (a debt/over-cap - # balance reads as fully spent rather than a nonsensical negative). + # Plan bar needs a positive allowance AND a remaining to place on it; spent is + # clamped so a debt/over-cap balance reads fully spent, not negative. plan_bar: Optional[UsageBar] = None if monthly is not None and monthly > 0 and sub_remaining is not None: - remaining = max(0.0, min(monthly, sub_remaining)) plan_bar = UsageBar( kind="plan", - remaining_usd=remaining, + remaining_usd=max(0.0, min(monthly, sub_remaining)), total_usd=monthly, spent_usd=max(0.0, monthly - sub_remaining), ) - # Top-up bar โ€” only when there are purchased dollars to show. No - # denominator (top-up has no monthly cap), so it renders full = balance. + # Top-up has no monthly cap, so the bar renders full = balance. topup_bar: Optional[UsageBar] = None if topup_remaining is not None and topup_remaining > 0: - topup_bar = UsageBar( - kind="topup", - remaining_usd=topup_remaining, - total_usd=topup_remaining, - spent_usd=0.0, - ) + topup_bar = UsageBar(kind="topup", remaining_usd=topup_remaining, total_usd=topup_remaining, spent_usd=0.0) return UsageModel( available=True, @@ -226,98 +213,51 @@ def usage_model_from_account(account_info: Any) -> UsageModel: def build_usage_model(*, timeout: float = 10.0) -> UsageModel: """Fetch account-info and build the shared usage model. Fail-open. - Dev override: ``HERMES_DEV_CREDITS_FIXTURE`` short-circuits to a fixture so - every usage state is testable without a live account (mirrors the existing - ``/usage`` credits-block fixture path). + ``HERMES_DEV_CREDITS_FIXTURE`` short-circuits to a fixture so every usage state + is testable without a live account. """ fixture = _dev_fixture_usage_model() if fixture is not None: return fixture - - 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 UsageModel(available=False) - except Exception: + if not nous_logged_in(): return UsageModel(available=False) - 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) - return usage_model_from_account(account) + return usage_model_from_account(fetch_nous_account(timeout)) except Exception: logger.debug("usage โ–ธ portal fetch failed (fail-open)", exc_info=True) return UsageModel(available=False) -# ============================================================================= -# Dev fixtures (throwaway scaffolding โ€” env-var driven, no live portal) -# ============================================================================= +# โ”€โ”€ Dev fixtures (throwaway scaffolding โ€” env-var driven, no live portal) โ”€โ”€โ”€โ”€ + +def _plan_bar(remaining: float, spent: float) -> UsageBar: + return UsageBar(kind="plan", remaining_usd=remaining, total_usd=20.0, spent_usd=spent) def _dev_fixture_usage_model() -> Optional[UsageModel]: - """Map ``HERMES_DEV_CREDITS_FIXTURE`` to a usage model for offline UX work. - - Recognized names: ``free | healthy | low | topup | depleted``. Returns - ``None`` when the env var is unset (real portal path runs). - """ + """``HERMES_DEV_CREDITS_FIXTURE`` -> fixture model (``free|healthy|low|topup|depleted``), else None.""" name = (os.getenv("HERMES_DEV_CREDITS_FIXTURE") or "").strip().lower() - if not name: - return None - - if name == "free": - return UsageModel(available=True, status="free", plan_name=None) - - if name in ("healthy", "mid"): - return UsageModel( - available=True, - status="healthy", - plan_name="Plus", - renews_at="2026-07-01", - subscription_remaining_usd=14.0, - total_spendable_usd=14.0, - plan_bar=UsageBar(kind="plan", remaining_usd=14.0, total_usd=20.0, spent_usd=6.0), - ) - - if name in ("topup", "top-up"): - return UsageModel( - available=True, - status="healthy", - plan_name="Plus", - renews_at="2026-07-01", - subscription_remaining_usd=14.0, - topup_remaining_usd=12.0, - total_spendable_usd=26.0, - plan_bar=UsageBar(kind="plan", remaining_usd=14.0, total_usd=20.0, spent_usd=6.0), + name = {"mid": "healthy", "top-up": "topup"}.get(name, name) + plus = dict(available=True, plan_name="Plus", renews_at="2026-07-01") + specs: dict[str, dict] = { + "free": dict(available=True, status="free", plan_name=None), + "healthy": dict( + **plus, status="healthy", subscription_remaining_usd=14.0, total_spendable_usd=14.0, + plan_bar=_plan_bar(14.0, 6.0), + ), + "topup": dict( + **plus, status="healthy", subscription_remaining_usd=14.0, topup_remaining_usd=12.0, + total_spendable_usd=26.0, plan_bar=_plan_bar(14.0, 6.0), topup_bar=UsageBar(kind="topup", remaining_usd=12.0, total_usd=12.0, spent_usd=0.0), - ) - - if name == "low": - return UsageModel( - available=True, - status="low", - plan_name="Plus", - renews_at="2026-07-01", - subscription_remaining_usd=3.4, - total_spendable_usd=3.4, - plan_bar=UsageBar(kind="plan", remaining_usd=3.4, total_usd=20.0, spent_usd=16.6), - ) - - if name == "depleted": - return UsageModel( - available=True, - status="depleted", - plan_name="Plus", - renews_at="2026-07-01", - subscription_remaining_usd=0.0, - total_spendable_usd=0.0, - plan_bar=UsageBar(kind="plan", remaining_usd=0.0, total_usd=20.0, spent_usd=20.0), - ) - - return None + ), + "low": dict( + **plus, status="low", subscription_remaining_usd=3.4, total_spendable_usd=3.4, + plan_bar=_plan_bar(3.4, 16.6), + ), + "depleted": dict( + **plus, status="depleted", subscription_remaining_usd=0.0, total_spendable_usd=0.0, + plan_bar=_plan_bar(0.0, 20.0), + ), + } + spec = specs.get(name) + return UsageModel(**spec) if spec else None diff --git a/agent/billing_view.py b/agent/billing_view.py index 01a804e65f..f2c0ef0fdf 100644 --- a/agent/billing_view.py +++ b/agent/billing_view.py @@ -1,12 +1,10 @@ -"""Surface-agnostic core for the Phase 2b Remote Spending screens. +"""Surface-agnostic core for the Remote Spending screens. One fetch/parse per concern, consumed identically by the CLI handler -(``cli.py::_show_billing``), the TUI JSON-RPC methods -(``tui_gateway/server.py``), and any other surface. Mirrors the proven -``agent/account_usage.py::build_credits_view`` pattern: parse the server payload -into a frozen dataclass; **fail open** โ€” when not logged in or the portal is -unreachable, return a struct with ``logged_in=False`` and let the surface degrade -gracefully (never crash). +(``cli.py::_show_billing``), the TUI JSON-RPC methods (``tui_gateway/server.py``), +and any other surface. Parse the server payload into a frozen dataclass and +**fail open**: when not logged in or the portal is unreachable, return a struct +with ``logged_in=False`` and let the surface degrade gracefully (never crash). Money discipline: the server emits decimal STRINGS (``"142.5"``, not fixed 2dp). We keep them as :class:`decimal.Decimal` end-to-end and only format for display. @@ -19,22 +17,16 @@ import os import uuid from dataclasses import dataclass from decimal import Decimal, InvalidOperation -from typing import Any, Optional +from typing import Any, Callable, Optional logger = logging.getLogger(__name__) -# ============================================================================= -# Decimal money helpers -# ============================================================================= +# โ”€โ”€ Decimal money helpers โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def parse_money(value: Any) -> Optional[Decimal]: - """Parse a server money value (decimal string) into :class:`Decimal`. - - Returns None for missing/invalid input. Never raises. Accepts str/int (and, - defensively, float โ€” though the server always sends strings). - """ + """Server money value (decimal string; defensively int/float) -> Decimal, or None. Never raises.""" if value is None: return None try: @@ -44,30 +36,32 @@ def parse_money(value: Any) -> Optional[Decimal]: return None -def format_money(value: Optional[Decimal]) -> str: - """Format a Decimal as ``$X`` / ``$X.YY`` for display. +def format_money(value: Optional[Decimal], *, grouped: bool = False) -> str: + """``$X`` for whole dollars, ``$X.YY`` (exactly 2dp) otherwise; ``None`` -> ``โ€”``. - Whole dollars show no decimals; any fractional amount shows exactly 2dp: - ``Decimal("142.5")`` โ†’ ``"$142.50"``, ``Decimal("100")`` โ†’ ``"$100"``, - ``Decimal("0.01")`` โ†’ ``"$0.01"``. + ``grouped=True`` adds thousands separators (``$1,234.50``) to mirror the TUI's + ``toLocaleString('en-US')`` on plan-catalog rows; the default is intentionally + ungrouped and asserted so across the other surfaces. """ if value is None: return "โ€”" + spec = ",f" if grouped else "f" if value == value.to_integral_value(): - # Whole dollars โ€” no decimal point. format(..., "f") avoids 1E+3 for 1000. - return f"${format(value.to_integral_value(), 'f')}" - # Fractional โ€” always show 2dp. - return f"${format(value.quantize(Decimal('0.01')), 'f')}" + # format(..., "f") avoids 1E+3 for 1000. + return f"${format(value.to_integral_value(), spec)}" + return f"${format(value.quantize(Decimal('0.01')), spec)}" -# ============================================================================= -# Parsed sub-structures -# ============================================================================= +def _optional_str(raw: dict, key: str) -> Optional[str]: + value = raw.get(key) + return value if isinstance(value, str) else None -# resolvedVia โ†’ the human answer to "why THIS card?". Keys are the server's card -# resolution rungs (NAS card-on-file ladder); absent/unknown rungs render no label -# so the display degrades cleanly on servers that don't send resolvedVia yet. +# โ”€โ”€ Parsed sub-structures โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + +# resolvedVia (server card-on-file ladder rung) โ†’ "why THIS card?". Unknown/absent +# rungs render no label so older servers degrade cleanly. _CARD_PROVENANCE_LABELS = { "subPin": "the card on your subscription", "customerDefault": "your default card saved on the portal", @@ -79,39 +73,34 @@ _CARD_PROVENANCE_LABELS = { class CardInfo: brand: str last4: str - # NAS card-on-file field (post card-resolver): which ladder rung found the - # card. Defaults off so pre-resolver payloads parse unchanged. - resolved_via: Optional[str] = None + resolved_via: Optional[str] = None # ladder rung; None on pre-resolver payloads @property def masked(self) -> str: - # A Link payment method has no card number (last4 = "") โ€” render the - # brand alone, not "Link ยทยทยทยท". + # A Link payment method has no card number (last4 = "") โ€” brand alone, not "Link ยทยทยทยท". if not self.last4: return self.brand return f"{self.brand} ยทยทยทยท{self.last4}" @property def provenance(self) -> Optional[str]: - """Human label for why this card was picked, or None (unknown rung / - server too old to say).""" + """Human label for why this card was picked, or None (unknown rung / old server).""" if self.resolved_via is None: return None return _CARD_PROVENANCE_LABELS.get(self.resolved_via) @property def display(self) -> str: - """The one-line card display: ``Visa ยทยทยทยท4242 โ€” the card on your - subscription`` (or just the masked card when provenance is unknown).""" + """``Visa ยทยทยทยท4242 โ€” the card on your subscription`` (masked only when provenance unknown).""" label = self.provenance return f"{self.masked} โ€” {label}" if label else self.masked @dataclass(frozen=True) class PaymentMethodInfo: - """The payment method on file. `kind` is "card", "link", or "unknown" - โ€” anything else is normalised to "unknown" at parse time, so consumers - only ever see fields that belong to the kind they are looking at.""" + """Payment method on file. ``kind`` is "card", "link", or "unknown" โ€” anything + else is normalised to "unknown" at parse time so consumers only see fields + that belong to the kind they are looking at.""" kind: str brand: Optional[str] = None @@ -119,8 +108,7 @@ class PaymentMethodInfo: wallet: Optional[str] = None email: Optional[str] = None resolved_via: Optional[str] = None - #: What the server called it, when we did not recognise the kind. - raw_kind: Optional[str] = None + raw_kind: Optional[str] = None # what the server called an unrecognised kind @dataclass(frozen=True) @@ -146,13 +134,30 @@ class AutoReload: card: Optional[AutoReloadCard] = None -@dataclass(frozen=True) -class BillingState: - """Parsed ``GET /api/billing/state`` โ€” the overview screen's data. +class OrgRoleCapability: + """``is_admin`` / ``can_change_plan`` shared by the billing and subscription states.""" - Fail-open: ``logged_in=False`` (and empty fields) when not logged in or the - portal is unreachable. - """ + role: Optional[str] + can_change_plan_raw: Optional[bool] + + @property + def is_admin(self) -> bool: + """Deprecated/display only โ€” legacy OWNER/ADMIN check, NOT a capability check + (use :attr:`can_change_plan` to gate plan-change actions).""" + return (self.role or "").upper() in ("OWNER", "ADMIN") + + @property + def can_change_plan(self) -> bool: + """Server capability when supplied; otherwise the legacy role fallback.""" + if self.can_change_plan_raw is not None: + return self.can_change_plan_raw + return self.is_admin + + +@dataclass(frozen=True) +class BillingState(OrgRoleCapability): + """Parsed ``GET /api/billing/state``. Fail-open: ``logged_in=False`` (empty + fields) when not logged in or the portal is unreachable.""" logged_in: bool org_id: Optional[str] = None @@ -170,37 +175,13 @@ class BillingState: monthly_cap: Optional[MonthlyCap] = None auto_reload: Optional[AutoReload] = None portal_url: Optional[str] = None - # When the fetch failed (vs cleanly not-logged-in), the message for the surface. - error: Optional[str] = None - - @property - def is_admin(self) -> bool: - """Deprecated/display only โ€” a legacy OWNER/ADMIN check. - - NOT a capability check; use :attr:`can_change_plan` for gating billing - plan-change actions. - """ - return (self.role or "").upper() in ("OWNER", "ADMIN") - - @property - def can_change_plan(self) -> bool: - """Server capability when supplied; otherwise the legacy role fallback.""" - if self.can_change_plan_raw is not None: - return self.can_change_plan_raw - return self.is_admin + error: Optional[str] = None # set when the fetch failed (vs cleanly not-logged-in) @property def can_charge(self) -> bool: - """True when the UI should offer charge/auto-reload actions. - - Uses the server-granted plan-change capability (``can_change_plan``, - which itself falls back to the legacy OWNER/ADMIN role check when the - server omits ``canChangePlan``) AND the per-org kill-switch. This lets - the server grant charge capability to non-OWNER/ADMIN roles (e.g. - FINANCE_ADMIN) via ``canChangePlan``, instead of hard-coding the - deprecated 3-role admin check. (The server still enforces; this is - just for graying out actions the user can't take.) - """ + """Offer charge/auto-reload actions: server-granted ``can_change_plan`` (so + e.g. FINANCE_ADMIN can be granted via ``canChangePlan``) AND the per-org + kill-switch. Display gating only โ€” the server still enforces.""" return self.can_change_plan and self.cli_billing_enabled @@ -211,11 +192,7 @@ def _parse_card(raw: Any) -> Optional[CardInfo]: last4 = raw.get("last4") if not (isinstance(brand, str) and isinstance(last4, str)): return None - # Post-resolver fields โ€” all optional so both payload generations parse. - resolved_via = raw.get("resolvedVia") - if not isinstance(resolved_via, str): - resolved_via = None - return CardInfo(brand=brand, last4=last4, resolved_via=resolved_via) + return CardInfo(brand=brand, last4=last4, resolved_via=_optional_str(raw, "resolvedVia")) def _parse_payment_method(raw: Any) -> Optional[PaymentMethodInfo]: @@ -224,33 +201,17 @@ def _parse_payment_method(raw: Any) -> Optional[PaymentMethodInfo]: kind = raw.get("kind") if not isinstance(kind, str): return None - - def _optional_string(key: str) -> Optional[str]: - value = raw.get(key) - return value if isinstance(value, str) else None - - resolved_via = _optional_string("resolvedVia") - brand = _optional_string("brand") - last4 = _optional_string("last4") - # Settle the kind here, the way _parse_card settles a card, so nothing - # downstream has to re-check which fields this kind is allowed to have. + resolved_via = _optional_str(raw, "resolvedVia") + brand = _optional_str(raw, "brand") + last4 = _optional_str(raw, "last4") + # Settle the kind here (like _parse_card) so nothing downstream re-checks fields. if kind == "card" and brand and last4: return PaymentMethodInfo( - kind="card", - brand=brand, - last4=last4, - wallet=_optional_string("wallet"), - resolved_via=resolved_via, + kind="card", brand=brand, last4=last4, wallet=_optional_str(raw, "wallet"), resolved_via=resolved_via ) if kind == "link": - return PaymentMethodInfo( - kind="link", - email=_optional_string("email"), - resolved_via=resolved_via, - ) - return PaymentMethodInfo( - kind="unknown", raw_kind=kind, resolved_via=resolved_via - ) + return PaymentMethodInfo(kind="link", email=_optional_str(raw, "email"), resolved_via=resolved_via) + return PaymentMethodInfo(kind="unknown", raw_kind=kind, resolved_via=resolved_via) def _parse_monthly_cap(raw: Any) -> Optional[MonthlyCap]: @@ -282,32 +243,29 @@ def _parse_auto_reload_card(raw: Any) -> Optional[AutoReloadCard]: return None if kind in ("canonical", "none"): return AutoReloadCard(kind=kind) - - payment_method_id = raw.get("paymentMethodId") - brand = raw.get("brand") - last4 = raw.get("last4") return AutoReloadCard( kind=kind, - payment_method_id=payment_method_id if isinstance(payment_method_id, str) else None, - brand=brand if isinstance(brand, str) else None, - last4=last4 if isinstance(last4, str) else None, + payment_method_id=_optional_str(raw, "paymentMethodId"), + brand=_optional_str(raw, "brand"), + last4=_optional_str(raw, "last4"), ) +def parse_org_fields(payload: dict[str, Any]) -> tuple[dict[str, Any], Optional[bool]]: + """``(org dict or {}, canChangePlan if bool else None)`` โ€” shared by both state parsers.""" + raw_org = payload.get("org") + ccp = payload.get("canChangePlan") + return (raw_org if isinstance(raw_org, dict) else {}), (ccp if isinstance(ccp, bool) else None) + + def billing_state_from_payload( payload: dict[str, Any], *, portal_url: Optional[str] = None ) -> BillingState: """Map a raw ``/api/billing/state`` JSON dict into :class:`BillingState`.""" - raw_org = payload.get("org") - org: dict[str, Any] = raw_org if isinstance(raw_org, dict) else {} + org, can_change_plan_raw = parse_org_fields(payload) raw_bounds = payload.get("bounds") bounds: dict[str, Any] = raw_bounds if isinstance(raw_bounds, dict) else {} - - presets: list[Decimal] = [] - for item in payload.get("chargePresets") or (): - parsed = parse_money(item) - if parsed is not None: - presets.append(parsed) + presets = [p for p in map(parse_money, payload.get("chargePresets") or ()) if p is not None] return BillingState( logged_in=True, @@ -315,11 +273,7 @@ def billing_state_from_payload( org_slug=org.get("slug"), org_name=org.get("name"), role=org.get("role"), - can_change_plan_raw=( - payload.get("canChangePlan") - if isinstance(payload.get("canChangePlan"), bool) - else None - ), + can_change_plan_raw=can_change_plan_raw, balance_usd=parse_money(payload.get("balanceUsd")), cli_billing_enabled=bool(payload.get("cliBillingEnabled")), charge_presets=tuple(presets), @@ -333,95 +287,100 @@ def billing_state_from_payload( ) -# ============================================================================= -# Fail-open builders (the surface front doors) -# ============================================================================= +# โ”€โ”€ Fail-open builders (the surface front doors) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ + + +def fetch_portal_state( + endpoint: str, + label: str, + *, + failed: Callable[..., Any], + parse: Callable[[dict, Optional[str]], Any], + portal_fallback: Callable[[str], str], + timeout: float, + log: logging.Logger, +): + """Shared fail-open fetch+parse for the billing/subscription overview builders. + + ``failed(**kw)`` builds the ``logged_in=False`` struct: bare on auth failure, + with ``error`` set on a portal/HTTP failure so the surface can show a clear + message. Prefers a server-supplied ``portalUrl`` (absolutized); else + ``portal_fallback(portal_base_url)``. + """ + try: + import hermes_cli.nous_billing as nb + except Exception: + return failed(error="billing client unavailable") + + try: + payload = getattr(nb, endpoint)(timeout=timeout) + except nb.BillingAuthError: + return failed() + except nb.BillingError as exc: + log.debug("%s โ–ธ /state fetch failed (fail-open)", label, exc_info=True) + return failed(error=str(exc)) + except Exception: + log.debug("%s โ–ธ /state unexpected error (fail-open)", label, exc_info=True) + return failed(error=f"could not load {label} state") + + raw_portal = payload.get("portalUrl") if isinstance(payload, dict) else None + portal_url = nb._absolutize_portal_url(raw_portal) if raw_portal else None + if not portal_url: + try: + portal_url = portal_fallback(nb.resolve_portal_base_url()) + except Exception: + portal_url = None + return parse(payload, portal_url) def build_billing_state(*, timeout: float = 15.0) -> BillingState: - """Fetch + parse ``/api/billing/state``. Fail-open. + """Fetch + parse ``/api/billing/state``. Fail-open (see :func:`fetch_portal_state`). - Returns ``BillingState(logged_in=False)`` when not logged in. On a portal/HTTP - failure, returns ``logged_in=False`` with ``error`` set so the surface can show - a clear message rather than crashing. - - Dev override: ``HERMES_DEV_BILLING_FIXTURE`` short-circuits to a fixture so the - card-on-file / admin / scope states are testable offline (mirrors - ``HERMES_DEV_CREDITS_FIXTURE`` for the usage model). + ``HERMES_DEV_BILLING_FIXTURE`` short-circuits to a fixture so card-on-file / + admin / scope states are testable offline. """ fixture = _dev_fixture_billing_state() if fixture is not None: return fixture - - try: - from hermes_cli.nous_billing import ( - BillingAuthError, - BillingError, - _absolutize_portal_url, - get_billing_state, - resolve_portal_base_url, - ) - except Exception: - return BillingState(logged_in=False, error="billing client unavailable") - - try: - payload = get_billing_state(timeout=timeout) - except BillingAuthError: - return BillingState(logged_in=False) - except BillingError as exc: - logger.debug("billing โ–ธ /state fetch failed (fail-open)", exc_info=True) - return BillingState(logged_in=False, error=str(exc)) - except Exception: - logger.debug("billing โ–ธ /state unexpected error (fail-open)", exc_info=True) - return BillingState(logged_in=False, error="could not load billing state") - - # Prefer a server-supplied portalUrl if present (resolved to absolute in case - # it's relative); else build the standard one. - raw_portal = payload.get("portalUrl") if isinstance(payload, dict) else None - portal_url = _absolutize_portal_url(raw_portal) if raw_portal else None - if not portal_url: - try: - portal_url = _fallback_portal_url(resolve_portal_base_url()) - except Exception: - portal_url = None - - return billing_state_from_payload(payload, portal_url=portal_url) + return fetch_portal_state( + "get_billing_state", + "billing", + failed=lambda **kw: BillingState(logged_in=False, **kw), + parse=lambda payload, portal_url: billing_state_from_payload(payload, portal_url=portal_url), + portal_fallback=lambda base: f"{base.rstrip('/')}/billing?topup=open", + timeout=timeout, + log=logger, + ) -def _fallback_portal_url(base: str) -> str: - """Standard billing deep-link when the server omits ``portalUrl``.""" - return f"{base.rstrip('/')}/billing?topup=open" - - -# ============================================================================= -# Dev fixtures (throwaway scaffolding โ€” env-var driven, no live portal) -# ============================================================================= +# โ”€โ”€ Dev fixtures (throwaway scaffolding โ€” env-var driven, no live portal) โ”€โ”€โ”€โ”€ def _dev_fixture_billing_state() -> Optional[BillingState]: - """Map ``HERMES_DEV_BILLING_FIXTURE`` to a :class:`BillingState` for offline UX. + """``HERMES_DEV_BILLING_FIXTURE`` -> :class:`BillingState` for offline UX; None when unset. - Recognized names:: - - nocard logged in ยท billing on ยท admin ยท NO card on file - card card on file ยท auto-reload off - card-autoreload card on file ยท auto-reload on - notadmin logged in ยท MEMBER role (billing actions disabled) - billing-off logged in ยท admin ยท per-org kill-switch OFF - logged-out not logged in - - Returns ``None`` when the env var is unset (the real portal path runs). - Mirrors ``HERMES_DEV_CREDITS_FIXTURE``; the usage *bar* still comes from - ``HERMES_DEV_CREDITS_FIXTURE`` (set both to pair a bar with a billing state). + nocard ยท card ยท card-sub (provenance label) ยท card-autoreload ยท notadmin (MEMBER) + ยท billing-off (per-org kill-switch) ยท logged-out. Unknown name โ†’ logged-out with + ``error`` so the misconfiguration is visible. Pair with ``HERMES_DEV_CREDITS_FIXTURE`` + for the usage bar. """ name = (os.getenv("HERMES_DEV_BILLING_FIXTURE") or "").strip().lower() if not name: return None + aliases = { + "logged_out": "logged-out", "loggedout": "logged-out", + "card_sub": "card-sub", + "card_autoreload": "card-autoreload", "autoreload": "card-autoreload", + "not-admin": "notadmin", "member": "notadmin", + "billing_off": "billing-off", "off": "billing-off", + } + name = aliases.get(name, name) + if name == "logged-out": + return BillingState(logged_in=False) - # Shared fixture portal host (matches subscription_view._DEV_FIXTURE_PORTAL โ€” - # prod host, not staging; the ?topup=open suffix is the /topup deep-link). - portal = "https://portal.nousresearch.com/billing?topup=open" + # Prod portal host (matches subscription_view._DEV_FIXTURE_PORTAL) + the /topup deep-link suffix. common: dict[str, Any] = dict( + logged_in=True, org_id="org_acme", org_slug="acme", org_name="Acme Inc", @@ -431,53 +390,35 @@ def _dev_fixture_billing_state() -> Optional[BillingState]: charge_presets=(Decimal("10"), Decimal("25"), Decimal("50")), min_usd=Decimal("5"), max_usd=Decimal("500"), - portal_url=portal, + portal_url="https://portal.nousresearch.com/billing?topup=open", ) card = CardInfo(brand="Visa", last4="4242") - autoreload_on = AutoReload(enabled=True, threshold_usd=Decimal("5"), reload_to_usd=Decimal("25")) - - if name in ("logged-out", "logged_out", "loggedout"): - return BillingState(logged_in=False) - if name == "nocard": - return BillingState(logged_in=True, card=None, **common) - if name == "card": - return BillingState(logged_in=True, card=card, **common) - if name in ("card-sub", "card_sub"): - # Post-resolver: the card came from the subscription (provenance label). - _sub_card = CardInfo(brand="Visa", last4="4242", resolved_via="subPin") - return BillingState(logged_in=True, card=_sub_card, **common) - if name in ("card-autoreload", "card_autoreload", "autoreload"): - return BillingState(logged_in=True, card=card, auto_reload=autoreload_on, **common) - if name in ("notadmin", "not-admin", "member"): - opts = {**common, "role": "MEMBER"} - return BillingState(logged_in=True, card=card, **opts) - if name in ("billing-off", "billing_off", "off"): - opts = {**common, "cli_billing_enabled": False} - return BillingState(logged_in=True, card=None, **opts) - - # Unknown name โ†’ logged-out so the misconfiguration is visible. - return BillingState(logged_in=False, error=f"unknown HERMES_DEV_BILLING_FIXTURE: {name}") + overrides: dict[str, dict[str, Any]] = { + "nocard": dict(card=None), + "card": dict(card=card), + "card-sub": dict(card=CardInfo(brand="Visa", last4="4242", resolved_via="subPin")), + "card-autoreload": dict( + card=card, auto_reload=AutoReload(enabled=True, threshold_usd=Decimal("5"), reload_to_usd=Decimal("25")) + ), + "notadmin": dict(card=card, role="MEMBER"), + "billing-off": dict(card=None, cli_billing_enabled=False), + } + if name not in overrides: + return BillingState(logged_in=False, error=f"unknown HERMES_DEV_BILLING_FIXTURE: {name}") + return BillingState(**{**common, **overrides[name]}) -# ============================================================================= -# Idempotency -# ============================================================================= +# โ”€โ”€ Idempotency โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def new_idempotency_key() -> str: - """Fresh UUID for a user-confirmed purchase (reuse on retry of the SAME buy). - - The ``Idempotency-Key`` header is mandatory on ``POST /charge``; generate one - per confirmed purchase and reuse it across retries so a double-submit collapses - to a single charge. Never reuse a key across different amounts (the server - returns 409 idempotency_conflict). - """ + """Fresh UUID for a user-confirmed purchase. ``Idempotency-Key`` is mandatory on + ``POST /charge``: reuse the key across retries of the SAME buy so a double-submit + collapses to one charge; never reuse across amounts (server 409 idempotency_conflict).""" return str(uuid.uuid4()) -# ============================================================================= -# Amount validation (Screen 3 custom input) -# ============================================================================= +# โ”€โ”€ Amount validation (custom charge input) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @dataclass(frozen=True) @@ -490,18 +431,13 @@ class AmountValidation: def validate_charge_amount( raw: str, *, min_usd: Optional[Decimal], max_usd: Optional[Decimal] ) -> AmountValidation: - """Validate a custom charge amount against bounds + 2dp (multipleOf 0.01). - - Mirrors the server's accept/reject so the UI can give instant feedback rather - than round-tripping a sure-to-fail charge. The server is still authoritative. - """ - cleaned = (raw or "").strip().lstrip("$").strip() - amount = parse_money(cleaned) + """Mirror the server's accept/reject (bounds + multipleOf 0.01) for instant UI + feedback; the server is still authoritative.""" + amount = parse_money((raw or "").strip().lstrip("$").strip()) if amount is None: return AmountValidation(ok=False, error="Enter a dollar amount, e.g. 100") if amount <= 0: return AmountValidation(ok=False, error="Amount must be greater than $0") - # multipleOf 0.01 โ€” reject sub-cent precision. if amount != amount.quantize(Decimal("0.01")): return AmountValidation(ok=False, error="Amount can't be smaller than a cent") if min_usd is not None and amount < min_usd: diff --git a/agent/credits_tracker.py b/agent/credits_tracker.py index 82e2d53caa..54f0de0795 100644 --- a/agent/credits_tracker.py +++ b/agent/credits_tracker.py @@ -1,30 +1,22 @@ -"""Credits tracking for Nous inference API responses. +"""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. -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!) +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 as the 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 _SENTINEL try: @@ -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: @property def 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") @property def 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 @property def 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 None used = self.subscription_limit_micros - self.subscription_micros return 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 sticky CREDITS_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_000 def 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} @dataclass class 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: str level: 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: + 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). - 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. + 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 True if 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. + """Reconcile credits notices against the latch (see :func:`new_credits_latch`). + Mutates ``latch`` IN PLACE. Pure โ€” no I/O, no agent/run_agent imports. - latch = {"active": set[str], "seen_below_90": bool, "usage_band": Optional[int], - "seen_grant_unspent": bool}. + ``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. - ``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. - - Returns ``(to_show: list[AgentNotice], to_clear: list[str])``. - Caller emits to_clear FIRST, then to_show. - - 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 + # 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 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 - ): + # 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"] = True - active = 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]] = None if 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 = None grant_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 None if 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_free if 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 None if 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, - ) + 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: - 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 + fields[name] = val - as_of_ms = _req_nonneg("x-nous-credits-as-of-ms") - if as_of_ms is _SENTINEL: + # 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 - # โ”€โ”€ Validate USD strings โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - remaining_usd = lowered.get("x-nous-credits-remaining-usd", "") - if not _validate_usd(remaining_usd): - return None - - 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): - return None - - # โ”€โ”€ 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: + if lm is _SENTINEL or lm < 0 or not _validate_usd(sub_limit_usd_raw): return None - if lm < 0: - return None - if 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_raw denominator_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. + """Return a fixture CreditsState for HERMES_DEV_CREDITS_FIXTURE, or None + (unknown name / "clear" / "none" / unset โ†’ 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. - - 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 = state if 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"] = True emit = 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 = None try: fixture = dev_fixture_credits_state() except Exception: fixture = None if 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 threading def _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 True except 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 False diff --git a/agent/fast_mode.py b/agent/fast_mode.py index b8121f6295..b258b00d89 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 overrides from 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_url fast = 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/iteration_budget.py b/agent/iteration_budget.py index 7d50026c17..0bb517bfcf 100644 --- a/agent/iteration_budget.py +++ b/agent/iteration_budget.py @@ -1,12 +1,10 @@ """Per-agent iteration budget โ€” thread-safe consume/refund counter. -Extracted from ``run_agent.py``. Each ``AIAgent`` instance (parent or -subagent) holds an :class:`IterationBudget`; the parent's cap comes from -``max_iterations`` (default 500), each subagent's cap comes from -``delegation.max_iterations`` (default 50). - -``run_agent`` re-exports ``IterationBudget`` so existing -``from run_agent import IterationBudget`` imports keep working unchanged. +Each ``AIAgent`` (parent or subagent) holds its own :class:`IterationBudget`: +the parent's cap is ``max_iterations`` (default 500), each subagent's is +``delegation.max_iterations`` (default 50), so total iterations across parent ++ subagents can exceed the parent's cap. ``run_agent`` re-exports the class so +``from run_agent import IterationBudget`` keeps working. """ from __future__ import annotations @@ -15,19 +13,9 @@ import threading class IterationBudget: - """Thread-safe iteration counter for an agent. - - Each agent (parent or subagent) gets its own ``IterationBudget``. - The parent's budget is capped at ``max_iterations`` (default 500). - Each subagent gets an independent budget capped at - ``delegation.max_iterations`` (default 50) โ€” this means total - iterations across parent + subagents can exceed the parent's cap. - Users control the per-subagent limit via ``delegation.max_iterations`` - in config.yaml. - - ``execute_code`` (programmatic tool calling) iterations are refunded via - :meth:`refund` so they don't eat into the budget. - """ + """Thread-safe iteration counter. ``execute_code`` (programmatic tool + calling) iterations are refunded via :meth:`refund` so they don't eat + into the budget.""" def __init__(self, max_total: int): self.max_total = max_total diff --git a/agent/lmstudio_reasoning.py b/agent/lmstudio_reasoning.py index f9ba588df5..799e8dd538 100644 --- a/agent/lmstudio_reasoning.py +++ b/agent/lmstudio_reasoning.py @@ -1,34 +1,27 @@ """LM Studio reasoning-effort resolution shared by the chat-completions transport and run_agent's iteration-limit summary path. -LM Studio publishes per-model ``capabilities.reasoning.allowed_options`` (e.g. -``["off","on"]`` for toggle-style models, ``["off","minimal","low"]`` for -graduated models). We map the user's ``reasoning_config`` onto LM Studio's -OpenAI-compatible vocabulary, then clamp against the model's allowed set so -the server doesn't 400 on an unsupported effort. +LM Studio publishes per-model ``capabilities.reasoning.allowed_options`` +(``["off","on"]`` for toggle models, ``["off","minimal","low"]`` for graduated +ones). We map the user's ``reasoning_config`` onto LM Studio's OpenAI-compatible +vocabulary, then clamp against the model's allowed set so the server doesn't 400. """ from __future__ import annotations from typing import List, Optional -# LM Studio accepts these top-level reasoning_effort values via its -# OpenAI-compatible chat.completions endpoint. +# Top-level reasoning_effort values LM Studio's OpenAI-compatible endpoint accepts. _LM_VALID_EFFORTS = {"none", "minimal", "low", "medium", "high", "xhigh"} -# Toggle-style models publish allowed_options as ["off","on"] in /api/v1/models. -# Map them onto the OpenAI-compatible request vocabulary. +# Toggle-style models publish allowed_options as ["off","on"]; map onto the +# request vocabulary. Also applied to the published allowed_options themselves. _LM_EFFORT_ALIASES = {"off": "none", "on": "medium"} -# Hermes' generic effort ladder grew past LM Studio's vocabulary ("max", -# "ultra"). Clamp the stronger generic levels onto LM Studio's ceiling: left -# alone they miss _LM_VALID_EFFORTS, keep the initialized "medium" default and -# are thereby conflated with unparseable input, so asking for more reasoning -# yields less than "xhigh". Mirrors the ceiling clamp every other provider -# applies (see agent/transports/codex.py). -# -# Deliberately separate from _LM_EFFORT_ALIASES: that mapping is also applied -# to the model's published allowed_options, which must not be rewritten. +# Hermes' ladder grew past LM Studio's vocabulary ("max", "ultra"). Without this +# ceiling clamp they miss _LM_VALID_EFFORTS, keep the "medium" default and are +# conflated with unparseable input โ€” asking for more yields less than "xhigh". +# Kept separate from _LM_EFFORT_ALIASES, which must not rewrite allowed_options. _LM_EFFORT_CLAMP = {"max": "xhigh", "ultra": "xhigh"} @@ -36,12 +29,12 @@ def resolve_lmstudio_effort( reasoning_config: Optional[dict], allowed_options: Optional[List[str]], ) -> Optional[str]: - """Return the ``reasoning_effort`` string to send to LM Studio, or ``None``. + """Return the ``reasoning_effort`` to send to LM Studio, or ``None``. ``None`` means "omit the field": the user picked a level the model can't - honor, so let LM Studio fall back to the model's declared default rather - than silently substituting a different effort. When ``allowed_options`` is - falsy (probe failed), skip clamping and send the resolved effort anyway. + honor, so LM Studio falls back to the model's declared default rather than + a silently substituted effort. Falsy ``allowed_options`` (probe failed) + skips clamping and sends the resolved effort anyway. """ effort = "medium" if reasoning_config and isinstance(reasoning_config, dict): diff --git a/agent/model_metadata.py b/agent/model_metadata.py index fb78714afd..38f49b041a 100644 --- a/agent/model_metadata.py +++ b/agent/model_metadata.py @@ -28,12 +28,9 @@ from agent.message_metadata import PERSISTENCE_ONLY_MESSAGE_FIELDS logger = logging.getLogger(__name__) -# ``requests`` (with urllib3) costs ~27 ms of the `import cli` waterfall and -# is only used inside the fetch functions below. It's resolved lazily: -# ``_ensure_requests()`` populates the module global on the runtime path, and -# the PEP 562 ``__getattr__`` covers external attribute access โ€” notably -# ``patch("agent.model_metadata.requests.get")`` in tests, which resolves the -# attribute at patch time. +# ``requests`` costs ~27 ms of the `import cli` waterfall, so it is resolved +# lazily: ``_ensure_requests()`` on the runtime path, PEP 562 ``__getattr__`` +# for external access (``patch("agent.model_metadata.requests.get")``). def _ensure_requests(): @@ -50,24 +47,12 @@ def __getattr__(name: str): def _resolve_requests_verify(base_url: str = "") -> bool | str: - """Resolve SSL verify setting for `requests` calls. + """SSL ``verify`` for ``requests`` probes; mirrors ``agent.ssl_verify.resolve_httpx_verify``. - Priority (mirrors ``agent.ssl_verify.resolve_httpx_verify`` so the - ``requests``-based ``/models`` probes agree with the httpx chat client): - - 1. Per-provider ``ssl_verify: false`` for ``base_url`` โ€” disable verification. - 2. Per-provider ``ssl_ca_cert`` for ``base_url`` โ€” an explicit CA bundle. - Without this, a custom endpoint whose chain only verifies against the - provider's configured bundle (not the process ``SSL_CERT_FILE``) logs a - spurious CERTIFICATE_VERIFY_FAILED on every probe even though the chat - path succeeds (per-provider ``ssl_ca_cert`` was reaching only httpx). - 3. Env vars ``HERMES_CA_BUNDLE`` / ``REQUESTS_CA_BUNDLE`` / ``SSL_CERT_FILE`` - (a single var covers both ``requests`` and ``httpx`` in-process). - 4. ``True`` โ€” defer to the requests default (certifi). - - ``base_url`` is optional so existing callers (OpenRouter, etc.) keep the - env-only behavior unchanged; only probes that pass a base_url pick up the - per-provider override. + Priority: per-provider ``ssl_verify: false`` -> per-provider ``ssl_ca_cert`` + (otherwise probes log spurious CERTIFICATE_VERIFY_FAILED while the httpx + chat path succeeds) -> HERMES_CA_BUNDLE / REQUESTS_CA_BUNDLE / SSL_CERT_FILE + -> ``True`` (certifi). Callers without a ``base_url`` keep env-only behavior. """ if base_url: try: @@ -107,23 +92,16 @@ _OLLAMA_TAG_PATTERN = re.compile( ) -# Tailscale's CGNAT range (RFC 6598). `ipaddress.is_private` excludes this -# block, so without an explicit check Ollama reached over Tailscale (e.g. -# `http://100.77.243.5:11434`) wouldn't be treated as local and its stream -# read / stale timeouts wouldn't get auto-bumped. Built once at import time. +# Tailscale CGNAT (RFC 6598): `ipaddress.is_private` excludes it, yet Ollama +# reached over Tailscale must count as local (timeout auto-bumps). _TAILSCALE_CGNAT = ipaddress.IPv4Network("100.64.0.0/10") def _strip_provider_prefix(model: str) -> str: - """Strip a recognised provider prefix from a model string. + """Strip a registry-known provider prefix: ``"local:m"`` -> ``"m"``. - Provider names and aliases come from the provider-profile registry, so - bundled and user plugins are recognised without a core catalog update. - - ``"local:my-model"`` โ†’ ``"my-model"`` - ``"qwen3.5:27b"`` โ†’ ``"qwen3.5:27b"`` (unchanged โ€” not a provider prefix) - ``"qwen:0.5b"`` โ†’ ``"qwen:0.5b"`` (unchanged โ€” Ollama model:tag) - ``"deepseek:latest"``โ†’ ``"deepseek:latest"``(unchanged โ€” Ollama model:tag) + Ollama ``model:tag`` ids are preserved even when the model half is a + provider name (``qwen:0.5b``, ``deepseek:latest``). """ if ":" not in model or model.startswith("http"): return model @@ -150,47 +128,24 @@ _MODEL_CACHE_TTL = 3600 _endpoint_model_metadata_cache: Dict[str, Dict[str, Dict[str, Any]]] = {} _endpoint_model_metadata_cache_time: Dict[str, float] = {} _ENDPOINT_MODEL_CACHE_TTL = 300 -# Bounded-lifetime cache: after the first successful probe we remember the -# server type so subsequent refreshes skip the full waterfall (no more 404 -# spam every 5 minutes on non-matching endpoints like /api/v1/models on vllm). -# Entries expire after _ENDPOINT_PROBE_TTL_SECONDS so a server swap on the -# same port (stop Ollama, start LM Studio) is eventually re-detected instead -# of being pinned to the stale type for the whole process lifetime. -# Values are (server_type, monotonic_timestamp). +# Server-type verdicts: (server_type, monotonic_ts). Positive verdicts live an +# hour (so a server swap on the same port is eventually re-detected); a None +# verdict gets the short TTL so a transient failure (server starting, key being +# fixed) recovers in minutes while still not re-running the waterfall each turn. _ENDPOINT_PROBE_TTL_SECONDS = 3600.0 -# A failed probe verdict (server_type is None โ€” no known endpoint answered) -# is cached for a much shorter window: the in-memory entry exists only to -# keep one image-bearing turn from re-running the 5-request waterfall on -# every subsequent turn (#89863 โ€” a keyed remote endpoint answered 401 to -# each leg and the None verdict was never cached, so every turn re-probed). -# Short TTL keeps a transient failure (server starting up, key being fixed) -# recoverable within minutes instead of pinning "undetected" for an hour. _ENDPOINT_PROBE_FAILURE_TTL_SECONDS = 300.0 _endpoint_probe_path_cache: Dict[str, tuple] = {} -# A configured endpoint that is routable-but-dead โ€” e.g. a corp LAN address -# while off-VPN โ€” blackholes TCP: the SYN draws no SYN-ACK, no RST and no ICMP -# error, so a probe waits out its full timeout instead of failing fast. Startup -# runs a whole waterfall of such probes across several functions here, and the -# stalls stack into a minute-long hang before the banner renders. -# -# Once ANY probe has actually observed a connect timeout for an endpoint, the -# others have nothing to gain by repeating it. Recording that observation and -# short-circuiting on it performs no network I/O of its own โ€” it adds no probe -# for callers or tests to mock, and it can only ever fire after a real timeout -# has already been paid, so it cannot suppress a probe that would have worked. +# Routable-but-dead endpoints (corp LAN off-VPN) blackhole TCP: every probe +# waits out its full connect timeout and startup stalls for a minute. Once ANY +# probe observed a connect timeout, later probes short-circuit for a while. +# Pure bookkeeping โ€” no network I/O, fires only after a real timeout was paid. _ENDPOINT_BLACKHOLE_TTL_SECONDS = 30.0 -# Values are monotonic timestamps of the last observed connect timeout. -_endpoint_blackhole_cache: Dict[str, float] = {} +_endpoint_blackhole_cache: Dict[str, float] = {} # host:port -> monotonic ts def _endpoint_host_key(base_url: str) -> Optional[str]: - """Return a ``host:port`` key for ``base_url``, or None if it has no host. - - Keyed on host:port rather than the full URL so every probe path for one - server โ€” ``/v1``-suffixed or not, LM Studio root or API root โ€” shares a - single entry. - """ + """``host:port`` key (None without a host) so every probe path for one server shares an entry.""" normalized = _normalize_base_url(base_url) if not normalized: return None @@ -217,13 +172,7 @@ def _note_endpoint_blackholed(base_url: str) -> None: def _endpoint_blackholed(base_url: str) -> bool: - """True if a recent probe to ``base_url`` timed out during TCP connect. - - Pure cache lookup; never touches the network. The entry expires after - _ENDPOINT_BLACKHOLE_TTL_SECONDS โ€” long enough to collapse one startup's - burst of probes, short enough that bringing the VPN up mid-session is - picked up without a restart. - """ + """True if a recent probe to ``base_url`` timed out during TCP connect (cache lookup only).""" if _ENDPOINT_BLACKHOLE_TTL_SECONDS <= 0: return False key = _endpoint_host_key(base_url) @@ -258,72 +207,79 @@ def _is_connect_timeout(exc: BaseException) -> bool: pass return False -# โ”€โ”€ Disk L2 for local-endpoint probe results โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ -# The in-process caches above die with the process, so every CLI cold start -# with a local model re-paid the probe waterfall in AIAgent.__init__: -# detect_local_server_type (up to 4 HTTP GETs, โ‰ค2 s each on a hung server) -# + /api/show (โ‰ค3 s). A short-TTL disk cache makes back-to-back CLI -# invocations hit disk instead of the network. Only SUCCESSFUL probes are -# persisted (a down server must not pin a negative verdict), and the TTL is -# short enough that swapping the server on a port (stop Ollama, start -# LM Studio) is picked up within minutes โ€” strictly fresher than the 1 h -# in-process TTL that already accepts that staleness. +# Disk L2 for local-endpoint probes so back-to-back CLI cold starts skip the +# waterfall. Only SUCCESSFUL probes are persisted (a down server must not pin +# a negative verdict); the TTL is shorter than the 1 h in-process one. _LOCAL_PROBE_DISK_TTL_SECONDS = 300.0 -def _local_probe_disk_cache_path() -> Path: +def _cache_file(name: str) -> Path: from hermes_constants import get_hermes_home - return get_hermes_home() / "cache" / "local_endpoint_probes.json" + return get_hermes_home() / "cache" / name -def _load_local_probe_disk_cache() -> Dict[str, Any]: +def _load_json_dict(path: Path) -> Dict[str, Any]: + """JSON object at ``path``, or {} when missing/invalid.""" try: - with _local_probe_disk_cache_path().open("r", encoding="utf-8") as f: + with path.open("r", encoding="utf-8") as f: data = json.load(f) return data if isinstance(data, dict) else {} except Exception: return {} -def _local_probe_disk_get(kind: str, key: str) -> Optional[Any]: - """Return a fresh cached value for ``kind:key``, else None.""" - entry = _load_local_probe_disk_cache().get(f"{kind}:{key}") +def _ttl_memo_get(path: Path, key: str, ttl: float, *, ts_key: str, value_key: str) -> Optional[Any]: + """Fresh (< ``ttl`` seconds) ``value_key`` of the ``key`` entry in a TTL memo file, else None.""" + entry = _load_json_dict(path).get(key) if not isinstance(entry, dict): return None try: - if (time.time() - float(entry["ts"])) >= _LOCAL_PROBE_DISK_TTL_SECONDS: + if (time.time() - float(entry[ts_key])) >= ttl: return None - return entry["value"] + return entry[value_key] except Exception: return None -def _local_probe_disk_put(kind: str, key: str, value: Any) -> None: - """Persist a successful probe result. Best-effort; prunes stale entries.""" +def _ttl_memo_put( + path: Path, key: str, value: Any, ttl: float, *, ts_key: str, value_key: str, what: str, ts_first: bool = False, +) -> None: + """Write ``key`` into a TTL memo file, dropping expired siblings. Best-effort.""" try: now = time.time() - data = _load_local_probe_disk_cache() data = { - k: v - for k, v in data.items() - if isinstance(v, dict) - and (now - float(v.get("ts", 0))) < _LOCAL_PROBE_DISK_TTL_SECONDS + k: v for k, v in _load_json_dict(path).items() + if isinstance(v, dict) and (now - float(v.get(ts_key, 0))) < ttl } - data[f"{kind}:{key}"] = {"value": value, "ts": now} - atomic_json_write( - _local_probe_disk_cache_path(), - data, - indent=0, - separators=(",", ":"), - ) + data[key] = {ts_key: now, value_key: value} if ts_first else {value_key: value, ts_key: now} + atomic_json_write(path, data, indent=0, separators=(",", ":")) except Exception as e: - logger.debug("Failed to save local probe disk cache: %s", e) + logger.debug("Failed to save %s: %s", what, e) + + +def _local_probe_disk_cache_path() -> Path: + return _cache_file("local_endpoint_probes.json") + + +def _local_probe_disk_get(kind: str, key: str) -> Optional[Any]: + """Return a fresh cached value for ``kind:key``, else None.""" + return _ttl_memo_get( + _local_probe_disk_cache_path(), f"{kind}:{key}", _LOCAL_PROBE_DISK_TTL_SECONDS, + ts_key="ts", value_key="value", + ) + + +def _local_probe_disk_put(kind: str, key: str, value: Any) -> None: + """Persist a successful probe result. Best-effort; prunes stale entries.""" + _ttl_memo_put( + _local_probe_disk_cache_path(), f"{kind}:{key}", value, _LOCAL_PROBE_DISK_TTL_SECONDS, + ts_key="ts", value_key="value", what="local probe disk cache", + ) def _get_model_metadata_cache_path() -> Path: """Return path to the OpenRouter model metadata disk cache.""" - from hermes_constants import get_hermes_home - return get_hermes_home() / "cache" / "openrouter_model_metadata.json" + return _cache_file("openrouter_model_metadata.json") def _model_metadata_disk_cache_age_seconds() -> Optional[float]: @@ -372,60 +328,33 @@ def _save_model_metadata_disk_cache(data: Dict[str, Dict[str, Any]]) -> None: def _get_endpoint_metadata_cache_path() -> Path: """On-disk memo of remote ``/models`` probes (see ``_endpoint_disk_cache_get``).""" - from hermes_constants import get_hermes_home - return get_hermes_home() / "cache" / "endpoint_model_metadata.json" + return _cache_file("endpoint_model_metadata.json") def _endpoint_disk_cache_get(normalized: str) -> Optional[Dict[str, Dict[str, Any]]]: - """Return a still-fresh (``_ENDPOINT_MODEL_CACHE_TTL``) disk memo for one endpoint. + """Fresh (``_ENDPOINT_MODEL_CACHE_TTL``) cross-process memo of a remote ``/models`` probe. - The in-memory endpoint cache only helps within a process. One-shot runs - (``hermes -q``, cron, every Bot Mode DM hop) start cold and re-probed the - live ``/models`` endpoint on every launch โ€” 0.3โ€“0.6s of pure network per - process on Nous, whose persistent context cache is bypassed by design so - the portal stays authoritative. This memo keeps that authority (same TTL - as the in-memory cache, so reconciliation still lands within 5 minutes) - while sharing the answer across processes. Local endpoints are never - memoized: their loaded context is transient (LM Studio reloads). + One-shot runs (``hermes -q``, cron, Bot Mode hops) start cold; Nous bypasses + the persistent context cache by design, so without this every launch paid + the live probe. Same TTL as the in-memory cache keeps the portal + authoritative. Local endpoints are never memoized (transient loaded context). """ - try: - with _get_endpoint_metadata_cache_path().open("r", encoding="utf-8") as f: - data = json.load(f) - entry = data.get(normalized) if isinstance(data, dict) else None - if not isinstance(entry, dict): - return None - if (time.time() - float(entry.get("at", 0))) >= _ENDPOINT_MODEL_CACHE_TTL: - return None - models = entry.get("models") - return models if isinstance(models, dict) else None - except Exception: - return None + models = _ttl_memo_get( + _get_endpoint_metadata_cache_path(), normalized, _ENDPOINT_MODEL_CACHE_TTL, + ts_key="at", value_key="models", + ) + return models if isinstance(models, dict) else None def _endpoint_disk_cache_put(normalized: str, cache: Dict[str, Dict[str, Any]]) -> None: """Memoize a successful remote ``/models`` probe; expired siblings are dropped.""" - try: - path = _get_endpoint_metadata_cache_path() - data: Dict[str, Any] = {} - if path.exists(): - with path.open("r", encoding="utf-8") as f: - loaded = json.load(f) - if isinstance(loaded, dict): - now = time.time() - data = { - k: v for k, v in loaded.items() - if isinstance(v, dict) and (now - float(v.get("at", 0))) < _ENDPOINT_MODEL_CACHE_TTL - } - data[normalized] = {"at": time.time(), "models": cache} - atomic_json_write(path, data, indent=0, separators=(",", ":")) - except Exception as e: - logger.debug("Failed to save endpoint model metadata disk cache: %s", e) + _ttl_memo_put( + _get_endpoint_metadata_cache_path(), normalized, cache, _ENDPOINT_MODEL_CACHE_TTL, + ts_key="at", value_key="models", what="endpoint model metadata disk cache", ts_first=True, + ) -# Descending tiers for context length probing when the model is unknown. -# We start at 256K (covers GPT-5.x, many current large-context models) and -# step down on context-length errors until one works. Tier[0] is also the -# default fallback when no detection method succeeds. +# Descending probe tiers for unknown models; tier[0] is also the default fallback. CONTEXT_PROBE_TIERS = [ 256_000, 128_000, @@ -438,9 +367,7 @@ CONTEXT_PROBE_TIERS = [ # Default context length when no detection method succeeds. DEFAULT_FALLBACK_CONTEXT = CONTEXT_PROBE_TIERS[0] -# (model, base_url) pairs that already emitted the fallback warning. -# The fallback result itself is deliberately never cached, so without this -# the warning would repeat on every resolution for the same unknown model. +# The fallback result is never cached, so dedupe its warning per (model, base_url). _FALLBACK_WARNED: set = set() @@ -459,29 +386,22 @@ def _warn_context_length_fallback(model: str, base_url: str) -> None: model, base_url or "default", f"{DEFAULT_FALLBACK_CONTEXT:,}", ) -# Minimum context length required to run Hermes Agent. Models with fewer -# tokens cannot maintain enough working memory for tool-calling workflows. -# Sessions, model switches, and cron jobs should reject models below this. +# Sessions, model switches and cron jobs reject models below this: too little +# working memory for tool-calling workflows. MINIMUM_CONTEXT_LENGTH = 64_000 -# Short-lived in-process cache for local-server context probes. Bounds the -# probe rate when the new local-endpoint live-probe paths (reconcile-on-hit + -# pre-defaults step 7) resolve the same model several times during one startup -# (banner, /model switch, compressor update_model). Keyed by (model, base_url); -# values are (result, monotonic_timestamp). Not persisted to disk โ€” cross- -# restart freshness is handled by the reconcile logic re-probing after expiry. +# In-process cache for local-server context probes, (model, base_url) -> +# (result, monotonic_ts): one startup resolves the same model several times +# (banner, /model switch, compressor update_model). Never persisted. _LOCAL_CTX_PROBE_TTL_SECONDS = 30.0 _LOCAL_CTX_PROBE_CACHE: Dict[tuple, tuple] = {} -# Thin fallback defaults โ€” only broad model family patterns. -# These fire only when provider is unknown AND models.dev/OpenRouter/Anthropic -# all miss. Replaced the previous 80+ entry dict. -# For provider-specific context lengths, models.dev is the primary source. +# Family-pattern fallbacks, used only when provider-aware sources all miss. +# Lookups are longest-key-first substring matches, so dict order is cosmetic +# and a specific key must be STRICTLY longer than its catch-all. DEFAULT_CONTEXT_LENGTHS = { - # Anthropic Claude 4.6 (1M context) โ€” bare IDs only to avoid - # fuzzy-match collisions (e.g. "anthropic/claude-sonnet-4" is a - # substring of "anthropic/claude-sonnet-4.6"). - # OpenRouter-prefixed models resolve via OpenRouter live API or models.dev. + # Anthropic โ€” bare ids only (prefixed ids resolve via OpenRouter/models.dev + # and would collide: "anthropic/claude-sonnet-4" โŠ‚ "anthropic/claude-sonnet-4.6"). "claude-fable-5": 1000000, "claude-fable": 1000000, "claude-opus-5": 1000000, @@ -496,15 +416,8 @@ DEFAULT_CONTEXT_LENGTHS = { "claude-sonnet-4.6": 1000000, # Catch-all for older Claude models (must sort after specific entries) "claude": 200000, - # OpenAI โ€” GPT-5 family (most have 400k; specific overrides first) - # Source: https://developers.openai.com/api/docs/models - # GPT-5.5 (launched Apr 23 2026) is 1.05M on the direct OpenAI API and - # ChatGPT Codex OAuth caps it at 272K; both paths resolve via their own - # provider-aware branches (_resolve_codex_oauth_context_length + models.dev). - # This hardcoded value is only reached when every probe misses. - # GPT-5.6 series (Sol/Terra/Luna, GA 2026-07-09) โ€” 1.05M on the direct - # OpenAI API (same as gpt-5.5). Codex OAuth caps these at 272K. - # (Lookups length-sort keys at match time, so dict order is cosmetic.) + # OpenAI โ€” direct-API windows (Codex OAuth caps gpt-5.4+/5.5/5.6 at 272K, + # resolved by its own branch). https://developers.openai.com/api/docs/models "gpt-5.6-luna": 1050000, "gpt-5.6-terra": 1050000, "gpt-5.6-sol": 1050000, @@ -512,13 +425,7 @@ DEFAULT_CONTEXT_LENGTHS = { "gpt-5.4-nano": 400000, # 400k (not 1.05M like full 5.4) "gpt-5.4-mini": 400000, # 400k (not 1.05M like full 5.4) "gpt-5.4": 1050000, # GPT-5.4, GPT-5.4 Pro (1.05M context) - # gpt-5.3-codex-spark is Codex-OAuth-only (ChatGPT Pro entitlement) and - # uses a smaller 128k window than other gpt-5.x slugs. Listed here as - # a defensive override so the longest-substring fallback doesn't match - # the generic "gpt-5" entry below (400k) and report the wrong limit if - # Spark's context ever needs to be resolved through this path. Real - # usage flows through _CODEX_OAUTH_CONTEXT_FALLBACK at line ~1113. - "gpt-5.3-codex-spark": 128000, + "gpt-5.3-codex-spark": 128000, # Codex-OAuth-only; keeps "gpt-5" (400k) from winning "gpt-5.1-chat": 128000, # Chat variant has 128k context "gpt-5": 400000, # GPT-5.x base, mini, codex variants (400k) "gpt-4.1": 1047576, @@ -531,12 +438,7 @@ DEFAULT_CONTEXT_LENGTHS = { "gemma-4-31b": 256000, "gemma-3": 131072, "gemma": 8192, # fallback for older gemma models - # DeepSeek โ€” V4 family ships with a 1M context window. The legacy - # aliases ``deepseek-chat`` / ``deepseek-reasoner`` are server-side - # mapped to the non-thinking / thinking modes of ``deepseek-v4-flash`` - # and inherit the same 1M window. The ``deepseek`` substring entry - # below remains as a 128K fallback for older / unknown DeepSeek model - # ids (e.g. via custom endpoints). + # DeepSeek โ€” V4 family is 1M; deepseek-chat/-reasoner alias v4-flash modes. # https://api-docs.deepseek.com/zh-cn/quick_start/pricing "deepseek-v4-pro": 1_000_000, "deepseek-v4-flash": 1_000_000, @@ -545,13 +447,8 @@ DEFAULT_CONTEXT_LENGTHS = { "deepseek": 128000, # Meta "llama": 131072, - # Thinking Machines โ€” Inkling family ships with a 1M context window - # (max output 256K). Verified against OpenRouter live metadata - # (context_length 1,048,576 for inkling, inkling-small, and the - # :free SKUs, 2026-08-27). Substring matching means "inkling" - # covers inkling-small and every :free/:batch variant; the :batch - # SKU's smaller live window (524,288) is served by the provider's - # live metadata when available. + # Thinking Machines โ€” covers inkling-small and :free/:batch variants (the + # :batch SKU's smaller live window comes from provider metadata). "inkling": 1_048_576, # Qwen โ€” specific model families before the catch-all. # Official docs: https://help.aliyun.com/zh/model-studio/developer-reference/ @@ -563,37 +460,18 @@ DEFAULT_CONTEXT_LENGTHS = { "qwen3-coder": 262144, # 256K context "qwen3-max": 262144, # 256K context (qwen3-max-2026-01-23 snapshot, Coding Plan) "qwen": 131072, - # MiniMax โ€” M3 is 1M context (max output 512K); M2.x series is 204,800. - # Keys use substring matching (longest-first), so "minimax-m3" wins over - # the generic "minimax" catch-all for the M3 slug on every surface - # (native MiniMax-M3, OpenRouter/Nous minimax/minimax-m3). - # https://platform.minimax.io/docs/api-reference/text-chat-openai + # MiniMax โ€” M3 is 1M; M2.x is 204,800. https://platform.minimax.io/docs/api-reference/text-chat-openai "minimax-m3": 1000000, "minimax": 204800, - # GLM โ€” GLM-5.2 and GLM-5.3 ship with a 1M context window. GLM-5.2 was - # verified empirically (needle-in-a-haystack retrieval at 789K prompt - # tokens succeeded with zero errors on api.z.ai/api/coding/paas/v4). - # GLM-5.3 uses the same base model (all gains are post-training) with - # 1M context / 128K max output per docs.z.ai/guides/llm/glm-5.3 - # (verified 2026-08-14). Older GLM models (5, 5.1, 5-turbo) are ~202K. - # Longest-key-first substring matching ensures "glm-5.2"/"glm-5.3" - # resolve to 1M while older variants still hit the generic 202K fallback. + # GLM โ€” 5.2/5.3 are 1M (5.2 verified empirically at 789K on api.z.ai); + # older GLM (5, 5.1, 5-turbo) ~202K. "glm-5.2": 1_048_576, - # OpenRouter's free GLM-5.2 variant is capped at 256K (live metadata, - # 2026-08-21) โ€” longer key wins over the 1M paid entry above. - "glm-5.2:free": 256_000, + "glm-5.2:free": 256_000, # OpenRouter free variant is capped; longer key wins "glm-5.3": 1_048_576, "glm": 202752, - # xAI Grok โ€” xAI /v1/models does not return context_length metadata, - # so these hardcoded fallbacks prevent Hermes from probing-down to - # the default 128k when the user points at https://api.x.ai/v1 - # via a custom provider. Values sourced from models.dev (2026-04). - # Keys use substring matching (longest-first), so e.g. "grok-4.20" - # matches "grok-4.20-0309-reasoning" / "-non-reasoning" / "-multi-agent-0309". - # OAuth-only slug; absent from GET /v1/models. xAI publishes a 200k - # usable context window for Composer 2.5 on Grok Build (SuperGrok / - # Premium+); /v1/responses additionally enforces a ~262144 input+output - # budget, but the usable context (what we track here) is 200k. + # xAI โ€” /v1/models returns no context_length, so these prevent probe-down + # on api.x.ai custom providers. grok-composer is OAuth-only: 200k usable + # (the /v1/responses ~262144 input+output budget is a separate limit). "grok-composer": 200000, # grok-composer-2.5-fast (Grok Build CLI) "grok-build-latest": 500000, # alias of grok-4.5 (early access) "grok-build": 256000, # grok-build-0.1 @@ -608,47 +486,26 @@ DEFAULT_CONTEXT_LENGTHS = { "grok-3": 131072, # grok-3, grok-3-mini, grok-3-fast, grok-3-mini-fast "grok-2": 131072, # grok-2, grok-2-1212, grok-2-latest "grok": 131072, # catch-all (grok-beta, unknown grok-*) - # Kimi โ€” K3 ships with a 1 Mi context window (1,048,576; verified against - # models.dev and OpenRouter live metadata, matching the endpoint-scoped - # override in _endpoint_scoped_context_length). Longest-key-first substring - # matching ensures "kimi-k3" resolves to 1M while older/unknown Kimi models - # still hit the generic 256K fallback. + # Kimi โ€” K3 is 1 Mi (matches the endpoint-scoped override); older Kimi 256K. "kimi-k3": 1_048_576, "kimi": 262144, - # Upstage Solar โ€” api.upstage.ai/v1/models does not return context_length, - # so these fallbacks keep token budgeting / compression from probing down - # to the 128k default. Ids are matched longest-first, so dated variants - # (e.g. solar-pro3-250127) resolve via their family prefix. - # Sources: Solar Pro 3 = 128K, Solar Pro 2 = 64K, Solar Mini = 32K, - # Solar Open 2 = 256K. + # Upstage Solar โ€” /v1/models returns no context_length; dated variants + # (solar-pro3-250127) resolve via the family prefix. "solar-open2": 262144, # 256K "solar-pro3": 131072, "solar-pro2": 65536, "solar-mini": 32768, - # Tencent โ€” Hy4 Preview (Hunyuan), 1M context window per OpenRouter - # live metadata (2026-08-28). Longest-key-first so this wins over any - # future shorter hy* catch-all. + # Tencent Hunyuan (262144 = 256 ร— 1024, aligned with OpenRouter live metadata) "hy4-preview": 1_048_576, - # Tencent โ€” Hy3 Preview (Hunyuan) with 256K context window. - # OpenRouter live metadata reports 262144 (256 ร— 1024); align the - # static fallback so cache and offline both agree (issue #22268). "hy3-preview": 262144, - # Tencent โ€” Hy3 (GA successor to Hy3 Preview), same 256K window. "hy3": 262144, - # OpenCode Zen โ€” "Ox Alpha" stealth model (x-preview-f-free). 1M context - # per OpenCode's launch announcement (2026-08-20); free, ZDR. + # "Ox Alpha" stealth model โ€” OpenCode Zen slug and OpenRouter slug "x-preview-f": 1_048_576, - # OpenRouter โ€” same "Ox Alpha" stealth model under its OpenRouter slug - # (stealth/ox-alpha). 1M context per OpenRouter live metadata (2026-08-20). "ox-alpha": 1_048_576, - # Nemotron โ€” NVIDIA's open-weights series (128K context across all sizes) - # EXCEPT 3.5 Lightning, which ships a 1M window (OpenRouter live metadata - # + OpenCode Zen free tier, verified 2026-08-21). + # NVIDIA Nemotron โ€” 128K across sizes except 3.5 Lightning (1M) "nemotron-3.5-lightning": 1_000_000, "nemotron": 131072, - # Poolside Laguna 2.1 (s/xs) โ€” 256K window per OpenRouter live metadata - # (2026-08-21). Covers laguna-s-2.1:free, laguna-xs-2.1:free, and the - # OpenCode Zen laguna-s-2.1-free slug via substring matching. + # Poolside Laguna 2.1 (covers :free and OpenCode Zen -free slugs) "laguna-s-2.1": 262144, "laguna-xs-2.1": 262144, # Arcee @@ -672,48 +529,26 @@ DEFAULT_CONTEXT_LENGTHS = { "zai-org/GLM-5": 202752, } -# xAI Grok models that ACCEPT the `reasoning.effort` parameter on -# api.x.ai. Verified live against /v1/responses 2026-05-10: -# -# ACCEPTS effort: grok-3-mini, grok-3-mini-fast, grok-4.20-multi-agent-0309, -# grok-4.3 -# REJECTS effort: grok-3, grok-4, grok-4-0709, grok-4-fast-(non-)reasoning, -# grok-4-1-fast-(non-)reasoning, grok-4.20-0309-(non-)reasoning, -# grok-code-fast-1 -# -# REJECTS-side models still reason natively โ€” they just don't expose an -# effort dial โ€” so callers should send no `reasoning` key at all rather -# than a default `medium` (which 400s with "Model X does not support -# parameter reasoningEffort"). +# xAI Grok models that ACCEPT `reasoning.effort` (verified live against +# /v1/responses). Unlisted Grok models still reason natively but 400 on the +# parameter ("Model X does not support parameter reasoningEffort"), so callers +# must send no `reasoning` key rather than a default `medium`. _GROK_EFFORT_CAPABLE_PREFIXES = ( "grok-3-mini", "grok-4.20-multi-agent", "grok-4.3", - # grok-4.5: verified live against /v1/responses 2026-07-08 โ€” accepts - # effort low/medium/high (default: high when omitted) but REJECTS - # "none" ("This model does not support `reasoning_effort` value `none`"), - # unlike grok-4.3. models.dev agrees: effort values [low, medium, high]. - "grok-4.5", - # grok-4.6: drop-in successor of grok-4.5 (same effort dial). - "grok-4.6", + "grok-4.5", # accepts low/medium/high (default high) but REJECTS "none", unlike grok-4.3 + "grok-4.6", # same effort dial as grok-4.5 ) def grok_supports_reasoning_effort(model: str) -> bool: - """Return True when an xAI Grok model accepts ``reasoning.effort``. - - Allowlist by substring (matches both bare ``grok-3-mini`` and - aggregator-prefixed ``x-ai/grok-3-mini``). Conservative by design: - if a future Grok model isn't listed, we send no effort dial rather - than 400. - """ + """Allowlist check (aggregator prefixes like ``x-ai/`` stripped); unknown Grok models get no effort dial.""" name = (model or "").strip().lower() if not name: return False - # Strip common aggregator prefixes (x-ai/, openrouter/x-ai/, xai/, ...) - for sep in ("/",): - if sep in name: - name = name.rsplit(sep, 1)[-1] + if "/" in name: + name = name.rsplit("/", 1)[-1] return any(name.startswith(prefix) for prefix in _GROK_EFFORT_CAPABLE_PREFIXES) @@ -797,16 +632,10 @@ _URL_TO_PROVIDER: Dict[str, str] = { "inference-api.nousresearch.com": "nous", "api.deepseek.com": "deepseek", "api.githubcopilot.com": "copilot", - # Enterprise Copilot endpoints look like api.enterprise.githubcopilot.com, - # api.business.githubcopilot.com, etc. Match the suffix so context-window - # resolution works for enterprise accounts too. - ".githubcopilot.com": "copilot", + ".githubcopilot.com": "copilot", # api.enterprise./api.business. Copilot hosts "models.github.ai": "copilot", - # GitHub Models free tier (Azure-hosted prototyping endpoint) โ€” same - # canonical provider as the Copilot API. Hard per-request token cap - # (often 8K) makes it unusable for Hermes' system prompt, but mapping - # it here lets us recognize the endpoint and emit a targeted hint - # instead of falling through the unknown-custom-endpoint path. + # GitHub Models free tier: ~8K per-request cap makes it unusable, but + # mapping it lets us emit a targeted hint instead of the custom-endpoint path. "models.inference.ai.azure.com": "copilot", "api.fireworks.ai": "fireworks", "opencode.ai": "opencode-go", @@ -821,8 +650,7 @@ _URL_TO_PROVIDER: Dict[str, str] = { "ollama.com": "ollama-cloud", } -# Auto-extend with hostnames derived from provider profiles. -# Any provider with a base_url not already in the map gets added automatically. +# Auto-extend with provider-profile hostnames not already mapped. try: for _pp in _list_providers(): _host = _pp.get_hostname() @@ -833,12 +661,7 @@ except Exception: def _infer_provider_from_url(base_url: str) -> Optional[str]: - """Infer the models.dev provider name from a base URL. - - This allows context length resolution via models.dev for custom endpoints - like DashScope (Alibaba), Z.AI, Kimi, etc. without requiring the user to - explicitly set the provider name in config. - """ + """models.dev provider name for a base URL (custom endpoints need no explicit provider).""" normalized = _normalize_base_url(base_url) if not normalized: return None @@ -864,18 +687,77 @@ def _is_known_provider_base_url(base_url: str) -> bool: return _infer_provider_from_url(base_url) is not None +def _server_root(base_url: str) -> str: + """Probe root for a local server: IPv4-resolved, ``/v1`` suffix stripped.""" + server_url = _localhost_to_ipv4(base_url.rstrip("/")) + if server_url.endswith("/v1"): + server_url = server_url[:-3] + return server_url + + +def _longest_key_match(table: Dict[str, int], model_lower: str) -> Optional[Tuple[str, int]]: + """First ``(key, value)`` whose key is a substring of ``model_lower``, longest key first. + + Longest-first makes specific entries (``gpt-5.4-mini``) win over their + family catch-all (``gpt-5``); ties keep table order (stable sort). + """ + for key, value in sorted(table.items(), key=lambda x: len(x[0]), reverse=True): + if key in model_lower: + return key, value + return None + + +def _ollama_show_context(data: Dict[str, Any], *, gguf_first: bool, minimum: Optional[int] = None) -> Optional[int]: + """Context length from an Ollama ``/api/show`` payload. + + ``parameters`` -> ``num_ctx`` is the Modelfile override (the RUNTIME window + Ollama allocates KV cache for); ``model_info.*.context_length`` is the GGUF + training max, which can exceed num_ctx. Local users control num_ctx, so + local probes prefer it; hosted Ollama operators may cap num_ctx + arbitrarily, so hosted probes prefer the GGUF value (``gguf_first``). + """ + def _num_ctx() -> Optional[int]: + for line in data.get("parameters", "").split("\n"): + if "num_ctx" in line: + parts = line.strip().split() + if len(parts) >= 2: + try: + ctx = int(parts[-1]) + except ValueError: + continue + if minimum is None or ctx >= minimum: + return ctx + return None + + def _gguf() -> Optional[int]: + for key, value in data.get("model_info", {}).items(): + if "context_length" in key and isinstance(value, (int, float)): + ctx = int(value) + if minimum is None or ctx >= minimum: + return ctx + return None + + for reader in ((_gguf, _num_ctx) if gguf_first else (_num_ctx, _gguf)): + ctx = reader() + if ctx is not None: + return ctx + return None + + +# (host, canonical paths, model ids, context) โ€” see _endpoint_scoped_context_length. +_ENDPOINT_SCOPED_CONTEXT = ( + ("api.kimi.com", {"/coding", "/coding/v1"}, {"k3", "kimi-k3", "kimi-k3-cot"}, 1_048_576), + ("integrate.api.nvidia.com", {"/v1"}, {"deepseek-ai/deepseek-v4-pro"}, 262_144), +) + + def _endpoint_scoped_context_length(model: str, base_url: str) -> Optional[int]: - """Return context metadata confirmed for one provider endpoint. + """Context confirmed for one provider endpoint only (see _ENDPOINT_SCOPED_CONTEXT). - Kimi Coding serves K3 under the bare slug ``k3``, but users may also - configure or select the public-facing aliases ``kimi-k3`` and - ``kimi-k3-cot``. Only canonical ``https://api.kimi.com/coding`` endpoints - (legacy Moonshot keys do not serve K3) get the 1 Mi context window. - - NVIDIA NIM serves ``deepseek-ai/deepseek-v4-pro`` with a 262,144-token - window even though DeepSeek's native endpoint serves the V4 family with a - 1M window. Keep the lower limit scoped to NVIDIA instead of weakening the - global model-family metadata. + Kimi Coding serves K3 (aliases kimi-k3, kimi-k3-cot) at 1 Mi only on the + canonical ``https://api.kimi.com/coding`` host โ€” legacy Moonshot keys do + not. NVIDIA NIM serves deepseek-v4-pro at 262,144 while DeepSeek's native + endpoint is 1M; the lower limit stays scoped to NVIDIA. """ normalized = _normalize_base_url(base_url) try: @@ -883,43 +765,31 @@ def _endpoint_scoped_context_length(model: str, base_url: str) -> Optional[int]: port = parsed.port except ValueError: return None + # Only canonical https://host[:443]/path with no credentials/query/fragment. if ( - parsed.scheme.lower() == "https" - and (parsed.hostname or "").lower() == "api.kimi.com" - and port in (None, 443) - and parsed.username is None - and parsed.password is None - and parsed.path.rstrip("/") in {"/coding", "/coding/v1"} - and not parsed.query - and not parsed.fragment - and model.strip().lower() in {"k3", "kimi-k3", "kimi-k3-cot"} + parsed.scheme.lower() != "https" + or port not in (None, 443) + or parsed.username is not None + or parsed.password is not None + or parsed.query + or parsed.fragment ): - return 1_048_576 - if ( - parsed.scheme.lower() == "https" - and (parsed.hostname or "").lower() == "integrate.api.nvidia.com" - and port in (None, 443) - and parsed.username is None - and parsed.password is None - and parsed.path.rstrip("/") == "/v1" - and not parsed.query - and not parsed.fragment - and model.strip().lower() == "deepseek-ai/deepseek-v4-pro" - ): - return 262_144 + return None + host = (parsed.hostname or "").lower() + path = parsed.path.rstrip("/") + model_key = model.strip().lower() + for scoped_host, paths, models, ctx in _ENDPOINT_SCOPED_CONTEXT: + if host == scoped_host and path in paths and model_key in models: + return ctx return None def _skip_persistent_context_cache(base_url: str, provider: str) -> bool: - """Return True when the on-disk context cache must not short-circuit probing. + """Providers whose on-disk context cache must not short-circuit probing. - LM Studio excludes caching because loaded context is transient โ€” the user - can reload the model with a different context_length at any time. - - Codex OAuth excludes caching because its context window is account- and - entitlement-specific metadata supplied by the authenticated /models - endpoint. A fallback value written after a transient probe failure must - not prevent a later live probe from observing an updated allocation. + LM Studio: loaded context is transient (the user can reload with another + context_length). Codex OAuth: the window is account/entitlement-specific, + and a fallback persisted after a transient failure would suppress revalidation. """ return (provider or "").strip().lower() in {"lmstudio", "openai-codex"} @@ -929,17 +799,25 @@ def _maybe_cache_local_context_length( base_url: str, length: int, ) -> None: - """Persist a locally probed context length only when it meets Hermes minimum. + """Persist a probed local window only at/above MINIMUM_CONTEXT_LENGTH. - Sub-minimum live windows (e.g. vLLM ``--max-model-len 32768``) are still - returned to callers so ``agent_init`` can fail with the existing - minimum-context guidance โ€” they must not be normalized into the on-disk cache - as if they were valid operating limits. + Sub-minimum windows are still returned so agent_init can reject them, but + must not be blessed into the on-disk cache as valid operating limits. """ if length >= MINIMUM_CONTEXT_LENGTH: save_context_length(model, base_url, length) +def _probe_local_context_length(model: str, base_url: str, api_key: str, provider: str) -> Optional[int]: + """Live local probe; persists a positive result unless the provider opts out of the disk cache.""" + local_ctx = _query_local_context_length(model, base_url, api_key=api_key) + if local_ctx and local_ctx > 0: + if not _skip_persistent_context_cache(base_url, provider): + _maybe_cache_local_context_length(model, base_url, local_ctx) + return local_ctx + return None + + def _reconcile_local_cached_context_length( model: str, base_url: str, @@ -948,14 +826,9 @@ def _reconcile_local_cached_context_length( ) -> int: """Return *cached* unless a live local probe reports a different limit. - vLLM/Ollama operators can restart with a new ``--max-model-len`` / ``num_ctx`` - without changing the model id. When the server is reachable, prefer its - reported window over a stale disk entry; when the probe fails (offline tests, - network blip), keep the cached value. - - Live probes below :data:`MINIMUM_CONTEXT_LENGTH` invalidate stale cache - entries but are not persisted โ€” startup should reject them, not bless a - sub-64K window as config. + Operators restart vLLM/Ollama with a new --max-model-len / num_ctx under + the same model id; a reachable server wins over the disk entry, a failed + probe keeps it. Sub-minimum live windows invalidate but are not persisted. """ live_ctx = _query_local_context_length(model, base_url, api_key=api_key) if live_ctx and live_ctx > 0 and live_ctx != cached: @@ -978,15 +851,9 @@ def _reconcile_local_cached_context_length( def is_local_endpoint(base_url: str) -> bool: - """Return True if base_url points to a local machine. - - Recognises loopback (``localhost``, ``127.0.0.0/8``, ``::1``), - container-internal DNS names (``host.docker.internal`` et al.), - RFC-1918 private ranges (``10/8``, ``172.16/12``, ``192.168/16``), - link-local, and Tailscale CGNAT (``100.64.0.0/10``). Tailscale CGNAT - is included so remote-but-trusted Ollama boxes reached over a - Tailscale mesh get the same timeout auto-bumps as localhost Ollama. - """ + """True for loopback, container-internal DNS, unqualified hosts, RFC-1918, + link-local and Tailscale CGNAT (so a trusted Ollama box over Tailscale gets + the same timeout auto-bumps as localhost).""" normalized = _normalize_base_url(base_url) if not normalized: return False @@ -1020,37 +887,26 @@ def is_local_endpoint(base_url: str) -> bool: if len(parts) == 4: try: first, second = int(parts[0]), int(parts[1]) - if first == 10: - return True - if first == 172 and 16 <= second <= 31: - return True - if first == 192 and second == 168: - return True - if first == 100 and 64 <= second <= 127: - return True except ValueError: - pass + return False + return ( + first == 10 + or (first == 172 and 16 <= second <= 31) + or (first == 192 and second == 168) + or (first == 100 and 64 <= second <= 127) + ) return False def _localhost_to_ipv4(url: str) -> str: """Rewrite a ``localhost`` HOST to ``127.0.0.1`` in a probe URL. - On Windows dual-stack machines, httpx resolves ``localhost`` to ``::1`` - first and pays a ~2s IPv6 connect timeout before falling back to IPv4 - when the local server only listens on IPv4 (LM Studio, Ollama defaults). - Probing the IPv4 loopback directly skips that penalty. - - Only the URL's own host component is rewritten (anchored at the scheme), - so a non-localhost URL whose path or query merely embeds the substring - ``http://localhost...`` (e.g. ``?upstream=http://localhost:11434``) - passes through untouched. + Windows dual-stack resolves localhost to ::1 first and pays a ~2s IPv6 + connect timeout when the server only listens on IPv4. Anchored at the + scheme so an embedded ``?upstream=http://localhost`` is untouched. """ if not url or not isinstance(url, str): - # Non-string values (test doubles, lazily-resolved config objects) - # previously flowed through these call sites untouched โ€” keep that - # contract; re.sub would raise TypeError. - return url + return url # non-string values (test doubles, lazy config) pass through return re.sub( r"^(https?://)localhost(?=[:/]|$)", r"\g<1>127.0.0.1", @@ -1060,34 +916,17 @@ def _localhost_to_ipv4(url: str) -> str: def detect_local_server_type(base_url: str, api_key: str = "") -> Optional[str]: - """Detect which local server is running at base_url by probing known endpoints. - - Returns one of: "ollama", "lm-studio", "vllm", "llamacpp", or None. - - The result is cached for the lifetime of the process so that repeated - calls (e.g. every 5-minute metadata refresh) never re-run the waterfall - and never spray 404s at endpoints the server does not expose. - """ + """Probe known endpoints: "ollama", "lm-studio", "vllm", "llamacpp", or None (TTL-cached).""" import httpx - normalized = _normalize_base_url(base_url) - - # Resolve localhost to IPv4 to avoid 2s IPv6 timeout on Windows dual-stack. - # Applied to ``normalized`` before deriving server/LM Studio URLs AND - # before the cache lookup, so localhost and 127.0.0.1 share a cache entry. - normalized = _localhost_to_ipv4(normalized) - - server_url = normalized - if server_url.endswith("/v1"): - server_url = server_url[:-3] + # IPv4-resolve BEFORE deriving server/LM Studio URLs and the cache lookup, + # so localhost and 127.0.0.1 share a cache entry. + normalized = _localhost_to_ipv4(_normalize_base_url(base_url)) + server_url = _server_root(normalized) lmstudio_url = _lmstudio_server_root(normalized) cached = _endpoint_probe_path_cache.get(server_url) if cached is not None: - # Positive verdicts live for the full TTL; a None verdict (probe - # waterfall answered nothing recognizable) gets the short failure - # TTL so it still throttles re-probing without pinning the - # endpoint as undetected for a whole hour (#89863). ttl = ( _ENDPOINT_PROBE_TTL_SECONDS if cached[0] is not None @@ -1096,15 +935,11 @@ def detect_local_server_type(base_url: str, api_key: str = "") -> Optional[str]: if (time.monotonic() - cached[1]) < ttl: return cached[0] - # The host already blackholed a connect: skip the waterfall below, each leg - # of which would otherwise burn its full 2s timeout. Deliberately NOT - # written to _endpoint_probe_path_cache โ€” that entry lives for an hour, - # which would pin the endpoint to "undetected" long after it comes back. + # Blackholed host: skip the waterfall. Deliberately NOT written to the + # hour-long verdict cache, which would pin "undetected" after it comes back. if _endpoint_blackholed(server_url): return None - # Disk L2: a fresh cross-process verdict skips the HTTP waterfall - # entirely (back-to-back CLI invocations, cron ticks). disk_hit = _local_probe_disk_get("server_type", server_url) if isinstance(disk_hit, str): _endpoint_probe_path_cache[server_url] = (disk_hit, time.monotonic()) @@ -1113,58 +948,40 @@ def detect_local_server_type(base_url: str, api_key: str = "") -> Optional[str]: headers = _auth_headers(api_key) def _probe_failed(exc: Exception) -> None: - """Swallow a probe error โ€” or abort the waterfall if we were blackholed. - - Re-raising propagates out of the ``with`` block to the outer handler, - so the remaining legs are skipped instead of each stalling in turn. - """ + """Swallow a probe error; on a connect timeout re-raise so the remaining legs are skipped.""" if _is_connect_timeout(exc): _note_endpoint_blackholed(server_url) raise exc + def _lm_studio(client) -> bool: + return client.get(f"{lmstudio_url}/api/v1/models").status_code == 200 + + def _ollama(client) -> bool: + # LM Studio answers /api/tags with {"error": ...} and status 200, so + # the body must actually carry "models". + r = client.get(f"{server_url}/api/tags") + return r.status_code == 200 and "models" in r.json() + + def _llamacpp(client) -> bool: + r = client.get(f"{server_url}/v1/props") + if r.status_code != 200: + r = client.get(f"{server_url}/props") # older builds: no /v1 prefix + return r.status_code == 200 and "default_generation_settings" in r.text + + def _vllm(client) -> bool: + r = client.get(f"{server_url}/version") + return r.status_code == 200 and "version" in r.json() + + # Most specific first: LM Studio's native API, then Ollama, llama.cpp, vLLM. + waterfall = (("lm-studio", _lm_studio), ("ollama", _ollama), ("llamacpp", _llamacpp), ("vllm", _vllm)) result: Optional[str] = None try: with httpx.Client(timeout=2.0, headers=headers) as client: - # LM Studio exposes /api/v1/models โ€” check first (most specific) - try: - r = client.get(f"{lmstudio_url}/api/v1/models") - if r.status_code == 200: - result = "lm-studio" - except Exception as exc: - _probe_failed(exc) - if result is None: - # Ollama exposes /api/tags and responds with {"models": [...]} - # LM Studio returns {"error": "Unexpected endpoint"} with status 200 - # on this path, so we must verify the response contains "models". + for name, probe in waterfall: try: - r = client.get(f"{server_url}/api/tags") - if r.status_code == 200: - try: - data = r.json() - if "models" in data: - result = "ollama" - except Exception: - pass - except Exception as exc: - _probe_failed(exc) - if result is None: - # llama.cpp exposes /v1/props (older builds used /props without the /v1 prefix) - try: - r = client.get(f"{server_url}/v1/props") - if r.status_code != 200: - r = client.get(f"{server_url}/props") # fallback for older builds - if r.status_code == 200 and "default_generation_settings" in r.text: - result = "llamacpp" - except Exception as exc: - _probe_failed(exc) - if result is None: - # vLLM: /version - try: - r = client.get(f"{server_url}/version") - if r.status_code == 200: - data = r.json() - if "version" in data: - result = "vllm" + if probe(client): + result = name + break except Exception as exc: _probe_failed(exc) except Exception: @@ -1174,10 +991,7 @@ def detect_local_server_type(base_url: str, api_key: str = "") -> Optional[str]: _endpoint_probe_path_cache[server_url] = (result, time.monotonic()) _local_probe_disk_put("server_type", server_url, result) else: - # Cache the negative verdict in memory only (never on disk โ€” a - # failure is often transient: server starting, key being fixed) - # so the very next turn does not re-run the whole waterfall - # against an endpoint that just answered nothing (#89863). + # Negative verdict in memory only (never on disk โ€” failures are often transient). _endpoint_probe_path_cache[server_url] = (None, time.monotonic()) return result @@ -1219,17 +1033,9 @@ def _extract_first_int(payload: Dict[str, Any], keys: tuple[str, ...]) -> Option def _extract_flat_context_length(payload: Dict[str, Any]) -> Optional[int]: - """Read a context WINDOW from the top level of a model-describe payload. - - Same key vocabulary as :func:`_extract_context_length` (the module's single - source of truth for what counts as a context window), but WITHOUT the - nested-dict walk โ€” for callers that hold a specific model object and must - not pick up a same-named key from an unrelated nested section. - - Critically, ``max_tokens`` is NOT in ``_CONTEXT_LENGTH_KEYS``: it lives in - ``_MAX_COMPLETION_KEYS`` because on an OpenAI-compatible ``/v1/models`` - passthrough it is the max *output* tokens, not the context window. - """ + """Top-level-only context WINDOW read (no nested walk, so an unrelated nested + section can't leak a same-named key). ``max_tokens`` is deliberately NOT a + window key: on OpenAI-compatible passthroughs it is the max OUTPUT.""" for key in _CONTEXT_LENGTH_KEYS: coerced = _coerce_reasonable_int(payload.get(key)) if coerced is not None: @@ -1246,27 +1052,17 @@ def _extract_max_completion_tokens(payload: Dict[str, Any]) -> Optional[int]: def _context_length_from_model_payload(payload: Dict[str, Any]) -> Optional[int]: - """Extract a context *window* from a ``/v1/models`` model object. + """Context window from a ``/v1/models`` object: window keys first, ``max_tokens`` last. - Prefers input-window keys (``max_model_len``, ``max_input_tokens``, - ``context_length``, โ€ฆ) via :func:`_extract_flat_context_length`. Falls back to - ``max_tokens`` only when no input-window field is present. - - Anthropic (and Anthropic-compatible proxies such as local reverse - proxies) expose both ``max_input_tokens`` (context window, e.g. 1M) and - ``max_tokens`` (max *output* length, e.g. 128k). Using ``max_tokens`` as - the context window under-reports the real limit, persists a stale value - into ``context_length_cache.yaml``, and makes the compressor fire far too - early (e.g. at 75% of 128k instead of 75% of 1M). + Anthropic-shaped payloads carry both ``max_input_tokens`` (1M window) and + ``max_tokens`` (128k OUTPUT cap); reading max_tokens first would persist a + stale window and fire the compressor at 75% of 128k instead of 1M. """ if not isinstance(payload, dict): return None ctx = _extract_flat_context_length(payload) if ctx is not None: return ctx - # Last resort for OpenAI-compat servers that only report max_tokens as - # the window. Safe for Anthropic shapes because max_input_tokens is - # present and already handled above. raw = payload.get("max_tokens") if isinstance(raw, (int, float)): ivalue = int(raw) @@ -1276,33 +1072,25 @@ def _context_length_from_model_payload(payload: Dict[str, Any]) -> Optional[int] def _extract_pricing(payload: Dict[str, Any]) -> Dict[str, Any]: - novita_input = payload.get("input_token_price_per_m") - novita_output = payload.get("output_token_price_per_m") - if novita_input is not None or novita_output is not None: - pricing: Dict[str, Any] = {} - if novita_input is not None: - pricing["prompt"] = str(float(novita_input) / 10_000 / 1_000_000) - if novita_output is not None: - pricing["completion"] = str(float(novita_output) / 10_000 / 1_000_000) - return pricing + def _per_token(source: Dict[str, Any], fields: Dict[str, str], scale) -> Dict[str, Any]: + # Provider $/MTok (or Novita's 1/10_000-$ per M) -> per-token strings so + # usage_pricing consumes them through the same path as OpenRouter. + return { + target: str(scale(float(source[key]))) + for target, key in fields.items() + if source.get(key) is not None + } - # DeepInfra ships pricing under ``metadata.pricing`` with $/MTok values: - # ``input_tokens``, ``output_tokens``, ``cache_read_tokens``. Convert to - # per-token strings so the generic cost machinery (usage_pricing.py) - # consumes them through the same path as OpenRouter / OpenAI. + novita_fields = {"prompt": "input_token_price_per_m", "completion": "output_token_price_per_m"} + if any(payload.get(k) is not None for k in novita_fields.values()): + return _per_token(payload, novita_fields, lambda v: v / 10_000 / 1_000_000) + + # DeepInfra ships pricing under ``metadata.pricing`` in $/MTok. metadata = payload.get("metadata") if isinstance(payload.get("metadata"), dict) else None deepinfra_pricing = metadata.get("pricing") if metadata else None - if isinstance(deepinfra_pricing, dict) and any( - k in deepinfra_pricing for k in ("input_tokens", "output_tokens", "cache_read_tokens") - ): - result: Dict[str, Any] = {} - if deepinfra_pricing.get("input_tokens") is not None: - result["prompt"] = str(float(deepinfra_pricing["input_tokens"]) / 1_000_000) - if deepinfra_pricing.get("output_tokens") is not None: - result["completion"] = str(float(deepinfra_pricing["output_tokens"]) / 1_000_000) - if deepinfra_pricing.get("cache_read_tokens") is not None: - result["cache_read"] = str(float(deepinfra_pricing["cache_read_tokens"]) / 1_000_000) - return result + deepinfra_fields = {"prompt": "input_tokens", "completion": "output_tokens", "cache_read": "cache_read_tokens"} + if isinstance(deepinfra_pricing, dict) and any(k in deepinfra_pricing for k in deepinfra_fields.values()): + return _per_token(deepinfra_pricing, deepinfra_fields, lambda v: v / 1_000_000) alias_map = { "prompt": ("prompt", "input", "input_cost_per_token", "prompt_token_cost"), @@ -1351,9 +1139,8 @@ def fetch_model_metadata(force_refresh: bool = False) -> Dict[str, Dict[str, Any try: _ensure_requests() - # Tuple (connect, read) โ€” flat timeout=10 means urllib3 can block 10s per - # retry stage through proxies that 403 CONNECT, ballooning to minutes - # (#46620). 5s connect / 10s read fails fast on unreachable hosts. + # (connect, read) tuple: a flat timeout lets urllib3 block per retry + # stage through proxies that 403 CONNECT, ballooning to minutes. response = requests.get(OPENROUTER_MODELS_URL, timeout=(5, 10), verify=_resolve_requests_verify()) response.raise_for_status() data = response.json() @@ -1394,16 +1181,99 @@ def fetch_model_metadata(force_refresh: bool = False) -> Dict[str, Dict[str, Any return {} +def _endpoint_model_entry(model: Dict[str, Any], model_id: str, context_length: Optional[int]) -> Dict[str, Any]: + """Cache entry for one ``/models`` item; optional keys are set only when known.""" + entry: Dict[str, Any] = {"name": model.get("name", model_id)} + if context_length is not None: + entry["context_length"] = context_length + max_completion_tokens = _extract_max_completion_tokens(model) + if max_completion_tokens is not None: + entry["max_completion_tokens"] = max_completion_tokens + pricing = _extract_pricing(model) + if pricing: + entry["pricing"] = pricing + return entry + + +def _lmstudio_native_models(normalized: str, headers: Dict[str, str]) -> Dict[str, Dict[str, Any]]: + """LM Studio ``/api/v1/models`` โ†’ cache; context comes from the first loaded instance.""" + response = requests.get( + _lmstudio_server_root(normalized).rstrip("/") + "/api/v1/models", + headers=headers, + timeout=(5, 10), + verify=_resolve_requests_verify(normalized), + ) + response.raise_for_status() + cache: Dict[str, Dict[str, Any]] = {} + for model in response.json().get("models", []): + if not isinstance(model, dict): + continue + model_id = model.get("key") or model.get("id") + if not model_id: + continue + context_length = None + for inst in model.get("loaded_instances", []) or []: + if not isinstance(inst, dict): + continue + cfg = inst.get("config", {}) + ctx = cfg.get("context_length") if isinstance(cfg, dict) else None + if isinstance(ctx, int) and ctx > 0: + context_length = ctx + break + entry = _endpoint_model_entry(model, model_id, context_length) + _add_model_aliases(cache, model_id, entry) + alt_id = model.get("id") + if isinstance(alt_id, str) and alt_id and alt_id != model_id: + _add_model_aliases(cache, alt_id, entry) + return cache + + +def _apply_llamacpp_props(cache: Dict[str, Dict[str, Any]], request_candidate: str, headers: Dict[str, str], verify) -> None: + """Overwrite ``context_length`` with llama.cpp's actually allocated ``n_ctx`` from /props. + + ``/v1/props`` first (current builds), ``/props`` for older ones. In router + mode the bare endpoint 400s, so each LOADED child's granted window is read + via ``/props?model=``; unloaded children are skipped โ€” probing could autoload them. + """ + base = request_candidate.rstrip("/").replace("/v1", "") + + def _props(params=None): + resp = requests.get(base + "/v1/props", params=params, headers=headers, timeout=5, verify=verify) + if not resp.ok: + resp = requests.get(base + "/props", params=params, headers=headers, timeout=5, verify=verify) + return resp + + props_resp = _props() + if props_resp.ok: + props = props_resp.json() + n_ctx = props.get("default_generation_settings", {}).get("n_ctx") + model_alias = props.get("model_alias", "") + if n_ctx and model_alias and model_alias in cache: + cache[model_alias]["context_length"] = n_ctx + return + native = requests.get(base + "/models", headers=headers, timeout=5, verify=verify) + if not native.ok: + return + for child in (native.json() or {}).get("data", [])[:16]: + if not isinstance(child, dict): + continue + child_id = child.get("id") + status = (child.get("status") or {}).get("value") + if not child_id or child_id not in cache or status not in ("loaded", "ready"): + continue + pr = _props({"model": child_id}) + if pr.ok: + child_ctx = (pr.json().get("default_generation_settings") or {}).get("n_ctx") + if child_ctx: + cache[child_id]["context_length"] = child_ctx + + def fetch_endpoint_model_metadata( base_url: str, api_key: str = "", force_refresh: bool = False, ) -> Dict[str, Dict[str, Any]]: - """Fetch model metadata from an OpenAI-compatible ``/models`` endpoint. - - This is used for explicit custom endpoints where hardcoded global model-name - defaults are unreliable. Results are cached in memory per base URL. - """ + """Model metadata from an OpenAI-compatible ``/models`` endpoint (cached per base URL).""" normalized = _normalize_base_url(base_url) if not normalized or _is_openrouter_base_url(normalized): return {} @@ -1421,9 +1291,7 @@ def fetch_endpoint_model_metadata( _endpoint_model_metadata_cache_time[normalized] = time.time() return memo - # Blackholed endpoint: every candidate below would spend its full 5s - # connect budget. Returned empty rather than cached, so the endpoint is - # retried as soon as the blackhole entry expires. + # Blackholed: return empty WITHOUT caching so it is retried once the entry expires. if _endpoint_blackholed(normalized): return {} @@ -1441,49 +1309,7 @@ def fetch_endpoint_model_metadata( if is_local_endpoint(normalized): try: if detect_local_server_type(normalized, api_key=api_key) == "lm-studio": - server_url = _lmstudio_server_root(normalized) - response = requests.get( - server_url.rstrip("/") + "/api/v1/models", - headers=headers, - timeout=(5, 10), - verify=_resolve_requests_verify(normalized), - ) - response.raise_for_status() - payload = response.json() - cache: Dict[str, Dict[str, Any]] = {} - for model in payload.get("models", []): - if not isinstance(model, dict): - continue - model_id = model.get("key") or model.get("id") - if not model_id: - continue - entry: Dict[str, Any] = {"name": model.get("name", model_id)} - - context_length = None - for inst in model.get("loaded_instances", []) or []: - if not isinstance(inst, dict): - continue - cfg = inst.get("config", {}) - ctx = cfg.get("context_length") if isinstance(cfg, dict) else None - if isinstance(ctx, int) and ctx > 0: - context_length = ctx - break - if context_length is not None: - entry["context_length"] = context_length - - max_completion_tokens = _extract_max_completion_tokens(model) - if max_completion_tokens is not None: - entry["max_completion_tokens"] = max_completion_tokens - - pricing = _extract_pricing(model) - if pricing: - entry["pricing"] = pricing - - _add_model_aliases(cache, model_id, entry) - alt_id = model.get("id") - if isinstance(alt_id, str) and alt_id and alt_id != model_id: - _add_model_aliases(cache, alt_id, entry) - + cache = _lmstudio_native_models(normalized, headers) _endpoint_model_metadata_cache[normalized] = cache _endpoint_model_metadata_cache_time[normalized] = time.time() return cache @@ -1493,14 +1319,10 @@ def fetch_endpoint_model_metadata( _note_endpoint_blackholed(normalized) for candidate in candidates: - # A connect timeout on one candidate condemns the host, not the path: - # the remaining candidates differ only by URL suffix, so trying them - # would repeat the same stall. + # A connect timeout condemns the host, not the path. if _endpoint_blackholed(normalized): break - # normalized/candidates stay unrewritten (cache key stability); only - # the outbound request target is IPv4-resolved to skip the multi-second - # dual-stack IPv6 connect timeout (see _localhost_to_ipv4). + # Cache keys stay unrewritten; only the outbound target is IPv4-resolved. request_candidate = _localhost_to_ipv4(candidate) url = request_candidate.rstrip("/") + "/models" response = None @@ -1528,67 +1350,11 @@ def fetch_endpoint_model_metadata( model_id = model.get("id") if not model_id: continue - entry: Dict[str, Any] = {"name": model.get("name", model_id)} - context_length = _extract_context_length(model) - if context_length is not None: - entry["context_length"] = context_length - max_completion_tokens = _extract_max_completion_tokens(model) - if max_completion_tokens is not None: - entry["max_completion_tokens"] = max_completion_tokens - pricing = _extract_pricing(model) - if pricing: - entry["pricing"] = pricing - _add_model_aliases(cache, model_id, entry) + _add_model_aliases(cache, model_id, _endpoint_model_entry(model, model_id, _extract_context_length(model))) - # If this is a llama.cpp server, query /props for actual allocated context - is_llamacpp = any( - m.get("owned_by") == "llamacpp" - for m in payload.get("data", []) if isinstance(m, dict) - ) - if is_llamacpp: + if any(m.get("owned_by") == "llamacpp" for m in payload.get("data", []) if isinstance(m, dict)): try: - # Try /v1/props first (current llama.cpp); fall back to /props for older builds - base = request_candidate.rstrip("/").replace("/v1", "") - _verify = _resolve_requests_verify(normalized) - props_resp = requests.get(base + "/v1/props", headers=headers, timeout=5, verify=_verify) - if not props_resp.ok: - props_resp = requests.get(base + "/props", headers=headers, timeout=5, verify=_verify) - if props_resp.ok: - props = props_resp.json() - gen_settings = props.get("default_generation_settings", {}) - n_ctx = gen_settings.get("n_ctx") - model_alias = props.get("model_alias", "") - if n_ctx and model_alias and model_alias in cache: - cache[model_alias]["context_length"] = n_ctx - else: - # Router mode: bare /props 400s and telemetry is - # per-child (?model=). Enumerate children via the - # native /models (carries status) and read each - # LOADED child's granted window โ€” the value the - # context policy actually granted, which the meter - # and compressor must follow. Unloaded children are - # skipped: probing them could trigger an autoload. - native = requests.get(base + "/models", headers=headers, timeout=5, verify=_verify) - if native.ok: - children = (native.json() or {}).get("data", []) - for child in children[:16]: - if not isinstance(child, dict): - continue - child_id = child.get("id") - status = (child.get("status") or {}).get("value") - if not child_id or child_id not in cache or status not in ("loaded", "ready"): - continue - pr = requests.get( - base + "/v1/props", params={"model": child_id}, - headers=headers, timeout=5, verify=_verify) - if not pr.ok: - pr = requests.get( - base + "/props", params={"model": child_id}, - headers=headers, timeout=5, verify=_verify) - if pr.ok: - child_ctx = (pr.json().get("default_generation_settings") or {}).get("n_ctx") - if child_ctx: - cache[child_id]["context_length"] = child_ctx + _apply_llamacpp_props(cache, request_candidate, headers, _resolve_requests_verify(normalized)) except Exception: pass @@ -1624,11 +1390,7 @@ def _resolve_endpoint_context_length( if len(endpoint_metadata) == 1: matched = next(iter(endpoint_metadata.values())) elif model: - # Substring fuzzy match โ€” only meaningful with a non-empty model - # name. An empty string is a substring of EVERY key, which would - # "match" whatever model the endpoint happens to list first (e.g. - # a 32K embedding model on the Nous portal) and poison the - # resolved context length for the whole agent. + # Substring match; "" would match EVERY key and poison the window. for key, entry in endpoint_metadata.items(): if model in key or key in model: matched = entry @@ -1761,17 +1523,8 @@ def get_next_probe_tier(current_length: int) -> Optional[int]: def parse_context_limit_from_error(error_msg: str) -> Optional[int]: - """Try to extract the actual context limit from an API error message. - - Many providers include the limit in their error text, e.g.: - - "maximum context length is 32768 tokens" - - "context_length_exceeded: 131072" - - "Maximum context size 32768 exceeded" - - "model's max context length is 65536" - - "input token count is 32825 but model only supports up to 32768" - """ + """Context limit quoted in a provider error ("maximum context length is 32768 tokens"), if any.""" error_lower = error_msg.lower() - # Pattern: look for numbers near context-related keywords patterns = [ r'max_model_len\s*(?:is\s*)?[:=(]?\s*(\d{4,})', # vLLM: "max_model_len 32768", "=32768", ": 32768", "(32768)", "is 32768" r'maximum model length\s*(?:is\s*)?[:=(]?\s*(\d{4,})', # vLLM alt: "maximum model length 131072", "... is 131072" @@ -1780,11 +1533,8 @@ def parse_context_limit_from_error(error_msg: str) -> Optional[int]: r'(\d{4,})\s*(?:token)?\s*(?:context|limit)', r'>\s*(\d{4,})\s*(?:max|limit|token)', # "250000 tokens > 200000 maximum" r'(\d{4,})\s*(?:max(?:imum)?)\b', # "200000 maximum" - # Google Gemini/Gemma: "Unable to submit request because the input - # token count is 32825 but model only supports up to 32768." The - # limit is the number AFTER "supports up to" โ€” the input count that - # precedes it must not be captured, so this pattern anchors on the - # "supports up to" phrase itself. + # Gemini: "input token count is 32825 but model only supports up to + # 32768" โ€” anchor on the phrase so the input count isn't captured. r'supports?\s+(?:only\s+)?up\s+to\s+(\d{4,})', ] for pattern in patterns: @@ -1801,114 +1551,45 @@ def get_context_length_from_provider_error( error_msg: str, current_context_length: int, ) -> Optional[int]: - """Return a provider-reported lower context limit, if one is present. + """Provider-reported limit LOWER than the current window, else None. - Context-overflow recovery must not invent a new model window size. Some - providers only say that the input exceeds the context window without - reporting the actual maximum. In that case callers should keep the - configured context length and try compression only, rather than stepping - down through guessed probe tiers (1M โ†’ 256K โ†’ 128K โ†’ ...). + Overflow recovery must not invent a window: when the provider only says + the input is too long, callers keep the configured length and compress + rather than stepping down guessed probe tiers. """ parsed_limit = parse_context_limit_from_error(error_msg) - if parsed_limit is None: - return None - if parsed_limit < current_context_length: + if parsed_limit is not None and parsed_limit < current_context_length: return parsed_limit return None def parse_available_output_tokens_from_error(error_msg: str) -> Optional[int]: - """Detect an "output cap too large" error and return how many output tokens are available. + """Available OUTPUT tokens from a "max_tokens too large" error, or None. - Background โ€” two distinct context errors exist: - 1. "Prompt too long" โ€” the INPUT itself exceeds the context window. - Fix: compress history, and only reduce context_length if the - provider explicitly reports the actual lower limit. - 2. "max_tokens too large" โ€” input is fine, but input + requested_output > window. - Fix: reduce max_tokens (the output cap) for this call. - Do NOT touch context_length โ€” the window hasn't shrunk. - - Anthropic's API returns errors like: - "max_tokens: 32768 > context_window: 200000 - input_tokens: 190000 = available_tokens: 10000" - - Returns the number of output tokens that would fit (e.g. 10000 above), or None if - the error does not look like a max_tokens-too-large error. + Distinct from "prompt too long" (input exceeds the window -> compress): + here input + requested_output > window, so the fix is a smaller max_tokens + for this call and context_length must NOT be touched. E.g. Anthropic: + "max_tokens: 32768 > context_window: 200000 - input_tokens: 190000 = available_tokens: 10000" -> 10000. """ error_lower = error_msg.lower() - - # Must look like an output-cap error, not a prompt-length error. - is_output_cap_error = ( - "max_tokens" in error_lower - and ("available_tokens" in error_lower or "available tokens" in error_lower) - ) or ( - # OpenRouter/Nous phrasing of the same condition. - "in the output" in error_lower - and "maximum context length" in error_lower - ) or ( - # LM Studio / llama.cpp / some OpenAI-compatible servers: - # "This model's maximum context length is 65536 tokens. However, you - # requested 65536 output tokens and your prompt contains 77409 - # characters ..." - # The "requested N output tokens" phrasing means the OUTPUT cap is the - # problem (the input itself fits) โ€” reduce max_tokens, don't compress. - "maximum context length" in error_lower - and "requested" in error_lower - and "output tokens" in error_lower - ) or ( - # DashScope / Alibaba Cloud (Qwen) phrasing. The provider rejects an - # over-cap output request with a bounded range whose upper bound IS the - # real max-output cap, e.g. - # "Range of max_tokens should be [1, 65536]" - # The input itself fits โ€” this is purely an output-cap error, so reduce - # max_tokens and retry; do NOT compress. - "range of max_tokens should be" in error_lower - ) or ( - # OpenAI-compatible relays may reject a request whose output cap exceeds - # the model's separate completion-token limit, e.g. - # "max_tokens (98304) exceeds model's maximum output tokens (65536)" - # This is independent of the input context window. - "exceeds model" in error_lower - and "maximum output tokens" in error_lower - ) - if not is_output_cap_error: + if not _any_phrase_group(error_lower, _PARSEABLE_OUTPUT_CAP_SIGNALS): return None - # Generic model-output-cap form: + # Direct cap figures, most specific first: # "max_tokens (98304) exceeds model's maximum output tokens (65536)" - _m_max_output = re.search( + # "Range of max_tokens should be [1, 65536]" (upper bound is the cap) + # "... = available_tokens: 10000" (Anthropic) + # "200000 - 190000 = 10000" (last number after "=") + for pattern in ( r'exceeds model(?:\'s)? maximum output tokens\s*\(?\s*(\d+)\s*\)?', - error_lower, - ) - if _m_max_output: - _cap = int(_m_max_output.group(1)) - if _cap >= 1: - return _cap - - # DashScope / Alibaba range form: "Range of max_tokens should be [1, 65536]". - # The upper bound is the available output cap. - _m_range = re.search( r'range of max_tokens should be\s*\[\s*\d+\s*,\s*(\d+)\s*\]', - error_lower, - ) - if _m_range: - _cap = int(_m_range.group(1)) - if _cap >= 1: - return _cap - - # Extract the available_tokens figure. - # Anthropic format: "โ€ฆ = available_tokens: 10000" - patterns = [ r'available_tokens[:\s]+(\d+)', r'available\s+tokens[:\s]+(\d+)', - # fallback: last number after "=" in expressions like "200000 - 190000 = 10000" r'=\s*(\d+)\s*$', - ] - for pattern in patterns: + ): match = re.search(pattern, error_lower) - if match: - tokens = int(match.group(1)) - if tokens >= 1: - return tokens + if match and int(match.group(1)) >= 1: + return int(match.group(1)) # OpenRouter/Nous format: "maximum context length is N โ€ฆ (A of text input, # B of tool input, C in the output)". Available output = ctx - text - tool. @@ -1922,13 +1603,8 @@ def parse_available_output_tokens_from_error(error_msg: str) -> Optional[int]: if _available >= 1: return _available - # LM Studio / llama.cpp style: context window is reported in tokens but the - # prompt size is reported in CHARACTERS, e.g. - # "maximum context length is 65536 tokens ... your prompt contains 77409 - # characters ...". - # Estimate the input tokens conservatively (~3 chars/token, which - # over-reserves the input so the retried output cap stays safely inside the - # window) and leave the remainder of the window for output. + # LM Studio / llama.cpp: window in tokens, prompt in CHARACTERS. ~3 + # chars/token over-reserves the input so the retried cap stays inside the window. _m_ctx_tok = re.search(r'maximum context length is (\d+)\s*token', error_lower) _m_chars = re.search(r'prompt contains (\d+)\s*character', error_lower) if _m_ctx_tok and _m_chars: @@ -1938,26 +1614,13 @@ def parse_available_output_tokens_from_error(error_msg: str) -> Optional[int]: if _available >= 1: return _available - # vLLM style: both the window and the prompt are reported in TOKENS, e.g. - # "This model's maximum context length is 131072 tokens. However, you - # requested 65536 output tokens and your prompt contains at least 65537 - # input tokens, for a total of at least 131073 tokens. Please reduce - # the length of the input prompt or the number of requested output - # tokens." - # Available output = window - input. When the input alone is at or over - # the window this stays None, so the caller correctly falls through to - # compression instead of futilely shrinking the output cap. - # - # Caveat: when max_tokens is the BINDING constraint, vLLM does not report - # the real prompt size at all. It back-computes a lower bound from the - # constraint itself -- "at least N input tokens" where - # N == window + 1 - requested_output -- so window - N is always exactly - # requested_output - 1. Subtracting the caller's safety margin then walks - # the cap down ~65 tokens per retry while the reported input walks up by - # the same amount, burning every compression attempt without ever fitting. - # Detect that degenerate case and halve the requested cap instead: it - # carries the same guarantee (strictly below what was rejected) and - # converges in one or two retries. + # vLLM: window and prompt both in TOKENS; available = window - input (None + # when the input alone overflows, so the caller compresses instead). + # When max_tokens is the BINDING constraint vLLM reports "at least N input + # tokens" with N == window + 1 - requested_output, so window - N is always + # requested_output - 1 and each retry walks the cap down by the safety + # margin without ever fitting. Detect that and halve the cap instead โ€” + # still strictly below what was rejected, converges in one or two retries. _m_vllm_input = re.search( r'prompt contains (?:at least )?(\d+)\s*input tokens', error_lower ) @@ -1975,107 +1638,72 @@ def parse_available_output_tokens_from_error(error_msg: str) -> Optional[int]: return None +# Each entry is a phrase group; the group matches when ALL phrases are present. +_OUTPUT_CAP_SIGNALS = ( + ("range of max_tokens should be",), # DashScope / Alibaba + ("available_tokens",), # Anthropic + ("available tokens",), + ("in the output", "maximum context length"), # OpenRouter / Nous + ("requested", "output tokens"), # LM Studio / llama.cpp + ("should be",), # generic "max_tokens should be <= N" + ("less than or equal",), + ("must be",), + ("exceeds model", "maximum output tokens"), # OpenAI-compatible relays +) +_INPUT_OVERFLOW_SIGNALS = ( + "prompt is too long", "prompt too long", "input is too long", "input token", + "prompt length", "prompt contains", "reduce the length", +) +# Narrower than _OUTPUT_CAP_SIGNALS: only phrasings we can extract a number from. +_PARSEABLE_OUTPUT_CAP_SIGNALS = ( + ("max_tokens", "available_tokens"), # Anthropic + ("max_tokens", "available tokens"), + ("in the output", "maximum context length"), # OpenRouter / Nous + # "requested N output tokens" means the OUTPUT cap is the problem (the + # input itself fits) โ€” reduce max_tokens, don't compress. + ("maximum context length", "requested", "output tokens"), # LM Studio / llama.cpp + # DashScope rejects an over-cap output request with a bounded range whose + # upper bound IS the real max-output cap: "Range of max_tokens should be [1, 65536]". + ("range of max_tokens should be",), + ("exceeds model", "maximum output tokens"), # "max_tokens (98304) exceeds model's maximum output tokens (65536)" +) + + +def _any_phrase_group(text: str, groups: tuple) -> bool: + return any(all(p in text for p in group) for group in groups) + + def is_output_cap_error(error_msg: str) -> bool: - """Return True if a 400 is about the OUTPUT cap (max_tokens) being too large. + """Yes/no sibling of :func:`parse_available_output_tokens_from_error` for wordings we can't parse a number from. - This is the broader sibling of :func:`parse_available_output_tokens_from_error`: - that function only returns a number when it can extract the available output - budget from a *known* provider phrasing. This one answers the cheaper - yes/no question โ€” "is this an output-cap error at all?" โ€” across providers - whose exact wording we may not yet parse a number from. - - Why this matters: an output-cap 400 is deterministic (every retry with the - same ``max_tokens`` gets the identical rejection). If such an error is - misclassified as a context-overflow it gets routed into the compression - loop, the compressor re-issues the call with the same oversized - ``max_tokens``, the provider rejects it identically, and the session - death-loops until "cannot compress further" (issue #55546, DashScope/Qwen: - "Range of max_tokens should be [1, 65536]"). Compression cannot help an - output-cap error โ€” the input already fits. - - The signal: the error talks about ``max_tokens`` (or its aliases) as a - cap/range/limit, and does NOT talk about the INPUT/prompt/context window - being too long. When both are present we defer to the context-overflow - path (a real input overflow can also mention max_tokens). + An output-cap 400 is deterministic: misclassified as a context overflow it + death-loops the compressor (same max_tokens, same rejection) until "cannot + compress further". Signal: talks about max_tokens as a cap/range/limit and + NOT about the input being too long; when both appear, defer to overflow. """ error_lower = error_msg.lower() - - mentions_output_param = ( - "max_tokens" in error_lower - or "max_output_tokens" in error_lower - or "max_completion_tokens" in error_lower - ) - if not mentions_output_param: + if not any(p in error_lower for p in ("max_tokens", "max_output_tokens", "max_completion_tokens")): return False - - # Phrasing that signals the OUTPUT cap specifically is the problem. - output_cap_signal = ( - "range of max_tokens should be" in error_lower # DashScope / Alibaba - or "available_tokens" in error_lower # Anthropic - or "available tokens" in error_lower - or ("in the output" in error_lower # OpenRouter / Nous - and "maximum context length" in error_lower) - or ("requested" in error_lower # LM Studio / llama.cpp - and "output tokens" in error_lower) - or "should be" in error_lower # generic "max_tokens should be <= N" - or "less than or equal" in error_lower - or "must be" in error_lower - or ("exceeds model" in error_lower - and "maximum output tokens" in error_lower) - ) - if not output_cap_signal: + if not _any_phrase_group(error_lower, _OUTPUT_CAP_SIGNALS): return False - - # If the error ALSO clearly describes an oversized INPUT, it is a genuine - # context overflow that happens to mention max_tokens โ€” let the - # context-overflow path handle it (it can compress the input). - input_overflow_signal = ( - "prompt is too long" in error_lower - or "prompt too long" in error_lower - or "input is too long" in error_lower - or "input token" in error_lower - or "prompt length" in error_lower - or "prompt contains" in error_lower - or "reduce the length" in error_lower - ) - return not input_overflow_signal + # An error that ALSO describes an oversized INPUT is a genuine context + # overflow that happens to mention max_tokens โ€” compression can fix it. + return not any(p in error_lower for p in _INPUT_OVERFLOW_SIGNALS) def _model_id_matches(candidate_id: str, lookup_model: str) -> bool: - """Return True if *candidate_id* (from server) matches *lookup_model* (configured). - - Supports two forms: - - Exact match: "nvidia-nemotron-super-49b-v1" == "nvidia-nemotron-super-49b-v1" - - Slug match: "nvidia/nvidia-nemotron-super-49b-v1" matches "nvidia-nemotron-super-49b-v1" - (the part after the last "/" equals lookup_model) - - This covers LM Studio's native API which stores models as "publisher/slug" - while users typically configure only the slug after the "local:" prefix. - """ - if candidate_id == lookup_model: - return True - # Slug match: basename of candidate equals the lookup name - if "/" in candidate_id and candidate_id.rsplit("/", 1)[1] == lookup_model: - return True - return False + """Exact match, or ``publisher/slug`` (LM Studio native ids) whose slug equals the configured name.""" + return candidate_id == lookup_model or ( + "/" in candidate_id and candidate_id.rsplit("/", 1)[1] == lookup_model + ) def query_ollama_num_ctx(model: str, base_url: str, api_key: str = "") -> Optional[int]: - """Query an Ollama server for the model's context length. - - Returns the model's maximum context from GGUF metadata via ``/api/show``, - or the explicit ``num_ctx`` from the Modelfile if set. Returns None if - the server is unreachable or not Ollama. - - This is the value that should be passed as ``num_ctx`` in Ollama chat - requests to override the default 2048. - """ + """Ollama ``/api/show`` context (Modelfile num_ctx, else GGUF max); the value to send as ``num_ctx``.""" import httpx bare_model = _strip_provider_prefix(model) - server_url = _localhost_to_ipv4(base_url.rstrip("/")) - if server_url.endswith("/v1"): - server_url = server_url[:-3] + server_url = _server_root(base_url) try: server_type = detect_local_server_type(base_url, api_key=api_key) @@ -2084,8 +1712,6 @@ def query_ollama_num_ctx(model: str, base_url: str, api_key: str = "") -> Option if server_type != "ollama": return None - # Disk L2: /api/show results are stable for a given (model, server) on - # human timescales โ€” skip the HTTP roundtrip on fresh cross-process hits. _disk_key = f"{server_url}|{bare_model}" disk_hit = _local_probe_disk_get("ollama_num_ctx", _disk_key) if isinstance(disk_hit, int) and disk_hit > 0: @@ -2098,29 +1724,10 @@ def query_ollama_num_ctx(model: str, base_url: str, api_key: str = "") -> Option resp = client.post(f"{server_url}/api/show", json={"name": bare_model}) if resp.status_code != 200: return None - data = resp.json() - - # Prefer explicit num_ctx from Modelfile parameters (user override) - params = data.get("parameters", "") - if "num_ctx" in params: - for line in params.split("\n"): - if "num_ctx" in line: - parts = line.strip().split() - if len(parts) >= 2: - try: - _ctx = int(parts[-1]) - _local_probe_disk_put("ollama_num_ctx", _disk_key, _ctx) - return _ctx - except ValueError: - pass - - # Fall back to GGUF model_info context_length (training max) - model_info = data.get("model_info", {}) - for key, value in model_info.items(): - if "context_length" in key and isinstance(value, (int, float)): - _ctx = int(value) - _local_probe_disk_put("ollama_num_ctx", _disk_key, _ctx) - return _ctx + ctx = _ollama_show_context(resp.json(), gguf_first=False) + if ctx is not None: + _local_probe_disk_put("ollama_num_ctx", _disk_key, ctx) + return ctx except Exception: pass return None @@ -2145,10 +1752,7 @@ def query_ollama_supports_vision(model: str, base_url: str, api_key: str = "") - except Exception: return None - server_url = _localhost_to_ipv4(base_url.rstrip("/")) - if server_url.endswith("/v1"): - server_url = server_url[:-3] - + server_url = _server_root(base_url) headers = _auth_headers(api_key) try: @@ -2177,35 +1781,14 @@ def query_ollama_supports_vision(model: str, base_url: str, api_key: str = "") - def _query_ollama_api_show(model: str, base_url: str, api_key: str = "") -> Optional[int]: - """Query an Ollama server's native ``/api/show`` for context length. + """Provider-agnostic Ollama ``/api/show`` context probe (any hostname; non-Ollama servers 404 fast). - Provider-agnostic: works against ANY Ollama-compatible server regardless - of hostname โ€” local Ollama, Ollama Cloud (``ollama.com``), custom Ollama - hosting behind a reverse proxy, etc. For non-Ollama servers the POST - returns 404/405 quickly; the function handles errors gracefully. - - Results are cached in ``_LOCAL_CTX_PROBE_CACHE`` (same 30s TTL, - positive-only โ€” see ``_query_local_context_length``) so back-to-back - resolutions during one startup issue a single POST instead of one per - call site. Failures are never memoized: a server that isn't up yet must - be re-probed once it comes up. - - For hosted servers the GGUF ``model_info.*.context_length`` is the - authoritative source: the user can't set their own ``num_ctx``, and the - OpenAI-compat ``/v1/models`` endpoint correctly omits ``context_length`` - per the OpenAI schema. - - Resolution order for hosted Ollama: - 1. ``model_info.*.context_length`` โ€” GGUF training max (authoritative) - 2. ``parameters`` โ†’ ``num_ctx`` โ€” server-side Modelfile override - The order is flipped vs ``query_ollama_num_ctx()`` because local users - control ``num_ctx`` themselves; hosted users can't. + GGUF-first (hosted users can't set num_ctx) โ€” the reverse of + query_ollama_num_ctx(). Positive results share _LOCAL_CTX_PROBE_CACHE under + a namespaced key (the two probes can differ for the same (model, url)). """ import time as _time - # Namespaced cache key: shares the TTL store with - # _query_local_context_length but never collides with its (model, url) - # keys โ€” the two probes can return different values for the same pair. cache_key = ("ollama_show", _strip_provider_prefix(model), base_url.rstrip("/")) now = _time.monotonic() cached = _LOCAL_CTX_PROBE_CACHE.get(cache_key) @@ -2222,10 +1805,7 @@ def _query_ollama_api_show_uncached(model: str, base_url: str, api_key: str = "" """Uncached body of ``_query_ollama_api_show`` โ€” one POST to ``/api/show``.""" import httpx - server_url = _localhost_to_ipv4(base_url.rstrip("/")) - if server_url.endswith("/v1"): - server_url = server_url[:-3] - + server_url = _server_root(base_url) if _endpoint_blackholed(server_url): return None @@ -2236,30 +1816,11 @@ def _query_ollama_api_show_uncached(model: str, base_url: str, api_key: str = "" resp = client.post(f"{server_url}/api/show", json={"name": model}) if resp.status_code != 200: return None - data = resp.json() - - # Hosted Ollama: GGUF model_info is the real max โ€” prefer it over - # num_ctx which the Cloud operator may have capped arbitrarily. - model_info = data.get("model_info", {}) - for key, value in model_info.items(): - if "context_length" in key and isinstance(value, (int, float)): - ctx = int(value) - if ctx >= 1024: - return ctx - - # Fall back to num_ctx from Modelfile parameters (rare on Cloud) - params = data.get("parameters", "") - if "num_ctx" in params: - for line in params.split("\n"): - if "num_ctx" in line: - parts = line.strip().split() - if len(parts) >= 2: - try: - ctx = int(parts[-1]) - if ctx >= 1024: - return ctx - except ValueError: - pass + # Hosted Ollama: the GGUF max is authoritative (the operator may + # have capped num_ctx arbitrarily). + ctx = _ollama_show_context(resp.json(), gguf_first=True, minimum=1024) + if ctx is not None: + return ctx except Exception as exc: if _is_connect_timeout(exc): _note_endpoint_blackholed(server_url) @@ -2267,62 +1828,38 @@ def _query_ollama_api_show_uncached(model: str, base_url: str, api_key: str = "" def _model_name_suggests_kimi(model: str) -> bool: - """Return True if the model name looks like a Kimi-family model. - - Catches ``kimi-k2.6``, ``kimi-k2.5``, ``kimi-k2-thinking``, - ``moonshotai/Kimi-K2.6``, and similar variants. Used as a guard - against stale OpenRouter metadata that underreports these models - as 32K context when they actually support 262K+. - """ + """Kimi family (``kimi-*``, ``moonshotai/*``) โ€” guard against stale 32K underreports.""" lower = model.lower() return lower.startswith("kimi") or "moonshot" in lower def _model_name_suggests_minimax_m3(model: str) -> bool: - """Return True if the model name looks like MiniMax M3. - - Catches ``MiniMax-M3``, ``minimax/minimax-m3``, and similar variants - across surfaces. Used by the models.dev underreport guard below and the - cache-control gating in agent_runtime_helpers (stale persisted cache - entries are handled generically by _stale_pre_catalog_cache_entry). - """ + """MiniMax M3 on any surface โ€” models.dev underreport guard and agent_runtime_helpers cache-control gating.""" return "minimax-m3" in model.lower() -# Catalog keys whose DEFAULT_CONTEXT_LENGTHS entry was added AFTER the model -# first became reachable through a shorter catch-all (or the 256K probe -# fallback). Builds from that window persisted the catch-all's value, and -# the step-1 persistent-cache hit would otherwise pin it forever. Each key -# listed here gets a stale-entry guard in get_model_context_length(): a -# cached value at or below what the old resolution path could have produced -# is treated as a pre-catalog leftover and dropped so the entry re-resolves -# against the current catalog. -# -# Only add keys whose catalog value is STRICTLY ABOVE every shorter matching -# key (and above the 256K fallback) โ€” the guard infers the stale threshold -# from those shorter keys, so a model whose true window is below its -# catch-all can never be listed here. +# Catalog keys added AFTER the model was reachable via a shorter catch-all (or +# the 256K fallback): older builds persisted that smaller value and the step-1 +# cache hit would pin it forever. A cached value at or below what the old path +# could produce is dropped and re-resolved. Only list keys whose catalog value +# is STRICTLY ABOVE every shorter matching key and the 256K fallback โ€” the +# threshold is inferred from those shorter keys. _PRE_CATALOG_STALE_KEYS = frozenset({ - "minimax-m3", # 1M; older builds persisted the "minimax" catch-all (204,800) - "grok-4.3", # 1M; pre-2026-05-15 builds persisted the "grok-4" catch-all (256,000) - "grok-4.6", # 500K; pre-catalog builds persisted the "grok-4" catch-all (256,000) - "grok-4-fast", # 2M; pre-2026-04-10 builds fell through to the 256K probe fallback - "grok-4.20", # 2M; pre-2026-04-10 builds fell through to the 256K probe fallback - "qwen3.6-plus", # 1M; pre-2026-05-17 builds persisted the "qwen" catch-all (131,072) + "minimax-m3", # 1M; "minimax" catch-all persisted 204,800 + "grok-4.3", # 1M; "grok-4" catch-all persisted 256,000 + "grok-4.6", # 500K; "grok-4" catch-all persisted 256,000 + "grok-4-fast", # 2M; fell through to the 256K fallback + "grok-4.20", # 2M; fell through to the 256K fallback + "qwen3.6-plus", # 1M; "qwen" catch-all persisted 131,072 }) def _stale_pre_catalog_cache_entry(model: str, cached: int) -> bool: - """Return True when a persisted context length is a pre-catalog leftover. + """True when a persisted window is a pre-catalog leftover (see _PRE_CATALOG_STALE_KEYS). - Generic replacement for the per-model ``_model_name_suggests_*`` guards - (MiniMax-M3, Grok-4.3, Grok-4.6, ...). The model must resolve โ€” by the - same longest-key-first substring match step 8 uses โ€” to a catalog key - listed in ``_PRE_CATALOG_STALE_KEYS``, and the cached value must be at or - below the best value the OLD resolution path could have produced: the - largest shorter matching catch-all entry, or ``DEFAULT_FALLBACK_CONTEXT`` - when no shorter key matches. Cached values above that threshold (e.g. a - genuine probe result) are never dropped. + The model must resolve (longest-key-first, as step 8) to a listed key and + the cached value must be <= the largest shorter matching catch-all (or the + 256K fallback). Values above that โ€” genuine probe results โ€” are kept. """ model_lower = model.lower() matches = [ @@ -2343,12 +1880,7 @@ def _stale_pre_catalog_cache_entry(model: str, cached: int) -> bool: def _model_name_suggests_minimax(model: str) -> bool: - """Return True if the model name looks like a MiniMax-family model. - - Catches ``MiniMax-M2.7``, ``minimax-m2.5``, ``MiniMaxAI/MiniMax-M2.5``, - and similar variants. Used as a guard against stale 32K metadata that - underreports the MiniMax M2 family, whose real context window is 204.8K. - """ + """MiniMax family (``minimax*``, ``minimaxai/*``) โ€” guard against stale 32K underreports (real: 204.8K).""" lower = model.lower() return lower.startswith("minimax") or "minimaxai/" in lower @@ -2359,19 +1891,7 @@ def _model_name_suggests_stale_32k_underreport(model: str) -> bool: def _query_local_context_length(model: str, base_url: str, api_key: str = "") -> Optional[int]: - """Query a local server for the model's context length (short-TTL cached). - - The live-probe paths added for local endpoints (reconcile-on-hit and the - pre-defaults step-7 probe) can fire this function several times in quick - succession during one startup โ€” banner display, ``/model`` switch, - compressor ``update_model`` all resolve the same model. Each raw probe - issues synchronous ``detect_local_server_type`` + query HTTP calls (bounded - by the 3s httpx timeout), so an unreachable/slow local server would pay - that cost repeatedly. A tiny in-process TTL cache collapses back-to-back - probes for the same (model, base_url) into one network round-trip without - persisting anything to disk (freshness across restarts is still handled by - the reconcile logic, which probes again once the TTL expires). - """ + """Local-server context probe, short-TTL cached (see _LOCAL_CTX_PROBE_CACHE).""" import time as _time cache_key = (_strip_provider_prefix(model), base_url.rstrip("/")) @@ -2381,12 +1901,8 @@ def _query_local_context_length(model: str, base_url: str, api_key: str = "") -> return cached[0] result = _query_local_context_length_uncached(model, base_url, api_key=api_key) - # Cache only positive results. A None/failure (server not up yet, - # connection refused, timeout) must NOT be memoized โ€” otherwise a probe - # that fails during a startup race would suppress a legit retry seconds - # later once the server is reachable. Positive-only caching still fully - # bounds the hot-path probe rate (a reachable server returns a value and - # gets cached); an unreachable one simply re-probes on the next call. + # Positive-only: a failure during a startup race must not suppress the + # retry seconds later once the server is up. if result: _LOCAL_CTX_PROBE_CACHE[cache_key] = (result, now) return result @@ -2396,14 +1912,9 @@ def _query_local_context_length_uncached(model: str, base_url: str, api_key: str """Query a local server for the model's context length.""" import httpx - # Strip recognised provider prefix (e.g., "local:model-name" โ†’ "model-name"). - # Ollama "model:tag" colons (e.g. "qwen3.5:27b") are intentionally preserved. model = _strip_provider_prefix(model) - # Strip /v1 suffix to get the server root - server_url = _localhost_to_ipv4(base_url.rstrip("/")) - if server_url.endswith("/v1"): - server_url = server_url[:-3] + server_url = _server_root(base_url) lmstudio_url = _localhost_to_ipv4(_lmstudio_server_root(base_url)) if _endpoint_blackholed(server_url): @@ -2418,38 +1929,18 @@ def _query_local_context_length_uncached(model: str, base_url: str, api_key: str try: with httpx.Client(timeout=3.0, headers=headers) as client: - # Ollama: /api/show returns model details with context info + # Ollama: num_ctx (runtime window) before the GGUF training max โ€” + # using the max would let conversations grow past what Ollama + # allocated and it would silently truncate. Matches query_ollama_num_ctx(). if server_type == "ollama": resp = client.post(f"{server_url}/api/show", json={"name": model}) if resp.status_code == 200: - data = resp.json() - # Prefer explicit num_ctx from Modelfile parameters: this is - # the *runtime* context Ollama will actually allocate KV cache - # for. The GGUF model_info.context_length is the training max, - # which can be larger than num_ctx โ€” using it here would let - # Hermes grow conversations past the runtime limit and Ollama - # would silently truncate. Matches query_ollama_num_ctx(). - params = data.get("parameters", "") - if "num_ctx" in params: - for line in params.split("\n"): - if "num_ctx" in line: - parts = line.strip().split() - if len(parts) >= 2: - try: - return int(parts[-1]) - except ValueError: - pass - # Fall back to GGUF model_info context_length (training max) - model_info = data.get("model_info", {}) - for key, value in model_info.items(): - if "context_length" in key and isinstance(value, (int, float)): - return int(value) + ctx = _ollama_show_context(resp.json(), gguf_first=False) + if ctx is not None: + return ctx - # LM Studio native API: /api/v1/models returns max_context_length. - # This is more reliable than the OpenAI-compat /v1/models which - # doesn't include context window information for LM Studio servers. - # Use _model_id_matches for fuzzy matching: LM Studio stores models as - # "publisher/slug" but users configure only "slug" after "local:" prefix. + # LM Studio native /api/v1/models (the OpenAI-compat list omits + # context); loaded-instance config is the runtime value. if server_type == "lm-studio": resp = client.get(f"{lmstudio_url}/api/v1/models") if resp.status_code == 200: @@ -2464,14 +1955,9 @@ def _query_local_context_length_uncached(model: str, base_url: str, api_key: str return int(ctx) break - # llama.cpp: /props reports default_generation_settings.n_ctx โ€” - # the RUNTIME window the server grants. Critically, the router - # answers this (from its preset) even for a model that is not - # currently loaded, while /v1/models reports meta=null until - # load. Without this probe, resolving a lazily-loaded model at - # session start finds no metadata and falls through to the - # name-pattern defaults, where a family catch-all (e.g. "qwen" - # = 131072) misreports a server launched at 262144. + # llama.cpp /props: the RUNTIME n_ctx, answered by the router even + # for a not-yet-loaded model (while /v1/models has meta=null), so a + # lazily-loaded model doesn't fall to a family catch-all. if server_type == "llamacpp": for props_path in (f"/props?model={model}", "/props"): try: @@ -2491,15 +1977,6 @@ def _query_local_context_length_uncached(model: str, base_url: str, api_key: str if resp.status_code == 200: data = resp.json() if isinstance(data, dict): - # Context-WINDOW keys only (canonical _CONTEXT_LENGTH_KEYS - # vocabulary). `max_tokens` is the max *output* tokens on - # OpenAI-compatible passthroughs (LiteLLM, Anthropic-compat - # shims, cloud proxies) โ€” e.g. 393216 for a 1M-context - # model โ€” so reading it ahead of real window keys collapses - # the window to the output cap and poisons the context - # cache. It is consulted only as an explicit last resort - # inside _context_length_from_model_payload, for servers - # that report nothing else. ctx = _context_length_from_model_payload(data) if ctx is not None: return ctx @@ -2523,10 +2000,8 @@ def _query_local_context_length_uncached(model: str, base_url: str, api_key: str if matched is None and len(models_list) == 1: matched = models_list[0] if matched is not None: - # llama.cpp nests the runtime context under meta.n_ctx; the - # vLLM/OpenAI keys are also checked. Runtime n_ctx is - # preferred over n_ctx_train (the training maximum, which - # can be larger than what the server actually allocates). + # Runtime n_ctx (llama.cpp nests it under meta) beats + # n_ctx_train, which can exceed what the server allocates. sources = [ s for s in (matched, matched.get("meta") or {}) @@ -2536,12 +2011,6 @@ def _query_local_context_length_uncached(model: str, base_url: str, api_key: str val = source.get("n_ctx") if isinstance(val, (int, float)) and val: return int(val) - # Canonical context-WINDOW keys (via _CONTEXT_LENGTH_KEYS) - # with max_tokens demoted to an explicit last resort โ€” - # sibling of the /v1/models/{id} path above; see that - # comment for why max_tokens must never win over a real - # window key (it is the max OUTPUT cap on - # Anthropic/OpenAI-compatible passthroughs). for source in sources: ctx = _context_length_from_model_payload(source) if ctx is not None: @@ -2554,23 +2023,14 @@ def _query_local_context_length_uncached(model: str, base_url: str, api_key: str def _normalize_model_version(model: str) -> str: - """Normalize version separators for matching. - - Nous uses dashes: claude-opus-4-6, claude-sonnet-4-5 - OpenRouter uses dots: claude-opus-4.6, claude-sonnet-4.5 - Normalize both to dashes for comparison. - """ + """Dots -> dashes so Nous ids (claude-opus-4-6) compare with OpenRouter's (claude-opus-4.6).""" return model.replace(".", "-") def _query_anthropic_context_length(model: str, base_url: str, api_key: str) -> Optional[int]: - """Query Anthropic's /v1/models endpoint for context length. - - Only works with regular ANTHROPIC_API_KEY (sk-ant-api*). - OAuth tokens (sk-ant-oat*) from Claude Code return 401. - """ + """Anthropic /v1/models max_input_tokens; OAuth tokens (sk-ant-oat*) 401 and are skipped.""" if not api_key or api_key.startswith("sk-ant-oat"): - return None # OAuth tokens can't access /v1/models + return None try: base = base_url.rstrip("/") if base.endswith("/v1"): @@ -2595,24 +2055,14 @@ def _query_anthropic_context_length(model: str, base_url: str, api_key: str) -> return None -# Known ChatGPT Codex OAuth context windows (observed via live -# chatgpt.com/backend-api/codex/models probe, Apr 2026). These are the -# `context_window` values, which are what Codex actually enforces โ€” the -# direct OpenAI API has larger limits for the same slugs, but Codex OAuth -# caps lower (e.g. gpt-5.5 is 1.05M on the API, 272K on Codex). -# -# Used as a fallback when the live probe fails (no token, network error). -# Longest keys first so substring match picks the most specific entry. +# Codex OAuth `context_window` values (what Codex enforces โ€” lower than the +# direct API for the same slugs). Fallback when the live probe fails; +# longest-key-first substring match. _CODEX_OAUTH_CONTEXT_FALLBACK: Dict[str, int] = { "gpt-5.1-codex-max": 272_000, "gpt-5.1-codex-mini": 272_000, "gpt-5.3-codex": 272_000, - # Spark runs on specialised low-latency hardware and exposes a smaller - # 128k window than other Codex OAuth slugs. Listed explicitly so the - # longest-key-first fallback resolves it correctly โ€” substring match - # on "gpt-5.3-codex" otherwise wins and reports 272k. Availability is - # gated by ChatGPT Pro entitlement on the Codex backend. - "gpt-5.3-codex-spark": 128_000, + "gpt-5.3-codex-spark": 128_000, # smaller window; listed so "gpt-5.3-codex" doesn't win "gpt-5.2-codex": 272_000, "gpt-5.4-mini": 272_000, "gpt-5.6-sol": 272_000, @@ -2625,58 +2075,36 @@ _CODEX_OAUTH_CONTEXT_FALLBACK: Dict[str, int] = { "gpt-5": 272_000, } -# Codex OAuth advertises 272K via /backend-api/codex/models for these -# families, but the backend actually ACCEPTS far more. OpenAI enabled the -# large-context window for ChatGPT-subscription Codex accounts on -# Aug 16 2026 (announced by @thsottiaux; previously API-key-only). -# Verified live against chatgpt.com/backend-api/codex/responses the same -# day: 911,276 input tokens completed OK on gpt-5.6-sol; ~925K+ rejected -# with ``context_length_exceeded`` (the 1.05M window minus reserved output -# headroom). gpt-5.6-terra, gpt-5.6-luna, and gpt-5.4 all completed 900,026 -# tokens OK. gpt-5.5 and gpt-5.4-mini still rejected >272K, so their -# advertisement is real enforcement and they are NOT listed. 900K keeps -# โ‰ฅ11K margin under the observed ceiling and matches the compaction point -# Codex's own client config documents for the 1M window. +# Codex OAuth advertises 272K for these families but ACCEPTS ~900K+ (verified +# live: 911,276 input tokens OK on gpt-5.6-sol; terra/luna/gpt-5.4 completed +# 900,026; gpt-5.5 and gpt-5.4-mini genuinely reject >272K and are NOT +# listed). 900K keeps โ‰ฅ11K margin under the observed ceiling. # -# OPT-IN ONLY (Aug 2026 policy, Teknium): the large window is exposed via -# explicit ``-900k`` picker variants (e.g. ``gpt-5.6-sol-900k``) โ€” the base -# slugs keep the advertised 272K so the cheaper limit is the default. A -# week of the 900K default burned through subscription usage for people -# who never asked for it. The variant suffix is a Hermes-side alias: it is -# stripped before the model id hits the wire (see -# ``strip_codex_context_variant_suffix`` callers in agent/transports/codex.py -# and agent/auxiliary_client.py). +# OPT-IN ONLY: the large window is exposed via explicit ``-900k`` picker +# variants; base slugs keep 272K so the cheaper limit is the default (a 900K +# default burned subscription usage for people who never asked). The suffix is +# a Hermes-side alias stripped before the wire (strip_codex_context_variant_suffix). # -# The bump is applied ONLY when the resolved value (live probe or fallback -# table) is exactly the known-stale 272,000 advertisement โ€” if OpenAI moves -# the advertised number in either direction (the gpt-5.6 family shifted -# 272K โ†’ 372K โ†’ 272K during July 2026), the catalog is trusted again and -# this table is inert. ``gpt-5.6`` is a FAMILY PREFIX (sol/terra/luna and -# dated snapshots; ``-pro`` slugs are not routable on Codex OAuth โ€” the -# backend 400s them โ€” so over-matching there is moot). ``gpt-5.4`` is EXACT: -# gpt-5.4-mini was probed and genuinely enforces 272K (rejected 500K), so -# prefix-matching the 5.4 family would over-report for mini. +# The bump fires ONLY when the resolved value is exactly the stale 272,000 +# advertisement; any other advertised number is trusted and the table is +# inert. ``gpt-5.6`` is a FAMILY PREFIX (``-pro`` slugs aren't routable on +# Codex, so over-matching is moot); ``gpt-5.4`` is EXACT because gpt-5.4-mini +# enforces 272K. _CODEX_OAUTH_VERIFIED_ABOVE_ADVERTISED_PREFIXES: Dict[str, int] = { - "gpt-5.6": 900_000, # sol / terra / luna โ€” all three verified live at 900K + "gpt-5.6": 900_000, # sol / terra / luna } _CODEX_OAUTH_VERIFIED_ABOVE_ADVERTISED_EXACT: Dict[str, int] = { - "gpt-5.4": 900_000, # verified live at 900K; gpt-5.4-mini rejected 500K โ€” excluded - "gpt-daybreak-blue-latest": 900_000, # exact Daybreak/Sol alias verified at 911,276 + "gpt-5.4": 900_000, + "gpt-daybreak-blue-latest": 900_000, # Daybreak/Sol alias } +_CODEX_OAUTH_STALE_ADVERTISED_CTX = 272_000 # the only advertised value the bump may override -# The advertised value the verified-above table is allowed to override. -_CODEX_OAUTH_STALE_ADVERTISED_CTX = 272_000 - -# Hermes-side picker suffix that opts a Codex slug into the live-verified -# large window. Never sent on the wire. +# Picker suffix opting a Codex slug into the verified large window; never sent on the wire. CODEX_CONTEXT_VARIANT_SUFFIX = "-900k" -# The ONLY base slugs eligible for a ``-900k`` variant: routable, -# live-verified models. gpt-5.6 family-prefix matching is deliberately NOT -# used here โ€” it would synthesize dead variants for ``-pro`` slugs (the -# Codex backend 400s them) and accept arbitrary future descendants that -# were never probed. Dated snapshots of the routable 5.6 bases are allowed -# via _CODEX_900K_SNAPSHOT_RE. +# The ONLY bases eligible for ``-900k``: routable, live-verified. No family +# prefixing here โ€” it would synthesize dead ``-pro`` variants and accept +# unprobed descendants. Dated snapshots of the 5.6 bases are allowed. _CODEX_900K_ELIGIBLE_BASES = frozenset({ "gpt-5.6-sol", "gpt-5.6-terra", @@ -2689,22 +2117,12 @@ _CODEX_900K_SNAPSHOT_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$") def _bare_codex_slug(model: Optional[str]) -> str: - """Lowercased slug with any ``vendor/`` namespace removed. - - Display/auxiliary callers pass ids like ``openai/gpt-5.6-sol-900k``; - the main-agent path normalizes the namespace away earlier, but this - resolver must accept both shapes (#92797 review). - """ + """Lowercased slug without ``vendor/`` (display/auxiliary callers pass ``openai/gpt-5.6-sol-900k``).""" return (model or "").strip().lower().rsplit("/", 1)[-1] def is_codex_900k_base(model: Optional[str]) -> bool: - """True when *model* (a BASE slug, no suffix) may carry a ``-900k`` variant. - - Single source of truth for the eligibility check โ€” used by picker - synthesis, context resolution, `/model` validation, and wire stripping - so the four sites can never drift apart. - """ + """Single source of truth for ``-900k`` eligibility (picker, resolution, /model validation, wire stripping).""" slug = _bare_codex_slug(model) if not slug or slug.endswith(CODEX_CONTEXT_VARIANT_SUFFIX): return False @@ -2720,11 +2138,7 @@ def is_codex_900k_base(model: Optional[str]) -> bool: def is_codex_context_variant(model: Optional[str]) -> bool: - """True when the model id is a VALID ``-900k`` opt-in variant. - - Requires both the suffix and an eligible base โ€” ``gpt-5.5-900k`` is not - a variant, it's an invalid alias. - """ + """Suffix AND eligible base โ€” ``gpt-5.5-900k`` is an invalid alias, not a variant.""" slug = _bare_codex_slug(model) if not slug.endswith(CODEX_CONTEXT_VARIANT_SUFFIX): return False @@ -2732,14 +2146,10 @@ def is_codex_context_variant(model: Optional[str]) -> bool: def strip_codex_context_variant_suffix(model: Optional[str]) -> str: - """Return the wire-safe slug with a VALID ``-900k`` suffix removed. + """Wire-safe slug with a VALID ``-900k`` suffix removed (vendor prefix kept). - The suffix is a Hermes picker alias (``gpt-5.6-sol-900k``); the Codex - backend only knows the base slug. Stripping is conditional on base - eligibility: an ineligible alias like ``gpt-5.5-900k`` is returned - unchanged so it fails honestly at the API instead of silently running - as a different model. Case-insensitive; preserves any ``vendor/`` - namespace prefix. + An ineligible alias (``gpt-5.5-900k``) is returned unchanged so it fails + honestly at the API instead of silently running as a different model. """ raw = (model or "").strip() if not raw.lower().endswith(CODEX_CONTEXT_VARIANT_SUFFIX): @@ -2751,23 +2161,12 @@ def strip_codex_context_variant_suffix(model: Optional[str]) -> str: def has_codex_context_variant(model_bare: str) -> bool: - """True when a Codex BASE slug should get a synthetic ``-900k`` entry. - - Thin alias over :func:`is_codex_900k_base` kept for the picker call - sites' readability. - """ + """Picker-side alias of :func:`is_codex_900k_base`.""" return is_codex_900k_base(model_bare) def _verified_codex_ctx_for_slug(model_bare: str) -> Optional[int]: - """Return the live-verified Codex cap for an OPTED-IN slug, or ``None``. - - The large window is opt-in: only VALID ``-900k`` picker variants - (e.g. ``gpt-5.6-sol-900k``) resolve to the verified cap. Base slugs - keep the advertised 272K so the cheaper default limit applies unless - the user explicitly selects the large-context variant; ineligible - aliases (``gpt-5.5-900k``) never resolve here. - """ + """Live-verified cap for a VALID ``-900k`` variant only; base slugs and ineligible aliases -> None.""" slug = _bare_codex_slug(model_bare) if not slug.endswith(CODEX_CONTEXT_VARIANT_SUFFIX): return None @@ -2793,18 +2192,10 @@ def _codex_oauth_token_fingerprint(access_token: str) -> str: def _extract_chatgpt_account_id(access_token: str) -> Optional[str]: - """Extract ``chatgpt_account_id`` from the Codex OAuth JWT. + """``chatgpt_account_id`` from the Codex OAuth JWT, or None on any parse error. - The Codex ``/backend-api/codex/models`` endpoint returns the per-account - catalog only when the ``ChatGPT-Account-Id`` header is present; without - it, the endpoint returns ``{"models":[]}`` (HTTP 200) and the context - probe falls back to the hardcoded defaults โ€” which can be stale or - wrong for the active account's plan. Mirrors the same extraction done - in ``auxiliary_client.py`` for the request path. - - Returns ``None`` on any parse error rather than raising, so a bad - token still surfaces as a normal probe failure instead of crashing - the metadata resolver. + Without the ``ChatGPT-Account-Id`` header /backend-api/codex/models returns + ``{"models":[]}`` (HTTP 200) and the probe silently falls back. Mirrors auxiliary_client.py. """ try: parts = access_token.split(".") @@ -2823,13 +2214,11 @@ def _extract_chatgpt_account_id(access_token: str) -> Optional[str]: def _fetch_codex_oauth_context_lengths_with_source( access_token: str, ) -> Tuple[Dict[str, int], bool]: - """Fetch Codex catalogue data and report whether it came from HTTP. + """Codex catalogue ``{slug: context_window}`` plus whether it came from HTTP. - The in-process cache is scoped by token fingerprint because Codex model - availability and context windows can vary by account entitlement. The raw - token is never retained in the cache key. The boolean is false for a - same-token in-process hit, which must not be treated as a fresh provider - confirmation when deciding whether to update persistent state. + Cached per token fingerprint (windows vary by entitlement; the raw token is + never a key). An in-process hit reports False: it is not a fresh provider + confirmation and must not drive persistent writes. """ global _codex_oauth_context_cache now = time.time() @@ -2879,45 +2268,21 @@ def _fetch_codex_oauth_context_lengths_with_source( return result, True -def _fetch_codex_oauth_context_lengths(access_token: str) -> Dict[str, int]: - """Probe the ChatGPT Codex /models endpoint for per-slug context windows. - - Codex OAuth imposes its own context limits that differ from the direct - OpenAI API (e.g. gpt-5.5 is 1.05M on the API, 272K on Codex). The - `context_window` field in each model entry is the authoritative source. - - Returns a ``{slug: context_window}`` dict. Empty on failure. - """ - result, _fresh = _fetch_codex_oauth_context_lengths_with_source(access_token) - return result - - def _resolve_codex_oauth_context_length_with_source( model: str, access_token: str = "" ) -> Tuple[Optional[int], str]: - """Resolve a Codex OAuth model's real context window. + """``(context_length, source)`` for a Codex OAuth slug. - Prefers a live probe of chatgpt.com/backend-api/codex/models (when we - have a bearer token), then falls back to ``_CODEX_OAUTH_CONTEXT_FALLBACK``. - - Returns ``(context_length, source)`` where source is ``"live"`` for a - value returned by a fresh authenticated endpoint probe, ``"memory"`` for - a same-token in-process catalogue hit, or ``"fallback"`` for the static - conservative table. Only ``"live"`` is eligible for persistent writes. + source: "live" (fresh authenticated probe โ€” the only one eligible for + persistent writes), "memory" (same-token in-process hit), "fallback" + (static table), or "" when unresolved. """ model_bare = _strip_provider_prefix(model).strip() if not model_bare: return None, "" def _apply_verified_bump(ctx: int, source: str) -> Tuple[int, str]: - """Lift a known-stale 272K advertisement to the live-verified cap. - - Only fires for explicit ``-900k`` picker variants (opt-in), and only - when the resolved value is EXACTLY the stale 272,000 advertisement - for a slug we have probed above it (see - ``_verified_codex_ctx_for_slug``). Any other advertised value โ€” - higher or lower โ€” is trusted as a real server-side change. - """ + """Lift an EXACT stale 272K advertisement to the verified cap for opted-in ``-900k`` variants only.""" bumped = _verified_codex_ctx_for_slug(model_bare) if bumped is not None and ctx == _CODEX_OAUTH_STALE_ADVERTISED_CTX: logger.debug( @@ -2927,11 +2292,7 @@ def _resolve_codex_oauth_context_length_with_source( return bumped, source return ctx, source - # ``-900k`` variants are Hermes picker aliases โ€” the Codex catalog only - # knows the base slug, so resolve against the stripped id. Also drop any - # ``vendor/`` namespace (``openai/gpt-5.6-sol-900k``): the main-agent - # path normalizes it away before reaching here, but display/auxiliary - # callers pass it through (#92797 review). + # The Codex catalog only knows the base slug (no -900k, no vendor/). lookup_bare = _bare_codex_slug(strip_codex_context_variant_suffix(model_bare)) if access_token: @@ -2945,53 +2306,25 @@ def _resolve_codex_oauth_context_length_with_source( if slug.lower() == model_lower: return _apply_verified_bump(ctx, live_source) - # Fallback: longest-key-first substring match over hardcoded defaults. - model_lower = lookup_bare.lower() - for slug, ctx in sorted( - _CODEX_OAUTH_CONTEXT_FALLBACK.items(), key=lambda x: len(x[0]), reverse=True - ): - if slug in model_lower: - return _apply_verified_bump(ctx, "fallback") - + hit = _longest_key_match(_CODEX_OAUTH_CONTEXT_FALLBACK, lookup_bare.lower()) + if hit: + return _apply_verified_bump(hit[1], "fallback") return None, "" -def _resolve_codex_oauth_context_length( - model: str, access_token: str = "" -) -> Optional[int]: - """Resolve a Codex OAuth model's context length (compatibility wrapper).""" - context_length, _source = _resolve_codex_oauth_context_length_with_source( - model, access_token=access_token, - ) - return context_length - - def _resolve_nous_context_length( model: str, base_url: str = "", api_key: str = "", ) -> Tuple[Optional[int], str]: - """Resolve Nous Portal model context length. + """``(context_length, source)`` for a Nous Portal model. - Tries the live Nous inference endpoint first (authoritative), then falls - back to OpenRouter metadata with suffix/version matching. - - Nous model IDs are bare after prefix-stripping (e.g. 'qwen3.6-plus', - 'claude-opus-4-6') while OpenRouter uses prefixed IDs (e.g. - 'qwen/qwen3.6-plus', 'anthropic/claude-opus-4.6'). Version - normalization (dotโ†”dash) is applied to handle name drifts. - - Returns ``(context_length, source)`` where ``source`` is one of: - - ``"portal"`` โ€” live /v1/models response (authoritative) - - ``"openrouter"`` โ€” OpenRouter cache fallback (non-authoritative; - callers must NOT persist this to the on-disk cache or a single - portal blip will freeze the wrong value in forever) - - ``""`` โ€” could not resolve + Portal /v1/models is authoritative ("portal") and may differ from OR (OR + says 1M for qwen3.6-plus; the portal 262144). Fallback matches OR's + prefixed ids against the bare Nous id with dot/dash normalisation + ("openrouter" โ€” callers must NOT persist it, or a portal blip freezes the + wrong value forever). "" when unresolved. """ - # Portal first โ€” the Nous /models endpoint is authoritative for what our - # infrastructure enforces and may differ from OR (e.g. OR reports 1M for - # qwen3.6-plus; the portal correctly says 262144). Fall back to the OR - # catalog only if the portal doesn't list the model. if base_url: portal_ctx = _resolve_endpoint_context_length(model, base_url, api_key=api_key) if portal_ctx is not None: @@ -3000,11 +2333,7 @@ def _resolve_nous_context_length( metadata = fetch_model_metadata() def _safe_ctx(or_id: str, entry: dict) -> Optional[int]: - """Return context length, but reject known stale 32K underreports. - - Apply the same guard used for the generic OpenRouter path (step 6 in - resolve_context_length) so the Nous portal path does not short-circuit it. - """ + """Context length minus the known stale 32K underreports (same guard as step 6).""" ctx = entry.get("context_length") if ctx is None: return None @@ -3045,6 +2374,161 @@ def _resolve_nous_context_length( return None, "" +def _validate_cached_context_length( + model: str, base_url: str, cached: int, is_bedrock_context: bool, *, api_key: str = "", +) -> Optional[int]: + """Step 1 of get_model_context_length: accept, repair, or drop a persisted entry. + + Returns the value to use, or None to fall through to live resolution + (the stale entry is invalidated first where noted). Order matters: a + value must be rejected as bogus before any provider-specific handling. + """ + # 0/negative is always a bug (corrupt cache, failed probe, manual edit); + # `0 is not None` would short-circuit the chain and hand the compressor a + # zero window, breaking every status-bar and /usage display downstream. + if cached <= 0: + logger.warning( + "Dropping non-positive cache entry %s@%s -> %s; re-resolving", + model, base_url, cached, + ) + _invalidate_cached_context_length(model, base_url) + return None + # Families stale third-party metadata underreports as 32K (Kimi, MiniMax). + if cached <= 32768 and _model_name_suggests_stale_32k_underreport(model): + logger.info( + "Dropping stale cached context entry %s@%s -> %s (known 32K underreport); " + "re-resolving via hardcoded defaults", + model, base_url, f"{cached:,}", + ) + _invalidate_cached_context_length(model, base_url) + return None + # Pre-catalog leftovers: a shorter catch-all (or the 256K fallback) was + # persisted before the specific entry existed (see _PRE_CATALOG_STALE_KEYS). + if _stale_pre_catalog_cache_entry(model, cached): + logger.info( + "Dropping stale pre-catalog cache entry %s@%s -> %s; " + "re-resolving via hardcoded defaults", + model, base_url, f"{cached:,}", + ) + _invalidate_cached_context_length(model, base_url) + return None + # Nous Portal: /v1/models is authoritative. Bypass (don't drop) the cache so + # step 5b reconciles pre-fix OR-seeded entries without touching the on-disk + # file when the portal is unreachable; the 300s in-memory endpoint cache + # makes the per-call cost ~0 within a process. + if _infer_provider_from_url(base_url) == "nous": + logger.debug( + "Bypassing persistent cache for %s@%s (Nous portal authoritative)", + model, base_url, + ) + return None + # Bedrock: the static table is a FLOOR, not an override โ€” probe-derived + # entries may legitimately exceed it (real window read from Bedrock's + # length-validation error), so only under-reporting entries are dropped. + if is_bedrock_context: + try: + from agent.bedrock_adapter import get_bedrock_context_length + bedrock_ctx = get_bedrock_context_length(model) + if cached < bedrock_ctx: + logger.info( + "Dropping stale Bedrock cache entry %s@%s -> %s; " + "using static Bedrock table value %s", + model, + base_url, + f"{cached:,}", + f"{bedrock_ctx:,}", + ) + _invalidate_cached_context_length(model, base_url) + return bedrock_ctx + except ImportError: + pass + return cached + if is_local_endpoint(base_url): + return _reconcile_local_cached_context_length(model, base_url, cached, api_key=api_key) + return cached + + +def _resolve_bedrock_context_length(model: str, base_url: str) -> Optional[int]: + """Step 1b: Bedrock static table + one cached live probe; None when boto3 is absent. + + Bedrock exposes no context window via metadata APIs, so + get_bedrock_context_length() probes the live endpoint (one fast + pre-inference length rejection). The result is cached per model โ€” keyed by + base_url, else a synthetic bedrock:// key so display/offline paths share it. + """ + try: + from agent.bedrock_adapter import ( + get_bedrock_context_length, + resolve_bedrock_region, + ) + except ImportError: + return None # boto3 not installed โ€” fall through to generic resolution + cache_key_url = base_url or "bedrock://" + cached = get_cached_context_length(model, cache_key_url) + if cached is not None: + return cached + # Region from the base_url host first, then the standard AWS chain. An + # empty region disables probing (table only). + region = "" + if base_url: + _m = re.search(r"bedrock-runtime\.([a-z0-9-]+)\.", base_url) + if _m: + region = _m.group(1) + if not region: + try: + region = resolve_bedrock_region() + except Exception: + region = "" + ctx = get_bedrock_context_length(model, region=region, probe=bool(region)) + # Only persist probe-derived values (region present); a pure table fallback + # must not poison the cache against a later successful probe. + if ctx and region: + save_context_length(model, cache_key_url, ctx) + return ctx + + +def _resolve_custom_endpoint_context_length(model: str, base_url: str, api_key: str, provider: str) -> int: + """Steps 2-3 for a truly custom endpoint: /models, local probes, Ollama /api/show, catalog, default.""" + context_length = _resolve_endpoint_context_length(model, base_url, api_key=api_key) + if context_length is not None: + return context_length + # Local endpoints: the Modelfile-aware probe first. _query_local_context_length + # prefers num_ctx, while _query_ollama_api_show returns the GGUF training max + # first, which can be larger and would create a false-safe compression window. + if is_local_endpoint(base_url): + local_ctx = _probe_local_context_length(model, base_url, api_key, provider) + if local_ctx: + return local_ctx + # 2b. Ollama native /api/show (GGUF-first for non-local). Non-Ollama servers 404/405 quickly. + ctx = _query_ollama_api_show(model, base_url, api_key=api_key) + if ctx is not None: + if not _skip_persistent_context_cache(base_url, provider): + save_context_length(model, base_url, ctx) + return ctx + # 3. Probe-down fallback after endpoint-specific detection failed + logger.info( + "Could not detect context length for model %r at %s โ€” " + "defaulting to %s tokens (probe-down). Set model.context_length " + "in config.yaml to override.", + model, base_url, f"{DEFAULT_FALLBACK_CONTEXT:,}", + ) + # 3b. Hardcoded catalog as a last resort: a proxied Anthropic gateway fails + # the probes above but its model name still matches DEFAULT_CONTEXT_LENGTHS + # (e.g. "claude-opus-4-8" -> 1M); without this the early return would + # silently cap context at 256K. + hit = _longest_key_match(DEFAULT_CONTEXT_LENGTHS, model.lower()) + if hit: + logger.info( + "Using hardcoded context length %s for model %r " + "(custom endpoint, catalog match on %r)", + f"{hit[1]:,}", model, hit[0], + ) + return hit[1] + # Same silent-256K bug class as the step-9 fallback โ€” warn here too. + _warn_context_length_fallback(model, base_url) + return DEFAULT_FALLBACK_CONTEXT + + def get_model_context_length( model: str, base_url: str = "", @@ -3083,12 +2567,10 @@ def get_model_context_length( if config_context_length is not None and isinstance(config_context_length, int) and config_context_length > 0: return config_context_length - # 0a. MoA virtual provider โ€” ``model`` is a preset name, not a real model, - # and ``base_url`` is the local virtual endpoint, so every probe below would - # miss and fall through to the 256K default. The aggregator is the acting - # model, so resolve the context window from the aggregator slot's real - # provider+model instead. References are advisory-only and never bound the - # acting context, so they're ignored here. + # 0a. MoA virtual provider: ``model`` is a preset name and ``base_url`` the + # local virtual endpoint, so every probe would miss. The aggregator is the + # acting model โ€” resolve its real provider+model (references are advisory + # and never bound the acting context). Falls through on failure. if (provider or "").strip().lower() == "moa": try: from hermes_cli.config import ( @@ -3117,15 +2599,11 @@ def get_model_context_length( ) except Exception: logger.debug("MoA aggregator context-length resolution failed", exc_info=True) - # Fall through to the generic default if aggregator resolution failed. - # 0b. model_overrides config โ€” EXPLICIT per-provider+model context_window - # override only (fill-gap _default entries are applied later, inside - # lookup_models_dev_context at step 5f, once the catalog has actually - # missed โ€” so a _default can never preempt custom_providers or live - # probes). This is the supported self-unblock path for models with - # wrong context in models.dev (#84482) and for custom/local models - # (#8731). Config-read only; never blocks on the network. + # 0b. model_overrides: EXPLICIT per-provider+model context_window only. + # Fill-gap _default entries apply later inside lookup_models_dev_context + # (step 5f) once the catalog has missed, so a _default can never preempt + # custom_providers or live probes. Config-read only; never touches the network. if provider and model: try: from agent.models_dev import _override_context_window @@ -3135,10 +2613,8 @@ def get_model_context_length( except Exception: pass # fall through to other resolution paths - # 0c. custom_providers per-model override โ€” check before any probe. - # This closes the gap where /model switch and display paths used to fall - # back to 128K despite the user having a per-model context_length set. - # See #15779. + # 0c. custom_providers per-model override โ€” before any probe, so /model + # switch and display paths honour a per-model context_length. if custom_providers and base_url and model: try: from hermes_cli.config import get_custom_provider_context_length @@ -3152,10 +2628,9 @@ def get_model_context_length( except Exception: pass # fall through to probing - # Malformed user-provided URLs (for example an unmatched IPv6 bracket) - # make urllib.parse raise. Context resolution should treat those as an - # unknown endpoint rather than crashing before the inference layer can - # report the configuration error itself. + # Malformed URLs (e.g. unmatched IPv6 bracket) make urllib.parse raise; + # treat them as an unknown endpoint so the inference layer reports the + # configuration error itself. if base_url: try: parsed_base_url = urlparse(_normalize_base_url(base_url)) @@ -3163,12 +2638,8 @@ def get_model_context_length( except ValueError: base_url = "" - # An empty/blank model id can't be meaningfully resolved: every probe - # below would either miss or โ€” worse โ€” fuzzy-match an arbitrary catalog - # entry (the endpoint matcher's `model in key` check is vacuously true - # for ""), returning whatever context length that random entry has and - # persisting it under a junk "@" cache key. Fall back to the - # default immediately instead. + # A blank model id would fuzzy-match an arbitrary catalog entry (`"" in key` + # is vacuously true) and persist it under a junk "@" cache key. if not str(model or "").strip(): logger.info( "No model id provided for context length resolution โ€” defaulting to %s tokens.", @@ -3176,14 +2647,13 @@ def get_model_context_length( ) return DEFAULT_FALLBACK_CONTEXT - # Normalise provider-prefixed model names (e.g. "local:model-name" โ†’ - # "model-name") so cache lookups and server queries use the bare ID that - # local servers actually know about. Ollama "model:tag" colons are preserved. + # Bare id for cache lookups and server queries ("local:x" -> "x"; Ollama + # "model:tag" colons preserved). model = _strip_provider_prefix(model) - # Endpoint-scoped provider metadata. Keep this ahead of the persistent - # cache so a value learned for a multiplexed provider's other endpoint - # cannot override the endpoint where the model was actually validated. + # Endpoint-scoped metadata goes AHEAD of the persistent cache so a value + # learned on a multiplexed provider's other endpoint cannot override the + # endpoint where the model was actually validated. endpoint_context = _endpoint_scoped_context_length(model, base_url) if endpoint_context is not None: return endpoint_context @@ -3194,138 +2664,24 @@ def get_model_context_length( and base_url_host_matches(base_url, "amazonaws.com") ) - # 1. Check persistent cache (model+provider) - # LM Studio is excluded โ€” its loaded context length is transient (the - # user can reload the model with a different context_length at any time - # via /api/v1/models/load), so a stale cached value would mask reloads. - # Codex OAuth is excluded because the authenticated /models catalogue is - # account-specific and a fallback must never suppress later revalidation. + # 1. Persistent cache (LM Studio / Codex OAuth excluded โ€” see + # _skip_persistent_context_cache). if base_url and not _skip_persistent_context_cache(base_url, provider): cached = get_cached_context_length(model, base_url) if cached is not None: - # Reject non-positive cached values โ€” a 0 or negative value - # is always a bug (corrupted cache, probe failure, or manual - # edit). Without this guard, `0 is not None` short-circuits - # the resolution chain and the compressor gets context_length=0, - # breaking every status-bar and /usage display downstream. - if cached <= 0: - logger.warning( - "Dropping non-positive cache entry %s@%s -> %s; re-resolving", - model, base_url, cached, - ) - _invalidate_cached_context_length(model, base_url) - # Invalidate stale 32k cache entries for model families known to - # be underreported by stale third-party metadata (Kimi, MiniMax). - elif cached <= 32768 and _model_name_suggests_stale_32k_underreport(model): - logger.info( - "Dropping stale cached context entry %s@%s -> %s (known 32K underreport); " - "re-resolving via hardcoded defaults", - model, base_url, f"{cached:,}", - ) - _invalidate_cached_context_length(model, base_url) - # Invalidate pre-catalog leftovers: models whose catalog entry was - # added after a shorter catch-all (or the 256K fallback) had - # already persisted a smaller value โ€” MiniMax-M3, Grok-4.3/-4.6/ - # -4-fast/-4.20, qwen3.6-plus, ... (see _PRE_CATALOG_STALE_KEYS). - # Drop the stale entry and fall through to the hardcoded default. - elif _stale_pre_catalog_cache_entry(model, cached): - logger.info( - "Dropping stale pre-catalog cache entry %s@%s -> %s; " - "re-resolving via hardcoded defaults", - model, base_url, f"{cached:,}", - ) - _invalidate_cached_context_length(model, base_url) - # Nous Portal: the portal /v1/models endpoint is authoritative. - # Bypass the persistent cache so step 5b can always reconcile - # against it โ€” this corrects pre-fix entries seeded from the - # OR catalog (the same OR underreport class that the Kimi/Qwen - # DEFAULT_CONTEXT_LENGTHS overrides exist to mitigate) without - # touching the on-disk file when the portal is unreachable. - # The in-memory 300s endpoint metadata cache makes the per-call - # cost amortise to ~0 within a process. - elif _infer_provider_from_url(base_url) == "nous": - logger.debug( - "Bypassing persistent cache for %s@%s (Nous portal authoritative)", - model, base_url, - ) - # Fall through; step 5b reconciles and overwrites if portal responds. - # Invalidate stale Bedrock entries seeded before the Claude 4.6+ - # long-context table was corrected to 1M. The static table is a - # FLOOR, not an override: probe-derived cache entries (step 1b) - # may legitimately exceed the table (real window read from - # Bedrock's length-validation error), so only under-reporting - # entries are dropped โ€” never a cached value above the table. - elif is_bedrock_context: - try: - from agent.bedrock_adapter import get_bedrock_context_length - bedrock_ctx = get_bedrock_context_length(model) - if cached < bedrock_ctx: - logger.info( - "Dropping stale Bedrock cache entry %s@%s -> %s; " - "using static Bedrock table value %s", - model, - base_url, - f"{cached:,}", - f"{bedrock_ctx:,}", - ) - _invalidate_cached_context_length(model, base_url) - return bedrock_ctx - except ImportError: - pass - return cached - else: - if is_local_endpoint(base_url): - return _reconcile_local_cached_context_length( - model, base_url, cached, api_key=api_key, - ) - return cached - - # 1b. AWS Bedrock โ€” use static context length table. - # Bedrock's ListFoundationModels API doesn't expose context window sizes, - # so we maintain a curated table in bedrock_adapter.py that reflects - # Bedrock-hosted model limits (e.g. older Claude 4 at 200K; Claude - # Opus/Sonnet 4.6+ at 1M). This must run BEFORE the custom-endpoint probe at - # step 2 โ€” bedrock-runtime..amazonaws.com is not in - # _URL_TO_PROVIDER, so it would otherwise be treated as a custom endpoint, - # fail the /models probe (Bedrock doesn't expose that shape), and fall - # back to the 128K default before reaching the original step 4b branch. - if is_bedrock_context: - try: - from agent.bedrock_adapter import ( - get_bedrock_context_length, - resolve_bedrock_region, + validated = _validate_cached_context_length( + model, base_url, cached, is_bedrock_context, api_key=api_key, ) - except ImportError: - pass # boto3 not installed โ€” fall through to generic resolution - else: - # Bedrock does not expose the context window via any metadata API, - # so get_bedrock_context_length() probes the live endpoint (one - # fast, pre-inference length rejection) to read the real window. - # Cache the probe result per model so we pay that cost once, not - # every turn โ€” keyed by base_url when present, else a synthetic - # bedrock:// key so display/offline paths share the entry. - cache_key_url = base_url or "bedrock://" - cached = get_cached_context_length(model, cache_key_url) - if cached is not None: - return cached - # Resolve region from the base_url host first, then the standard - # AWS region chain. An empty region disables probing (table only). - region = "" - if base_url: - _m = re.search(r"bedrock-runtime\.([a-z0-9-]+)\.", base_url) - if _m: - region = _m.group(1) - if not region: - try: - region = resolve_bedrock_region() - except Exception: - region = "" - ctx = get_bedrock_context_length(model, region=region, probe=bool(region)) - if ctx and region: - # Only persist probe-derived values (region present); a pure - # table fallback shouldn't poison the cache against a later - # successful probe. - save_context_length(model, cache_key_url, ctx) + if validated is not None: + return validated + + # 1b. AWS Bedrock static table + probe. Must run BEFORE the custom-endpoint + # step: bedrock-runtime..amazonaws.com is not in _URL_TO_PROVIDER, + # so it would be treated as a custom endpoint, fail the /models probe and + # fall back to the default. + if is_bedrock_context: + ctx = _resolve_bedrock_context_length(model, base_url) + if ctx is not None: return ctx if provider == "novita" or (base_url and base_url_host_matches(base_url, "api.novita.ai")): @@ -3335,67 +2691,11 @@ def get_model_context_length( save_context_length(model, base_url, ctx) return ctx - # 2. Active endpoint metadata for truly custom/unknown endpoints. - # Known providers (Copilot, OpenAI, Anthropic, etc.) skip this โ€” their - # /models endpoint may report a provider-imposed limit (e.g. Copilot - # returns 128k) instead of the model's full context (400k). models.dev - # has the correct per-provider values and is checked at step 5+. + # 2. Live /models for truly custom endpoints. Known providers skip this: + # their /models may report a provider-imposed limit (Copilot: 128k) rather + # than the model's window (400k); models.dev is consulted at step 5+. if _is_custom_endpoint(base_url) and not _is_known_provider_base_url(base_url): - context_length = _resolve_endpoint_context_length(model, base_url, api_key=api_key) - if context_length is not None: - return context_length - if not _is_known_provider_base_url(base_url): - # For local endpoints, run the probe that respects configured - # Modelfile context values first. _query_local_context_length - # prefers num_ctx from Modelfile, while _query_ollama_api_show - # returns the GGUF training max first which can be larger and - # would create a false-safe window for compression (#63122). - # Non-local endpoints preserve the existing GGUF-first behavior. - if is_local_endpoint(base_url): - local_ctx = _query_local_context_length(model, base_url, api_key=api_key) - if local_ctx and local_ctx > 0: - if not _skip_persistent_context_cache(base_url, provider): - _maybe_cache_local_context_length(model, base_url, local_ctx) - return local_ctx - # 2b. Ollama native /api/show โ€” non-local endpoints preserve - # the existing generic /api/show GGUF-first behavior. - # Non-Ollama servers return 404/405 quickly. - ctx = _query_ollama_api_show(model, base_url, api_key=api_key) - if ctx is not None: - if not _skip_persistent_context_cache(base_url, provider): - save_context_length(model, base_url, ctx) - return ctx - # 3. Probe-down fallback after endpoint-specific detection failed - logger.info( - "Could not detect context length for model %r at %s โ€” " - "defaulting to %s tokens (probe-down). Set model.context_length " - "in config.yaml to override.", - model, base_url, f"{DEFAULT_FALLBACK_CONTEXT:,}", - ) - # 3b. Before falling back to the hard 256K default, consult the - # hardcoded catalog as a last resort. A proxied/custom Anthropic - # gateway (e.g. corporate proxy) fails the Ollama/local probes - # above, but the model name may still match an entry in - # DEFAULT_CONTEXT_LENGTHS (e.g. "claude-opus-4-8" โ†’ 1M). - # Without this, the early return here short-circuits the catalog - # lookup at step 8 and silently caps context at 256K. - model_lower = model.lower() - for default_model, length in sorted( - DEFAULT_CONTEXT_LENGTHS.items(), - key=lambda x: len(x[0]), - reverse=True, - ): - if default_model in model_lower: - logger.info( - "Using hardcoded context length %s for model %r " - "(custom endpoint, catalog match on %r)", - f"{length:,}", model, default_model, - ) - return length - # Same silent-256K bug class as the step-9 fallback below โ€” - # warn here too so custom/local endpoints aren't left invisible. - _warn_context_length_fallback(model, base_url) - return DEFAULT_FALLBACK_CONTEXT + return _resolve_custom_endpoint_context_length(model, base_url, api_key, provider) # 4. Anthropic /v1/models API (only for regular API keys, not OAuth) if provider == "anthropic" or ( @@ -3405,24 +2705,15 @@ def get_model_context_length( if ctx: return ctx - # 4b. (Bedrock handled earlier at step 1b โ€” before custom-endpoint probe.) - - # 5. Provider-aware lookups (before generic OpenRouter cache) - # These are provider-specific and take priority over the generic OR cache, - # since the same model can have different context limits per provider - # (e.g. claude-opus-4.6 is 1M on Anthropic but 128K on GitHub Copilot). - # If provider is generic (openrouter/custom/empty), try to infer from URL. + # 5. Provider-aware lookups โ€” before the generic OR cache, since the same + # 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 API โ€” max_prompt_tokens from the user's account. - # This catches account-specific models (e.g. claude-opus-4.6-1m) that - # don't exist in models.dev. For models that ARE in models.dev, this - # returns the provider-enforced limit which is what users can actually use. + # 5a. Copilot live /models โ€” account-specific models (claude-opus-4.6-1m) + # absent from models.dev, and the provider-enforced limit for the rest. if effective_provider in {"copilot", "copilot-acp", "github-copilot"}: try: from hermes_cli.models import get_copilot_model_context @@ -3437,26 +2728,20 @@ def get_model_context_length( model, base_url=base_url or "", api_key=api_key or "" ) if ctx: - # Persist ONLY portal-derived values. Caching an OR-fallback - # value here would freeze in a wrong number on the first portal - # blip / auth glitch and step-1 would short-circuit it forever. - # OR's catalog is community-maintained and is precisely why the - # Kimi/Qwen DEFAULT_CONTEXT_LENGTHS overrides exist โ€” we don't - # want it leaking into the persistent cache for Nous URLs. + # Persist ONLY portal-derived values: an OR-fallback value cached + # on a portal blip would be frozen in by step 1 forever. if base_url and source == "portal": save_context_length(model, base_url, ctx) return ctx if effective_provider == "openai-codex": - # Codex OAuth enforces lower context limits than the direct OpenAI - # API for the same slug (e.g. gpt-5.5 is 1.05M on the API but 272K - # on Codex). Authoritative source is Codex's own /models endpoint. + # Codex OAuth enforces lower limits than the direct API for the same + # slug (gpt-5.5: 1.05M vs 272K); its own /models is authoritative. codex_ctx, codex_source = _resolve_codex_oauth_context_length_with_source( model, access_token=api_key or "", ) if codex_ctx: - # Only a successful authenticated catalogue response is safe to - # persist. The static fallback is deliberately runtime-only so a - # transient OAuth/network failure cannot poison future probes. + # Only a fresh authenticated catalogue response may be persisted; + # the static fallback must not poison future probes. if base_url and codex_source == "live": save_context_length(model, base_url, codex_ctx) return codex_ctx @@ -3466,17 +2751,10 @@ def get_model_context_length( ctx = _resolve_endpoint_context_length(model, base_url, api_key=api_key) if ctx is not None: return ctx - # 5e. Ollama native /api/show probe โ€” runs for providers whose base_url - # is NOT a known non-Ollama provider. Ollama-compatible servers expose - # this endpoint regardless of hostname (local Ollama, Ollama Cloud, - # custom Ollama hosting). The OpenAI-compat /v1/models endpoint - # correctly omits context_length per the OpenAI schema, but /api/show - # returns the authoritative GGUF model_info.context_length. - # Known hosted providers (OpenRouter, Anthropic, OpenAI, โ€ฆ) are skipped: - # they are definitively not Ollama, the POST always 404s, and the result - # is never cached for them โ€” so every fresh process used to pay a - # ~300ms blocking HTTP round-trip on the first-turn critical path - # (measured against openrouter.ai; worse on slow DNS). + # 5e. Ollama native /api/show for any base_url that is not a known + # non-Ollama provider (OpenAI-compat /v1/models omits context_length; the + # GGUF model_info is authoritative). Known hosted providers are skipped: + # the POST always 404s and cost ~300ms on the first-turn critical path. if base_url: _inferred_for_probe = _infer_provider_from_url(base_url) _skip_ollama_probe = ( @@ -3489,16 +2767,10 @@ def get_model_context_length( if not _skip_persistent_context_cache(base_url, provider): save_context_length(model, base_url, ctx) return ctx - # 5f. OpenRouter live /models metadata โ€” authoritative for OpenRouter-routed - # models. OpenRouter's catalog carries per-model context_length (e.g. - # anthropic/claude-fable-5 -> 1M) and refreshes as new slugs ship, so it - # must win over both models.dev (step 5g) and the hardcoded family catch-all - # (step 8). Before this branch, an OpenRouter selection set - # effective_provider="openrouter", which (a) made the models.dev lookup miss - # brand-new slugs and (b) skipped the step-6 OR fallback (gated on `not - # effective_provider`), so a fresh slug like claude-fable-5 fell through to - # the generic "claude": 200K entry and under-reported a 1M window. Mirrors - # the dedicated Nous/Copilot/GMI branches above. + # 5f. OpenRouter live /models โ€” authoritative for OR-routed models and + # refreshed as new slugs ship, so it must win over models.dev (5g) and the + # family catch-all (8): otherwise a brand-new slug (claude-fable-5, 1M) + # falls through to the generic "claude": 200K entry. if effective_provider == "openrouter": metadata = fetch_model_metadata() entry = metadata.get(model) @@ -3528,10 +2800,8 @@ def get_model_context_length( ctx = catalog return ctx - # 6. OpenRouter live API metadata โ€” provider-unaware fallback. - # Only consulted when the provider is unknown (no effective_provider), - # because OpenRouter data is community-maintained and can be incorrect - # for models that belong to known providers with curated defaults. + # 6. OpenRouter metadata, provider-unaware fallback โ€” only when the + # provider is unknown (OR data is community-maintained). if not effective_provider: metadata = fetch_model_metadata() if model in metadata: @@ -3551,26 +2821,18 @@ def get_model_context_length( # ``Hermes-3-Llama-3.1-70B`` substring-match ``llama`` (131072) even when # vLLM is running at a lower ``--max-model-len`` (e.g. 32768 on limited VRAM). if base_url and is_local_endpoint(base_url): - local_ctx = _query_local_context_length(model, base_url, api_key=api_key) - if local_ctx and local_ctx > 0: - if not _skip_persistent_context_cache(base_url, provider): - _maybe_cache_local_context_length(model, base_url, local_ctx) + local_ctx = _probe_local_context_length(model, base_url, api_key, provider) + if local_ctx: return local_ctx - # 8. Hardcoded defaults (fuzzy match โ€” longest key first for specificity) - # Only check `default_model in model` (is the key a substring of the input). - # The reverse (`model in default_model`) causes shorter names like - # "claude-sonnet-4" to incorrectly match "claude-sonnet-4-6" and return 1M. - model_lower = model.lower() - for default_model, length in sorted( - DEFAULT_CONTEXT_LENGTHS.items(), key=lambda x: len(x[0]), reverse=True - ): - if default_model in model_lower: - return length + # 8. Hardcoded defaults: `key in model` only โ€” the reverse would let + # "claude-sonnet-4" match "claude-sonnet-4-6" and return 1M. + hit = _longest_key_match(DEFAULT_CONTEXT_LENGTHS, model.lower()) + if hit: + return hit[1] - # 9. Default fallback โ€” warn (deduped per model+endpoint) so - # small-context models don't silently get 256K. See - # _warn_context_length_fallback for rationale. + # 9. Default fallback โ€” warn (deduped per model+endpoint) so small-context + # models don't silently get 256K. _warn_context_length_fallback(model, base_url) return DEFAULT_FALLBACK_CONTEXT @@ -3583,15 +2845,7 @@ async def get_model_context_length_async( provider: str = "", custom_providers: list | None = None, ) -> int: - """Async variant of get_model_context_length. - - Offloads the entire synchronous resolution chain (which contains - blocking HTTP calls via ``requests``) to a background thread so it - does not freeze the asyncio event loop and cause Discord heartbeat - timeouts. - - Shares all logic with the sync version โ€” no code duplication. - """ + """get_model_context_length on a worker thread (its blocking HTTP would stall the event loop).""" import asyncio return await asyncio.to_thread( get_model_context_length, @@ -3616,10 +2870,8 @@ def _is_cjk_token_dense_char(ch: str) -> bool: ) -# Same codepoint ranges as _is_cjk_token_dense_char, as a compiled character -# class so dense-char counting runs in C (``len(text) - len(re.sub(...))``) -# instead of a per-char Python loop. MUST stay in sync with -# _is_cjk_token_dense_char. +# Same ranges as _is_cjk_token_dense_char (MUST stay in sync) so dense-char +# counting runs in C rather than a per-char Python loop. _CJK_DENSE_RE = re.compile( "[\u1100-\u11ff" # Hangul Jamo "\u2e80-\u9fff" # CJK radicals/ideographs @@ -3631,31 +2883,20 @@ _CJK_DENSE_RE = re.compile( def estimate_tokens_rough(text: str) -> int: - """Rough token estimate for pre-flight checks. + """Rough token estimate: ceil(chars/4), CJK/Hangul/Kana codepoints ~1 token each. - Uses ceiling division so short texts (1-3 chars) never estimate as - 0 tokens, which would cause the compressor and pre-flight checks to - systematically undercount when many short tool results are present. - CJK/Hangul/Kana text is much denser than English under common LLM - tokenizers, so count those codepoints as roughly one token each instead - of applying the English-centric ~4 chars/token rule. - - Perf: this runs on every message in every preflight/compaction walk, - including MB-scale tool outputs, so the common all-ASCII case must stay - O(1). ``str.isascii()`` is a flag check on CPython's compact unicode - representation (no scan), and the CJK counting itself is a single - C-level ``re.findall`` rather than a per-character Python loop. + Ceiling division keeps short texts from estimating 0 (systematic + undercount with many short tool results). Runs on every message of every + preflight walk, so the all-ASCII case must stay O(1): ``str.isascii()`` is + a flag check on CPython and the CJK count is a single C-level regex pass. """ if not text: return 0 text = str(text) if text.isascii(): - # O(1) fast path โ€” ASCII text cannot contain token-dense CJK chars. return (len(text) + 3) // 4 dense = len(text) - len(_CJK_DENSE_RE.sub("", text)) - if not dense: - # Non-ASCII but no CJK (accents, Cyrillic, emoji, ...): keep the - # classic ~4 chars/token rule. + if not dense: # non-ASCII but no CJK (accents, Cyrillic, emoji) return (len(text) + 3) // 4 sparse = len(text) - dense return dense + ((sparse + 3) // 4) @@ -3666,29 +2907,20 @@ def estimate_messages_tokens_rough( ) -> int: """Rough token estimate for a message list (pre-flight only). - Image parts (base64 PNG/JPEG) are counted as a flat ~1500 tokens per - image โ€” the Anthropic pricing model โ€” instead of counting raw base64 - character length. Without this, a single ~1MB screenshot would be - estimated at ~250K tokens and trigger premature context compression. + Images cost a flat ~1500 tokens each (Anthropic's model) rather than their + base64 length, which would put a 1MB screenshot at ~250K. - ``charge_stale_thinking`` mirrors the tail-budget walk's policy - (``context_compressor._estimate_msg_budget_tokens``, #73624): generic - thinking text (``reasoning`` / ``reasoning_content``) rides the wire for - at most the NEWEST assistant turn on routes that do not echo stale - reasoning back (Codex Responses ships encrypted ``codex_reasoning_items`` - instead of the text keys; strict chat-completions providers strip or - one-space-pad the field). Passing ``False`` excludes those keys on every - assistant turn but the newest, so the compaction TRIGGER sees the same - size class as the tail-protection walk โ€” the disagreement made - reasoning-heavy codex_responses sessions fire preflight forever while the - walk found nothing to compact (#84371 dead loop). Default ``True`` - preserves the conservative full charge for callers without route context. + ``charge_stale_thinking=False`` mirrors the tail-budget walk + (``context_compressor._estimate_msg_budget_tokens``): on routes that don't + echo stale reasoning, ``reasoning``/``reasoning_content`` ride the wire only + for the NEWEST assistant turn, so excluding them elsewhere keeps the + compaction TRIGGER in the same size class as the walk โ€” otherwise + reasoning-heavy sessions fire preflight forever while the walk finds + nothing to compact. Default True is the conservative full charge. - Per-message results are memoized (see ``_estimate_message_tokens_cached``) - keyed on a deep *identity fingerprint* of the message, so re-walking a - long history every iteration only pays for messages whose object graph - actually changed. The memo is exact: equal fingerprints imply identical - leaf objects and structure, hence an identical estimate. + Per-message results are memoized on an identity fingerprint (see + ``_estimate_message_tokens_cached``); equal fingerprints imply identical + leaves and structure, hence identical estimates. """ _IMAGE_TOKEN_COST = 1500 if not charge_stale_thinking: @@ -3735,29 +2967,15 @@ def _strip_stale_thinking_for_estimate( return out -# --- Per-message token-estimate memo ------------------------------------- -# -# ``estimate_messages_tokens_rough`` is called on the full history every -# loop iteration (conversation_loop preflight), repeatedly during compaction -# telemetry, and inside an O(n^2) shrink loop in moa_loop. The per-message -# helpers are pure functions of the message's value, so a memo keyed on a -# fingerprint that uniquely determines the value is exactly equivalent. -# -# Fingerprint design (soundness argument): -# * strings are fingerprinted by ``id()`` AND pinned (a strong reference is -# stored in the cache entry). While the entry lives, that id cannot be -# reused by another object, so id-equality implies object-equality โ€” -# strings are immutable, so value-equality too (no #50372-style aliasing). -# * ints/floats/bools/None are fingerprinted by value. -# * dicts/lists recurse structurally, preserving key order โ€” ``str(shadow)`` -# depends on insertion order, so order is part of the key. -# * any other type aborts the memo and falls through to a direct compute. -# Equal fingerprints therefore imply deep-equal messages built from identical -# immutable leaves โ‡’ identical ``str(shadow)`` bytes โ‡’ identical estimate. -# -# Because the api_messages build shallow-copies history dicts each iteration, -# the copies share the same content strings โ€” so unchanged history messages -# hit the memo even though the outer dicts are fresh objects every turn. +# Per-message token-estimate memo. The estimate is a pure function of the +# message value, so a fingerprint that uniquely determines the value is exact: +# * strings by ``id()`` AND pinned (strong ref in the entry) โ€” while the +# entry lives the id can't be reused, and strings are immutable, so +# id-equality implies value-equality; +# * ints/floats/bools/None by value; dicts/lists structurally, preserving +# key order (``str(shadow)`` depends on it); any other type aborts the memo. +# api_messages shallow-copies history dicts each turn but shares the content +# strings, so unchanged messages still hit. _MSG_TOKENS_CACHE: Dict[Any, Tuple[list, int]] = {} _MSG_TOKENS_CACHE_MAX = 4096 @@ -3838,23 +3056,13 @@ def _count_image_tokens(msg: Dict[str, Any], cost_per_image: int) -> int: def _wire_message_shadow(msg: Dict[str, Any]) -> Dict[str, Any]: """Shadow of a message holding only what the provider actually receives. - Two adjustments to the raw persisted dict: - - * ``api_content`` is a SUBSTITUTE for ``content``, not an addition to it. - ``turn_context.substitute_api_content()`` pops the sidecar and overwrites - ``content`` at every API-bound build site, so exactly one of the two is - ever sent. Counting both double-counts any message whose sidecar differs - from its clean stored content (2.00x on a 40KB sidecar). - - The substitution mirrors that helper's guard exactly: only a non-empty - STRING sidecar on a ``user``/``assistant`` row displaces ``content``. - Any other sidecar shape is popped and discarded on the wire without - touching ``content``, so a shadow that substituted unconditionally - would UNDERcount those rows โ€” the dangerous direction, since it makes - compaction fire too late and the turn dies on a hard context error. - * Base64 image payloads are replaced with a placeholder; they are charged - separately at a flat rate by ``_count_image_tokens``, and counting their - raw chars here would massively overestimate usage. + * ``api_content`` SUBSTITUTES ``content`` (``turn_context.substitute_api_content`` + pops it and overwrites content at every API-bound build), so exactly one + is counted. The guard is mirrored exactly: only a non-empty STRING sidecar + on a user/assistant row displaces content; any other shape is discarded on + the wire, and substituting it would UNDERcount โ€” the dangerous direction + (compaction fires too late, the turn dies on a hard context error). + * Base64 images become a placeholder; ``_count_image_tokens`` charges them flat. """ sidecar = msg.get("api_content") sidecar_wins = ( @@ -3862,16 +3070,11 @@ def _wire_message_shadow(msg: Dict[str, Any]) -> Dict[str, Any]: and bool(sidecar) and msg.get("role") in ("user", "assistant") ) - # The internal ``reasoning`` key never ships: every request build pops it - # after (optionally) promoting it into ``reasoning_content`` (see - # ``apply_reasoning_content_policy`` / conversation_loop's api_messages - # build). When a message carries BOTH keys โ€” the normal shape on - # reasoning-echo providers, which pin ``reasoning_content`` at creation - # time while ``reasoning`` holds the same text for trajectory storage โ€” - # counting both charged the same thinking twice and inflated the rough - # estimate by up to +53% against provider-reported prompt_tokens - # (#84371 comment data, llama.cpp/Qwen). Keep ``reasoning`` only as the - # promotion proxy when no ``reasoning_content`` exists to displace it. + # ``reasoning`` never ships as-is: request builds pop it after optionally + # promoting it into ``reasoning_content``. When both exist (reasoning-echo + # providers pin reasoning_content; reasoning holds the same text for the + # trajectory) counting both inflated estimates up to +53%; keep + # ``reasoning`` only as the promotion proxy when nothing displaces it. _rc = msg.get("reasoning_content") drop_reasoning_dup = isinstance(_rc, str) and bool(_rc.strip()) shadow: Dict[str, Any] = {} @@ -3881,15 +3084,11 @@ def _wire_message_shadow(msg: Dict[str, Any]) -> Dict[str, Any]: if k == "reasoning" and drop_reasoning_dup: continue if k == "api_content": - # Always popped before the request is built; only counted when it - # actually replaces ``content``. if sidecar_wins: shadow["content"] = v continue if k == "content": if sidecar_wins: - # The sidecar wins on the wire; skip the clean copy so the - # same logical content is not counted twice. continue if isinstance(v, list): cleaned = [] @@ -3911,17 +3110,6 @@ def _wire_message_shadow(msg: Dict[str, Any]) -> Dict[str, Any]: return shadow -def _estimate_message_chars(msg: Dict[str, Any]) -> int: - """Char count for token estimation, excluding base64 image data. - - Base64 images are counted via `_count_image_tokens` instead; including - their raw chars here would massively overestimate token usage. - """ - if not isinstance(msg, dict): - return len(str(msg)) - return len(str(_wire_message_shadow(msg))) - - def _estimate_message_tokens_without_images(msg: Dict[str, Any]) -> int: """Token estimate for a message shadow with image payloads stripped.""" if not isinstance(msg, dict): @@ -3936,27 +3124,17 @@ def estimate_request_tokens_rough( tools: Optional[List[Dict[str, Any]]] = None, charge_stale_thinking: bool = True, ) -> int: - """Rough token estimate for a full chat-completions request. - - Includes the major payload buckets Hermes sends to providers: - system prompt, conversation messages, and tool schemas. With 50+ - tools enabled, schemas alone can add 20-30K tokens โ€” a significant - blind spot when only counting messages. Image content is counted - at a flat per-image cost (see estimate_messages_tokens_rough). - - ``charge_stale_thinking`` is forwarded to - ``estimate_messages_tokens_rough`` โ€” pass ``False`` when the active - route provably strips stale assistant thinking at send time (see - ``message_sanitization.stale_thinking_reaches_wire``, #84371). - """ + """Rough token estimate for a full request: system prompt + messages + tool + schemas (50+ tools add 20-30K on their own). ``charge_stale_thinking`` + is forwarded โ€” pass False when the route provably strips stale thinking + (``message_sanitization.stale_thinking_reaches_wire``).""" total = 0 if system_prompt: total += estimate_tokens_rough(system_prompt) if messages: if charge_stale_thinking: - # Positional-compatible call: test seams and plugin engines - # monkeypatch estimate_messages_tokens_rough with (messages)-only - # signatures; only the route-aware False path needs the kwarg. + # Positional call: test seams and plugin engines monkeypatch + # estimate_messages_tokens_rough with (messages)-only signatures. total += estimate_messages_tokens_rough(messages) else: total += estimate_messages_tokens_rough( @@ -3967,26 +3145,16 @@ def estimate_request_tokens_rough( return total -# --- Usage-anchored context accounting ------------------------------------ -# -# Provider responses carry ``usage.prompt_tokens`` โ€” EXACT ground truth for -# everything sent on that request (system prompt + tool schemas + full -# history). Re-estimating the whole conversation with chars/4 heuristics on -# every context-size check compounds error over the entire transcript (flat -# 1500-token images, CJK density, provider replay blobs). Anchoring on the -# last real usage shrinks the estimation window to the messages appended -# since that response; the error self-corrects at every new response. -# -# The anchor is a plain dict so callers can store it anywhere: -# prompt_tokens / completion_tokens โ€” provider-reported usage at capture. -# base_count โ€” len(messages) at capture time (the assistant reply for the -# captured response is NOT yet appended at the capture site; when it -# appears at index base_count its cost is covered by completion_tokens, -# so the delta walk skips it). -# base_last_id / base_last_role โ€” identity fingerprint of the last message -# at capture time. Compaction, splices, and history rewrites shift or -# replace that element, failing the check and falling back to full -# estimation. Belt-and-braces on top of explicit invalidation. +# Usage-anchored context accounting: ``usage.prompt_tokens`` is EXACT ground +# truth for everything sent on that request, so anchoring on the last real +# usage shrinks chars/4 estimation to the messages appended since and the +# error self-corrects at every response. Anchor dict fields: +# prompt_tokens / completion_tokens โ€” provider usage at capture. +# base_count โ€” len(messages) at capture; the reply for that response is not +# yet appended and its cost is covered by completion_tokens, so the delta +# walk skips it when it appears at index base_count. +# base_last_id / base_last_role โ€” identity of the last message at capture; +# compaction/splices/rewrites replace it and fall back to full estimation. def capture_usage_anchor( @@ -4001,9 +3169,7 @@ def capture_usage_anchor( except (TypeError, ValueError): return None if pt <= 0 or not isinstance(messages, list): - # No usable usage (some OpenAI-compatible endpoints omit it) โ€” the - # caller keeps whatever anchor it had, or stays on pure estimation. - return None + return None # no usable usage (some endpoints omit it) โ€” caller keeps its anchor base_count = len(messages) last = messages[-1] if base_count else None return { @@ -4021,22 +3187,10 @@ def anchored_context_tokens( *, charge_stale_thinking: bool = True, ) -> Optional[int]: - """Context size anchored on the last provider-reported usage. - - Returns ``prompt_tokens + completion_tokens`` of the anchored response - plus a rough estimate of ONLY the messages appended since โ€” or ``None`` - when the anchor is missing or stale (caller falls back to full - estimation). The assistant reply produced by the anchored response - (first appended message after the base) is skipped: its cost is already - counted exactly by ``completion_tokens``. - - ``charge_stale_thinking`` is forwarded to the delta estimate โ€” pass - ``False`` to exclude transient ``reasoning``/``reasoning_content`` text - on all but the newest assistant message in the delta (the durable- - transcript view used by display surfaces; see the turn-base anchor in - ``agent/conversation_loop.py``). Default ``True`` preserves the - conservative full charge for request-size callers. - """ + """Anchored prompt+completion tokens plus a rough estimate of ONLY the + messages appended since; None when the anchor is missing or stale. The + anchored response's own reply is skipped (already in completion_tokens). + ``charge_stale_thinking`` is forwarded to the delta estimate.""" if not isinstance(anchor, dict) or not isinstance(messages, list): return None base_count = anchor.get("base_count") or 0 @@ -4053,8 +3207,6 @@ def anchored_context_tokens( if delta: first = delta[0] if isinstance(first, dict) and first.get("role") == "assistant": - # The anchored response's own reply โ€” already counted exactly by - # completion_tokens above. delta = delta[1:] if delta: total += estimate_messages_tokens_rough( @@ -4063,13 +3215,8 @@ def anchored_context_tokens( return total -# NOTE: tool schemas can be large. Avoid repeated `str(tools)` conversions, -# which are CPU-heavy and can stall GUI event loops under GIL pressure. -# -# Keyed by ``id(tools)``. A long-lived gateway/desktop backend builds many -# transient tool lists over its lifetime, so the cache is bounded and evicts -# oldest-first (insertion-ordered dict) once it exceeds the cap. The cap is -# generous relative to how rarely toolsets are rebuilt within a process. +# Keyed by ``id(tools)``; bounded, evicts oldest-first. Avoids repeated +# ``str(tools)`` on large schemas, which stalls GUI event loops under GIL pressure. _TOOLS_TOKENS_CACHE: dict[int, Tuple[int, str, str, int]] = {} _TOOLS_TOKENS_CACHE_MAX = 256 @@ -4090,8 +3237,6 @@ def _estimate_tools_tokens_rough(tools: List[Dict[str, Any]]) -> int: if not tools: return 0 - # Cache by list identity. Tools are rebuilt rarely (toolset changes), - # but token estimates are requested frequently (preflight, compaction). key = id(tools) n = len(tools) first = _tool_name_for_cache(tools[0]) if n else "" @@ -4103,9 +3248,7 @@ def _estimate_tools_tokens_rough(tools: List[Dict[str, Any]]) -> int: if cached_n == n and cached_first == first and cached_last == last: return cached_tokens - # Fast, stable rough estimate: sum lengths of the major schema fields. - # This avoids the pathological `str(tools)` path while still scaling with - # schema size (descriptions + parameters dominate). + # Sum the major schema fields (descriptions + parameters dominate). total_chars = 0 for tool in tools: if not isinstance(tool, dict): @@ -4124,16 +3267,12 @@ def _estimate_tools_tokens_rough(tools: List[Dict[str, Any]]) -> int: total_chars += len(name) if isinstance(desc, str): total_chars += len(desc) - # Parameters can be nested; JSON is closer to over-the-wire size than repr(). - try: + try: # JSON is closer to wire size than repr() total_chars += len(json.dumps(params, ensure_ascii=False, separators=(",", ":"))) except Exception: total_chars += len(str(params)) tokens = (total_chars + 3) // 4 - # Bound the cache: drop the oldest entry when the cap is exceeded so a - # long-running process can't accumulate an unbounded number of stale - # ``id(tools)`` entries (id values are recycled after GC anyway). if len(_TOOLS_TOKENS_CACHE) >= _TOOLS_TOKENS_CACHE_MAX: _TOOLS_TOKENS_CACHE.pop(next(iter(_TOOLS_TOKENS_CACHE)), None) _TOOLS_TOKENS_CACHE[key] = (n, first, last, tokens) diff --git a/agent/models_dev.py b/agent/models_dev.py index fca9201eb6..7d197ec1db 100644 --- a/agent/models_dev.py +++ b/agent/models_dev.py @@ -1,39 +1,24 @@ """Models.dev registry integration โ€” primary database for providers and models. -Fetches from https://models.dev/api.json โ€” a community-maintained database -of 4000+ models across 109+ providers. Provides: +Fetches https://models.dev/api.json (4000+ models, 100+ providers): provider +metadata (name, base URL, env vars, docs) and model metadata (context window, +max output, cost/M tokens, capabilities, modalities, knowledge cutoff, +open-weights flag, family, deprecation status). -- **Provider metadata**: name, base URL, env vars, documentation link -- **Model metadata**: context window, max output, cost/M tokens, capabilities - (reasoning, tools, vision, PDF, audio), modalities, knowledge cutoff, - open-weights flag, family grouping, deprecation status +Resolution order: in-memory cache (fresh, or stale served immediately while +one background daemon thread refreshes) โ†’ disk cache +(~/.hermes/models_dev_cache.json, any age) โ†’ network, only when no cache +exists at all. Failed refreshes back off for 5 minutes process-wide. -Data resolution order: - 1. In-memory cache (fresh, or stale served immediately while a single - background daemon thread refreshes) - 2. Disk cache (~/.hermes/models_dev_cache.json โ€” any age; stale data is - served rather than blocking callers on the network) - 3. Network fetch (https://models.dev/api.json) โ€” only when no cache - exists at all; failed refreshes back off for 5 minutes process-wide - -Network hardening: - -- **ETag conditional GET**: network refreshes send ``If-None-Match`` - with the last-known ETag whenever a servable registry is held (memory, - hydrated from disk on cold force-refresh). A 304 Not Modified response - is a no-op โ€” the existing cache is re-confirmed fresh without - re-downloading the full registry (โ‰ˆ2 MB). The ETag is persisted - atomically alongside the cache file. -- **No-network-on-hot-paths invariant**: resolution, picker, and resume - paths NEVER perform network I/O. ``allow_network=False`` is threaded - through every query function, and hot-path callers (vision routing, - image routing, cost guard, context-length lookup) pass it explicitly. +Invariants: +- **ETag conditional GET**: refreshes send ``If-None-Match`` whenever a + servable registry is held; a 304 re-confirms the cache without + re-downloading ~2 MB. The ETag sidecar is persisted with the cache body. +- **No network on hot paths**: resolution, picker, and resume paths pass + ``allow_network=False`` and never perform network I/O. - **Corrupt-cache rejection**: a disk cache that fails to parse, is not a - dict, or is empty is ignored with a warning rather than served as - ``{}`` and silently breaking provider/model resolution. -- **Mirror URL override**: ``models_dev.url`` in config.yaml lets - deployments point at a mirror (e.g. a self-hosted copy) without code - changes. + dict, or is empty is quarantined with a warning rather than served as ``{}``. +- **Mirror URL override**: ``models_dev.url`` in config.yaml. Other modules should import the dataclasses and query functions from here rather than parsing the raw JSON themselves. @@ -41,6 +26,7 @@ rather than parsing the raw JSON themselves. import json import logging +import re import threading import time from dataclasses import dataclass @@ -67,7 +53,7 @@ _models_dev_refresh_in_flight = False # --------------------------------------------------------------------------- -# Dataclasses โ€” rich metadata for providers and models +# Dataclasses # --------------------------------------------------------------------------- @dataclass @@ -120,32 +106,18 @@ class ModelInfo: def supports_audio_input(self) -> bool: return "audio" in self.input_modalities - def format_cost(self) -> str: - """Human-readable cost string, e.g. '$3.00/M in, $15.00/M out'.""" - if not self.has_cost_data(): - return "unknown" - parts = [f"${self.cost_input:.2f}/M in", f"${self.cost_output:.2f}/M out"] - if self.cost_cache_read is not None: - parts.append(f"cache read ${self.cost_cache_read:.2f}/M") - return ", ".join(parts) - def format_capabilities(self) -> str: """Human-readable capabilities, e.g. 'reasoning, tools, vision, PDF'.""" - caps = [] - if self.reasoning: - caps.append("reasoning") - if self.tool_call: - caps.append("tools") - if self.supports_vision(): - caps.append("vision") - if self.supports_pdf(): - caps.append("PDF") - if self.supports_audio_input(): - caps.append("audio") - if self.structured_output: - caps.append("structured output") - if self.open_weights: - caps.append("open weights") + flags = ( + (self.reasoning, "reasoning"), + (self.tool_call, "tools"), + (self.supports_vision(), "vision"), + (self.supports_pdf(), "PDF"), + (self.supports_audio_input(), "audio"), + (self.structured_output, "structured output"), + (self.open_weights, "open weights"), + ) + caps = [label for on, label in flags if on] return ", ".join(caps) if caps else "basic" @@ -161,6 +133,18 @@ class ProviderInfo: model_count: int = 0 +@dataclass +class ModelCapabilities: + """Structured capability metadata for a model from models.dev.""" + + supports_tools: bool = True + supports_vision: bool = False + supports_reasoning: bool = False + context_window: int = 200000 + max_output_tokens: int = 8192 + model_family: str = "" + + # --------------------------------------------------------------------------- # Provider ID mapping: Hermes โ†” models.dev # --------------------------------------------------------------------------- @@ -194,16 +178,12 @@ PROVIDER_TO_MODELS_DEV: Dict[str, str] = { "gemini": "google", "google": "google", "xai": "xai", - # xAI OAuth is an authentication/transport path for the same xAI model - # catalog, so model metadata should resolve through the xAI provider. - "xai-oauth": "xai", + "xai-oauth": "xai", # OAuth is a transport path for the same xAI catalog "xiaomi": "xiaomi", "nvidia": "nvidia", - # Meta Model API (Muse Spark family, api.meta.ai). models.dev keys these - # under the "meta" provider id; Hermes' provider is "meta-ai" (and the - # api.meta.ai host reverse-maps to "meta-ai"), so without both aliases the - # context/pricing lookup misses and muse-spark-* falls back to the generic - # 256K default instead of its true 1M window. + # Meta Model API (Muse Spark, api.meta.ai): models.dev keys it "meta", the + # Hermes provider is "meta-ai"; both aliases are needed or muse-spark-* + # falls back to the generic 256K default instead of its true 1M window. "meta-ai": "meta", "meta": "meta", "groq": "groq", @@ -214,8 +194,7 @@ PROVIDER_TO_MODELS_DEV: Dict[str, str] = { "ollama-cloud": "ollama-cloud", } -# Reverse mapping: models.dev id โ†’ Hermes ids (built lazily; many-to-one, -# e.g. both "meta" and "meta-ai" may map to the same models.dev id). +# Reverse mapping: models.dev id โ†’ Hermes ids (built lazily; many-to-one). _MODELS_DEV_TO_PROVIDER: Optional[Dict[str, List[str]]] = None @@ -230,21 +209,22 @@ def _models_dev_to_hermes_ids(mdev_id: str) -> List[str]: return _MODELS_DEV_TO_PROVIDER.get(mdev_id, []) +# --------------------------------------------------------------------------- +# Disk cache + ETag sidecar +# --------------------------------------------------------------------------- def _get_cache_path() -> Path: - """Return path to disk cache file.""" from hermes_constants import get_hermes_home return get_hermes_home() / "models_dev_cache.json" def _get_etag_path() -> Path: - """Return path to the ETag sidecar file for conditional GET.""" from hermes_constants import get_hermes_home return get_hermes_home() / "models_dev_cache.etag" def _load_etag() -> str: - """Load the last-known ETag from disk, or empty string if missing.""" + """Last-known ETag from disk, or "" if missing.""" try: etag_path = _get_etag_path() if etag_path.exists(): @@ -255,7 +235,6 @@ def _load_etag() -> str: def _save_etag(etag: str) -> None: - """Persist an ETag to the sidecar file atomically.""" try: from utils import atomic_write_text @@ -269,9 +248,9 @@ def _save_etag(etag: str) -> None: def _clear_etag() -> None: """Delete the ETag sidecar so the next fetch is unconditional. - Called when the cached registry the ETag vouches for is gone or - unusable โ€” sending If-None-Match without a servable cache invites a - 304 that would leave the process with no data at all. + Called when the registry the ETag vouches for is gone or unusable: an + If-None-Match without a servable cache invites a 304 that leaves the + process with no data at all. """ try: _get_etag_path().unlink(missing_ok=True) @@ -280,12 +259,8 @@ def _clear_etag() -> None: def _get_models_dev_url() -> str: - """Resolve the models.dev API URL, honoring a config.yaml override. - - The ``models_dev.url`` config key lets deployments point at a mirror - (e.g. a self-hosted copy behind a corporate proxy) without code changes. - Falls back to the default public URL when unset or empty. - """ + """The models.dev API URL, honoring the ``models_dev.url`` config override + (mirrors / self-hosted copies).""" try: from hermes_cli.config import cfg_get, load_config_readonly cfg = load_config_readonly() @@ -294,23 +269,19 @@ def _get_models_dev_url() -> str: return url.strip() except Exception: pass - # Fall back to the module global (not the constant) so existing - # code/tests that patch MODELS_DEV_URL keep working. + # Module global (not a captured constant) so code/tests that patch + # MODELS_DEV_URL keep working. return MODELS_DEV_URL def _validate_registry(data: Any) -> bool: - """Return True if *data* is a non-empty dict suitable for serving.""" + """True if *data* is a non-empty dict suitable for serving.""" return isinstance(data, dict) and len(data) > 0 def _load_disk_cache() -> Dict[str, Any]: - """Load models.dev data from disk cache. - - A corrupt cache (invalid JSON, not a dict, or empty) is rejected with - a warning so it doesn't silently masquerade as ``{}`` and break - provider/model resolution for every caller. - """ + """Load the disk cache; a corrupt/empty one is quarantined with a warning + so it never masquerades as ``{}`` and breaks provider/model resolution.""" try: cache_path = _get_cache_path() if cache_path.exists(): @@ -336,14 +307,12 @@ def _load_disk_cache() -> Dict[str, Any]: def _quarantine_corrupt_cache(cache_path: Path) -> None: - """Move a rejected cache aside and drop its ETag sidecar. + """Rename a rejected cache aside and drop its ETag sidecar. - Renaming (rather than leaving the file in place) makes the rejection - a one-time event: without it, every hot-path call that finds the - in-memory cache empty re-reads and re-parses the corrupt file and - re-emits the warning until a network fetch succeeds. The sidecar is - cleared because it vouches for a registry we no longer hold โ€” a 304 - against a missing cache would leave the process with no data at all. + Renaming makes the rejection a one-time event โ€” otherwise every hot-path + call that finds the in-memory cache empty re-parses the corrupt file and + re-warns until a network fetch succeeds. The sidecar vouches for a registry + we no longer hold, so it goes too. """ try: cache_path.rename(cache_path.with_suffix(".json.corrupt")) @@ -353,46 +322,34 @@ def _quarantine_corrupt_cache(cache_path: Path) -> None: def _disk_cache_age_seconds() -> Optional[float]: - """Return age (in seconds) of the disk cache file, or None if missing. - - Used by ``fetch_models_dev`` to short-circuit the network probe when - a recent on-disk cache exists. Errors (missing file, permission - denied, weird filesystem) all return None โ€” callers fall through - to the network fetch path. - """ + """Age of the disk cache file in seconds, or None if missing/unreadable + (or mtime in the future from clock skew โ€” treated as unknown freshness so + callers fall through to the network rather than trusting it forever).""" try: cache_path = _get_cache_path() if not cache_path.exists(): return None - mtime = cache_path.stat().st_mtime - age = time.time() - mtime - # Negative age means the file's mtime is in the future (clock skew - # or system clock reset). Treat as "unknown freshness" โ†’ fall - # through to network so we don't serve potentially-bad data - # forever. - if age < 0: - return None - return age + age = time.time() - cache_path.stat().st_mtime + return age if age >= 0 else None except Exception as e: logger.debug("Failed to stat models.dev disk cache: %s", e) return None def _save_disk_cache(data: Dict[str, Any], etag: str = "") -> None: - """Save models.dev data to disk cache atomically. - - Also persists the ETag sidecar when *etag* is non-empty so the next - refresh can issue a conditional GET. - """ + """Save the registry atomically, plus the ETag sidecar when non-empty.""" try: - cache_path = _get_cache_path() - atomic_json_write(cache_path, data, indent=None, separators=(",", ":")) + atomic_json_write(_get_cache_path(), data, indent=None, separators=(",", ":")) except Exception as e: logger.debug("Failed to save models.dev disk cache: %s", e) if etag: _save_etag(etag) +# --------------------------------------------------------------------------- +# Network refresh (all state mutation happens under _models_dev_fetch_lock) +# --------------------------------------------------------------------------- + class _NotModified(Exception): """Server returned 304 Not Modified โ€” existing cache is still valid.""" @@ -400,22 +357,14 @@ class _NotModified(Exception): def _fetch_models_dev_from_network( *, conditional: bool = False ) -> Tuple[Dict[str, Any], str]: - """Fetch the live models.dev registry. + """Fetch the live registry; returns ``(registry, etag)`` (etag "" if none). - ``conditional`` enables ETag conditional GET (``If-None-Match`` with - the sidecar's ETag). Callers must pass True ONLY while holding - ``_models_dev_fetch_lock`` AND holding a servable registry the 304 - can re-confirm โ€” a conditional request without one invites a 304 - that leaves the process with no data at all (previously a permanent - empty-registry loop when the sidecar outlived a corrupt cache file). - A 304 raises ``_NotModified`` so the caller can re-confirm the - existing cache's freshness without re-downloading the full payload. - - Returns ``(registry, etag)``; the etag is empty when the server sent - none. The caller persists it together with the cache body - (``_commit_registry``) so the sidecar can never get ahead of the data - it vouches for. Raises on network errors and on an empty/invalid - registry payload. + ``conditional`` sends ``If-None-Match`` with the sidecar's ETag and raises + ``_NotModified`` on 304. Pass True ONLY while holding + ``_models_dev_fetch_lock`` AND a servable registry โ€” a conditional request + without one invites a 304 that leaves the process with no data (formerly a + permanent empty-registry loop when the sidecar outlived a corrupt cache). + Raises on network errors and on an empty/invalid payload. """ url = _get_models_dev_url() headers: Dict[str, str] = {} @@ -424,11 +373,8 @@ def _fetch_models_dev_from_network( if etag: headers["If-None-Match"] = etag - # Tuple (connect, read): a flat timeout=15 let a blackholed connect - # stall the first-turn critical path for the full 15 s. 5 s connect - # fails fast on unreachable hosts; 10 s read still tolerates a slow - # registry response (matches the OpenRouter fetch convention in - # agent/model_metadata.py). + # (connect, read) timeout: 5 s connect fails fast on blackholed hosts + # instead of stalling the first turn; 10 s read tolerates a slow registry. response = requests.get(url, headers=headers, timeout=(5, 10)) if response.status_code == 304: @@ -443,11 +389,11 @@ def _fetch_models_dev_from_network( def _mark_stale_cache_grace() -> None: - """Give stale cache data a short in-memory grace before retrying refresh. + """Give stale cache data a 5-minute in-memory grace before retrying refresh. - Only ever moves the timestamp forward: if a background refresh completed - between the caller's staleness check and this call, the fresh timestamp - is preserved instead of being rewound to a 5-minute grace. + Only ever moves the timestamp forward, so a background refresh that + completed between the caller's staleness check and this call keeps its + fresh timestamp. """ global _models_dev_cache_time grace_time = time.time() - _MODELS_DEV_CACHE_TTL + _MODELS_DEV_RETRY_DELAY @@ -456,12 +402,10 @@ def _mark_stale_cache_grace() -> None: def _commit_registry(data: Dict[str, Any], *, etag: str = "", where: str) -> None: - """Persist a freshly fetched registry: disk + in-mem + clear backoff. + """Persist a fetched registry: disk + in-mem + clear backoff. - Callers must hold ``_models_dev_fetch_lock`` so a failing refresh on one - path can never stomp the state a succeeding refresh on the other path - just committed (e.g. a failing background worker re-arming the backoff - immediately after a successful ``force_refresh``). + Callers hold ``_models_dev_fetch_lock`` so a failing refresh on one path + can never stomp state a succeeding refresh on the other just committed. """ global _models_dev_cache, _models_dev_cache_time, _models_dev_retry_after _save_disk_cache(data, etag) @@ -477,21 +421,14 @@ def _commit_registry(data: Dict[str, Any], *, etag: str = "", where: str) -> Non def _confirm_cache_not_modified(*, where: str) -> None: - """Re-confirm the existing cache as fresh after a 304 Not Modified. - - Callers must hold ``_models_dev_fetch_lock``. Clears the backoff and - resets the in-memory cache timestamp so the next caller hits the fast - path. The disk cache itself is not rewritten โ€” its contents are - unchanged, only its freshness marker is advanced. - """ + """After a 304: clear backoff and re-mark the held cache fresh (disk is + untouched โ€” only the freshness marker advances). Caller holds the lock.""" global _models_dev_cache_time, _models_dev_retry_after if not _models_dev_cache: - # Pathological: a 304 arrived but we hold no registry. Should be - # unreachable now that conditional GETs require a servable cache - # (see _fetch_models_dev_from_network); kept as defense in depth - # because this state previously caused a permanent empty-registry - # loop. Drop the sidecar so the next attempt is unconditional and - # arm the normal failure backoff instead of marking {} "fresh". + # A 304 with no registry held should be unreachable (conditional GETs + # require a servable cache) but previously caused a permanent + # empty-registry loop: drop the sidecar and arm the normal backoff + # rather than marking {} "fresh". _clear_etag() _models_dev_retry_after = time.time() + _MODELS_DEV_RETRY_DELAY logger.warning( @@ -510,10 +447,7 @@ def _confirm_cache_not_modified(*, where: str) -> None: def _note_refresh_failure(exc: Exception, *, where: str) -> None: - """Record a failed refresh: arm the process-wide 5-minute backoff. - - Callers must hold ``_models_dev_fetch_lock`` (see ``_commit_registry``). - """ + """Arm the process-wide 5-minute backoff. Caller holds the lock.""" global _models_dev_retry_after _models_dev_retry_after = time.time() + _MODELS_DEV_RETRY_DELAY logger.debug( @@ -528,11 +462,10 @@ def _background_refresh_models_dev() -> None: """Best-effort refresh after serving stale cache data.""" global _models_dev_refresh_in_flight try: - # Fetch INSIDE the lock: symmetric with the foreground path, so - # conditional-GET inputs (memory cache + etag sidecar) can't be - # mutated mid-fetch by a concurrent force_refresh, and the two - # paths can't double-download concurrently. Hot-path callers are - # unaffected โ€” they return stale data without touching this lock. + # Fetch INSIDE the lock, symmetric with the foreground path: the + # conditional-GET inputs (memory cache + sidecar) can't be mutated + # mid-fetch by a concurrent force_refresh and the two paths can't + # double-download. Hot-path callers never touch this lock. with _models_dev_fetch_lock: data, etag = _fetch_models_dev_from_network( conditional=bool(_models_dev_cache) @@ -550,11 +483,8 @@ def _background_refresh_models_dev() -> None: def _start_background_refresh_models_dev() -> None: - """Start one daemon refresh worker if none is already running. - - Honors the process-wide failure backoff: after a failed refresh, - no new background worker is spawned until ``_models_dev_retry_after``. - """ + """Start one daemon refresh worker if none is running and the failure + backoff has elapsed.""" global _models_dev_refresh_in_flight if time.time() < _models_dev_retry_after: return @@ -570,8 +500,8 @@ def _start_background_refresh_models_dev() -> None: try: thread.start() except Exception as e: - # Thread/fd exhaustion: clear the flag so refresh isn't disabled - # for the rest of the process lifetime. Callers still get stale data. + # Thread/fd exhaustion: clear the flag so refresh isn't disabled for + # the rest of the process. Callers still get stale data. with _models_dev_refresh_lock: _models_dev_refresh_in_flight = False logger.debug("Failed to start models.dev refresh thread: %s", e) @@ -580,38 +510,28 @@ def _start_background_refresh_models_dev() -> None: def fetch_models_dev( force_refresh: bool = False, *, allow_network: bool = True ) -> Dict[str, Any]: - """Fetch models.dev registry. Cache hierarchy: in-mem โ†’ disk โ†’ network. + """Fetch the models.dev registry (dict keyed by provider ID; {} on failure). - Returns the full registry dict keyed by provider ID, or empty dict on failure. + Cache hierarchy when ``force_refresh=False``: + 1. Fresh in-memory cache โ†’ return. + 2. Stale in-memory cache โ†’ return it and refresh in one background daemon + thread. Callers never block on the network while any cache exists; + models.dev only changes when providers add models, so stale data beats + a foreground timeout. + 3. Disk cache (any age) โ†’ populate in-mem and return; a stale one + triggers the same background refresh. Corrupt/empty is rejected. + 4. No cache โ†’ singleflight foreground network fetch, saved to disk+mem. + 5. Any failed refresh suppresses automatic refreshes for 5 minutes. - Network requests use ETag conditional GET when a cached ETag exists - AND a servable registry is held (on a cold ``force_refresh`` the - memory cache is hydrated from disk first). A 304 Not Modified - response re-confirms the existing cache's freshness without - re-downloading the full (~2 MB) registry. + ``force_refresh=True`` (``hermes config refresh``) bypasses the cache fast + paths and the backoff, falling back to cached data only if the call fails. + ``allow_network=False`` returns any memory/disk cache regardless of age and + never makes a request โ€” for latency-sensitive paths (gateway route-identity + checks, vision routing, context-length lookup). - Cache hierarchy (when ``force_refresh=False``): - 1. Fresh in-memory cache โ†’ return immediately. - 2. Stale in-memory cache โ†’ return immediately and refresh in a single - background daemon thread. Callers never block on the network while - any cache exists; ``models.dev`` only changes when providers add - new models, so stale data is preferable to a foreground timeout. - 3. Disk cache file (any age) โ†’ load, populate in-mem, return - immediately. Stale disk caches trigger the same background refresh. - A corrupt or empty disk cache is rejected with a warning. - 4. No cache at all โ†’ singleflight foreground network fetch. On - success, save to disk + in-mem and return. - 5. Any failed refresh (foreground or background) suppresses further - automatic refreshes for 5 minutes process-wide. - - When ``force_refresh=True`` (used by ``hermes config refresh``, the - \"refresh model catalog\" code path), cache fast paths and the failure - backoff are bypassed; the function hits the network and only falls back - to cached data if the call fails. When ``allow_network=False``, any - memory or disk cache is returned regardless of age and no request is - made โ€” used by latency-sensitive paths (gateway route-identity checks, - vision routing, context-length lookup) that must never wait on the - network. + Network requests use ETag conditional GET when a servable registry is held + (a cold ``force_refresh`` hydrates memory from disk first); a 304 + re-confirms the cache without re-downloading ~2 MB. """ global _models_dev_cache, _models_dev_cache_time, _models_dev_retry_after @@ -627,8 +547,7 @@ def fetch_models_dev( ) return _models_dev_cache - # Stage 1: fresh in-memory cache wins. This is the hot path on - # long-lived processes โ€” no I/O, no system calls. + # Stage 1: fresh in-memory cache โ€” the hot path, no I/O. if ( not force_refresh and _models_dev_cache @@ -636,8 +555,7 @@ def fetch_models_dev( ): return _models_dev_cache - # Stage 2: stale in-memory cache is still better than blocking provider - # resolution on a foreground network timeout. Refresh it in the background. + # Stage 2: stale in-memory cache beats blocking on the network. if not force_refresh and _models_dev_cache: _mark_stale_cache_grace() _start_background_refresh_models_dev() @@ -646,11 +564,8 @@ def fetch_models_dev( ) return _models_dev_cache - # Stage 3: disk cache short-circuits the network call. - # Only kicks in on cold-start processes (in-mem cache is empty) and only - # when the user hasn't asked for a forced refresh. A stale disk cache is - # deliberately usable: provider/model resolution should not hang just - # because models.dev is unreachable. + # Stage 3: disk cache (cold-start only). A stale disk cache is deliberately + # usable so resolution doesn't hang when models.dev is unreachable. if not force_refresh: disk_age = _disk_cache_age_seconds() if disk_age is not None: @@ -658,8 +573,8 @@ def fetch_models_dev( if disk_data: _models_dev_cache = disk_data if disk_age < _MODELS_DEV_CACHE_TTL: - # Anchor in-mem TTL to the disk file's age so we don't - # extend an already-aging cache by another full hour. + # Anchor the in-mem TTL to the file's age so an aging + # cache isn't extended by another full TTL. _models_dev_cache_time = time.time() - disk_age logger.debug( "Loaded models.dev from fresh disk cache " @@ -675,28 +590,20 @@ def fetch_models_dev( ) return _models_dev_cache - # Failed automatic refreshes are process-wide. Avoid making every caller - # retry the same unreachable endpoint while no usable cache exists. + # Process-wide backoff: don't make every caller retry an unreachable + # endpoint while no usable cache exists. if not force_refresh and time.time() < _models_dev_retry_after: return _models_dev_cache - # Stage 4: singleflight foreground network fetch โ€” only reached when no - # memory or disk cache exists (or on force_refresh). Recheck state after - # acquiring the lock because another caller may have refreshed or - # established backoff while we waited. + # Stage 4: singleflight foreground fetch. Recheck state under the lock โ€” + # another caller may have refreshed or armed the backoff while we waited. with _models_dev_fetch_lock: now = time.time() - if not force_refresh: - if _models_dev_cache: - return _models_dev_cache - if now < _models_dev_retry_after: - return _models_dev_cache + if not force_refresh and (_models_dev_cache or now < _models_dev_retry_after): + return _models_dev_cache - # Cold force_refresh (fresh CLI process): stages 1-3 were skipped, - # so the memory cache may be empty even though a servable disk - # cache + ETag sidecar exist. Hydrate first so the conditional GET - # fires (a 304 then re-confirms the disk data instead of - # re-downloading the full ~2 MB registry). + # Cold force_refresh: stages 1-3 were skipped, so hydrate memory from + # disk first so the conditional GET fires and a 304 can re-confirm it. if force_refresh and not _models_dev_cache: disk = _load_disk_cache() if disk: @@ -710,16 +617,13 @@ def fetch_models_dev( _commit_registry(data, etag=etag, where="foreground") return data except _NotModified: - # Server confirmed our cache is still valid. Re-confirm freshness - # without re-downloading the full registry. _confirm_cache_not_modified(where="foreground") return _models_dev_cache except Exception as e: _note_refresh_failure(e, where="foreground") - # Stage 5: network failed โ€” return any stale memory/disk cache. Cache - # freshness remains expired; the retry-after timestamp controls when - # the next automatic request is allowed. + # Stage 5: network failed โ€” serve any stale memory/disk cache. Freshness + # stays expired; the retry-after timestamp gates the next attempt. if not _models_dev_cache: _models_dev_cache = _load_disk_cache() _models_dev_cache_time = 0 @@ -732,163 +636,157 @@ def fetch_models_dev( return _models_dev_cache -def lookup_models_dev_context( - provider: str, model: str, *, allow_network: bool = False -) -> Optional[int]: - """Look up context_length for a provider+model combo in models.dev. +# --------------------------------------------------------------------------- +# Catalog access helpers +# --------------------------------------------------------------------------- - Returns the context window in tokens, or None if not found. - Handles case-insensitive matching and filters out context=0 entries. +def _fetch_registry(allow_network: bool) -> Dict[str, Any]: + # Keep the zero-argument call on the allow_network path: dozens of test + # sites monkeypatch fetch_models_dev with zero-arg lambdas. + return fetch_models_dev() if allow_network else fetch_models_dev(allow_network=False) - An EXPLICIT ``model_overrides`` config entry for this provider+model - wins over the catalog value; ``_default`` entries fill the gap only - when the catalog has no answer โ€” the supported self-unblock path for - models with wrong or missing context in models.dev (#84482). - ``allow_network`` defaults to False โ€” context-length lookup is a - hot path (called during every conversation turn) and must never block - on the network. Pass True only from explicit refresh flows. +def _registry_models(mdev_id: str, *, allow_network: bool) -> Optional[Dict[str, Any]]: + """The ``models`` dict of a models.dev provider entry, or None.""" + provider_data = _fetch_registry(allow_network).get(mdev_id) + if not isinstance(provider_data, dict): + return None + models = provider_data.get("models", {}) + return models if isinstance(models, dict) else None + + +def _get_provider_models( + provider: str, *, allow_network: bool = False +) -> Optional[Dict[str, Any]]: + """Resolve a Hermes provider ID to its models dict, or None if unknown. + + ``allow_network`` defaults to False โ€” called from hot paths (vision/image + routing, capability checks) that must never block. """ - # Explicit config override โ€” checked before catalog so it always wins. - override_ctx = _override_context_window(provider, model) - if override_ctx is not None: - return override_ctx - mdev_provider_id = PROVIDER_TO_MODELS_DEV.get(provider) if not mdev_provider_id: - return _default_override_context(provider) + return None + return _registry_models(mdev_provider_id, allow_network=allow_network) - # NOTE: keep the zero-argument call on the allow_network path. Dozens - # of test sites monkeypatch fetch_models_dev with zero-arg lambdas; - # passing the kwarg unconditionally breaks them all (TypeError). - data = ( - fetch_models_dev() - if allow_network - else fetch_models_dev(allow_network=False) - ) - provider_data = data.get(mdev_provider_id) - if not isinstance(provider_data, dict): - return _default_override_context(provider) - models = provider_data.get("models", {}) - if not isinstance(models, dict): - return _default_override_context(provider) +def _iter_model_entries(models: Dict[str, Any], model: str, *, suffix_fallback: bool = True): + """Yield ``(model_id, entry)`` candidates: exact, case-insensitive, then + (optionally) ``:cloud``/``-cloud`` suffixed forms. - # Exact match + The suffix fallback exists because some providers (e.g. ollama-cloud) + store ``kimi-k2.6:cloud`` while the live API returns the bare name; + without it context lookup falls through to stale OpenRouter metadata and + trips the 64k minimum-context guard. Every consumer shares this order so + "is this model in the catalog" means the same thing everywhere โ€” a + suffix-keyed catalog model must count as KNOWN for ``model_overrides`` + fill-gap ``_default`` semantics. + """ entry = models.get(model) - if entry: - ctx = _extract_context(entry) - if ctx: - return ctx - - # Case-insensitive match + if isinstance(entry, dict): + yield model, entry model_lower = model.lower() for mid, mdata in models.items(): - if mid.lower() == model_lower: - ctx = _extract_context(mdata) - if ctx: - return ctx - - # Suffix-aware fallback: some providers (e.g. ollama-cloud) store - # model IDs with :cloud / -cloud suffixes in models.dev while the - # live API returns bare names. Without this, kimi-k2.6 misses the - # kimi-k2.6:cloud entry and falls through to stale OpenRouter metadata - # reporting 32768 โ€” tripping the 64k minimum-context guard. - # The suffix-stripping in fetch_ollama_cloud_models() handles the - # model-picker UX; this handles the context-length lookup path. + if mid.lower() == model_lower and isinstance(mdata, dict): + yield mid, mdata + if not suffix_fallback: + return for suffix in (":cloud", "-cloud"): - suffixed_key = model + suffix - entry = models.get(suffixed_key) - if entry: - ctx = _extract_context(entry) - if ctx: - return ctx - # Also try case-insensitive + entry = models.get(model + suffix) + if isinstance(entry, dict): + yield model + suffix, entry suffixed_lower = model_lower + suffix for mid, mdata in models.items(): - if mid.lower() == suffixed_lower: - ctx = _extract_context(mdata) - if ctx: - return ctx - - # Catalog miss โ€” a _default override may fill the gap (#84482). - return _default_override_context(provider) + if mid.lower() == suffixed_lower and isinstance(mdata, dict): + yield mid, mdata -def _default_override_context(provider: str) -> Optional[int]: - """Fill-gap context from a ``_default`` override, for catalog misses.""" - default = _default_model_override(provider) - if default is None: - return None - return _override_int(default, "context_window") +def _find_model_entry(models: Dict[str, Any], model: str) -> Optional[Dict[str, Any]]: + """First catalog entry for *model* (exact, case-insensitive, suffix), or None.""" + for _mid, entry in _iter_model_entries(models, model): + return entry + return None -def _extract_context(entry: Dict[str, Any]) -> Optional[int]: - """Extract context_length from a models.dev model entry. - - Returns None for invalid/zero values (some audio/image models have context=0). - """ +def _extract_limit(entry: Any, key: str) -> Optional[int]: + """Positive int ``entry.limit[key]`` or None (audio/image models have context=0).""" if not isinstance(entry, dict): return None limit = entry.get("limit") if not isinstance(limit, dict): return None - ctx = limit.get("context") - if isinstance(ctx, (int, float)) and ctx > 0: - return int(ctx) + value = limit.get(key) + if isinstance(value, (int, float)) and value > 0: + return int(value) return None +def _extract_context(entry: Dict[str, Any]) -> Optional[int]: + """Context length from a models.dev model entry, or None if invalid/zero.""" + return _extract_limit(entry, "context") + + +def lookup_models_dev_context( + provider: str, model: str, *, allow_network: bool = False +) -> Optional[int]: + """Context window in tokens for provider+model, or None if not found. + + An EXPLICIT ``model_overrides`` entry wins over the catalog; ``_default`` + entries fill the gap only when the catalog has no answer (the supported + self-unblock path for models with wrong/missing context in models.dev). + Catalog entries with context=0 are skipped in favour of later candidates. + + ``allow_network`` defaults to False โ€” this runs every conversation turn + and must never block; pass True only from explicit refresh flows. + """ + override_ctx = _override_context_window(provider, model) + if override_ctx is not None: + return override_ctx + + models = _get_provider_models(provider, allow_network=allow_network) + if models is not None: + for _mid, entry in _iter_model_entries(models, model): + ctx = _extract_context(entry) + if ctx: + return ctx + return _default_override_context(provider) + + # --------------------------------------------------------------------------- -# Model capability metadata +# Per-model metadata overrides (config.yaml โ†’ model_overrides) # --------------------------------------------------------------------------- - - -@dataclass -class ModelCapabilities: - """Structured capability metadata for a model from models.dev.""" - - supports_tools: bool = True - supports_vision: bool = False - supports_reasoning: bool = False - context_window: int = 200000 - max_output_tokens: int = 8192 - model_family: str = "" - - -# --------------------------------------------------------------------------- # -# Per-model metadata overrides (config.yaml โ†’ model_overrides) # -# --------------------------------------------------------------------------- # # # Canonical override schema (the ONLY key space consumers accept): # context_window, max_output_tokens, supports_tools, supports_vision, # supports_reasoning, model_family # -# Resolution semantics: -# 1. ``model_overrides..`` โ€” explicit override. Always -# wins over the catalog for the fields it sets (partial patch). -# 2. ``model_overrides.._default`` / ``model_overrides._default`` -# โ€” FILL-GAP defaults. They apply ONLY to models the catalog does not -# know (the #8731/#84482 self-unblock path for custom/local/new -# models) and never displace catalog data for known models. A -# ``_default: {context_window: 128000}`` therefore cannot clamp every -# catalog-known model of a provider. +# Resolution: ``model_overrides..`` is an explicit override +# that always wins over the catalog for the fields it sets (partial patch). +# ``model_overrides.._default`` / ``model_overrides._default`` are +# FILL-GAP defaults: they apply ONLY to models the catalog does not know (the +# self-unblock path for custom/local/new models) and never displace catalog +# data โ€” a ``_default: {context_window: 128000}`` cannot clamp every +# catalog-known model of a provider. # -# Provider keys accept the Hermes provider id (as used elsewhere in -# config.yaml) or the models.dev provider id. Model ids match exactly, -# then case-insensitively (mirroring catalog lookup). +# Provider keys accept the Hermes provider id or the models.dev provider id. +# Model ids match exactly, then case-insensitively (mirroring catalog lookup). _OVERRIDE_WARNED_KEYS: set = set() +# Safe defaults for models absent from the catalog (tools on, vision/reasoning +# off, 200K context); shared by get_model_capabilities and get_model_info so +# the two unknown-model paths agree. +_UNKNOWN_MODEL_BASE: Dict[str, Any] = { + "limit": {"context": 200000, "output": 8192}, + "tool_call": True, +} + def _load_model_overrides() -> Dict[str, Any]: - """Load the ``model_overrides`` config section. + """The ``model_overrides`` config section ({} on any failure). - No local memoization on purpose: ``load_config_readonly()`` is already - (mtime, size)-cached upstream (a hit is ~one stat, no deepcopy, no - parse), and an ``id(cfg)``-keyed layer here can serve stale overrides - after a config reload when CPython reuses the freed dict's address. - Returns empty dict on any failure. + Deliberately not memoized: ``load_config_readonly()`` is already + (mtime, size)-cached upstream, and an ``id(cfg)``-keyed layer here can + serve stale overrides after a reload when CPython reuses the dict address. """ try: from hermes_cli.config import cfg_get, load_config_readonly @@ -899,12 +797,7 @@ def _load_model_overrides() -> Dict[str, Any]: def _provider_override_section(provider: str) -> Optional[Dict[str, Any]]: - """Return the override section for *provider*, or None. - - Accepts either the Hermes provider id or the models.dev provider id as - the config key, so ``copilot`` and ``github-copilot`` both work - regardless of which id space a caller passes in. - """ + """Override section for *provider* (keyed by Hermes OR models.dev id), or None.""" overrides = _load_model_overrides() if not overrides: return None @@ -929,11 +822,8 @@ def _provider_override_section(provider: str) -> Optional[Dict[str, Any]]: def _explicit_model_override(provider: str, model: str) -> Optional[Dict[str, Any]]: - """Return the explicit per-provider+model override dict, or None. - - Model ids match exactly first, then case-insensitively (skipping the - ``_default`` sentinel), mirroring catalog lookup behavior. - """ + """Explicit per-provider+model override dict (exact, then case-insensitive + skipping the ``_default`` sentinel), or None.""" model_key = (model or "").strip() if not model_key: return None @@ -955,18 +845,13 @@ def _explicit_model_override(provider: str, model: str) -> Optional[Dict[str, An def _default_model_override(provider: str) -> Optional[Dict[str, Any]]: - """Return the fill-gap ``_default`` override for *provider*, or None. - - Checks the per-provider ``_default`` first, then the global one. Only - consulted for models the catalog does not know โ€” see the block comment. - """ + """Fill-gap ``_default`` override: per-provider first, then global; or None.""" section = _provider_override_section(provider) if section is not None: default = section.get("_default") if isinstance(default, dict): return default - overrides = _load_model_overrides() - global_default = overrides.get("_default") + global_default = _load_model_overrides().get("_default") if isinstance(global_default, dict): return global_default return None @@ -975,11 +860,7 @@ def _default_model_override(provider: str) -> Optional[Dict[str, Any]]: def _override_for( provider: str, model: str, *, catalog_hit: bool ) -> Optional[Dict[str, Any]]: - """Select the override dict for a lookup, honoring fill-gap semantics. - - Explicit per-provider+model overrides always apply. ``_default`` - entries apply only when the catalog has no entry for the model. - """ + """Explicit override if any; else the ``_default`` only on a catalog miss.""" explicit = _explicit_model_override(provider, model) if explicit is not None: return explicit @@ -1010,18 +891,21 @@ def _override_int(override: Dict[str, Any], key: str) -> Optional[int]: def _override_context_window(provider: str, model: str) -> Optional[int]: - """Return the EXPLICITLY overridden context_window, or None. + """EXPLICITLY overridden context_window, or None. Explicit-only on purpose: this runs early in the resolution chain - (agent/model_metadata.py step 0b, before custom_providers and live - probes), where a ``_default`` must not preempt more specific sources. - Fill-gap defaults are applied later by ``lookup_models_dev_context`` - once the catalog has actually missed. + (agent/model_metadata.py, before custom_providers and live probes) where + a ``_default`` must not preempt more specific sources; fill-gap defaults + apply later in ``lookup_models_dev_context`` once the catalog has missed. """ ov = _explicit_model_override(provider, model) - if ov is None: - return None - return _override_int(ov, "context_window") + return _override_int(ov, "context_window") if ov is not None else None + + +def _default_override_context(provider: str) -> Optional[int]: + """Fill-gap context from a ``_default`` override, for catalog misses.""" + default = _default_model_override(provider) + return _override_int(default, "context_window") if default is not None else None def _override_to_catalog_shape( @@ -1029,14 +913,9 @@ def _override_to_catalog_shape( ) -> Tuple[Dict[str, Any], Optional[bool]]: """Translate canonical override keys into a models.dev-shaped patch. - ``get_model_info``/``_parse_model_info`` consume the raw catalog shape - (``limit.context``, ``tool_call``, ...). All override consumers accept - ONE canonical schema (the documented ``context_window``/``supports_*`` - keys), so this boundary translates rather than forcing users to know - the internal catalog shape. - - Returns ``(patch, vision)`` โ€” vision is returned out-of-band (not as - a key in the patch) because it maps onto the catalog's + Consumers read the raw catalog shape (``limit.context``, ``tool_call``, ...) + while users write ONE canonical schema, so this boundary translates. + Returns ``(patch, vision)`` โ€” vision is out-of-band because it maps onto the ``modalities.input`` list rather than a scalar field. """ patch: Dict[str, Any] = {} @@ -1065,12 +944,9 @@ def _override_to_catalog_shape( def _merge_catalog_entry_with_override( raw: Dict[str, Any], override: Dict[str, Any] ) -> Dict[str, Any]: - """Patch a catalog entry with a canonical-schema override. - - Sub-dicts (``limit``, ``modalities``) are merged, not clobbered โ€” an - override setting only ``context_window`` must not wipe the catalog's - ``limit.output``. - """ + """Patch a catalog entry with a canonical-schema override. Sub-dicts + (``limit``, ``modalities``) are merged, not clobbered โ€” setting only + ``context_window`` must not wipe the catalog's ``limit.output``.""" shaped, vision_override = _override_to_catalog_shape(override) merged = dict(raw) limit_patch = shaped.pop("limit", None) @@ -1094,192 +970,64 @@ def _merge_catalog_entry_with_override( return merged -def _get_provider_models( - provider: str, *, allow_network: bool = False -) -> Optional[Dict[str, Any]]: - """Resolve a Hermes provider ID to its models dict from models.dev. +# --------------------------------------------------------------------------- +# Model capability metadata +# --------------------------------------------------------------------------- - Returns the models dict or None if the provider is unknown or has no data. - - ``allow_network`` defaults to False โ€” this is called from hot paths - (vision routing, image routing, capability checks) and must never block. - """ - mdev_provider_id = PROVIDER_TO_MODELS_DEV.get(provider) - if not mdev_provider_id: - return None - - # NOTE: keep the zero-argument call on the allow_network path. Dozens - # of test sites monkeypatch fetch_models_dev with zero-arg lambdas; - # passing the kwarg unconditionally breaks them all (TypeError). - data = ( - fetch_models_dev() - if allow_network - else fetch_models_dev(allow_network=False) - ) - provider_data = data.get(mdev_provider_id) - if not isinstance(provider_data, dict): - return None - - models = provider_data.get("models", {}) - if not isinstance(models, dict): - return None - - return models - - -def _find_model_entry(models: Dict[str, Any], model: str) -> Optional[Dict[str, Any]]: - """Find a model entry: exact, case-insensitive, then suffix fallback. - - The ``:cloud``/``-cloud`` suffix fallback mirrors - ``lookup_models_dev_context`` so "is this model in the catalog" means - the same thing to every consumer โ€” important for ``model_overrides`` - fill-gap ``_default`` semantics, where a suffix-keyed catalog model - (e.g. ``kimi-k2.6:cloud``) must count as KNOWN and keep its catalog - metadata rather than being displaced by a ``_default``. - """ - # Exact match - entry = models.get(model) - if isinstance(entry, dict): - return entry - - # Case-insensitive match - model_lower = model.lower() - for mid, mdata in models.items(): - if mid.lower() == model_lower and isinstance(mdata, dict): - return mdata - - # Suffix-aware fallback (e.g. ollama-cloud stores kimi-k2.6:cloud - # while the live API returns the bare name). - for suffix in (":cloud", "-cloud"): - entry = models.get(model + suffix) - if isinstance(entry, dict): - return entry - suffixed_lower = model_lower + suffix - for mid, mdata in models.items(): - if mid.lower() == suffixed_lower and isinstance(mdata, dict): - return mdata - - return None +def _entry_supports_vision(entry: Dict[str, Any]) -> bool: + """Prefer explicit ``modalities.input`` (the older ``attachment`` flag can be + stale or too broad for image routing); fall back to it only when the input + modalities are absent/invalid.""" + input_mods = entry.get("modalities", {}) + input_mods = input_mods.get("input") if isinstance(input_mods, dict) else None + if isinstance(input_mods, list): + return "image" in input_mods + return bool(entry.get("attachment", False)) def get_model_capabilities( provider: str, model: str, *, allow_network: bool = False ) -> Optional[ModelCapabilities]: - """Look up full capability metadata from models.dev cache. + """Capability metadata from the models.dev cache, or None if unresolvable. - Uses the existing fetch_models_dev() and PROVIDER_TO_MODELS_DEV mapping. - Returns None if model not found. + EXPLICIT ``model_overrides`` entries patch catalog values for the fields + they set; ``_default`` entries fill the gap only for models the catalog + does not know. Unspecified fields fall through to the catalog value, or to + safe defaults (tools on, vision/reasoning off, 200K/8K) when absent. - EXPLICIT ``model_overrides`` entries (per-provider+model) win over - catalog values for the fields they set. ``_default`` entries fill the - gap only for models the catalog does not know โ€” the supported - self-unblock path for custom/local models (#8731) and for models with - wrong metadata in models.dev (#84482). An override may set any subset - of fields; unspecified fields fall through to the catalog value (or - sensible defaults when the model is absent from the catalog). - - ``allow_network`` defaults to False โ€” capability lookup is a hot path - (vision routing, image routing) and must never block on the network. - - Extracts from model entry fields: - - reasoning (bool) โ†’ supports_reasoning - - tool_call (bool) โ†’ supports_tools - - attachment (bool) โ†’ supports_vision - - limit.context (int) โ†’ context_window - - limit.output (int) โ†’ max_output_tokens - - family (str) โ†’ model_family + ``allow_network`` defaults to False โ€” vision/image routing is a hot path. """ models = _get_provider_models(provider, allow_network=allow_network) entry = _find_model_entry(models, model) if models is not None else None - # Select the override AFTER the catalog lookup: explicit overrides - # always apply; _default entries only fill gaps for catalog misses. + # Select the override AFTER the catalog lookup: _default only fills misses. override = _override_for(provider, model, catalog_hit=entry is not None) - - # If no catalog entry and no override, we can't resolve capabilities. if entry is None and override is None: return None - # Start from catalog entry (if found), else use defaults. - if entry is not None: - supports_tools = bool(entry.get("tool_call", False)) - # Vision: prefer explicit `modalities.input` when models.dev provides it. - # The older `attachment` flag can be stale or too broad for image routing; - # fall back to it only when the input modalities are absent/invalid. - input_mods = entry.get("modalities", {}) - if isinstance(input_mods, dict): - input_mods = input_mods.get("input") - else: - input_mods = None - if isinstance(input_mods, list): - supports_vision = "image" in input_mods - else: - supports_vision = bool(entry.get("attachment", False)) - supports_reasoning = bool(entry.get("reasoning", False)) - - limit = entry.get("limit", {}) - if not isinstance(limit, dict): - limit = {} - - ctx = limit.get("context") - context_window = int(ctx) if isinstance(ctx, (int, float)) and ctx > 0 else 200000 - - out = limit.get("output") - max_output_tokens = int(out) if isinstance(out, (int, float)) and out > 0 else 8192 - - model_family = entry.get("family", "") or "" - else: - # Unknown model โ€” derive sensible defaults. The override will - # patch whichever fields it specifies; the rest stay at defaults - # that are safe for agentic use (tools on, vision/reasoning off). - supports_tools = True - supports_vision = False - supports_reasoning = False - context_window = 200000 - max_output_tokens = 8192 - model_family = "" - - # Apply override patches (each field is optional in the override dict). + raw = entry if entry is not None else _UNKNOWN_MODEL_BASE if override is not None: - if "supports_tools" in override: - supports_tools = bool(override["supports_tools"]) - if "supports_vision" in override: - supports_vision = bool(override["supports_vision"]) - if "supports_reasoning" in override: - supports_reasoning = bool(override["supports_reasoning"]) - ctx_ov = _override_int(override, "context_window") - if ctx_ov is not None: - context_window = ctx_ov - out_ov = _override_int(override, "max_output_tokens") - if out_ov is not None: - max_output_tokens = out_ov - if "model_family" in override: - model_family = str(override["model_family"] or "") + raw = _merge_catalog_entry_with_override(raw, override) return ModelCapabilities( - supports_tools=supports_tools, - supports_vision=supports_vision, - supports_reasoning=supports_reasoning, - context_window=context_window, - max_output_tokens=max_output_tokens, - model_family=model_family, + supports_tools=bool(raw.get("tool_call", False)), + supports_vision=_entry_supports_vision(raw), + supports_reasoning=bool(raw.get("reasoning", False)), + context_window=_extract_limit(raw, "context") or 200000, + max_output_tokens=_extract_limit(raw, "output") or 8192, + model_family=raw.get("family", "") or "", ) def list_provider_models( provider: str, *, allow_network: bool = True ) -> List[str]: - """Return all model IDs for a provider from models.dev. - - Returns an empty list if the provider is unknown or has no data. - - ``allow_network`` defaults to True โ€” this is called from the model - picker (``hermes model``), which is an interactive user-facing flow - where a fresh catalog is worth a short network wait. - """ + """All model IDs for a provider ([] if unknown). ``allow_network`` defaults + to True: the model picker is interactive and a fresh catalog is worth a + short wait.""" from hermes_cli.models import normalize_provider provider = normalize_provider(provider) or provider - + models = _get_provider_models(provider, allow_network=allow_network) if models is None: return [] @@ -1289,19 +1037,16 @@ def list_provider_models( ] -# Patterns that indicate non-agentic or noise models (TTS, embedding, -# dated preview snapshots, live/streaming-only, image-only). -import re +# Non-agentic or noise models (TTS, embedding, dated preview snapshots, +# live/streaming-only, image-only). _NOISE_PATTERNS: re.Pattern = re.compile( r"-tts\b|embedding|live-|-(preview|exp)-\d{2,4}[-_]|" r"-image\b|-image-preview\b|-customtools\b", re.IGNORECASE, ) -# Google's live Gemini catalogs currently include a mix of stale slugs and -# Gemma models whose TPM quotas are too small for normal Hermes agent traffic. -# Keep capability metadata available for direct/manual use, but hide these from -# the Gemini model catalogs we surface in setup and model selection. +# Hidden from the Gemini catalogs surfaced in setup/model selection (capability +# metadata stays available for direct/manual use). _GOOGLE_HIDDEN_MODELS = frozenset({ # Low-TPM Gemma models that trip Google input-token quota walls under # agent-style traffic despite advertising large context windows. @@ -1318,8 +1063,7 @@ _GOOGLE_HIDDEN_MODELS = frozenset({ "gemma-3-12b-it", "gemma-3-27b", "gemma-3-27b-it", - # Stale/retired Google slugs that still surface through models.dev-backed - # Gemini selection but 404 on the current Google endpoints. + # Stale/retired Google slugs that 404 on the current endpoints. "gemini-1.5-flash", "gemini-1.5-pro", "gemini-1.5-flash-8b", @@ -1331,52 +1075,33 @@ _GOOGLE_HIDDEN_MODELS = frozenset({ def _should_hide_from_provider_catalog(provider: str, model_id: str) -> bool: provider_lower = (provider or "").strip().lower() model_lower = (model_id or "").strip().lower() - if provider_lower in {"gemini", "google"} and model_lower in _GOOGLE_HIDDEN_MODELS: - return True - return False + return provider_lower in {"gemini", "google"} and model_lower in _GOOGLE_HIDDEN_MODELS def list_agentic_models( provider: str, *, allow_network: bool = True ) -> List[str]: - """Return model IDs suitable for agentic use from models.dev. - - Filters for tool_call=True and excludes noise (TTS, embedding, - dated preview snapshots, live/streaming, image-only models). - Returns an empty list on any failure. - - ``allow_network`` defaults to True โ€” like ``list_provider_models``, - this is called from interactive model selection flows. - """ + """Model IDs suitable for agentic use: tool_call=True, minus hidden and + noise models. [] on any failure. ``allow_network`` defaults to True (called + from interactive model selection).""" models = _get_provider_models(provider, allow_network=allow_network) if models is None: return [] - - result = [] - for mid, entry in models.items(): - if not isinstance(entry, dict): - continue - if _should_hide_from_provider_catalog(provider, mid): - continue - if not entry.get("tool_call", False): - continue - if _NOISE_PATTERNS.search(mid): - continue - result.append(mid) - return result - + return [ + mid for mid, entry in models.items() + if isinstance(entry, dict) + and not _should_hide_from_provider_catalog(provider, mid) + and entry.get("tool_call", False) + and not _NOISE_PATTERNS.search(mid) + ] # --------------------------------------------------------------------------- -# Rich dataclass constructors โ€” parse raw models.dev JSON into dataclasses +# Rich dataclass constructors + queries # --------------------------------------------------------------------------- def _parse_model_info(model_id: str, raw: Dict[str, Any], provider_id: str) -> ModelInfo: """Convert a raw models.dev model entry dict into a ModelInfo dataclass.""" - limit = raw.get("limit") or {} - if not isinstance(limit, dict): - limit = {} - cost = raw.get("cost") or {} if not isinstance(cost, dict): cost = {} @@ -1384,16 +1109,11 @@ def _parse_model_info(model_id: str, raw: Dict[str, Any], provider_id: str) -> M modalities = raw.get("modalities") or {} if not isinstance(modalities, dict): modalities = {} - input_mods = modalities.get("input") or [] output_mods = modalities.get("output") or [] - ctx = limit.get("context") - ctx_int = int(ctx) if isinstance(ctx, (int, float)) and ctx > 0 else 0 - out = limit.get("output") - out_int = int(out) if isinstance(out, (int, float)) and out > 0 else 0 - inp = limit.get("input") - inp_int = int(inp) if isinstance(inp, (int, float)) and inp > 0 else None + def _cost(key: str) -> Optional[float]: + return float(cost[key]) if key in cost and cost[key] is not None else None return ModelInfo( id=model_id, @@ -1408,13 +1128,13 @@ def _parse_model_info(model_id: str, raw: Dict[str, Any], provider_id: str) -> M open_weights=bool(raw.get("open_weights", False)), input_modalities=tuple(input_mods) if isinstance(input_mods, list) else (), output_modalities=tuple(output_mods) if isinstance(output_mods, list) else (), - context_window=ctx_int, - max_output=out_int, - max_input=inp_int, + context_window=_extract_limit(raw, "context") or 0, + max_output=_extract_limit(raw, "output") or 0, + max_input=_extract_limit(raw, "input"), cost_input=float(cost.get("input", 0) or 0), cost_output=float(cost.get("output", 0) or 0), - cost_cache_read=float(cost["cache_read"]) if "cache_read" in cost and cost["cache_read"] is not None else None, - cost_cache_write=float(cost["cache_write"]) if "cache_write" in cost and cost["cache_write"] is not None else None, + cost_cache_read=_cost("cache_read"), + cost_cache_write=_cost("cache_write"), knowledge_cutoff=raw.get("knowledge", "") or "", release_date=raw.get("release_date", "") or "", status=raw.get("status", "") or "", @@ -1436,115 +1156,47 @@ def _parse_provider_info(provider_id: str, raw: Dict[str, Any]) -> ProviderInfo: ) -# --------------------------------------------------------------------------- -# Provider-level queries -# --------------------------------------------------------------------------- - def get_provider_info( provider_id: str, *, allow_network: bool = True ) -> Optional[ProviderInfo]: - """Get full provider metadata from models.dev. + """Provider metadata by Hermes or models.dev ID, or None if not cataloged. - Accepts either a Hermes provider ID (e.g. "kilocode") or a models.dev - ID (e.g. "kilo"). Returns None if the provider is not in the catalog. - - ``allow_network`` defaults to True โ€” the primary caller is - ``resolve_provider_full`` during interactive setup, where a fresh - catalog is worth a short network wait. Hot-path callers should pass - ``allow_network=False``. + ``allow_network`` defaults to True โ€” the primary caller is interactive + setup (``resolve_provider_full``). Hot-path callers pass False. """ - # Resolve Hermes ID โ†’ models.dev ID mdev_id = PROVIDER_TO_MODELS_DEV.get(provider_id, provider_id) - - # NOTE: keep the zero-argument call on the default path. Dozens of test - # sites monkeypatch fetch_models_dev with zero-arg lambdas; passing the - # kwarg unconditionally would break them all (they raise TypeError). - data = ( - fetch_models_dev() - if allow_network - else fetch_models_dev(allow_network=False) - ) - raw = data.get(mdev_id) + raw = _fetch_registry(allow_network).get(mdev_id) if not isinstance(raw, dict): return None - return _parse_provider_info(mdev_id, raw) -# --------------------------------------------------------------------------- -# Model-level queries (rich ModelInfo) -# --------------------------------------------------------------------------- - def get_model_info( provider_id: str, model_id: str, *, allow_network: bool = False ) -> Optional[ModelInfo]: - """Get full model metadata from models.dev. + """Full model metadata by Hermes or models.dev provider ID (exact match, + then case-insensitive), or None if not found. - Accepts Hermes or models.dev provider ID. Tries exact match then - case-insensitive fallback. Returns None if not found. + ``model_overrides`` use the same canonical schema as every other consumer + and are translated into the catalog shape here with sub-dicts merged, not + clobbered. EXPLICIT entries patch known catalog models; ``_default`` + entries fill the gap only for models the catalog does not know. - ``model_overrides`` entries use the SAME canonical schema as every - other consumer (``context_window``, ``max_output_tokens``, - ``supports_*``, ``model_family``) โ€” they are translated into the - catalog shape at this boundary, and sub-dicts (``limit``, - ``modalities``) are merged rather than clobbered. EXPLICIT entries - patch known catalog models; ``_default`` entries fill the gap only - for models the catalog does not know (#8731, #84482). - - ``allow_network`` defaults to False โ€” model info lookup is a hot path - (cost guard, inventory) and must never block on the network. + ``allow_network`` defaults to False โ€” cost guard and inventory are hot paths. """ mdev_id = PROVIDER_TO_MODELS_DEV.get(provider_id, provider_id) - def _from_override_alone() -> Optional[ModelInfo]: - override = _override_for(provider_id, model_id, catalog_hit=False) - if override is None: - return None - # Seed the same safe defaults get_model_capabilities uses for - # unknown models (200K context, tools on) so the two - # unknown-model paths agree; the override patches its fields on - # top. - base = { - "limit": {"context": 200000, "output": 8192}, - "tool_call": True, - } - shaped = _merge_catalog_entry_with_override(base, override) - return _parse_model_info(model_id, shaped, mdev_id) - - # NOTE: keep the zero-argument call on the allow_network path. Dozens - # of test sites monkeypatch fetch_models_dev with zero-arg lambdas; - # passing the kwarg unconditionally breaks them all (TypeError). - data = ( - fetch_models_dev() - if allow_network - else fetch_models_dev(allow_network=False) - ) - pdata = data.get(mdev_id) - if not isinstance(pdata, dict): - return _from_override_alone() - - models = pdata.get("models", {}) - if not isinstance(models, dict): - return _from_override_alone() - - def _with_override(mid: str, raw: Dict[str, Any]) -> ModelInfo: - override = _override_for(provider_id, model_id, catalog_hit=True) + def _resolve(mid: str, raw: Dict[str, Any], *, catalog_hit: bool) -> Optional[ModelInfo]: + override = _override_for(provider_id, model_id, catalog_hit=catalog_hit) if override is not None: - merged = _merge_catalog_entry_with_override(raw, override) - return _parse_model_info(mid, merged, mdev_id) + raw = _merge_catalog_entry_with_override(raw, override) + elif not catalog_hit: + return None return _parse_model_info(mid, raw, mdev_id) - # Exact match - raw = models.get(model_id) - if isinstance(raw, dict): - return _with_override(model_id, raw) - - # Case-insensitive fallback - model_lower = model_id.lower() - for mid, mdata in models.items(): - if mid.lower() == model_lower and isinstance(mdata, dict): - return _with_override(mid, mdata) - - # Model not in catalog โ€” an override (explicit or _default) may still - # provide the metadata. - return _from_override_alone() + models = _registry_models(mdev_id, allow_network=allow_network) + if models is not None: + for mid, raw in _iter_model_entries(models, model_id, suffix_fallback=False): + return _resolve(mid, raw, catalog_hit=True) + # Not in catalog โ€” an override (explicit or _default) may still provide it. + return _resolve(model_id, _UNKNOWN_MODEL_BASE, catalog_hit=False) diff --git a/agent/portal_tags.py b/agent/portal_tags.py index 453ba1bbfb..8b1782b451 100644 --- a/agent/portal_tags.py +++ b/agent/portal_tags.py @@ -1,32 +1,16 @@ """Centralized Nous Portal request tags. -Every Hermes request that hits the Nous Portal โ€” main agent loop, auxiliary -client (compression / titles / vision / web_extract / session_search / etc.), -and any future code path โ€” must carry the same product-attribution tags so -Nous can attribute usage to Hermes Agent and bucket it by client release. +Every Hermes request to the Nous Portal (main loop, auxiliary client, fallback +paths) must carry the same product-attribution tags, sent in OpenAI-compatible +``extra_body['tags']``:: -Tag shape (sent in OpenAI-compatible ``extra_body['tags']``): + ["product=hermes-agent", "client=hermes-client-v<__version__>"] - [ - "product=hermes-agent", - "client=hermes-client-v<__version__>", - ] - -The version is sourced live from ``hermes_cli.__version__`` so it auto-aligns -to whatever release is installed; the release script -(``scripts/release.py``) regex-bumps that single string, and every Portal -request picks up the new tag on the next process start. - -Why one helper instead of inlining the literal at each site: -* Four call sites (main loop profile, aux client, run_agent compression - fallback, web_tools fallback) used to drift apart โ€” see PR #24194 which - only got the aux site, leaving the main loop sending a different tag set. -* Tests should assert the same tag list everywhere; centralizing makes that - assertion a one-liner against this module. - -Do NOT pre-compute these as module-level constants in the consumers. The -version can change at runtime (editable installs, hot-reload tooling), and -``hermes_cli.__version__`` is the canonical source of truth. +One helper instead of inlined literals: the call sites drifted apart before, +and tests can assert one tag list everywhere. The version is read live from +``hermes_cli.__version__`` (the release script bumps that single string) โ€” do +NOT pre-compute it as a module constant in consumers; it can change at runtime +(editable installs, hot reload). """ from __future__ import annotations @@ -34,63 +18,47 @@ from __future__ import annotations from contextvars import ContextVar from typing import List, Optional -# โ”€โ”€ Ambient conversation context โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ -# -# The main agent loop knows its ``session_id``; the dozens of auxiliary call -# sites (compression, title generation, vision, web_extract, session_search, -# MoA reference/aggregator slots, curator, kanban helpers, ...) do not โ€” they -# funnel through ``agent.auxiliary_client.call_llm`` which has no session -# handle. Rather than threading a ``session_id`` parameter through every one -# of those call sites (and every future one), the agent loop publishes the -# active conversation id here and ``nous_portal_tags()`` picks it up as a -# fallback whenever no explicit ``session_id`` is passed. -# -# ContextVar (not a module global) so concurrent agents in one process โ€” -# gateway sessions, delegate_task subagents, batch runners โ€” never see each -# other's conversation id. Worker threads spawned via -# ``tools.thread_context.propagate_context_to_thread`` (background review, -# MoA fan-out, tool executor) inherit it through the copied Context; bare -# threads (title generator) capture it explicitly at spawn time. +# Ambient conversation id (ATTRIBUTION value, sent as ``conversation=``). +# The agent loop publishes it at turn entry; the dozens of auxiliary call +# sites funnelling through ``auxiliary_client.call_llm`` (no session handle) +# pick it up via ``nous_portal_tags()`` instead of threading a session_id +# parameter everywhere. A ContextVar, not a module global, so concurrent agents +# in one process (gateway sessions, delegate subagents) never see each other's +# id; ``tools.thread_context.propagate_context_to_thread`` workers inherit it, +# bare threads capture it at spawn time. _conversation_id: ContextVar[Optional[str]] = ContextVar( "nous_portal_conversation_id", default=None ) - -# โ”€โ”€ Ambient routing/affinity scope โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ -# -# Separate from the conversation id above, which is an ATTRIBUTION value: it -# names the conversation a request belongs to and is sent to the Portal as -# ``conversation=``. The affinity scope is a ROUTING value โ€” OpenRouter's -# sticky ``session_id``, Nous Portal's sticky key and xAI's ``x-grok-conv-id`` -# use it to pin one conversation to one backend/prompt cache. -# -# The two agree for every host that keeps one session id per conversation, so -# the providers historically read the attribution id for both. They diverge -# for a host that mints one physical session per RESPONSE: attribution still -# resolves per row, while routing must follow the key the host declared for -# the whole chat (``agent.prompt_cache_scope.declared_conversation_scope``, -# issue #96811). Only that declared value is published here โ€” unset means -# "no declaration", and consumers fall back to the conversation id exactly as -# before, so delegate trees keep sharing their parent's sticky key. +# Ambient affinity scope (ROUTING value): OpenRouter's sticky ``session_id``, +# Nous Portal's sticky key and xAI's ``x-grok-conv-id`` pin a conversation to +# one backend/prompt cache. Usually equal to the conversation id, but a host +# that mints one physical session per RESPONSE must route on the key it +# declared for the whole chat (``prompt_cache_scope.declared_conversation_scope``). +# Only that declared value is published; unset means consumers fall back to the +# conversation id, so delegate trees keep sharing their parent's sticky key. _affinity_scope: ContextVar[Optional[str]] = ContextVar( "hermes_affinity_scope", default=None ) -def set_affinity_scope(scope: Optional[str]): - """Publish the declared routing/affinity scope for this turn. +def _reset_var(var: ContextVar, token) -> None: + """Reset ``var``; a token from another Context (reset on a different + thread) falls back to clearing rather than raising in cleanup paths.""" + try: + var.reset(token) + except Exception: + var.set(None) - Returns the ContextVar token; pair with :func:`reset_affinity_scope`. - """ + +def set_affinity_scope(scope: Optional[str]): + """Publish the declared routing/affinity scope; returns the ContextVar token.""" return _affinity_scope.set(scope or None) def reset_affinity_scope(token) -> None: """Restore the previous affinity scope (pair with ``set_affinity_scope``).""" - try: - _affinity_scope.reset(token) - except Exception: - _affinity_scope.set(None) + _reset_var(_affinity_scope, token) def get_affinity_scope() -> Optional[str]: @@ -101,22 +69,16 @@ def get_affinity_scope() -> Optional[str]: def set_conversation_context(conversation_id: Optional[str]): """Publish the active conversation id for ambient Portal tagging. - Called by the agent loop at turn entry with the conversation's stable - id (the session-lineage ROOT id, so the tag survives context-compression - session rotation). Pass ``None`` to clear. Returns the ContextVar token - so callers can ``reset_conversation_context(token)`` on turn exit. + Called by the agent loop at turn entry with the session-lineage ROOT id + (so the tag survives context-compression rotation). ``None`` clears. + Returns the ContextVar token for ``reset_conversation_context``. """ return _conversation_id.set(conversation_id or None) def reset_conversation_context(token) -> None: """Restore the previous conversation context (pair with ``set_...``).""" - try: - _conversation_id.reset(token) - except Exception: - # Token from another Context (e.g. reset on a different thread) โ€” - # fall back to clearing rather than raising in cleanup paths. - _conversation_id.set(None) + _reset_var(_conversation_id, token) def get_conversation_context() -> Optional[str]: @@ -125,11 +87,7 @@ def get_conversation_context() -> Optional[str]: def _hermes_version() -> str: - """Return the current Hermes release version, e.g. ``"0.13.0"``. - - Falls back to ``"unknown"`` if ``hermes_cli`` cannot be imported (should - never happen in a real install โ€” guarded for defensive testing). - """ + """Current Hermes release version; ``"unknown"`` if hermes_cli is unimportable.""" try: from hermes_cli import __version__ return __version__ @@ -138,48 +96,24 @@ def _hermes_version() -> str: def hermes_client_tag() -> str: - """Return the ``client=...`` tag for Nous Portal requests. - - Format: ``client=hermes-client-v..``. - """ + """``client=hermes-client-v..``.""" return f"client=hermes-client-v{_hermes_version()}" def conversation_tag(session_id: str) -> str: - """Return the ``conversation=...`` tag for a Hermes session/conversation. - - Format: ``conversation=``. ``session_id`` is the canonical - Hermes conversation identifier (``AIAgent.session_id``) โ€” the same value - used for ``~/.hermes/sessions/`` storage, session logs, and lineage. - - Unlike the product/client tags this is high-cardinality (one value per - conversation), so it is only appended when a session id is actually - available โ€” never as part of the always-on base tag set. - """ + """``conversation=`` โ€” high-cardinality, so only appended when + a session id is actually available, never in the always-on base set.""" return f"conversation={session_id}" def nous_portal_tags(session_id: str | None = None) -> List[str]: - """Return the canonical list of Nous Portal product tags. + """Return a fresh list of the canonical Nous Portal tags. - Always returns a fresh list so callers can mutate it freely - (e.g. ``merged_extra.setdefault("tags", []).extend(nous_portal_tags())``). - - When ``session_id`` is provided, a ``conversation=`` tag is - appended so Portal usage can be attributed to a specific Hermes - conversation. When it is omitted, the ambient conversation context - (``set_conversation_context``, published by the agent loop at turn - entry) is used instead โ€” this is how auxiliary calls (compression, - titles, vision, MoA slots, ...) inherit the conversation tag without - per-call-site plumbing. Callers outside any conversation (e.g. the - auxiliary client's import-time base tags) get the canonical two-tag set. + The ambient conversation context (lineage ROOT id published by the agent + loop) wins over the explicit ``session_id``, which remains a fallback for + callers outside any agent turn; with neither, the two-tag base set. """ tags = ["product=hermes-agent", hermes_client_tag()] - # Ambient context first: the agent loop publishes the lineage ROOT id - # (stable across context-compression rotation and delegate subagent - # trees), which is the better conversation key than a per-segment - # session_id passed explicitly. The explicit argument remains as a - # fallback for callers running outside any agent turn. effective = get_conversation_context() or session_id if effective: tags.append(conversation_tag(effective)) diff --git a/agent/reasoning_effort.py b/agent/reasoning_effort.py index b6d89b0599..5c7f232dc5 100644 --- a/agent/reasoning_effort.py +++ b/agent/reasoning_effort.py @@ -1,37 +1,26 @@ """Canonical reasoning-effort vocabulary and wire clamping. Hermes' internal effort ladder (``hermes_constants.VALID_REASONING_EFFORTS`` -plus the ``none`` disable level) is wider than what any single provider wire -accepts. Historically every transport and provider profile hand-rolled its own -translation map, and the class of bugs that produced was constant: a new -internal level (``ultra``) leaking to a wire that rejects it with HTTP 400 -(#89503, #70058), or an unknown level being dropped to a weak default so the -strongest ask resolved *weaker* than an explicit ``high`` โ€” a ladder -inversion (#74295, #87279). - -This module is the single source of truth both kinds of code use instead: +plus ``none``) is wider than any single provider wire accepts. Hand-rolled +per-transport translation maps produced two recurring bugs: a new internal +level (``ultra``) leaking to a wire that 400s on it, and an unknown level +dropped to a weak default so the strongest ask resolved *weaker* than an +explicit ``high`` (ladder inversion). This module is the single source of +truth instead: - :data:`EFFORT_LADDER` โ€” canonical lowโ†’high ordering. -- :func:`clamp_effort` โ€” the one clamping policy: keep a supported level - verbatim, otherwise take the **nearest weaker** supported level (never - silently escalate cost above what was asked), and only when nothing weaker - exists take the weakest supported level (a provider whose minimum thinking - level is ``high`` serves ``high`` for a ``low`` ask โ€” GLM-5.2's shape). -- Named wire-vocabulary constants for the common OpenAI-compatible surfaces, - so call sites declare *data* ("this route accepts these levels") rather - than logic. +- :func:`clamp_effort` โ€” keep a supported level verbatim, else the **nearest + weaker** supported level (never silently escalate cost); only when nothing + weaker exists take the weakest supported level (GLM-5.2's floor is ``high``). +- Named wire-vocabulary constants so call sites declare *data*, not logic. Rules for call sites: - -1. **Wire shape stays local.** Whether a route wants ``extra_body.reasoning``, - a top-level ``reasoning_effort`` string, or a ``thinking`` toggle is the - caller's business. Only the *vocabulary math* lives here. -2. **Unset stays unset.** ``clamp_effort`` translates an explicit request; it - does not invent one. When the user expressed no effort, prefer omitting - the field so the server default applies. -3. **Never patch a predicate.** When a provider rejects a level, fix its - declared supported set (data), never add another vendor-name special case - at the call site. +1. Wire shape (``extra_body.reasoning`` vs top-level ``reasoning_effort`` vs + a ``thinking`` toggle) stays local; only the vocabulary math lives here. +2. Unset stays unset: ``clamp_effort`` translates an explicit request, never + invents one โ€” omit the field so the server default applies. +3. Never patch a predicate: when a provider rejects a level, fix its declared + supported set (data), not the call site. """ from __future__ import annotations @@ -39,32 +28,26 @@ from __future__ import annotations import re from typing import Optional, Sequence -#: K3 slug detector โ€” matches ``k3`` as a delimited token (``k3``, -#: ``k3-256k``, ``kimi-k3``, ``kimi-k3-cot``) without matching K2-era names -#: (``kimi-k2.6``). From #76427 by @ruizanthony. +#: Matches ``k3`` as a delimited token (``k3``, ``k3-256k``, ``kimi-k3-cot``) +#: without matching K2-era names (``kimi-k2.6``). _KIMI_K3_SLUG_RE = re.compile(r"(?:^|[^a-z0-9])k3(?:[^a-z0-9]|$)") -# Canonical lowโ†’high ordering used for nearest-level clamping. Superset of -# hermes_constants.VALID_REASONING_EFFORTS ("none" included so an explicit -# disable can be clamped too when a provider publishes it as a level). +# Canonical lowโ†’high ordering for nearest-level clamping. Includes "none" so an +# explicit disable can be clamped when a provider publishes it as a level. EFFORT_LADDER: tuple[str, ...] = ( "none", "minimal", "low", "medium", "high", "xhigh", "max", "ultra", ) -# ``ultra`` is Hermes-internal ladder vocabulary (the Codex product tier); no -# provider wire accepts it verbatim anywhere. Every declared wire set below -# therefore stops at ``max`` โ€” ``ultra`` always clamps down. +# ``ultra`` is Hermes-internal (the Codex product tier); no wire accepts it, so +# every declared set below stops at ``max`` and ``ultra`` always clamps down. -#: The widest OpenAI-compatible wire vocabulary (OpenRouter, Nous Portal): -#: exactly max|xhigh|high|medium|low|minimal|none. +#: Widest OpenAI-compatible wire vocabulary (OpenRouter, Nous Portal). OPENAI_COMPAT_WIRE_EFFORTS: tuple[str, ...] = ( "none", "minimal", "low", "medium", "high", "xhigh", "max", ) -#: OpenAI/Codex Responses backend โ€” per-model vocabulary, live-verified -#: (Aug 2026): ``minimal`` is rejected by both generations (clamps to low); -#: ``max`` is gpt-5.6-only โ€” gpt-5.5 rejects it with "Supported values are: -#: 'none', 'low', 'medium', 'high', 'xhigh'" (#68365's premise, confirmed). +#: OpenAI/Codex Responses, per model generation (live-verified): ``minimal`` +#: is rejected by both (clamps to low); ``max`` is gpt-5.6-only. CODEX_GPT56_EFFORTS: tuple[str, ...] = ( "none", "low", "medium", "high", "xhigh", "max", ) @@ -80,78 +63,64 @@ def codex_supported_efforts(model: Optional[str]) -> tuple[str, ...]: return CODEX_LEGACY_EFFORTS -#: Backward-compat alias (pre-#68365-verification name). -CODEX_RESPONSES_EFFORTS: tuple[str, ...] = CODEX_GPT56_EFFORTS - #: xAI Responses โ€” Grok 4.6+ accepts xhigh; older Grok tops out at high. XAI_GROK46_EFFORTS: tuple[str, ...] = ("low", "medium", "high", "xhigh") XAI_LEGACY_EFFORTS: tuple[str, ...] = ("low", "medium", "high") -#: Actual Computer relays (SGLang/vLLM): none/low/medium/high/max. +#: Actual Computer relays (SGLang/vLLM). ACTUAL_RELAY_EFFORTS: tuple[str, ...] = ("none", "low", "medium", "high", "max") -#: Moonshot/Kimi K3: low/high/max (server default high). +#: Moonshot/Kimi K3 (server default high) vs K2-era models. KIMI_K3_EFFORTS: tuple[str, ...] = ("low", "high", "max") -#: Moonshot/Kimi K2-era models: low/medium/high. KIMI_K2_EFFORTS: tuple[str, ...] = ("low", "medium", "high") -#: OpenCode "Ox Alpha" stealth model (x-preview-f-free): thinking is always -#: on and the wire accepts exactly low/high/max โ€” medium/none/xhigh 400 with -#: "This model always engages in thinking and cannot be disabled; please use -#: low, high, or max" (verified live 2026-08-21). xhigh rounds up to max. +#: OpenCode "Ox Alpha" (x-preview-f-free): thinking cannot be disabled and the +#: wire accepts exactly low/high/max (medium/none/xhigh 400); xhigh rounds up. OX_ALPHA_EFFORTS: tuple[str, ...] = ("low", "high", "max") OX_ALPHA_OVERRIDES: dict[str, str] = {"xhigh": "max"} -#: Tencent TokenHub: low/medium/high. +#: Tencent TokenHub. TOKENHUB_EFFORTS: tuple[str, ...] = ("low", "medium", "high") -#: Nebius Token Factory: low/medium/high (top-level reasoning_effort knob). +#: Nebius Token Factory (top-level reasoning_effort knob). NEBIUS_EFFORTS: tuple[str, ...] = ("low", "medium", "high") -#: Kimi K3's vendor-documented translation quirks (platform.kimi.ai -#: thinking-model guide): ``high`` is K3's positional middle AND server -#: default, so ``medium`` rounds to it rather than down to ``low``; ``xhigh`` -#: rounds up to ``max`` (K3's top tier), matching the kimi-coding plugin. +#: Kimi K3 vendor-documented quirks: ``high`` is K3's positional middle AND +#: server default, so ``medium`` rounds to it rather than down to ``low``; +#: ``xhigh`` rounds up to ``max`` (K3's top tier). KIMI_K3_OVERRIDES: dict[str, str] = {"medium": "high", "xhigh": "max"} -#: GLM-5.2 native reasoning_effort knob: exactly two enabled levels, -#: ``high`` (its minimum thinking level) and ``max`` (per Z.AI/BigModel -#: docs). ``xhigh`` requests the top tier, not the floor. +#: GLM-5.2 native knob: exactly ``high`` (its minimum thinking level) and +#: ``max``; ``xhigh`` requests the top tier, not the floor. GLM52_EFFORTS: tuple[str, ...] = ("high", "max") GLM52_OVERRIDES: dict[str, str] = {"xhigh": "max"} -#: GLM-5.3 widens the knob to a graded low/medium/high/max scale โ€” verified -#: live on api.z.ai/api/coding/paas/v4 (issue #91789, 2026-08-21): every -#: level accepted with monotonic reasoning-token scaling (low=4, medium=11, -#: high=98, max=125 on the probe prompt). ``xhigh`` requests the top tier. +#: GLM-5.3 widens the knob to a graded scale (live-verified, monotonic +#: reasoning-token scaling); ``xhigh`` requests the top tier. GLM53_EFFORTS: tuple[str, ...] = ("low", "medium", "high", "max") GLM53_OVERRIDES: dict[str, str] = {"xhigh": "max"} -#: DeepSeek V4 OpenAI-compat endpoint: low/medium/high/max; ``xhigh`` -#: requests the top tier (matches the shipped profile mapping). +#: DeepSeek V4 OpenAI-compat endpoint; ``xhigh`` requests the top tier. DEEPSEEK_V4_EFFORTS: tuple[str, ...] = ("low", "medium", "high", "max") DEEPSEEK_V4_OVERRIDES: dict[str, str] = {"xhigh": "max"} -#: Ollama Cloud /v1/chat/completions: accepts {none, low, medium, high, max}; -#: rejects ``minimal`` with HTTP 400. ``xhigh`` requests the top tier. +#: Ollama Cloud /v1/chat/completions: rejects ``minimal`` with HTTP 400. OLLAMA_CLOUD_EFFORTS: tuple[str, ...] = ("none", "low", "medium", "high", "max") OLLAMA_CLOUD_OVERRIDES: dict[str, str] = {"xhigh": "max"} -#: Meta Model API (Muse): minimal..xhigh; rejects ``none``. +#: Meta Model API (Muse): rejects ``none``. META_AI_EFFORTS: tuple[str, ...] = ("minimal", "low", "medium", "high", "xhigh") -#: Upstage Solar Pro/Open: low/medium/high. +#: Upstage Solar Pro/Open. SOLAR_EFFORTS: tuple[str, ...] = ("low", "medium", "high") def kimi_supported_efforts(model: Optional[str]) -> tuple[str, ...]: - """Supported effort set for a Moonshot/Kimi model slug. + """Supported effort set for a Moonshot/Kimi slug. - K3 is served as the bare slug ``k3``, plan variants like ``k3-256k``, - and the ``kimi-k3*`` aliases; its documented set is low/high/max. - Everything earlier speaks low/medium/high. Boundary-matched so K2-era - names (``kimi-k2.6``) never match (detection regex from #76427 by - @ruizanthony). + K3 is served as bare ``k3``, plan variants (``k3-256k``) and ``kimi-k3*`` + aliases; everything earlier speaks low/medium/high. Boundary-matched so + K2-era names (``kimi-k2.6``) never match. """ m = (model or "").strip().lower().split("/")[-1] if _KIMI_K3_SLUG_RE.search(m): @@ -166,22 +135,14 @@ def clamp_effort( ) -> Optional[str]: """Clamp a requested reasoning effort onto a wire's supported levels. - ``overrides`` is an optional declared mapping consulted first, for routes - whose vendor documents a translation that differs from nearest-weaker - (Kimi K3 documents ``medium โ†’ high``: high is its positional middle and - server default). Overrides are data, not logic โ€” a call site never adds - vendor ``if``\\ s around this function. - - Otherwise: returns the requested effort unchanged when it is supported, - when the supported set is unknown (``None``/empty), or when the effort - isn't a recognized ladder level (custom providers may use bespoke names โ€” - pass through rather than guess). Otherwise returns the **nearest weaker** - supported level, so a clamp never silently escalates cost; when nothing - weaker exists, the weakest supported level is returned (the caller asked - for *some* thinking and the provider's floor is the closest honest match). - - The policy is monotonic: a stronger request never resolves to a weaker - wire level than a weaker request would. + ``overrides`` (a declared vendor mapping, e.g. Kimi K3 ``medium โ†’ high``) + is consulted first. Otherwise the request passes through unchanged when it + is supported, when the supported set is unknown/empty, or when it isn't a + recognized ladder level (custom providers may use bespoke names). Else the + **nearest weaker** supported level is returned so a clamp never escalates + cost; when nothing weaker exists, the weakest supported level is (the + provider's floor is the closest honest match). Monotonic: a stronger + request never resolves weaker than a weaker request would. """ requested = str(effort or "").strip().lower() if not requested or not supported: @@ -199,9 +160,8 @@ def clamp_effort( return mapped if requested not in EFFORT_LADDER: return effort - # "none" disables reasoning โ€” it is never a *degradation target* for an - # enabled ask (clamping "minimal" to "none" would silently switch - # thinking off). It still passes through verbatim when requested. + # "none" disables reasoning โ€” never a degradation target for an enabled + # ask (clamping "minimal" to "none" would silently switch thinking off). candidates = [level for level in supported_norm if level != "none"] if not candidates: return effort @@ -218,9 +178,8 @@ def clamp_effort( def requested_effort(reasoning_config: Optional[dict]) -> Optional[str]: """Extract the user's explicit effort from a reasoning config, or None. - Returns ``None`` when the config is absent, malformed, carries no effort, - or reasoning is explicitly disabled โ€” callers should then omit the wire - field entirely so the server default applies (rule 2 above). + None when the config is absent/malformed, carries no effort, or reasoning + is explicitly disabled โ€” callers then omit the wire field (rule 2 above). """ if not isinstance(reasoning_config, dict): return None diff --git a/agent/reasoning_summaries.py b/agent/reasoning_summaries.py index 2dd1144fce..eeeaae1289 100644 --- a/agent/reasoning_summaries.py +++ b/agent/reasoning_summaries.py @@ -1,32 +1,13 @@ """Boundary repair for providers that stream reasoning as discrete summary parts. -Reasoning-summary models (OpenAI's gpt-5.x family, and anything relaying the -Responses API onto the OpenAI chat wire) do not stream a chain of thought token -by token. They emit one ``reasoning_content`` delta per *completed* summary -part, each opening with a bold markdown heading:: - - {"delta": {"reasoning_content": "**Investigating likely culprit PRs**"}} - {"delta": {"reasoning_content": "**Inspecting message schema**"}} - -On the Responses API those parts are delimited by ``summary_index`` -(``response.reasoning_summary_part.added`` / ``.done``). The OpenAI chat wire -carries no such field โ€” verified live against Nous Portal's -``openai/gpt-5.6-sol``, whose reasoning chunks contain nothing but -``delta.reasoning_content`` โ€” so the boundary cannot be recovered from -metadata, and consumers that concatenate deltas glue the parts together: - - **Investigating likely culprit PRs****Inspecting message schema** - -That ``****`` run is neither a bold close nor a bold open to a markdown parser, -so the whole trace renders as one unbroken, unspaced, half-bold paragraph. - -The AI SDK hit exactly this (vercel/ai#6742) and fixed it upstream by starting -a new reasoning part per ``summary_index``. That route needs the index, which -this wire does not give us, so we re-derive the boundary from the one signal it -does carry: a delta opening a bold heading. Hermes' own Responses adapter -already joins its summary parts with a blank line -(``agent/codex_responses_adapter.py``), so this brings the chat-completions -stream in line with the path that keeps the structure. +Reasoning-summary models (OpenAI gpt-5.x and anything relaying the Responses +API onto the OpenAI chat wire) emit one ``reasoning_content`` delta per +*completed* summary part, each opening with a bold heading. The Responses API +delimits parts by ``summary_index``; the chat wire carries no such field +(verified live on Nous Portal ``openai/gpt-5.6-sol``), so concatenating deltas +glues ``**One****Two**`` into one half-bold paragraph. We re-derive the +boundary from the one signal the wire keeps โ€” a delta opening a bold heading โ€” +matching the blank-line join Hermes' own Responses adapter already does. """ from __future__ import annotations @@ -37,31 +18,20 @@ __all__ = ["separate_glued_reasoning_blocks"] def separate_glued_reasoning_blocks(previous: str, delta: str) -> str: """Return *delta*, prefixed with a paragraph break when it glues onto *previous*. - *previous* is the reasoning text accumulated so far (only its tail matters). - A break is inserted when *delta* opens a bold heading and *previous* is - mid-line, which is the summary-part boundary the chat wire drops. Both - shapes the upstream issue reports are covered: a heading-only part butting - against the next heading (``**One****Two**``), and a part whose prose body - butts against the next heading (``...interaction!**Next**``). - - Token-streamed reasoning is left alone: its deltas carry their own leading - whitespace, so *previous* ends mid-line only when the model really did run - two parts together. + A break is inserted when *delta* opens a *closed* bold heading and + *previous* (the accumulated reasoning; only its tail matters) is mid-line. + Covers a heading butting a heading (``**One****Two**``) and prose butting a + heading (``...interaction!**Next**``). Token-streamed reasoning is left + alone: its deltas carry their own whitespace, and a fragment that merely + opens emphasis (``**`` alone) is not a part boundary โ€” summary parts always + carry the whole heading in one delta. """ if not previous or not delta: return delta - if not delta.startswith("**"): return delta - - # Already separated โ€” the provider (or an earlier part) ended the line. if previous[-1].isspace(): return delta - - # Require a *closed* heading. A token-streamed fragment that merely opens - # emphasis ("**" then "bold" then "**" across three deltas) is not a part - # boundary; a summary part always carries its whole heading in one delta. if "**" not in delta[2:]: return delta - return f"\n\n{delta}" diff --git a/agent/reasoning_timeouts.py b/agent/reasoning_timeouts.py index 4f6194903a..322b803878 100644 --- a/agent/reasoning_timeouts.py +++ b/agent/reasoning_timeouts.py @@ -1,53 +1,23 @@ -"""Per-reasoning-model stale-timeout floor for known reasoning models. +"""Per-model stale-timeout FLOOR for known reasoning models. -Reasoning models (those that emit extended thinking blocks before their -first content token) routinely exceed Hermes's default chat-model -stale detectors: +Reasoning models (extended thinking before the first content token) routinely +exceed the default chat-model stale detectors (stream ``HERMES_STREAM_STALE_TIMEOUT`` +180s, non-stream ``HERMES_API_CALL_STALE_TIMEOUT`` 90s): upstream proxies / +load-balancers idle-kill the stream mid-think, surfacing as +``BrokenPipeError``/``RemoteProtocolError`` on the next read. The existing +stale-detector scaling consults :func:`get_reasoning_stale_timeout_floor` and +applies ``max(default, floor)``. Being a floor it: -* Stream stale detector: ``HERMES_STREAM_STALE_TIMEOUT`` default 180s - ``agent/chat_completion_helpers.py:2544`` -* Non-stream stale detector: ``HERMES_API_CALL_STALE_TIMEOUT`` default 90s - ``run_agent.py:1140`` +* never overrides explicit user config (``providers..models.. + stale_timeout_seconds`` / ``request_timeout_seconds`` win โ€” this never runs + in that branch); +* never lowers an existing threshold; +* has zero effect on non-allowlisted models (resolver returns ``None``). -For NVIDIA Nemotron 3 Ultra on the hosted NIM gateway the empirical -upstream idle kill is ~120s (first-party reproduction at -NVIDIA/NemoClaw#4846 โ€” TTFB ~31s, stream dies at 120s). The same -failure mode exists on OpenAI o1/o3, Anthropic Opus 4.x thinking, -DeepSeek R1, Qwen QwQ, xAI Grok reasoning โ€” every cloud reasoning -model hits upstream-proxies / load-balancers with idle timeouts -shorter than the model's thinking phase. Result: the stale detector -kills the connection mid-think, surfacing as -``BrokenPipeError``/``RemoteProtocolError`` on the next read. - -This module provides a floor that the existing stale-detector scaling -blocks consult via :func:`get_reasoning_stale_timeout_floor` and -apply as ``max(default, floor)``. It is a FLOOR: - -* Never overrides explicit user config (``providers..models..stale_timeout_seconds`` - or ``request_timeout_seconds`` already wins โ€” this code never runs - in that branch). -* Never lowers an existing threshold. -* Has zero effect on non-reasoning models โ€” they are not in the - allowlist and the resolver returns ``None``. - -Matching uses start-anchored regex on the slug-only component of -the model name (after stripping any aggregator prefix like -``openai/``, ``x-ai/``, ``anthropic/``). The right-anchor matches -end-of-string or a ``-``/``.``/``_`` slug separator, so ``qwen3-235b`` -matches the ``qwen3`` family entry (a future model slug would be -``qwen3-235b-instruct`` and would also match) but ``some-other-qwen3`` -does NOT match ``qwen3`` (the ``-qwen3`` is not at start of slug). - -The ``o1`` case is the most delicate: a model named -``llama-4-70b-o1-preview`` is a hypothetical community derivative that -should NOT trigger the reasoning-model floor for the user (the user -chose a non-OpenAI model, not a reasoning model). The start-of-slug -anchor naturally excludes this โ€” the matched ``o1-preview`` is at -position 11 of the slug, not at position 0. The previous substring- -with-trailing-hyphen design would have over-matched here, which is -why start-of-slug anchoring is the right shape. - -Fixes #52217. +Matching is start-anchored on the slug after any aggregator prefix +(``openai/``, ``x-ai/``) with an end-or-separator right anchor, so +``qwen3-235b`` matches ``qwen3`` but ``some-other-qwen3`` and a hypothetical +``llama-4-70b-o1-preview`` do not trigger the ``o1`` floor. """ from __future__ import annotations @@ -56,41 +26,25 @@ import re from typing import Optional -# (slug, floor_seconds). Each slug is matched as a discrete -# word-boundary component via the wrapper regex in ``_match_any`` -# below. Order is irrelevant โ€” the first regex match wins. +# (slug, floor_seconds). Order irrelevant โ€” longest slug wins at match time. _REASONING_STALE_TIMEOUT_FLOORS: tuple[tuple[str, int], ...] = ( - # NVIDIA Nemotron โ€” reasoning models behind hosted NIM with - # documented 60-180s upstream idle kill (NVIDIA/NemoClaw#4846: - # 120s measured). + # NVIDIA Nemotron behind hosted NIM: documented 60-180s upstream idle kill. ("nemotron-3-ultra", 600), ("nemotron-3-super", 600), ("nemotron-3-nano", 300), ("nemotron-3.5-lightning", 300), - # DeepSeek โ€” R1 and V4 reasoning models on hosted NIM / DeepSeek direct. - # V4 series emits reasoning_content in a separate delta field before - # final content, requiring the same extended stale timeout floor. + # DeepSeek R1 / V4 (reasoning_content streamed before final content). ("deepseek-r1", 600), ("deepseek-reasoner", 600), ("deepseek-v4-flash", 600), ("deepseek-v4-pro", 600), - # Qwen โ€” QwQ reasoning + Qwen3 thinking variants. QwQ-32B - # preview is the stable slug; ``qwen3`` covers the family of - # thinking-mode Qwen3 models (qwen3-235b-a22b, qwen3-32b, etc.) - # without over-matching every Qwen3 instruct variant โ€” the - # right-anchor requires the slug to be at the start of the - # remaining model name, so ``qwen3-235b-instruct`` (instruct is - # NOT a thinking variant) would still match. Acceptable - # trade-off: instruct variants of qwen3 get the 180s floor - # even though they don't reason. The cost is a slightly longer - # wait on a hung provider; the alternative (matching only - # ``qwen3-.*-thinking``) breaks the moment NVIDIA or Alibaba - # ships a slightly different naming shape. + # Qwen QwQ + the qwen3 family. Instruct variants also match ``qwen3`` โ€” + # accepted: a slightly longer wait on a hung provider beats a pattern + # (``qwen3-.*-thinking``) that breaks on the next naming shape. ("qwq-32b", 300), ("qwen3", 180), - # OpenAI o-series โ€” known multi-minute TTFB. Each variant - # enumerated explicitly so bare ``o1`` doesn't over-match - # ``olmo-1`` or hypothetical future community derivatives. + # OpenAI o-series: each variant enumerated so bare ``o1`` cannot + # over-match ``olmo-1`` or community derivatives. ("o1", 600), ("o1-mini", 600), ("o1-pro", 600), @@ -99,80 +53,36 @@ _REASONING_STALE_TIMEOUT_FLOORS: tuple[tuple[str, int], ...] = ( ("o3-pro", 600), ("o3-mini", 300), ("o4-mini", 300), - # Anthropic Claude 4.x thinking variants. Anchored at - # ``claude-opus-4`` so non-thinking Claude 3.x or future - # non-reasoning Claude variants don't match. + # Anthropic Claude 4.x+ thinking variants (anchored so 3.x never matches). ("claude-opus-4", 240), ("claude-opus-5", 240), ("claude-sonnet-5", 180), ("claude-sonnet-4.5", 180), ("claude-sonnet-4.6", 180), - # Anthropic Mythos-class named reasoning models (claude-fable-5, โ€ฆ). - # 1M context + 128K output โ€” heavier thinking phase than the - # numbered Claude line, so the floor is in the deep-reasoning tier - # alongside o1 / deepseek-r1 / nemotron-3-ultra. Without this - # entry the stale-stream detector kills fable-5's thinking phase - # at the default 180s (300s with context scaling), tripping the - # cross-turn circuit breaker after 5 consecutive stale kills. + # Mythos-class named models (claude-fable-5): 1M ctx + 128K output, a + # heavier thinking phase than the numbered line โ€” deep-reasoning tier, + # otherwise the stale detector trips the cross-turn circuit breaker. ("claude-fable", 600), - # xAI Grok reasoning variants. Explicit reasoning-only keys - # plus one for the ``non-reasoning`` variant so users picking - # the fast variant don't get the 300s floor. Bare ``grok-3``, - # ``grok-4`` etc. don't match โ€” only the explicit reasoning / - # non-reasoning pairs. + # xAI Grok: explicit reasoning / non-reasoning pairs only, so bare + # ``grok-3``/``grok-4`` fast variants don't inherit the 300s floor. ("grok-4-fast-reasoning", 300), ("grok-4.20-reasoning", 300), ("grok-4.5", 300), ("grok-4.6", 300), ("grok-4-fast-non-reasoning", 180), - # "Ox Alpha" stealth reasoning model (stealth/ox-alpha on OpenRouter, - # x-preview-f-free on OpenCode Zen). Marketed as a reasoning model for - # long-horizon coding/agentic work; 1M context โ€” same tier as the Grok - # reasoning variants. + # "Ox Alpha" stealth reasoning model (OpenRouter / OpenCode Zen slugs). ("ox-alpha", 300), ("x-preview-f-free", 300), - # Thinking Machines Inkling (thinkingmachines/inkling[-small][:free] - # on OpenRouter). Reasoning model (OpenRouter supported_parameters - # includes "reasoning"); 1M context โ€” same tier as the Grok - # reasoning variants and Ox Alpha. "inkling" left-anchors on the - # slug after the aggregator prefix and the right anchor accepts the - # "-" separator, so inkling-small and the :free SKUs all match. + # Thinking Machines Inkling; covers inkling-small and :free SKUs. ("inkling", 300), ) -# Pre-compile each pattern. Wrapper = start-of-slug + slug + end-or- -# separator, where ``start-of-slug`` means start-of-string OR -# immediately after the last ``/`` (aggregator separator) and -# ``end-or-separator`` means end-of-string OR a ``-``/``.``/``_``. -# -# Why start-of-slug and not start-of-string: aggregator prefixes -# like ``openai/`` should not affect matching โ€” the slug identity is -# the part after the last ``/``. Stripping the aggregator prefix in -# :func:`get_reasoning_stale_timeout_floor` before regex matching -# gives the wrapper a clean start-of-string anchor. -# -# Why end-or-separator on the right: ``openai/o3-mini`` must match -# the ``o3-mini`` slug (the right anchor is end-of-string). And -# ``openai/o3-mini-2025-01-31`` must also match ``o3-mini`` (the right -# anchor is the ``-`` separator). But ``openai/o3-mini-fork`` should -# NOT match ``o3-mini`` if we wanted to exclude forks โ€” though the -# pattern ``o3-mini-fork`` would be matched as a derivative anyway, -# so we accept that community forks inheriting the same prefix are -# treated as reasoning models (a reasonable default โ€” the upstream -# gateway timing is the same). -# Pre-compile all patterns at module load time to avoid per-call regex -# compilation and thread-safety issues with the mutable _PATTERN_CACHE. -# The list is built once at import and never mutated afterwards, so it is -# safe for free-threaded Python 3.13+ without any locking. The slug is kept -# in each entry for debuggability (log/inspection), even though _match_any -# only consumes floor + pattern. +# Pre-compiled once at import (immutable afterwards โ€” safe under free-threaded +# Python). Right anchor: end-of-string or a slug separator; ``:`` is included +# because OpenRouter routing suffixes (``:free``, ``:nitro``) attach directly +# to the slug. Sorted longest-first so ``o3-mini`` beats ``o3``. _SORTED_REASONING_FLOORS: list[tuple[str, float, re.Pattern[str]]] = [ - # Right anchor: end-of-string or a slug separator. ``:`` is in the - # separator class because OpenRouter SKU/routing suffixes - # (``:free``, ``:batch``, ``:nitro``, ``:floor``) attach directly to - # the slug โ€” ``thinkingmachines/inkling:free`` must match the - # ``inkling`` entry the same way ``inkling-small`` does. (slug, floor, re.compile(r"^" + re.escape(slug) + r"(?:$|[\-._:])")) for slug, floor in sorted( _REASONING_STALE_TIMEOUT_FLOORS, key=lambda kv: -len(kv[0]) @@ -180,38 +90,14 @@ _SORTED_REASONING_FLOORS: list[tuple[str, float, re.Pattern[str]]] = [ ] -def _match_any(model_lower: str) -> Optional[float]: - """Return the floor for the first matching slug, else None. - - Each table entry is matched as a start-of-slug prefix with the - slug-separator-or-end-of-string right-anchor. Table iteration - order is irrelevant: longest slug wins (so ``o3-mini`` beats - ``o3`` on a model like ``openai/o3-mini``). - """ - for _slug, floor, pattern in _SORTED_REASONING_FLOORS: - if pattern.search(model_lower): - return float(floor) - return None - - def get_reasoning_stale_timeout_floor(model: object) -> Optional[float]: """Return the stale-timeout floor (seconds) for a known reasoning model. - Returns ``None`` when the model is not in the allowlist or the - argument is empty / not a string. Matching uses - word-boundary-anchored regex on the lowercased model name, so - ``openai/o3-mini`` matches the ``o3-mini`` slug but - ``olmo-1`` does NOT match ``o1`` (the ``o1`` substring is not - at a word boundary inside ``olmo-1``). - - Aggregator prefixes (``openai/``, ``x-ai/``, ``anthropic/`` etc.) - are preserved through matching โ€” the ``/`` is itself a word - boundary, so ``openai/o3-mini`` matches ``o3-mini`` because the - ``/`` before ``o3-mini`` satisfies the left-anchor alternation. - - This is a FLOOR โ€” callers must apply it as ``max(default, floor)`` - and only when no explicit user-configured per-model - ``stale_timeout_seconds`` exists. + ``None`` when the model is not allowlisted or the argument is empty / not + a string. The aggregator prefix (everything up to the last ``/``) is + stripped so the slug is matched start-anchored. Callers apply this as + ``max(default, floor)`` and only when no explicit per-model + ``stale_timeout_seconds`` is configured. >>> get_reasoning_stale_timeout_floor("nvidia/nemotron-3-ultra-550b-a55b") 600.0 @@ -243,9 +129,9 @@ def get_reasoning_stale_timeout_floor(model: object) -> Optional[float]: name = model.strip().lower() if not name: return None - # Strip aggregator prefix (everything before and including the - # last ``/``). The wrapper regex anchors at start-of-string, so - # the slug identity is the bare model name. if "/" in name: name = name.rsplit("/", 1)[1] - return _match_any(name) + for _slug, floor, pattern in _SORTED_REASONING_FLOORS: + if pattern.search(name): + return float(floor) + return None diff --git a/agent/subscription_view.py b/agent/subscription_view.py index c2c55e0ee2..4a62017a29 100644 --- a/agent/subscription_view.py +++ b/agent/subscription_view.py @@ -1,19 +1,13 @@ """Surface-agnostic core for the ``/subscription`` TUI screen. -Companion to :mod:`agent.billing_view` โ€” same fail-open philosophy: when not -logged in or the portal is unreachable, return a struct with ``logged_in=False`` -and let the surface degrade gracefully (never crash). Money is decimal end-to-end -(server emits decimal strings); we only format for display. +Companion to :mod:`agent.billing_view` โ€” same fail-open philosophy (``logged_in=False`` +when not logged in / portal unreachable; never crash) and decimal money end-to-end. -The TUI ``SubscriptionOverlay`` drives the plan change in-terminal (V3): it -previews the effect, then schedules a downgrade / cancellation / resume -(chargeless) or applies an upgrade (charges the card on the subscription). The -portal deep-link (built locally from ``portal_url`` + ``org_id``) remains the -fallback for an upgrade that needs 3DS / was declined. - -WS1 dependency: ``GET /api/billing/subscription`` is a NAS endpoint (WS1 Phase A). -Until it ships, the fail-open contract handles 404s โ€” the builder returns -``logged_in=False`` and the surface degrades gracefully. +The TUI ``SubscriptionOverlay`` drives the plan change in-terminal: preview, then +schedule a downgrade / cancellation / resume (chargeless) or apply an upgrade +(charges the subscription card). The portal deep-link (``portal_url`` + ``org_id``) +remains the fallback for an upgrade that needs 3DS / was declined. Until the NAS +``GET /api/billing/subscription`` endpoint ships, 404s take the fail-open path. """ from __future__ import annotations @@ -24,24 +18,21 @@ from dataclasses import dataclass from decimal import Decimal from typing import Any, Optional -from agent.billing_view import parse_money +from agent.billing_view import OrgRoleCapability, fetch_portal_state, format_money, parse_money, parse_org_fields logger = logging.getLogger(__name__) -# ============================================================================= -# Parsed sub-structures -# ============================================================================= +# โ”€โ”€ Parsed sub-structures โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ @dataclass(frozen=True) class CurrentSubscription: """The user's active subscription. ``None`` (not this object) = no plan. - When present, ``tier_id`` / ``tier_name`` / ``monthly_credits`` / - ``cycle_ends_at`` are always set (NAS guarantees a present ``current`` is a - fully-populated plan). Only ``credits_remaining`` and the cancel/downgrade - fields are optional. + NAS guarantees a present ``current`` is fully populated: ``tier_id`` / + ``tier_name`` / ``monthly_credits`` / ``cycle_ends_at`` are always set; only + ``credits_remaining`` and the cancel/downgrade fields are optional. """ tier_id: Optional[str] = None @@ -57,12 +48,11 @@ class CurrentSubscription: @dataclass(frozen=True) class SubscriptionTier: - """A selectable plan in the catalog โ€” one row of the in-terminal tier picker. + """One row of the tier picker (mirrors NAS ``SubscriptionTierOption``). - Mirrors NAS's ``SubscriptionTierOption``. ``is_current`` marks the active plan - (shown but not selectable); ``is_enabled=False`` is a grandfathered tier the - user is on but that can no longer be selected. ``tier_order`` sorts the picker - and drives the upgrade-vs-downgrade direction hint. + ``is_current`` = active plan (shown, not selectable); ``is_enabled=False`` = a + grandfathered tier the user is on but can no longer select. ``tier_order`` sorts + the picker and drives the upgrade-vs-downgrade hint. """ tier_id: str @@ -76,13 +66,11 @@ class SubscriptionTier: @dataclass(frozen=True) class SubscriptionChangePreview: - """Parsed ``POST /api/billing/subscription/preview`` โ€” what a change would do. + """Parsed ``POST /api/billing/subscription/preview``. - ``effect`` is the disposition the commit would take: - - ``charge_now`` โ†’ an upgrade; ``amount_due_now_cents`` is the prorated charge. - - ``scheduled`` โ†’ a downgrade / same-price change at ``effective_at`` (period end). - - ``no_op`` โ†’ already on the target tier. - - ``blocked`` โ†’ the commit would be refused; ``reason`` says why. + ``effect``: ``charge_now`` (upgrade; ``amount_due_now_cents`` is the prorated + charge) ยท ``scheduled`` (downgrade / same-price change at ``effective_at``) ยท + ``no_op`` (already on target) ยท ``blocked`` (commit refused; ``reason`` says why). """ effect: str @@ -97,12 +85,9 @@ class SubscriptionChangePreview: @dataclass(frozen=True) -class SubscriptionState: - """Parsed ``GET /api/billing/subscription`` โ€” the overview screen's data. - - Fail-open: ``logged_in=False`` (and empty fields) when not logged in or the - portal is unreachable. - """ +class SubscriptionState(OrgRoleCapability): + """Parsed ``GET /api/billing/subscription``. Fail-open: ``logged_in=False`` + (empty fields) when not logged in or the portal is unreachable.""" logged_in: bool org_name: Optional[str] = None @@ -113,35 +98,15 @@ class SubscriptionState: current: Optional[CurrentSubscription] = None tiers: tuple[SubscriptionTier, ...] = () # selectable catalog (picker) portal_url: Optional[str] = None - # When the fetch failed (vs cleanly not-logged-in), the message for the surface. - error: Optional[str] = None - - @property - def is_admin(self) -> bool: - """Deprecated/display only โ€” a legacy OWNER/ADMIN check. - - NOT a capability check; use :attr:`can_change_plan` for gating billing - plan-change actions. - """ - return (self.role or "").upper() in ("OWNER", "ADMIN") - - @property - def can_change_plan(self) -> bool: - """Server capability when supplied; otherwise the legacy role fallback.""" - if self.can_change_plan_raw is not None: - return self.can_change_plan_raw - return self.is_admin + error: Optional[str] = None # set when the fetch failed (vs cleanly not-logged-in) -# ============================================================================= -# Payload parsing -# ============================================================================= +# โ”€โ”€ Payload parsing โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def _parse_current(raw: Any) -> Optional[CurrentSubscription]: - # "No plan" is wire-represented as current:null (free personal OR team) โ€” - # the old all-null-object shape is gone. A present current is a real plan, - # so guard on a real tier id and return None otherwise. + # "No plan" is wire-represented as current:null; a present current is a real + # plan, so guard on a real tier id and return None otherwise. if not isinstance(raw, dict): return None tier_id = raw.get("tierId") or raw.get("id") @@ -161,11 +126,8 @@ def _parse_current(raw: Any) -> Optional[CurrentSubscription]: def _coalesce(*vals: Any) -> Any: - """First non-``None`` value (preserves a legit ``0``/``0.0``, unlike ``or``). - - NAS sends ``0`` for the free tier's ``tierOrder`` / ``dollarsPerMonth``; a plain - ``x or default`` would drop those, so coalesce on ``None`` specifically. - """ + """First non-``None`` value. NAS sends ``0`` for the free tier's ``tierOrder`` / + ``dollarsPerMonth``, which a plain ``x or default`` would drop.""" for v in vals: if v is not None: return v @@ -197,8 +159,7 @@ def subscription_change_preview_from_payload( effect = payload.get("effect") cents = payload.get("amountDueNowCents") return SubscriptionChangePreview( - # An unrecognized/missing effect is treated as ``blocked`` โ€” fail safe, never - # charge on a malformed quote. + # Unrecognized/missing effect โ†’ ``blocked``: fail safe, never charge on a malformed quote. effect=effect if isinstance(effect, str) else "blocked", reason=payload.get("reason") or None, current_tier_id=payload.get("currentTierId"), @@ -215,89 +176,49 @@ def subscription_state_from_payload( payload: dict[str, Any], *, portal_url: Optional[str] = None ) -> SubscriptionState: """Map a raw ``/api/billing/subscription`` JSON dict into :class:`SubscriptionState`.""" - raw_org = payload.get("org") - org: dict[str, Any] = raw_org if isinstance(raw_org, dict) else {} - + org, can_change_plan_raw = parse_org_fields(payload) raw_context = payload.get("context") - context = raw_context if raw_context in ("personal", "team") else "personal" - raw_tiers = payload.get("tiers") tiers = ( tuple(t for t in (_parse_tier(x) for x in raw_tiers) if t is not None) if isinstance(raw_tiers, list) else () ) - return SubscriptionState( logged_in=True, org_name=org.get("name"), org_id=org.get("id") or None, role=org.get("role"), - can_change_plan_raw=( - payload.get("canChangePlan") - if isinstance(payload.get("canChangePlan"), bool) - else None - ), - context=context, + can_change_plan_raw=can_change_plan_raw, + context=raw_context if raw_context in ("personal", "team") else "personal", current=_parse_current(payload.get("current")), tiers=tiers, portal_url=portal_url, ) -# ============================================================================= -# Fail-open builders (the surface front doors) -# ============================================================================= +# โ”€โ”€ Fail-open builders (the surface front doors) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def build_subscription_state(*, timeout: float = 15.0) -> SubscriptionState: - """Fetch + parse ``GET /api/billing/subscription``. Fail-open. + """Fetch + parse ``GET /api/billing/subscription``. Fail-open (see + :func:`agent.billing_view.fetch_portal_state`). - Returns ``SubscriptionState(logged_in=False)`` when not logged in. On a - portal/HTTP failure, returns ``logged_in=False`` with ``error`` set so the - surface can show a clear message rather than crashing. - - Dev override: when ``HERMES_DEV_SUBSCRIPTION_FIXTURE`` names a fixture state, - ``/subscription`` renders from that fixture instead of the real portal โ€” so - every plan/cancel/downgrade/team/not-admin state is testable on both - the CLI and TUI without a live account. Throwaway scaffolding; see - :func:`dev_fixture_subscription_state`. + ``HERMES_DEV_SUBSCRIPTION_FIXTURE`` short-circuits to a fixture so every + plan/cancel/downgrade/team/not-admin state is testable on CLI and TUI offline. """ fixture = dev_fixture_subscription_state() if fixture is not None: return fixture - - try: - from hermes_cli.nous_billing import ( - BillingAuthError, - BillingError, - _absolutize_portal_url, - get_subscription_state, - resolve_portal_base_url, - ) - except Exception: - return SubscriptionState(logged_in=False, error="billing client unavailable") - - try: - payload = get_subscription_state(timeout=timeout) - except BillingAuthError: - return SubscriptionState(logged_in=False) - except BillingError as exc: - logger.debug("subscription โ–ธ /state fetch failed (fail-open)", exc_info=True) - return SubscriptionState(logged_in=False, error=str(exc)) - except Exception: - logger.debug("subscription โ–ธ /state unexpected error (fail-open)", exc_info=True) - return SubscriptionState(logged_in=False, error="could not load subscription state") - - raw_portal = payload.get("portalUrl") if isinstance(payload, dict) else None - portal_url = _absolutize_portal_url(raw_portal) if raw_portal else None - if not portal_url: - try: - portal_url = resolve_portal_base_url() - except Exception: - portal_url = None - - return subscription_state_from_payload(payload, portal_url=portal_url) + return fetch_portal_state( + "get_subscription_state", + "subscription", + failed=lambda **kw: SubscriptionState(logged_in=False, **kw), + parse=lambda payload, portal_url: subscription_state_from_payload(payload, portal_url=portal_url), + portal_fallback=lambda base: base, + timeout=timeout, + log=logger, + ) def subscription_manage_url( @@ -305,33 +226,24 @@ def subscription_manage_url( ) -> Optional[str]: """Build ``{portal_origin}/manage-subscription?org_id=[&plan=]``. - Mirrors the TUI's ``buildManageUrl`` (``subscription.ts``): the deep-link - target is NAS's OWN ``/manage-subscription`` page (NOT the Stripe Billing - Portal โ€” decided Jun 23), which routes upgradeโ†’Checkout / downgradeโ†’scheduled - internally. ``org_id`` pins the page to the right account in multi-org - situations. Returns ``None`` when no portal URL is resolvable. - - ``tier_id`` (the stable ``tiers[]`` id, never a name/slug) is appended as - ``plan=`` so the portal preselects the picked plan โ€” only for a NEW - subscription / upgrade the user chose. The portal validates it and simply - ignores an unknown tier, so the CLI appends unconditionally when a tier was - picked (parity with the TUI's ``?plan=``). + Mirrors the TUI's ``buildManageUrl``: the target is NAS's OWN ``/manage-subscription`` + page (NOT the Stripe Billing Portal), which routes upgradeโ†’Checkout / + downgradeโ†’scheduled internally. ``org_id`` pins the right account in multi-org + situations. ``tier_id`` (the stable ``tiers[]`` id, never a name/slug) preselects + the picked plan; the portal ignores an unknown tier, so it's appended + unconditionally when picked. None when no portal URL is resolvable. """ - from urllib.parse import urlencode, urlsplit, urlunsplit + from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit if not state.portal_url: return None - try: parts = urlsplit(state.portal_url) except Exception: return None - if parts.scheme not in ("http", "https") or not parts.netloc: return None - from urllib.parse import parse_qsl - # Preserve unrelated portal query params; org_id / plan are contract-owned # (org_id before plan โ€” insertion order is the emitted query order). params = dict(parse_qsl(parts.query, keep_blank_values=True)) @@ -341,68 +253,34 @@ def subscription_manage_url( params["org_id"] = state.org_id if tier_id: params["plan"] = tier_id - query = urlencode(params) - return urlunsplit((parts.scheme, parts.netloc, "/manage-subscription", query, "")) + return urlunsplit((parts.scheme, parts.netloc, "/manage-subscription", urlencode(params), "")) -# ============================================================================= -# Shared plan-catalog helpers (consumed by the CLI Free catalog + paid picker) -# ============================================================================= - - -def _format_dollars_grouped(value: Optional[Decimal]) -> str: - """``$1,000`` / ``$1,234.50`` โ€” the whole-vs-fractional rule of - ``billing_view.format_money`` but thousands-grouped, matching the TUI's - ``toLocaleString('en-US')``. - - The shared ``format_money`` is intentionally ungrouped (and asserted so across - other surfaces), so plan-catalog rows group locally to mirror the TUI. - """ - if value is None: - return "โ€”" - if value == value.to_integral_value(): - return f"${format(value.to_integral_value(), ',f')}" - return f"${format(value.quantize(Decimal('0.01')), ',f')}" +# โ”€โ”€ Shared plan-catalog helpers (CLI Free catalog + paid picker) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ def selectable_tiers(state: SubscriptionState) -> list[SubscriptionTier]: - """Enabled paid tiers other than the current plan, cheapest first. - - One derivation shared by the CLI Free catalog and the paid change picker: - ``is_enabled and not is_current and tier_order > 0`` (free / no-sub excluded โ€” - dropping to free is a cancellation), sorted by ``tier_order``. - """ + """Enabled paid tiers other than the current plan, cheapest first (``tier_order > 0`` + โ€” dropping to free is a cancellation, not a plan pick).""" return sorted( - ( - t - for t in (state.tiers or ()) - if t.is_enabled and not t.is_current and (t.tier_order or 0) > 0 - ), + (t for t in (state.tiers or ()) if t.is_enabled and not t.is_current and (t.tier_order or 0) > 0), key=lambda t: t.tier_order or 0, ) def format_tier_row(tier: SubscriptionTier) -> str: - """``name ยท $X/mo[ ยท $Y credits/mo]`` โ€” the shared plan-catalog row. - - Mirrors the TUI Free rows (``subscriptionOverlay.tsx``): thousands-grouped - money, and the ``$Y credits/mo`` suffix ONLY when monthly credits are present - and > 0 (a ``None`` / zero-credits tier hides it โ€” never ``ยท โ€” credits/mo`` or - ``ยท $0 credits/mo``). - """ - row = f"{tier.name} ยท {_format_dollars_grouped(tier.dollars_per_month)}/mo" + """``name ยท $X/mo[ ยท $Y credits/mo]`` โ€” thousands-grouped money (mirrors the TUI + Free rows); the credits suffix appears ONLY when monthly credits are present and > 0.""" + row = f"{tier.name} ยท {format_money(tier.dollars_per_month, grouped=True)}/mo" mc = tier.monthly_credits if mc is not None and mc > 0: - row += f" ยท {_format_dollars_grouped(mc)} credits/mo" + row += f" ยท {format_money(mc, grouped=True)} credits/mo" return row def is_upgrade(state: SubscriptionState, tier_id: str) -> bool: - """True when ``tier_id`` ranks above the current plan by ``tier_order``. - - Prefers the active subscription's tier; falls back to the ``tiers[]`` - ``is_current`` marker (what the picker derives from), else 0 (free). - """ + """True when ``tier_id`` ranks above the current plan by ``tier_order``. Prefers the + active subscription's tier; falls back to the ``tiers[]`` ``is_current`` marker, else 0.""" orders = {t.tier_id: (t.tier_order or 0) for t in (state.tiers or ())} cur_id = state.current.tier_id if state.current else None if cur_id is not None and cur_id in orders: @@ -412,96 +290,63 @@ def is_upgrade(state: SubscriptionState, tier_id: str) -> bool: return orders.get(tier_id, 0) > cur_order -# ============================================================================= -# Dev fixtures (throwaway scaffolding โ€” env-var driven, no live portal) -# ============================================================================= +# โ”€โ”€ Dev fixtures (throwaway scaffolding โ€” env-var driven, no live portal) โ”€โ”€โ”€โ”€ _DEV_FIXTURE_PORTAL = "https://portal.nousresearch.com/billing" def _dev_current(**over: Any) -> CurrentSubscription: base: dict[str, Any] = dict( - tier_id="plus", - tier_name="Plus", - monthly_credits=Decimal("1000"), - credits_remaining=Decimal("420"), - cycle_ends_at="2026-07-01", + tier_id="plus", tier_name="Plus", monthly_credits=Decimal("1000"), + credits_remaining=Decimal("420"), cycle_ends_at="2026-07-01", ) - base.update(over) - return CurrentSubscription(**base) + return CurrentSubscription(**{**base, **over}) def _dev_tiers(current_id: Optional[str]) -> tuple[SubscriptionTier, ...]: """A sample plan catalog for fixtures (marks ``current_id`` as the active tier).""" - specs = ( - ("free", "Free", 0, "0", "0"), - ("plus", "Plus", 1, "20", "1000"), - ("super", "Super", 2, "40", "3000"), - ("ultra", "Ultra", 3, "80", "7000"), - ) + specs = (("free", "Free", 0, "0", "0"), ("plus", "Plus", 1, "20", "1000"), + ("super", "Super", 2, "40", "3000"), ("ultra", "Ultra", 3, "80", "7000")) return tuple( SubscriptionTier( - tier_id=tid, - name=name, - tier_order=order, - dollars_per_month=parse_money(dpm), - monthly_credits=parse_money(mc), - is_current=(tid == current_id), - is_enabled=True, + tier_id=tid, name=name, tier_order=order, dollars_per_month=parse_money(dpm), + monthly_credits=parse_money(mc), is_current=(tid == current_id), is_enabled=True, ) for tid, name, order, dpm, mc in specs ) def dev_fixture_subscription_state() -> Optional[SubscriptionState]: - """Return a fixture :class:`SubscriptionState` for ``HERMES_DEV_SUBSCRIPTION_FIXTURE``. + """``HERMES_DEV_SUBSCRIPTION_FIXTURE`` -> fixture :class:`SubscriptionState`; None when unset. - Lets every CLI/TUI subscription state be exercised without a live portal: - - free | mid | top | not-admin | downgrade | cancel | team | - logged-out - - Returns ``None`` when the env var is unset/empty (the real portal path runs). - Throwaway scaffolding โ€” mirrors ``HERMES_DEV_CREDITS_FIXTURE``. + ``free | mid | top | not-admin | downgrade | cancel | team | logged-out``. Unknown + name โ†’ logged-out with ``error`` so the misconfiguration is visible. """ name = (os.getenv("HERMES_DEV_SUBSCRIPTION_FIXTURE") or "").strip().lower() if not name: return None - - common = dict(org_name="Acme Inc", org_id="org_acme", role="OWNER", portal_url=_DEV_FIXTURE_PORTAL) - - if name in ("logged-out", "logged_out", "loggedout"): + name = {"logged_out": "logged-out", "loggedout": "logged-out", "mid-tier": "mid", + "top-tier": "top", "member": "not-admin"}.get(name, name) + if name == "logged-out": return SubscriptionState(logged_in=False) - if name == "free": - return SubscriptionState(logged_in=True, current=None, tiers=_dev_tiers(None), **common) - if name in ("mid", "mid-tier"): - return SubscriptionState(logged_in=True, current=_dev_current(), tiers=_dev_tiers("plus"), **common) - if name in ("top", "top-tier"): - return SubscriptionState( - logged_in=True, + + common = dict(logged_in=True, org_name="Acme Inc", org_id="org_acme", role="OWNER", portal_url=_DEV_FIXTURE_PORTAL) + plus = dict(current=_dev_current(), tiers=_dev_tiers("plus")) + states: dict[str, dict[str, Any]] = { + "free": dict(current=None, tiers=_dev_tiers(None)), + "mid": plus, + "top": dict( current=_dev_current(tier_id="ultra", tier_name="Ultra", monthly_credits=Decimal("7000"), credits_remaining=Decimal("5000")), tiers=_dev_tiers("ultra"), - **common, - ) - if name in ("not-admin", "member"): - return SubscriptionState(logged_in=True, current=_dev_current(), tiers=_dev_tiers("plus"), **{**common, "role": "MEMBER"}) - if name == "downgrade": - return SubscriptionState( - logged_in=True, + ), + "not-admin": {**plus, "role": "MEMBER"}, + "downgrade": dict( current=_dev_current(tier_id="super", tier_name="Super", monthly_credits=Decimal("3000"), credits_remaining=Decimal("1500"), pending_downgrade_tier_name="Plus", pending_downgrade_at="2026-07-15"), tiers=_dev_tiers("super"), - **common, - ) - if name == "cancel": - return SubscriptionState( - logged_in=True, - current=_dev_current(cancel_at_period_end=True, cancellation_effective_at="2026-07-01"), - tiers=_dev_tiers("plus"), - **common, - ) - if name == "team": - return SubscriptionState(logged_in=True, context="team", current=None, org_name="Acme Engineering", org_id="org_eng", role="OWNER", portal_url=_DEV_FIXTURE_PORTAL) - - # Unknown name โ†’ behave as logged-out so the misconfiguration is visible. - return SubscriptionState(logged_in=False, error=f"unknown HERMES_DEV_SUBSCRIPTION_FIXTURE: {name}") - + ), + "cancel": dict(current=_dev_current(cancel_at_period_end=True, cancellation_effective_at="2026-07-01"), tiers=_dev_tiers("plus")), + "team": dict(context="team", current=None, org_name="Acme Engineering", org_id="org_eng"), + } + if name not in states: + return SubscriptionState(logged_in=False, error=f"unknown HERMES_DEV_SUBSCRIPTION_FIXTURE: {name}") + return SubscriptionState(**{**common, **states[name]}) diff --git a/agent/thinking_timeout_guidance.py b/agent/thinking_timeout_guidance.py index bd8a44cb71..0801014ff9 100644 --- a/agent/thinking_timeout_guidance.py +++ b/agent/thinking_timeout_guidance.py @@ -1,30 +1,11 @@ """Thinking-timeout detection and user-facing guidance for reasoning models. -When a known reasoning model (NVIDIA Nemotron 3 Ultra, OpenAI o1/o3, -Anthropic Opus 4.x thinking, DeepSeek R1, Qwen QwQ, xAI Grok reasoning) -hits a transport-layer error before the first content token arrives, the -upstream proxy has almost certainly idle-killed a long thinking stream โ€” -not a true context overflow or a configuration error. The user needs -distinct guidance for this case: - - "The model's thinking phase exceeded the upstream proxy's idle - timeout before the first content token arrived. This is a known - issue with reasoning models behind cloud gateways (NVIDIA NIM, - OpenAI, Anthropic, DeepSeek). Workarounds in priority order: - 1. Set `providers..models..stale_timeout_seconds: 900` - in `~/.hermes/config.yaml` to extend the per-call timeout... - 2. Lower `reasoning_budget` or set `reasoning_effort: medium`... - 3. Use a smaller / faster reasoning model..." - -The existing `_is_stream_drop` guidance at -``agent/conversation_loop.py:3464-3486`` fires for large-file-write -stream drops ("try execute_code with Python's open() for large files") -which is the WRONG advice for the thinking-timeout case. This module -provides the detection and the message as standalone helpers so the -detection logic is unit-testable without driving the full retry loop, -and the message text can be regression-tested for spelling and accuracy. - -Part 2 of Fixes #52310. +When a known reasoning model hits a transport-layer error before the first +content token, the upstream proxy has almost certainly idle-killed a long +thinking stream โ€” not a context overflow or configuration error. The generic +stream-drop guidance in conversation_loop ("use execute_code for large files") +is wrong for that case, so detection and message live here as standalone, +unit-testable helpers. """ from __future__ import annotations @@ -32,12 +13,9 @@ from __future__ import annotations from typing import Optional -# Substring set that identifies a transport-layer failure on the -# response stream. Same shape as the existing -# ``_SERVER_DISCONNECT_PATTERNS`` in ``agent/error_classifier.py:394`` -# but extended to also catch the OSS-level error signature -# (``broken pipe`` / ``errno 32``) that the upstream kill surfaces -# to the OpenAI SDK wrapper. +# Transport-layer failure signatures on the response stream โ€” the classifier's +# server-disconnect set plus the OS-level ``broken pipe`` / ``errno 32`` the +# upstream kill surfaces through the OpenAI SDK wrapper. _THINKING_TIMEOUT_SUBSTRINGS: tuple[str, ...] = ( "broken pipe", "errno 32", @@ -50,53 +28,22 @@ _THINKING_TIMEOUT_SUBSTRINGS: tuple[str, ...] = ( def is_thinking_timeout(classified: object, model: str, error_msg: str) -> bool: - """Return True when a reasoning model's thinking phase hit a transport kill. + """True when a reasoning model's thinking phase hit a transport kill. - Args: - classified: a :class:`agent.error_classifier.ClassifiedError` instance - (duck-typed here to avoid an import cycle in unit tests). - model: the model slug at failure time (e.g. - ``"nvidia/nemotron-3-ultra-550b-a55b"``). - error_msg: lowercased string representation of the underlying - exception (typically ``str(api_error).lower()``). - - Returns True when ALL conditions hold: - 1. ``classified.reason == FailoverReason.timeout`` (the classifier - override at ``agent/error_classifier.py:720-738`` ensures this - is the case for reasoning models even on large sessions). - 2. ``api_error`` has no ``.status_code`` attribute set (transport - disconnect, not an HTTP error). - 3. ``model`` is in the reasoning-model allowlist (reuses - ``agent.reasoning_timeouts.get_reasoning_stale_timeout_floor``). - 4. ``error_msg`` contains one of the transport-kill substrings. - - Non-reasoning models always return False. Non-transport errors - (billing / rate_limit / auth / context_overflow / format_error) - always return False. HTTP-status errors always return False. + All must hold: ``classified.reason`` is the ``timeout`` FailoverReason + (duck-typed via ``.value`` to avoid importing error_classifier), ``model`` + is in the reasoning allowlist (``reasoning_timeouts``), and ``error_msg`` + carries a transport-kill substring. The caller gates on the error having no + HTTP ``status_code`` before calling. Non-reasoning models and non-transport + errors (billing / rate_limit / auth / context_overflow) return False. """ - # Import here (not at module top) to keep this helper cheap to - # import even from callers that don't need it. ``agent.reasoning_timeouts`` - # is small and dependency-free. from agent.reasoning_timeouts import get_reasoning_stale_timeout_floor - # Condition 1: classifier says timeout. Use a string/value check - # rather than importing FailoverReason so this module has zero - # import cycles from the error_classifier package. reason = getattr(classified, "reason", None) - reason_value = getattr(reason, "value", None) - if reason_value != "timeout": + if getattr(reason, "value", None) != "timeout": return False - - # Condition 2: no HTTP status code (transport, not API error). - # Caller is expected to gate on ``getattr(api_error, "status_code", None) is None`` - # before calling this helper; the surface here is just the post-gate - # boolean so the caller can pass an already-prepped error_msg. - - # Condition 3: reasoning model allowlist. if get_reasoning_stale_timeout_floor(model) is None: return False - - # Condition 4: transport-kill substring in the error message. error_msg_lower = (error_msg or "").lower() return any(p in error_msg_lower for p in _THINKING_TIMEOUT_SUBSTRINGS) @@ -104,18 +51,11 @@ def is_thinking_timeout(classified: object, model: str, error_msg: str) -> bool: def build_thinking_timeout_guidance( provider: str, model: str, model_label: Optional[str] = None, ) -> str: - """Return the user-facing guidance string appended to ``_final_response``. + """User-facing guidance appended to the final response. - Args: - provider: provider slug (e.g. ``"nvidia"``, ``"openai"``). - model: bare model slug the user would put in their config - (e.g. ``"nemotron-3-ultra-550b-a55b"`` if the user uses - NVIDIA direct, or the full ``"nvidia/nemotron-3-ultra-550b-a55b"`` - if they go through an aggregator). Used verbatim in the - config snippet so the user can copy-paste. - model_label: optional short label for the model name in the - prose (e.g. ``"Nemotron 3 Ultra"``). Falls back to the - slug if not provided. + ``model`` is used verbatim in the config snippet so it is copy-pasteable + (bare slug for direct providers, ``vendor/slug`` through aggregators); + ``model_label`` is the optional prose name, defaulting to the slug. """ label = model_label or model return ( diff --git a/agent/usage_pricing.py b/agent/usage_pricing.py index 9af08f6dc0..a56b7982a3 100644 --- a/agent/usage_pricing.py +++ b/agent/usage_pricing.py @@ -12,14 +12,11 @@ from utils import base_url_host_matches, base_url_hostname logger = logging.getLogger(__name__) -DEFAULT_PRICING = {"input": 0.0, "output": 0.0} - _ZERO = Decimal("0") _ONE_MILLION = Decimal("1000000") _NOUS_DEFAULT_BASE_URL = "https://inference-api.nousresearch.com/v1" -# Sub-cent cost threshold: below $0.01, render at 4 decimal places so -# the display is non-zero (e.g. $0.0046 instead of $0.00). See #79220. +# Below $0.01, render at 4 dp so cheap-model costs never display as $0.00. _SUBCENT_THRESHOLD = Decimal("0.01") # Attached to every CostResult with status="included" so consumers can @@ -28,33 +25,19 @@ _INCLUDED_NOTE = "subscription-included; no provider invoice for usage" def format_cost_label(amount: Decimal) -> str: - """Format a cost amount as a display label. + """Format a cost as a display label, scaling precision to magnitude. - Scales precision to magnitude: - - Zero โ†’ "$0.00" - - Sub-cent (< $0.01) โ†’ "~$0.0046" (4 dp; amounts that ROUND to - 0.0000 at 4 dp โ€” i.e. at or below $0.00005 under banker's - rounding โ€” fall back to "~$<0.0001" so the label never reads - as zero) - - Normal โ†’ "~$1.23" (2 dp) - - This fixes #79220 where sub-cent per-turn costs on cheap models - (DeepSeek, etc.) rendered as "$0.00" despite amount_usd carrying - full Decimal precision. - - Shared by per-response cost labels (estimate_usage_cost) and the - insights cost-bucket formatters โ€” keep both surfaces on this one - implementation so sub-cent honesty can't regress on one of them. + Zero โ†’ "$0.00"; sub-cent โ†’ "~$0.0046" (4 dp, or "~$<0.0001" when the + amount rounds to 0.0000 so the label never reads as zero); else "~$1.23". + Shared by per-response cost labels and the insights cost-bucket + formatters so sub-cent honesty cannot regress on one surface. """ if amount == _ZERO: return "$0.00" if amount < _SUBCENT_THRESHOLD: label = f"~${amount:.4f}" - # A positive amount that rounds to 0.0000 at 4 dp would render - # "~$0.0000" โ€” a zero-looking label, the exact #79220 dishonesty. - # Comparing the rendered label checks the truth directly (a naive - # `< 0.00005` threshold misses the exact boundary under - # ROUND_HALF_EVEN). + # Compare the rendered label: a naive `< 0.00005` threshold misses + # the exact boundary under ROUND_HALF_EVEN. return label if label != "~$0.0000" else "~$<0.0001" return f"~${amount:.2f}" @@ -89,12 +72,9 @@ class CanonicalUsage: return self.prompt_tokens + self.output_tokens def __add__(self, other: "CanonicalUsage") -> "CanonicalUsage": - """Sum two usage buckets (e.g. MoA advisor fan-out + aggregator). - - ``raw_usage`` is dropped on the sum โ€” it describes a single API - response and cannot be meaningfully merged. ``request_count`` adds so - callers can see how many underlying API calls a combined figure covers. - """ + """Sum two usage buckets. ``raw_usage`` (single-response detail) is + dropped; ``request_count`` adds so callers see how many API calls a + combined figure covers.""" if not isinstance(other, CanonicalUsage): return NotImplemented return CanonicalUsage( @@ -127,12 +107,10 @@ class PricingEntry: source_url: Optional[str] = None pricing_version: Optional[str] = None fetched_at: Optional[datetime] = None - # Context-tiered pricing (e.g. Gemini Pro models charge higher rates once - # the prompt exceeds 200k tokens). When ``tier_threshold_tokens`` is set - # and ``usage.prompt_tokens`` (input + cache read + cache write) exceeds - # it, the ``*_above`` rates replace the base rates for the WHOLE request โ€” - # that matches Google's billing semantics (not marginal/bracketed rates). - # Any ``*_above`` field left as None falls back to its base rate. + # Context-tiered pricing (e.g. Gemini Pro above 200k prompt tokens): when + # ``usage.prompt_tokens`` exceeds ``tier_threshold_tokens`` the ``*_above`` + # rates replace the base rates for the WHOLE request (Google's semantics, + # not marginal brackets). A None ``*_above`` falls back to its base rate. tier_threshold_tokens: Optional[int] = None input_cost_per_million_above: Optional[Decimal] = None output_cost_per_million_above: Optional[Decimal] = None @@ -153,886 +131,175 @@ class CostResult: _UTC_NOW = lambda: datetime.now(timezone.utc) -# Official docs snapshot entries. Models whose published pricing and cache -# semantics are stable enough to encode exactly. +def _snap( + inp: str, + out: str, + cache_read: Optional[str] = None, + cache_write: Optional[str] = None, + *, + version: str, + url: Optional[str] = None, + **tiers: Any, +) -> PricingEntry: + """Build an official-docs snapshot entry from per-million USD rate strings.""" + return PricingEntry( + input_cost_per_million=Decimal(inp), + output_cost_per_million=Decimal(out), + cache_read_cost_per_million=Decimal(cache_read) if cache_read is not None else None, + cache_write_cost_per_million=Decimal(cache_write) if cache_write is not None else None, + source="official_docs_snapshot", + source_url=url, + pricing_version=version, + **tiers, + ) + + +# (source_url, pricing_version) shared by the entries of one snapshot. +_OPENAI_56 = dict(url="https://openai.com/index/previewing-gpt-5-6-sol/", version="openai-gpt-5.6-2026-07") +_ANTHROPIC = dict(url="https://platform.claude.com/docs/en/about-claude/pricing", version="anthropic-pricing-2026-05") +_OPENAI = dict(url="https://openai.com/api/pricing/", version="openai-pricing-2026-03-16") +_DEEPSEEK = dict(url="https://api-docs.deepseek.com/quick_start/pricing", version="deepseek-pricing-2026-07") +_GOOGLE = dict(url="https://ai.google.dev/pricing", version="google-pricing-2026-07-07") +_GOOGLE_NEW = dict(url="https://ai.google.dev/gemini-api/docs/pricing", version="google-pricing-2026-07-28") +_BEDROCK_URL = "https://aws.amazon.com/bedrock/pricing/" +_BEDROCK_ANTHROPIC = dict(url=_BEDROCK_URL, version="anthropic-list-2026-07") +_BEDROCK = dict(url=_BEDROCK_URL, version="bedrock-pricing-2026-04") +_FIREWORKS = dict(url="https://docs.fireworks.ai/serverless/pricing", version="fireworks-pricing-2026-07") + +# Official docs snapshot: models whose published pricing and cache semantics +# are stable enough to encode exactly. Positional rates are per 1M tokens: +# (input, output[, cache_read[, cache_write]]). _OFFICIAL_DOCS_PRICING: Dict[tuple[str, str], PricingEntry] = { - # โ”€โ”€ OpenAI GPT-5.6 series (Sol/Terra/Luna) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - # Announced in limited preview 2026-06-26; GA 2026-07-09 at the same - # rates (Sol $5/$30, Terra $2.50/$15, Luna $1/$6 per 1M in/out). Cache - # writes are billed at 1.25x the uncached input rate; cache reads get the - # standard 90% discount (0.10x input, confirmed: Sol $0.50/M cached). - # Note: "Sol Fast mode" ($12.5/$75, up to 750 tok/s via Cerebras) is a - # separate serving tier, not covered by these entries. The "-pro" - # variants (high-effort modes, GA alongside base tiers) bill at the - # SAME per-token rates and are aliased onto these entries below the - # dict (they cost more per task by consuming more tokens, not by a - # higher rate โ€” verified against OpenRouter's live pricing 2026-07-09). - # Source: https://openai.com/index/previewing-gpt-5-6-sol/ - ( - "openai", - "gpt-5.6-sol", - ): PricingEntry( - input_cost_per_million=Decimal("5.00"), - output_cost_per_million=Decimal("30.00"), - cache_read_cost_per_million=Decimal("0.50"), - cache_write_cost_per_million=Decimal("6.25"), - source="official_docs_snapshot", - source_url="https://openai.com/index/previewing-gpt-5-6-sol/", - pricing_version="openai-gpt-5.6-2026-07", + # OpenAI GPT-5.6 (Sol/Terra/Luna). Cache write = 1.25x input, cache read = + # 0.10x input. "-pro" high-effort modes bill at the same per-token rates + # (aliased below the dict); "Sol Fast mode" is a separate tier, not covered. + ("openai", "gpt-5.6-sol"): _snap("5.00", "30.00", "0.50", "6.25", **_OPENAI_56), + ("openai", "gpt-5.6-terra"): _snap("2.50", "15.00", "0.25", "3.125", **_OPENAI_56), + ("openai", "gpt-5.6-luna"): _snap("1.00", "6.00", "0.10", "1.25", **_OPENAI_56), + # Anthropic Claude 4.8; fast mode is a separate model id at a 2x premium. + ("anthropic", "claude-opus-4-8"): _snap("5.00", "25.00", "0.50", "6.25", **_ANTHROPIC), + ("anthropic", "claude-opus-4-8-fast"): _snap( + "10.00", "50.00", "1.00", "12.50", + url="https://openrouter.ai/anthropic/claude-opus-4.8-fast", version="anthropic-pricing-2026-05", ), - ( - "openai", - "gpt-5.6-terra", - ): PricingEntry( - input_cost_per_million=Decimal("2.50"), - output_cost_per_million=Decimal("15.00"), - cache_read_cost_per_million=Decimal("0.25"), - cache_write_cost_per_million=Decimal("3.125"), - source="official_docs_snapshot", - source_url="https://openai.com/index/previewing-gpt-5-6-sol/", - pricing_version="openai-gpt-5.6-2026-07", - ), - ( - "openai", - "gpt-5.6-luna", - ): PricingEntry( - input_cost_per_million=Decimal("1.00"), - output_cost_per_million=Decimal("6.00"), - cache_read_cost_per_million=Decimal("0.10"), - cache_write_cost_per_million=Decimal("1.25"), - source="official_docs_snapshot", - source_url="https://openai.com/index/previewing-gpt-5-6-sol/", - pricing_version="openai-gpt-5.6-2026-07", - ), - # โ”€โ”€ Anthropic Claude 4.8 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - # Same $5/$25 base pricing as 4.6/4.7. Fast-mode variant is a separate - # model ID with 2x premium (vs the 6x premium on older Opus generations). - # Source: https://openrouter.ai/anthropic/claude-opus-4.8 - ( - "anthropic", - "claude-opus-4-8", - ): PricingEntry( - input_cost_per_million=Decimal("5.00"), - output_cost_per_million=Decimal("25.00"), - cache_read_cost_per_million=Decimal("0.50"), - cache_write_cost_per_million=Decimal("6.25"), - source="official_docs_snapshot", - source_url="https://platform.claude.com/docs/en/about-claude/pricing", - pricing_version="anthropic-pricing-2026-05", - ), - ( - "anthropic", - "claude-opus-4-8-fast", - ): PricingEntry( - input_cost_per_million=Decimal("10.00"), - output_cost_per_million=Decimal("50.00"), - cache_read_cost_per_million=Decimal("1.00"), - cache_write_cost_per_million=Decimal("12.50"), - source="official_docs_snapshot", - source_url="https://openrouter.ai/anthropic/claude-opus-4.8-fast", - pricing_version="anthropic-pricing-2026-05", - ), - # โ”€โ”€ Anthropic Claude Sonnet 5 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - # Launched 2026-06-30. Introductory pricing ($2/$10 per MTok) runs - # through 2026-08-31, after which it reverts to $3/$15 (matching - # Sonnet 4.6). Update this entry when the intro window closes. - # Source: https://platform.claude.com/docs/en/about-claude/pricing - ( - "anthropic", - "claude-sonnet-5", - ): PricingEntry( - input_cost_per_million=Decimal("2.00"), - output_cost_per_million=Decimal("10.00"), - cache_read_cost_per_million=Decimal("0.20"), - cache_write_cost_per_million=Decimal("2.50"), - source="official_docs_snapshot", - source_url="https://platform.claude.com/docs/en/about-claude/pricing", - pricing_version="anthropic-pricing-2026-06-intro", - ), - # โ”€โ”€ Anthropic Claude 4.7 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - # Opus 4.5/4.6/4.7 share $5/$25 pricing (new tokenizer, up to 35% more - # tokens for the same text). - # Source: https://platform.claude.com/docs/en/about-claude/pricing - ( - "anthropic", - "claude-opus-4-7", - ): PricingEntry( - input_cost_per_million=Decimal("5.00"), - output_cost_per_million=Decimal("25.00"), - cache_read_cost_per_million=Decimal("0.50"), - cache_write_cost_per_million=Decimal("6.25"), - source="official_docs_snapshot", - source_url="https://platform.claude.com/docs/en/about-claude/pricing", - pricing_version="anthropic-pricing-2026-05", - ), - ( - "anthropic", - "claude-opus-4-7-20250507", - ): PricingEntry( - input_cost_per_million=Decimal("5.00"), - output_cost_per_million=Decimal("25.00"), - cache_read_cost_per_million=Decimal("0.50"), - cache_write_cost_per_million=Decimal("6.25"), - source="official_docs_snapshot", - source_url="https://platform.claude.com/docs/en/about-claude/pricing", - pricing_version="anthropic-pricing-2026-05", - ), - # โ”€โ”€ Anthropic Claude 4.6 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - ( - "anthropic", - "claude-opus-4-6", - ): PricingEntry( - input_cost_per_million=Decimal("5.00"), - output_cost_per_million=Decimal("25.00"), - cache_read_cost_per_million=Decimal("0.50"), - cache_write_cost_per_million=Decimal("6.25"), - source="official_docs_snapshot", - source_url="https://platform.claude.com/docs/en/about-claude/pricing", - pricing_version="anthropic-pricing-2026-05", - ), - ( - "anthropic", - "claude-opus-4-6-20250414", - ): PricingEntry( - input_cost_per_million=Decimal("5.00"), - output_cost_per_million=Decimal("25.00"), - cache_read_cost_per_million=Decimal("0.50"), - cache_write_cost_per_million=Decimal("6.25"), - source="official_docs_snapshot", - source_url="https://platform.claude.com/docs/en/about-claude/pricing", - pricing_version="anthropic-pricing-2026-05", - ), - ( - "anthropic", - "claude-sonnet-4-6", - ): PricingEntry( - input_cost_per_million=Decimal("3.00"), - output_cost_per_million=Decimal("15.00"), - cache_read_cost_per_million=Decimal("0.30"), - cache_write_cost_per_million=Decimal("3.75"), - source="official_docs_snapshot", - source_url="https://platform.claude.com/docs/en/about-claude/pricing", - pricing_version="anthropic-pricing-2026-05", - ), - ( - "anthropic", - "claude-sonnet-4-6-20250414", - ): PricingEntry( - input_cost_per_million=Decimal("3.00"), - output_cost_per_million=Decimal("15.00"), - cache_read_cost_per_million=Decimal("0.30"), - cache_write_cost_per_million=Decimal("3.75"), - source="official_docs_snapshot", - source_url="https://platform.claude.com/docs/en/about-claude/pricing", - pricing_version="anthropic-pricing-2026-05", - ), - # โ”€โ”€ Anthropic Claude 4.5 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - ( - "anthropic", - "claude-opus-4-5", - ): PricingEntry( - input_cost_per_million=Decimal("5.00"), - output_cost_per_million=Decimal("25.00"), - cache_read_cost_per_million=Decimal("0.50"), - cache_write_cost_per_million=Decimal("6.25"), - source="official_docs_snapshot", - source_url="https://platform.claude.com/docs/en/about-claude/pricing", - pricing_version="anthropic-pricing-2026-05", - ), - ( - "anthropic", - "claude-sonnet-4-5", - ): PricingEntry( - input_cost_per_million=Decimal("3.00"), - output_cost_per_million=Decimal("15.00"), - cache_read_cost_per_million=Decimal("0.30"), - cache_write_cost_per_million=Decimal("3.75"), - source="official_docs_snapshot", - source_url="https://platform.claude.com/docs/en/about-claude/pricing", - pricing_version="anthropic-pricing-2026-05", - ), - ( - "anthropic", - "claude-haiku-4-5", - ): PricingEntry( - input_cost_per_million=Decimal("1.00"), - output_cost_per_million=Decimal("5.00"), - cache_read_cost_per_million=Decimal("0.10"), - cache_write_cost_per_million=Decimal("1.25"), - source="official_docs_snapshot", - source_url="https://platform.claude.com/docs/en/about-claude/pricing", - pricing_version="anthropic-pricing-2026-05", - ), - # โ”€โ”€ Anthropic Claude 4 / 4.1 โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - ( - "anthropic", - "claude-opus-4-20250514", - ): PricingEntry( - input_cost_per_million=Decimal("15.00"), - output_cost_per_million=Decimal("75.00"), - cache_read_cost_per_million=Decimal("1.50"), - cache_write_cost_per_million=Decimal("18.75"), - source="official_docs_snapshot", - source_url="https://platform.claude.com/docs/en/about-claude/pricing", - pricing_version="anthropic-pricing-2026-05", - ), - ( - "anthropic", - "claude-sonnet-4-20250514", - ): PricingEntry( - input_cost_per_million=Decimal("3.00"), - output_cost_per_million=Decimal("15.00"), - cache_read_cost_per_million=Decimal("0.30"), - cache_write_cost_per_million=Decimal("3.75"), - source="official_docs_snapshot", - source_url="https://platform.claude.com/docs/en/about-claude/pricing", - pricing_version="anthropic-pricing-2026-05", + # Claude Sonnet 5: introductory $2/$10 through 2026-08-31, then $3/$15 + # (matching Sonnet 4.6). Update this entry when the intro window closes. + ("anthropic", "claude-sonnet-5"): _snap( + "2.00", "10.00", "0.20", "2.50", url=_ANTHROPIC["url"], version="anthropic-pricing-2026-06-intro" ), + # Claude 4.5/4.6/4.7 Opus share $5/$25 (new tokenizer, up to 35% more tokens). + ("anthropic", "claude-opus-4-7"): _snap("5.00", "25.00", "0.50", "6.25", **_ANTHROPIC), + ("anthropic", "claude-opus-4-7-20250507"): _snap("5.00", "25.00", "0.50", "6.25", **_ANTHROPIC), + ("anthropic", "claude-opus-4-6"): _snap("5.00", "25.00", "0.50", "6.25", **_ANTHROPIC), + ("anthropic", "claude-opus-4-6-20250414"): _snap("5.00", "25.00", "0.50", "6.25", **_ANTHROPIC), + ("anthropic", "claude-sonnet-4-6"): _snap("3.00", "15.00", "0.30", "3.75", **_ANTHROPIC), + ("anthropic", "claude-sonnet-4-6-20250414"): _snap("3.00", "15.00", "0.30", "3.75", **_ANTHROPIC), + ("anthropic", "claude-opus-4-5"): _snap("5.00", "25.00", "0.50", "6.25", **_ANTHROPIC), + ("anthropic", "claude-sonnet-4-5"): _snap("3.00", "15.00", "0.30", "3.75", **_ANTHROPIC), + ("anthropic", "claude-haiku-4-5"): _snap("1.00", "5.00", "0.10", "1.25", **_ANTHROPIC), + ("anthropic", "claude-opus-4-20250514"): _snap("15.00", "75.00", "1.50", "18.75", **_ANTHROPIC), + ("anthropic", "claude-sonnet-4-20250514"): _snap("3.00", "15.00", "0.30", "3.75", **_ANTHROPIC), # OpenAI - ( - "openai", - "gpt-4o", - ): PricingEntry( - input_cost_per_million=Decimal("2.50"), - output_cost_per_million=Decimal("10.00"), - cache_read_cost_per_million=Decimal("1.25"), - source="official_docs_snapshot", - source_url="https://openai.com/api/pricing/", - pricing_version="openai-pricing-2026-03-16", - ), - ( - "openai", - "gpt-4o-mini", - ): PricingEntry( - input_cost_per_million=Decimal("0.15"), - output_cost_per_million=Decimal("0.60"), - cache_read_cost_per_million=Decimal("0.075"), - source="official_docs_snapshot", - source_url="https://openai.com/api/pricing/", - pricing_version="openai-pricing-2026-03-16", - ), - ( - "openai", - "gpt-4.1", - ): PricingEntry( - input_cost_per_million=Decimal("2.00"), - output_cost_per_million=Decimal("8.00"), - cache_read_cost_per_million=Decimal("0.50"), - source="official_docs_snapshot", - source_url="https://openai.com/api/pricing/", - pricing_version="openai-pricing-2026-03-16", - ), - ( - "openai", - "gpt-4.1-mini", - ): PricingEntry( - input_cost_per_million=Decimal("0.40"), - output_cost_per_million=Decimal("1.60"), - cache_read_cost_per_million=Decimal("0.10"), - source="official_docs_snapshot", - source_url="https://openai.com/api/pricing/", - pricing_version="openai-pricing-2026-03-16", - ), - ( - "openai", - "gpt-4.1-nano", - ): PricingEntry( - input_cost_per_million=Decimal("0.10"), - output_cost_per_million=Decimal("0.40"), - cache_read_cost_per_million=Decimal("0.025"), - source="official_docs_snapshot", - source_url="https://openai.com/api/pricing/", - pricing_version="openai-pricing-2026-03-16", - ), - ( - "openai", - "o3", - ): PricingEntry( - input_cost_per_million=Decimal("10.00"), - output_cost_per_million=Decimal("40.00"), - cache_read_cost_per_million=Decimal("2.50"), - source="official_docs_snapshot", - source_url="https://openai.com/api/pricing/", - pricing_version="openai-pricing-2026-03-16", - ), - ( - "openai", - "o3-mini", - ): PricingEntry( - input_cost_per_million=Decimal("1.10"), - output_cost_per_million=Decimal("4.40"), - cache_read_cost_per_million=Decimal("0.55"), - source="official_docs_snapshot", - source_url="https://openai.com/api/pricing/", - pricing_version="openai-pricing-2026-03-16", - ), - # โ”€โ”€ Anthropic older models (pre-4.5 generation) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ - ( - "anthropic", - "claude-3-5-sonnet-20241022", - ): PricingEntry( - input_cost_per_million=Decimal("3.00"), - output_cost_per_million=Decimal("15.00"), - cache_read_cost_per_million=Decimal("0.30"), - cache_write_cost_per_million=Decimal("3.75"), - source="official_docs_snapshot", - source_url="https://platform.claude.com/docs/en/about-claude/pricing", - pricing_version="anthropic-pricing-2026-05", - ), - ( - "anthropic", - "claude-3-5-haiku-20241022", - ): PricingEntry( - input_cost_per_million=Decimal("0.80"), - output_cost_per_million=Decimal("4.00"), - cache_read_cost_per_million=Decimal("0.08"), - cache_write_cost_per_million=Decimal("1.00"), - source="official_docs_snapshot", - source_url="https://platform.claude.com/docs/en/about-claude/pricing", - pricing_version="anthropic-pricing-2026-05", - ), - ( - "anthropic", - "claude-3-opus-20240229", - ): PricingEntry( - input_cost_per_million=Decimal("15.00"), - output_cost_per_million=Decimal("75.00"), - cache_read_cost_per_million=Decimal("1.50"), - cache_write_cost_per_million=Decimal("18.75"), - source="official_docs_snapshot", - source_url="https://platform.claude.com/docs/en/about-claude/pricing", - pricing_version="anthropic-pricing-2026-05", - ), - ( - "anthropic", - "claude-3-haiku-20240307", - ): PricingEntry( - input_cost_per_million=Decimal("0.25"), - output_cost_per_million=Decimal("1.25"), - cache_read_cost_per_million=Decimal("0.03"), - cache_write_cost_per_million=Decimal("0.30"), - source="official_docs_snapshot", - source_url="https://platform.claude.com/docs/en/about-claude/pricing", - pricing_version="anthropic-pricing-2026-05", - ), - # DeepSeek - # Snapshot of https://api-docs.deepseek.com/quick_start/pricing (2026-07). - # deepseek-chat / deepseek-reasoner are deprecated 2026-07-24 and now alias + ("openai", "gpt-4o"): _snap("2.50", "10.00", "1.25", **_OPENAI), + ("openai", "gpt-4o-mini"): _snap("0.15", "0.60", "0.075", **_OPENAI), + ("openai", "gpt-4.1"): _snap("2.00", "8.00", "0.50", **_OPENAI), + ("openai", "gpt-4.1-mini"): _snap("0.40", "1.60", "0.10", **_OPENAI), + ("openai", "gpt-4.1-nano"): _snap("0.10", "0.40", "0.025", **_OPENAI), + ("openai", "o3"): _snap("10.00", "40.00", "2.50", **_OPENAI), + ("openai", "o3-mini"): _snap("1.10", "4.40", "0.55", **_OPENAI), + # Anthropic pre-4.5 generation + ("anthropic", "claude-3-5-sonnet-20241022"): _snap("3.00", "15.00", "0.30", "3.75", **_ANTHROPIC), + ("anthropic", "claude-3-5-haiku-20241022"): _snap("0.80", "4.00", "0.08", "1.00", **_ANTHROPIC), + ("anthropic", "claude-3-opus-20240229"): _snap("15.00", "75.00", "1.50", "18.75", **_ANTHROPIC), + ("anthropic", "claude-3-haiku-20240307"): _snap("0.25", "1.25", "0.03", "0.30", **_ANTHROPIC), + # DeepSeek. deepseek-chat / deepseek-reasoner are deprecated aliases of # deepseek-v4-flash's non-thinking / thinking modes โ€” same rates. - ( - "deepseek", - "deepseek-chat", - ): PricingEntry( - input_cost_per_million=Decimal("0.14"), - output_cost_per_million=Decimal("0.28"), - cache_read_cost_per_million=Decimal("0.0028"), - source="official_docs_snapshot", - source_url="https://api-docs.deepseek.com/quick_start/pricing", - pricing_version="deepseek-pricing-2026-07", - ), - ( - "deepseek", - "deepseek-reasoner", - ): PricingEntry( - input_cost_per_million=Decimal("0.14"), - output_cost_per_million=Decimal("0.28"), - cache_read_cost_per_million=Decimal("0.0028"), - source="official_docs_snapshot", - source_url="https://api-docs.deepseek.com/quick_start/pricing", - pricing_version="deepseek-pricing-2026-07", - ), - ( - "deepseek", - "deepseek-v4-pro", - ): PricingEntry( - input_cost_per_million=Decimal("0.435"), - output_cost_per_million=Decimal("0.87"), - cache_read_cost_per_million=Decimal("0.003625"), - source="official_docs_snapshot", - source_url="https://api-docs.deepseek.com/quick_start/pricing", - pricing_version="deepseek-pricing-2026-07", - ), - ( - "deepseek", - "deepseek-v4-flash", - ): PricingEntry( - input_cost_per_million=Decimal("0.14"), - output_cost_per_million=Decimal("0.28"), - cache_read_cost_per_million=Decimal("0.0028"), - source="official_docs_snapshot", - source_url="https://api-docs.deepseek.com/quick_start/pricing", - pricing_version="deepseek-pricing-2026-07", - ), + ("deepseek", "deepseek-chat"): _snap("0.14", "0.28", "0.0028", **_DEEPSEEK), + ("deepseek", "deepseek-reasoner"): _snap("0.14", "0.28", "0.0028", **_DEEPSEEK), + ("deepseek", "deepseek-v4-pro"): _snap("0.435", "0.87", "0.003625", **_DEEPSEEK), + ("deepseek", "deepseek-v4-flash"): _snap("0.14", "0.28", "0.0028", **_DEEPSEEK), # Google Gemini - ( - "google", - "gemini-3.6-flash", - ): PricingEntry( - input_cost_per_million=Decimal("1.50"), - output_cost_per_million=Decimal("7.50"), - cache_read_cost_per_million=Decimal("0.15"), - source="official_docs_snapshot", - source_url="https://ai.google.dev/gemini-api/docs/pricing", - pricing_version="google-pricing-2026-07-28", - ), - ( - "google", - "gemini-3.5-flash", - ): PricingEntry( - input_cost_per_million=Decimal("1.50"), - output_cost_per_million=Decimal("9.00"), - cache_read_cost_per_million=Decimal("0.15"), - source="official_docs_snapshot", - source_url="https://ai.google.dev/pricing", - pricing_version="google-pricing-2026-07-07", - ), - ( - "google", - "gemini-3.5-flash-lite", - ): PricingEntry( - input_cost_per_million=Decimal("0.30"), - output_cost_per_million=Decimal("2.50"), - cache_read_cost_per_million=Decimal("0.03"), - source="official_docs_snapshot", - source_url="https://ai.google.dev/gemini-api/docs/pricing", - pricing_version="google-pricing-2026-07-28", - ), - ( - "google", - "gemini-3.1-pro", - ): PricingEntry( - input_cost_per_million=Decimal("2.00"), - output_cost_per_million=Decimal("12.00"), - cache_read_cost_per_million=Decimal("0.20"), + ("google", "gemini-3.6-flash"): _snap("1.50", "7.50", "0.15", **_GOOGLE_NEW), + ("google", "gemini-3.5-flash"): _snap("1.50", "9.00", "0.15", **_GOOGLE), + ("google", "gemini-3.5-flash-lite"): _snap("0.30", "2.50", "0.03", **_GOOGLE_NEW), + ("google", "gemini-3.1-pro"): _snap( + "2.00", "12.00", "0.20", tier_threshold_tokens=200_000, input_cost_per_million_above=Decimal("4.00"), output_cost_per_million_above=Decimal("18.00"), cache_read_cost_per_million_above=Decimal("0.40"), - source="official_docs_snapshot", - source_url="https://ai.google.dev/pricing", - pricing_version="google-pricing-2026-07-07", + **_GOOGLE, ), - ( - "google", - "gemini-3.1-flash-lite", - ): PricingEntry( - input_cost_per_million=Decimal("0.25"), - output_cost_per_million=Decimal("1.50"), - cache_read_cost_per_million=Decimal("0.025"), - source="official_docs_snapshot", - source_url="https://ai.google.dev/pricing", - pricing_version="google-pricing-2026-07-07", - ), - ( - "google", - "gemini-3-pro-preview", - ): PricingEntry( - input_cost_per_million=Decimal("2.00"), - output_cost_per_million=Decimal("12.00"), - cache_read_cost_per_million=Decimal("0.20"), - source="official_docs_snapshot", - source_url="https://ai.google.dev/pricing", - pricing_version="google-pricing-2026-07-07", - ), - ( - "google", - "gemini-3-flash-preview", - ): PricingEntry( - input_cost_per_million=Decimal("0.50"), - output_cost_per_million=Decimal("3.00"), - cache_read_cost_per_million=Decimal("0.05"), - source="official_docs_snapshot", - source_url="https://ai.google.dev/pricing", - pricing_version="google-pricing-2026-07-07", - ), - ( - "google", - "gemini-2.5-pro", - ): PricingEntry( - input_cost_per_million=Decimal("1.25"), - output_cost_per_million=Decimal("10.00"), - cache_read_cost_per_million=Decimal("0.125"), + ("google", "gemini-3.1-flash-lite"): _snap("0.25", "1.50", "0.025", **_GOOGLE), + ("google", "gemini-3-pro-preview"): _snap("2.00", "12.00", "0.20", **_GOOGLE), + ("google", "gemini-3-flash-preview"): _snap("0.50", "3.00", "0.05", **_GOOGLE), + ("google", "gemini-2.5-pro"): _snap( + "1.25", "10.00", "0.125", tier_threshold_tokens=200_000, input_cost_per_million_above=Decimal("2.50"), output_cost_per_million_above=Decimal("15.00"), - source="official_docs_snapshot", - source_url="https://ai.google.dev/pricing", - pricing_version="google-pricing-2026-07-07", + **_GOOGLE, ), - ( - "google", - "gemini-2.5-flash", - ): PricingEntry( - input_cost_per_million=Decimal("0.15"), - output_cost_per_million=Decimal("0.60"), - cache_read_cost_per_million=Decimal("0.015"), - source="official_docs_snapshot", - source_url="https://ai.google.dev/pricing", - pricing_version="google-pricing-2026-07-07", - ), - ( - "google", - "gemini-2.0-flash", - ): PricingEntry( - input_cost_per_million=Decimal("0.10"), - output_cost_per_million=Decimal("0.40"), - cache_read_cost_per_million=Decimal("0.01"), - source="official_docs_snapshot", - source_url="https://ai.google.dev/pricing", - pricing_version="google-pricing-2026-07-07", - ), - # AWS Bedrock โ€” pricing per the Bedrock pricing page. - # Bedrock charges the same per-token rates as the model provider but - # through AWS billing. These are the on-demand prices (no commitment). - # Source: https://aws.amazon.com/bedrock/pricing/ - # Current-gen Claude Opus on Bedrock. Commercial Bedrock on-demand - # mirrors Anthropic's published list price for the Claude line - # ($5/$25 for Opus 4.6/4.7/4.8; cache write = 1.25x input at the - # 5-minute TTL, cache read = 0.1x input). NOTE: the AWS Price List API - # had not published these SKUs machine-readably as of 2026-07 โ€” these - # are commercial-list snapshots pending an authoritative machine source. - ( - "bedrock", - "anthropic.claude-opus-4-8", - ): PricingEntry( - input_cost_per_million=Decimal("5.00"), - output_cost_per_million=Decimal("25.00"), - cache_read_cost_per_million=Decimal("0.50"), - cache_write_cost_per_million=Decimal("6.25"), - source="official_docs_snapshot", - source_url="https://aws.amazon.com/bedrock/pricing/", - pricing_version="anthropic-list-2026-07", - ), - ( - "bedrock", - "anthropic.claude-opus-4-7", - ): PricingEntry( - input_cost_per_million=Decimal("5.00"), - output_cost_per_million=Decimal("25.00"), - cache_read_cost_per_million=Decimal("0.50"), - cache_write_cost_per_million=Decimal("6.25"), - source="official_docs_snapshot", - source_url="https://aws.amazon.com/bedrock/pricing/", - pricing_version="anthropic-list-2026-07", - ), - ( - "bedrock", - "anthropic.claude-opus-4-6", - ): PricingEntry( - input_cost_per_million=Decimal("5.00"), - output_cost_per_million=Decimal("25.00"), - cache_read_cost_per_million=Decimal("0.50"), - cache_write_cost_per_million=Decimal("6.25"), - source="official_docs_snapshot", - source_url="https://aws.amazon.com/bedrock/pricing/", - pricing_version="anthropic-list-2026-07", - ), - ( - "bedrock", - "anthropic.claude-sonnet-5", - ): PricingEntry( - input_cost_per_million=Decimal("3.00"), - output_cost_per_million=Decimal("15.00"), - cache_read_cost_per_million=Decimal("0.30"), - cache_write_cost_per_million=Decimal("3.75"), - source="official_docs_snapshot", - source_url="https://aws.amazon.com/bedrock/pricing/", - pricing_version="bedrock-pricing-2026-06", - ), - ( - "bedrock", - "anthropic.claude-sonnet-4-6", - ): PricingEntry( - input_cost_per_million=Decimal("3.00"), - output_cost_per_million=Decimal("15.00"), - cache_read_cost_per_million=Decimal("0.30"), - cache_write_cost_per_million=Decimal("3.75"), - source="official_docs_snapshot", - source_url="https://aws.amazon.com/bedrock/pricing/", - pricing_version="bedrock-pricing-2026-04", - ), - ( - "bedrock", - "anthropic.claude-sonnet-4-5", - ): PricingEntry( - input_cost_per_million=Decimal("3.00"), - output_cost_per_million=Decimal("15.00"), - cache_read_cost_per_million=Decimal("0.30"), - cache_write_cost_per_million=Decimal("3.75"), - source="official_docs_snapshot", - source_url="https://aws.amazon.com/bedrock/pricing/", - pricing_version="bedrock-pricing-2026-04", - ), - ( - "bedrock", - "anthropic.claude-haiku-4-5", - ): PricingEntry( - input_cost_per_million=Decimal("0.80"), - output_cost_per_million=Decimal("4.00"), - cache_read_cost_per_million=Decimal("0.08"), - cache_write_cost_per_million=Decimal("1.00"), - source="official_docs_snapshot", - source_url="https://aws.amazon.com/bedrock/pricing/", - pricing_version="bedrock-pricing-2026-04", - ), - ( - "bedrock", - "amazon.nova-pro", - ): PricingEntry( - input_cost_per_million=Decimal("0.80"), - output_cost_per_million=Decimal("3.20"), - source="official_docs_snapshot", - source_url="https://aws.amazon.com/bedrock/pricing/", - pricing_version="bedrock-pricing-2026-04", - ), - ( - "bedrock", - "amazon.nova-lite", - ): PricingEntry( - input_cost_per_million=Decimal("0.06"), - output_cost_per_million=Decimal("0.24"), - source="official_docs_snapshot", - source_url="https://aws.amazon.com/bedrock/pricing/", - pricing_version="bedrock-pricing-2026-04", - ), - ( - "bedrock", - "amazon.nova-micro", - ): PricingEntry( - input_cost_per_million=Decimal("0.035"), - output_cost_per_million=Decimal("0.14"), - source="official_docs_snapshot", - source_url="https://aws.amazon.com/bedrock/pricing/", - pricing_version="bedrock-pricing-2026-04", + ("google", "gemini-2.5-flash"): _snap("0.15", "0.60", "0.015", **_GOOGLE), + ("google", "gemini-2.0-flash"): _snap("0.10", "0.40", "0.01", **_GOOGLE), + # AWS Bedrock on-demand: same per-token rates as the model provider, billed + # through AWS. Current-gen Claude rows are commercial-list snapshots (the AWS + # Price List API had not published these SKUs machine-readably). + ("bedrock", "anthropic.claude-opus-4-8"): _snap("5.00", "25.00", "0.50", "6.25", **_BEDROCK_ANTHROPIC), + ("bedrock", "anthropic.claude-opus-4-7"): _snap("5.00", "25.00", "0.50", "6.25", **_BEDROCK_ANTHROPIC), + ("bedrock", "anthropic.claude-opus-4-6"): _snap("5.00", "25.00", "0.50", "6.25", **_BEDROCK_ANTHROPIC), + ("bedrock", "anthropic.claude-sonnet-5"): _snap( + "3.00", "15.00", "0.30", "3.75", url=_BEDROCK_URL, version="bedrock-pricing-2026-06" ), + ("bedrock", "anthropic.claude-sonnet-4-6"): _snap("3.00", "15.00", "0.30", "3.75", **_BEDROCK), + ("bedrock", "anthropic.claude-sonnet-4-5"): _snap("3.00", "15.00", "0.30", "3.75", **_BEDROCK), + ("bedrock", "anthropic.claude-haiku-4-5"): _snap("0.80", "4.00", "0.08", "1.00", **_BEDROCK), + ("bedrock", "amazon.nova-pro"): _snap("0.80", "3.20", **_BEDROCK), + ("bedrock", "amazon.nova-lite"): _snap("0.06", "0.24", **_BEDROCK), + ("bedrock", "amazon.nova-micro"): _snap("0.035", "0.14", **_BEDROCK), # MiniMax - ( - "minimax", - "minimax-m2.7", - ): PricingEntry( - input_cost_per_million=Decimal("0.30"), - output_cost_per_million=Decimal("1.20"), - source="official_docs_snapshot", - pricing_version="minimax-pricing-2026-04", - ), - ( - "minimax-cn", - "minimax-m2.7", - ): PricingEntry( - input_cost_per_million=Decimal("0.30"), - output_cost_per_million=Decimal("1.20"), - source="official_docs_snapshot", - pricing_version="minimax-pricing-2026-04", - ), - # Fireworks AI โ€” serverless pricing for the models hermes typically routes - # through when configured with provider="fireworks". Fireworks publishes a - # cached_input rate per model alongside input/output, which maps to - # cache_read_cost_per_million. No separately published cache_write rate. - # Snapshot of https://docs.fireworks.ai/serverless/pricing (Standard tier). - ( - "fireworks", - "kimi-k2p6", - ): PricingEntry( - input_cost_per_million=Decimal("0.95"), - output_cost_per_million=Decimal("4.00"), - cache_read_cost_per_million=Decimal("0.16"), - source="official_docs_snapshot", - source_url="https://docs.fireworks.ai/serverless/pricing", - pricing_version="fireworks-pricing-2026-07", - ), - ( - "fireworks", - "kimi-k2p7-code", - ): PricingEntry( - input_cost_per_million=Decimal("0.95"), - output_cost_per_million=Decimal("4.00"), - cache_read_cost_per_million=Decimal("0.19"), - source="official_docs_snapshot", - source_url="https://docs.fireworks.ai/serverless/pricing", - pricing_version="fireworks-pricing-2026-07", - ), - ( - "fireworks", - "glm-5p2", - ): PricingEntry( - input_cost_per_million=Decimal("1.40"), - output_cost_per_million=Decimal("4.40"), - cache_read_cost_per_million=Decimal("0.14"), - source="official_docs_snapshot", - source_url="https://docs.fireworks.ai/serverless/pricing", - pricing_version="fireworks-pricing-2026-07", - ), - ( - "fireworks", - "deepseek-v4-pro", - ): PricingEntry( - input_cost_per_million=Decimal("1.74"), - output_cost_per_million=Decimal("3.48"), - cache_read_cost_per_million=Decimal("0.145"), - source="official_docs_snapshot", - source_url="https://docs.fireworks.ai/serverless/pricing", - pricing_version="fireworks-pricing-2026-07", - ), - ( - "fireworks", - "deepseek-v4-flash", - ): PricingEntry( - input_cost_per_million=Decimal("0.14"), - output_cost_per_million=Decimal("0.28"), - cache_read_cost_per_million=Decimal("0.028"), - source="official_docs_snapshot", - source_url="https://docs.fireworks.ai/serverless/pricing", - pricing_version="fireworks-pricing-2026-07", - ), - ( - "fireworks", - "qwen3p7-plus", - ): PricingEntry( - input_cost_per_million=Decimal("0.40"), - output_cost_per_million=Decimal("1.60"), - cache_read_cost_per_million=Decimal("0.08"), - source="official_docs_snapshot", - source_url="https://docs.fireworks.ai/serverless/pricing", - pricing_version="fireworks-pricing-2026-07", - ), - ( - "fireworks", - "minimax-m3", - ): PricingEntry( - input_cost_per_million=Decimal("0.30"), - output_cost_per_million=Decimal("1.20"), - cache_read_cost_per_million=Decimal("0.06"), - source="official_docs_snapshot", - source_url="https://docs.fireworks.ai/serverless/pricing", - pricing_version="fireworks-pricing-2026-07", - ), - ( - "fireworks", - "gpt-oss-120b", - ): PricingEntry( - input_cost_per_million=Decimal("0.15"), - output_cost_per_million=Decimal("0.60"), - cache_read_cost_per_million=Decimal("0.015"), - source="official_docs_snapshot", - source_url="https://docs.fireworks.ai/serverless/pricing", - pricing_version="fireworks-pricing-2026-07", - ), - ( - "fireworks", - "gpt-oss-20b", - ): PricingEntry( - input_cost_per_million=Decimal("0.07"), - output_cost_per_million=Decimal("0.30"), - cache_read_cost_per_million=Decimal("0.035"), - source="official_docs_snapshot", - source_url="https://docs.fireworks.ai/serverless/pricing", - pricing_version="fireworks-pricing-2026-07", - ), - ( - "fireworks", - "glm-5p1", - ): PricingEntry( - input_cost_per_million=Decimal("1.40"), - output_cost_per_million=Decimal("4.40"), - cache_read_cost_per_million=Decimal("0.26"), - source="official_docs_snapshot", - source_url="https://docs.fireworks.ai/serverless/pricing", - pricing_version="fireworks-pricing-2026-07", - ), - ( - "fireworks", - "minimax-m2p7", - ): PricingEntry( - input_cost_per_million=Decimal("0.30"), - output_cost_per_million=Decimal("1.20"), - cache_read_cost_per_million=Decimal("0.06"), - source="official_docs_snapshot", - source_url="https://docs.fireworks.ai/serverless/pricing", - pricing_version="fireworks-pricing-2026-07", - ), - # Fast/turbo serving tiers โ€” exposed as accounts/fireworks/routers/, - # so rsplit("/", 1) yields these distinct ids with their own (higher) rates. - ( - "fireworks", - "kimi-k2p6-fast", - ): PricingEntry( - input_cost_per_million=Decimal("2.00"), - output_cost_per_million=Decimal("8.00"), - cache_read_cost_per_million=Decimal("0.30"), - source="official_docs_snapshot", - source_url="https://docs.fireworks.ai/serverless/pricing", - pricing_version="fireworks-pricing-2026-07", - ), - ( - "fireworks", - "kimi-k2p6-turbo", - ): PricingEntry( - input_cost_per_million=Decimal("2.00"), - output_cost_per_million=Decimal("8.00"), - cache_read_cost_per_million=Decimal("0.30"), - source="official_docs_snapshot", - source_url="https://docs.fireworks.ai/serverless/pricing", - pricing_version="fireworks-pricing-2026-07", - ), - ( - "fireworks", - "kimi-k2p7-code-fast", - ): PricingEntry( - input_cost_per_million=Decimal("1.90"), - output_cost_per_million=Decimal("8.00"), - cache_read_cost_per_million=Decimal("0.38"), - source="official_docs_snapshot", - source_url="https://docs.fireworks.ai/serverless/pricing", - pricing_version="fireworks-pricing-2026-07", - ), - ( - "fireworks", - "glm-5p2-fast", - ): PricingEntry( - input_cost_per_million=Decimal("2.10"), - output_cost_per_million=Decimal("6.60"), - cache_read_cost_per_million=Decimal("0.21"), - source="official_docs_snapshot", - source_url="https://docs.fireworks.ai/serverless/pricing", - pricing_version="fireworks-pricing-2026-07", - ), - ( - "fireworks", - "glm-5p1-fast", - ): PricingEntry( - input_cost_per_million=Decimal("2.80"), - output_cost_per_million=Decimal("8.80"), - cache_read_cost_per_million=Decimal("0.52"), - source="official_docs_snapshot", - source_url="https://docs.fireworks.ai/serverless/pricing", - pricing_version="fireworks-pricing-2026-07", - ), + ("minimax", "minimax-m2.7"): _snap("0.30", "1.20", version="minimax-pricing-2026-04"), + ("minimax-cn", "minimax-m2.7"): _snap("0.30", "1.20", version="minimax-pricing-2026-04"), + # Fireworks AI serverless (Standard tier). Fireworks publishes a per-model + # cached_input rate (โ†’ cache_read) but no separate cache_write rate. + ("fireworks", "kimi-k2p6"): _snap("0.95", "4.00", "0.16", **_FIREWORKS), + ("fireworks", "kimi-k2p7-code"): _snap("0.95", "4.00", "0.19", **_FIREWORKS), + ("fireworks", "glm-5p2"): _snap("1.40", "4.40", "0.14", **_FIREWORKS), + ("fireworks", "deepseek-v4-pro"): _snap("1.74", "3.48", "0.145", **_FIREWORKS), + ("fireworks", "deepseek-v4-flash"): _snap("0.14", "0.28", "0.028", **_FIREWORKS), + ("fireworks", "qwen3p7-plus"): _snap("0.40", "1.60", "0.08", **_FIREWORKS), + ("fireworks", "minimax-m3"): _snap("0.30", "1.20", "0.06", **_FIREWORKS), + ("fireworks", "gpt-oss-120b"): _snap("0.15", "0.60", "0.015", **_FIREWORKS), + ("fireworks", "gpt-oss-20b"): _snap("0.07", "0.30", "0.035", **_FIREWORKS), + ("fireworks", "glm-5p1"): _snap("1.40", "4.40", "0.26", **_FIREWORKS), + ("fireworks", "minimax-m2p7"): _snap("0.30", "1.20", "0.06", **_FIREWORKS), + # Fast/turbo tiers are exposed as accounts/fireworks/routers/, so + # rsplit("/", 1) yields these distinct ids with their own (higher) rates. + ("fireworks", "kimi-k2p6-fast"): _snap("2.00", "8.00", "0.30", **_FIREWORKS), + ("fireworks", "kimi-k2p6-turbo"): _snap("2.00", "8.00", "0.30", **_FIREWORKS), + ("fireworks", "kimi-k2p7-code-fast"): _snap("1.90", "8.00", "0.38", **_FIREWORKS), + ("fireworks", "glm-5p2-fast"): _snap("2.10", "6.60", "0.21", **_FIREWORKS), + ("fireworks", "glm-5p1-fast"): _snap("2.80", "8.80", "0.52", **_FIREWORKS), } +del _OPENAI_56, _ANTHROPIC, _OPENAI, _DEEPSEEK, _GOOGLE, _GOOGLE_NEW +del _BEDROCK_URL, _BEDROCK_ANTHROPIC, _BEDROCK, _FIREWORKS -# GPT-5.6 "-pro" high-effort variants bill at the same per-token rates as -# their base tiers (more tokens per task, not a higher rate). Alias them -# onto the base entries so the snapshot stays single-source. The Hermes-side -# "-900k" large-context Codex picker variants are the same underlying model -# (the suffix is stripped on the wire), so they alias identically. +# GPT-5.6 "-pro" high-effort variants bill at the base tier's per-token rates +# (more tokens per task, not a higher rate); the Hermes-side "-900k" Codex +# picker variants are the same model with the suffix stripped on the wire. +# Alias both onto the base entries so the snapshot stays single-source. for _base_56 in ("gpt-5.6-sol", "gpt-5.6-terra", "gpt-5.6-luna"): - _OFFICIAL_DOCS_PRICING[("openai", f"{_base_56}-pro")] = _OFFICIAL_DOCS_PRICING[ - ("openai", _base_56) - ] - _OFFICIAL_DOCS_PRICING[("openai", f"{_base_56}-900k")] = _OFFICIAL_DOCS_PRICING[ - ("openai", _base_56) - ] + _OFFICIAL_DOCS_PRICING[("openai", f"{_base_56}-pro")] = _OFFICIAL_DOCS_PRICING[("openai", _base_56)] + _OFFICIAL_DOCS_PRICING[("openai", f"{_base_56}-900k")] = _OFFICIAL_DOCS_PRICING[("openai", _base_56)] del _base_56 -# The direct Gemini provider currently exposes preview IDs for these two -# models. Keep the official snapshot keyed by both their documented stable -# names and the provider's emitted IDs so a catalog selection is billable. +# The direct Gemini provider emits preview IDs for these two models; key the +# snapshot by both the documented stable name and the emitted ID. for _alias, _canonical in { "gemini-3.1-pro-preview": "gemini-3.1-pro", "gemini-3.1-flash-lite-preview": "gemini-3.1-flash-lite", }.items(): - _OFFICIAL_DOCS_PRICING[("google", _alias)] = _OFFICIAL_DOCS_PRICING[ - ("google", _canonical) - ] + _OFFICIAL_DOCS_PRICING[("google", _alias)] = _OFFICIAL_DOCS_PRICING[("google", _canonical)] del _alias, _canonical @@ -1053,12 +320,10 @@ def _to_int(value: Any) -> int: def _usage_get(obj: Any, name: str, default: Any = 0) -> Any: - """Read a field from a usage object that may be a dict or an attribute object. + """Read a usage field from either a dict or an attribute object. - The Responses API can return usage as either a typed SDK object (accessible - via ``getattr``) or a plain ``dict`` (from JSON deserialisation). Using - ``getattr`` on a dict silently yields the default, zeroing out all token - counts. This helper normalises access so both shapes work transparently. + The Responses API returns usage as a typed SDK object OR a plain dict; + ``getattr`` on a dict silently yields the default and zeroes every count. """ if isinstance(obj, dict): return obj.get(name, default) @@ -1066,14 +331,28 @@ def _usage_get(obj: Any, name: str, default: Any = 0) -> Any: def _usage_count(value: Any) -> int: - """Coerce a usage counter to a non-negative integer. - - Providers occasionally emit malformed negative counters; clamp them to 0 - so a bad field cannot corrupt session accounting (#85706). - """ + """Coerce a usage counter to a non-negative int (providers occasionally + emit negative counters; clamp so they cannot corrupt session accounting).""" return max(0, _to_int(value)) +def _usage_field(obj: Any, name: str, *path: str) -> int: + """``_usage_count`` of ``obj.name[.path...]``; 0 if any hop is falsy.""" + for hop in (name, *path): + if not obj: + return 0 + obj = _usage_get(obj, hop, 0) + return _usage_count(obj) + + +def _first_nonzero(obj: Any, *paths: tuple[str, ...]) -> int: + """First non-zero ``_usage_field`` across candidate paths, else 0.""" + for path in paths: + value = _usage_field(obj, *path) + if value: + return value + return 0 + def resolve_billing_route( model_name: str, @@ -1089,77 +368,57 @@ def resolve_billing_route( provider_name = inferred_provider model = bare_model + url = base_url or "" + bare = model.split("/")[-1] + + def host(name: str) -> bool: + return base_url_host_matches(url, name) + if provider_name == "openai-codex": - return BillingRoute(provider="openai-codex", model=model, base_url=base_url or "", billing_mode="subscription_included") - if provider_name == "openrouter" or base_url_host_matches(base_url or "", "openrouter.ai"): - return BillingRoute(provider="openrouter", model=model, base_url=base_url or "", billing_mode="official_models_api") - if provider_name == "nous" or base_url_host_matches(base_url or "", "inference-api.nousresearch.com"): + return BillingRoute(provider="openai-codex", model=model, base_url=url, billing_mode="subscription_included") + if provider_name == "openrouter" or host("openrouter.ai"): + return BillingRoute(provider="openrouter", model=model, base_url=url, billing_mode="official_models_api") + if provider_name == "nous" or host("inference-api.nousresearch.com"): return BillingRoute(provider="nous", model=model, base_url=base_url or _NOUS_DEFAULT_BASE_URL, billing_mode="official_models_api") if provider_name == "anthropic": - return BillingRoute(provider="anthropic", model=model.split("/")[-1], base_url=base_url or "", billing_mode="official_docs_snapshot") - # "openai-api" is the picker/registry slug for direct api.openai.com; it - # bills identically to bare "openai", so normalize it here โ€” otherwise the - # ("openai", ) _OFFICIAL_DOCS_PRICING keys are unreachable from the - # openai-api provider path. + return BillingRoute(provider="anthropic", model=bare, base_url=url, billing_mode="official_docs_snapshot") + # "openai-api" is the picker slug for direct api.openai.com; it bills as + # bare "openai", whose keys the snapshot uses. if provider_name in {"openai", "openai-api"}: - return BillingRoute(provider="openai", model=model.split("/")[-1], base_url=base_url or "", billing_mode="official_docs_snapshot") + return BillingRoute(provider="openai", model=bare, base_url=url, billing_mode="official_docs_snapshot") if provider_name in {"minimax", "minimax-cn"}: - return BillingRoute(provider=provider_name, model=model.split("/")[-1], base_url=base_url or "", billing_mode="official_docs_snapshot") - # Google AI Studio (Gemini) and Vertex AI host the same Gemini models. - # Price them off the official docs snapshot โ€” the pricing keys are - # keyed on provider='google', so normalize every Google-flavored - # provider name/host onto it. Strip the "google/" vendor prefix the - # Vertex OpenAI-compat endpoint requires so the pricing key matches. + return BillingRoute(provider=provider_name, model=bare, base_url=url, billing_mode="official_docs_snapshot") + # AI Studio and Vertex host the same Gemini models; the snapshot is keyed on + # provider='google', and the Vertex "google/" vendor prefix is stripped. if ( provider_name in {"google", "gemini", "vertex", "google-gemini", "google-ai-studio", "google-vertex", "vertex-ai"} - or base_url_host_matches(base_url or "", "aiplatform.googleapis.com") - or base_url_host_matches(base_url or "", "generativelanguage.googleapis.com") + or host("aiplatform.googleapis.com") + or host("generativelanguage.googleapis.com") ): - return BillingRoute(provider="google", model=model.split("/")[-1], base_url=base_url or "", billing_mode="official_docs_snapshot") - if provider_name == "fireworks" or base_url_host_matches(base_url or "", "api.fireworks.ai"): - # Fireworks model ids look like accounts/fireworks/models/; - # rsplit("/", 1)[-1] yields just which is what the dict keys on. - return BillingRoute(provider="fireworks", model=model.rsplit("/", 1)[-1], base_url=base_url or "", billing_mode="official_docs_snapshot") + return BillingRoute(provider="google", model=bare, base_url=url, billing_mode="official_docs_snapshot") + if provider_name == "fireworks" or host("api.fireworks.ai"): + # Fireworks ids look like accounts/fireworks/models/; keys use . + return BillingRoute(provider="fireworks", model=model.rsplit("/", 1)[-1], base_url=url, billing_mode="official_docs_snapshot") if provider_name in {"custom", "local"} or (base and base_url_hostname(base) in ("localhost", "127.0.0.1")): - return BillingRoute(provider=provider_name or "custom", model=model, base_url=base_url or "", billing_mode="unknown") - return BillingRoute(provider=provider_name or "unknown", model=model.split("/")[-1] if model else "", base_url=base_url or "", billing_mode="unknown") + return BillingRoute(provider=provider_name or "custom", model=model, base_url=url, billing_mode="unknown") + return BillingRoute(provider=provider_name or "unknown", model=bare if model else "", base_url=url, billing_mode="unknown") def _normalize_bedrock_model_name(model: str) -> str: """Normalize a Bedrock model id to its bare foundation-model form. - Bedrock cross-region inference profiles prefix the foundation model id - with a region scope (``us.`` / ``global.`` / ``eu.`` / ``apac.`` / ``au.`` - / ...), e.g. ``us.anthropic.claude-opus-4-7`` or - ``au.anthropic.claude-sonnet-4-5-20250929-v1:0``. The pricing table is - keyed on the bare ``anthropic.claude-*`` id, so the prefix must be - stripped before the lookup or every cross-region session prices as - unknown. Note Asia-Pacific uses ``apac.`` (a bare ``ap.`` never matches - an ``apac.*`` id) and Australia/New Zealand use ``au.``. Also normalizes - dot-notation version numbers (``4.7`` โ†’ ``4-7``) and the documented - trailing date, revision, and profile components (``-20250514-v1:0``). + Cross-region inference profiles prefix the id with a region scope + (``us.``/``global.``/``apac.``/``au.``/...); the pricing table is keyed on + the bare ``anthropic.claude-*`` id, so the prefix is stripped. Also maps + dotted versions (``4.7`` โ†’ ``4-7``) and strips only the documented + trailing date/revision/profile components (``-20250514-v1:0``). """ name = model.lower().strip() - for prefix in ( - "global.", - "us.", - "eu.", - "apac.", - "ap.", - "au.", - "jp.", - "ca.", - "sa.", - "me.", - "af.", - ): + for prefix in ("global.", "us.", "eu.", "apac.", "ap.", "au.", "jp.", "ca.", "sa.", "me.", "af."): if name.startswith(prefix): name = name[len(prefix):] break name = re.sub(r"(\d+)\.(\d+)", r"\1-\2", name) - # Bedrock inference profile IDs append these documented components to the - # foundation model ID. Strip only the trailing forms, not arbitrary model - # name continuations that could be a distinct SKU. name = re.sub(r":\d+$", "", name) name = re.sub(r"-v\d+$", "", name) name = re.sub(r"-\d{8}$", "", name) @@ -1167,39 +426,26 @@ def _normalize_bedrock_model_name(model: str) -> str: def _normalize_anthropic_model_name(model: str) -> str: - """Normalize Anthropic model name variants to canonical form. - - Handles: - - Dot notation: claude-opus-4.7 โ†’ claude-opus-4-7 - - Short aliases: claude-opus-4.7 โ†’ claude-opus-4-7 - - Strips anthropic/ prefix if present - """ + """Strip an ``anthropic/`` prefix and map dotted versions (4.7 โ†’ 4-7).""" name = model.lower().strip() if name.startswith("anthropic/"): name = name[len("anthropic/"):] - # Normalize dots to dashes in version numbers (e.g. 4.7 โ†’ 4-7, 4.6 โ†’ 4-6) - # But preserve the rest of the name structure - name = re.sub(r"(\d+)\.(\d+)", r"\1-\2", name) - return name + return re.sub(r"(\d+)\.(\d+)", r"\1-\2", name) def _lookup_official_docs_pricing(route: BillingRoute) -> Optional[PricingEntry]: model = route.model.lower() - # Direct lookup first entry = _OFFICIAL_DOCS_PRICING.get((route.provider, model)) if entry: return entry - # Try normalized name for Anthropic (handles dot-notation like opus-4.7) - if route.provider == "anthropic": - normalized = _normalize_anthropic_model_name(model) - if normalized != model: - entry = _OFFICIAL_DOCS_PRICING.get((route.provider, normalized)) - if entry: - return entry - # Bedrock cross-region inference profiles carry a region prefix - # (us./global./eu./...) that the bare pricing keys don't have. - if route.provider == "bedrock": - normalized = _normalize_bedrock_model_name(model) + # Anthropic dot-notation (opus-4.7) and Bedrock region-prefixed ids need + # normalizing before a second lookup. + normalize = { + "anthropic": _normalize_anthropic_model_name, + "bedrock": _normalize_bedrock_model_name, + }.get(route.provider) + if normalize: + normalized = normalize(model) if normalized != model: entry = _OFFICIAL_DOCS_PRICING.get((route.provider, normalized)) if entry: @@ -1242,16 +488,14 @@ def _pricing_entry_from_metadata( if prompt is None and completion is None and request is None: return None - def _per_token_to_per_million(value: Optional[Decimal]) -> Optional[Decimal]: - if value is None: - return None - return value * _ONE_MILLION + def _per_million(value: Optional[Decimal]) -> Optional[Decimal]: + return None if value is None else value * _ONE_MILLION return PricingEntry( - input_cost_per_million=_per_token_to_per_million(prompt), - output_cost_per_million=_per_token_to_per_million(completion), - cache_read_cost_per_million=_per_token_to_per_million(cache_read), - cache_write_cost_per_million=_per_token_to_per_million(cache_write), + input_cost_per_million=_per_million(prompt), + output_cost_per_million=_per_million(completion), + cache_read_cost_per_million=_per_million(cache_read), + cache_write_cost_per_million=_per_million(cache_write), request_cost=request, source="provider_models_api", source_url=source_url, @@ -1298,132 +542,74 @@ def normalize_usage( ) -> CanonicalUsage: """Normalize raw API response usage into canonical token buckets. - Handles three API shapes: - - Anthropic: input_tokens/output_tokens/cache_read_input_tokens/cache_creation_input_tokens - - Codex Responses: input_tokens includes cache tokens; input_tokens_details.cached_tokens separates them - - OpenAI Chat Completions: prompt_tokens includes cache tokens; prompt_tokens_details.cached_tokens separates them - - In both Codex and OpenAI modes, input_tokens is derived by subtracting cache - tokens from the total โ€” the API contract is that input/prompt totals include - cached tokens and the details object breaks them out. + Three shapes: Anthropic (input/output/cache_read_input/cache_creation_input + tokens), Codex Responses and OpenAI Chat Completions. In the latter two the + input/prompt total INCLUDES cached tokens and the ``*_details`` object breaks + them out, so input_tokens is derived by subtraction. """ if not response_usage: return CanonicalUsage() provider_name = (provider or "").strip().lower() mode = (api_mode or "").strip().lower() + u = response_usage if mode == "anthropic_messages" or provider_name == "anthropic": - input_tokens = _usage_count(_usage_get(response_usage, "input_tokens", 0)) - output_tokens = _usage_count(_usage_get(response_usage, "output_tokens", 0)) - cache_read_tokens = _usage_count(_usage_get(response_usage, "cache_read_input_tokens", 0)) - cache_write_tokens = _usage_count( - _usage_get(response_usage, "cache_creation_input_tokens", 0) - ) + input_tokens = _usage_field(u, "input_tokens") + output_tokens = _usage_field(u, "output_tokens") + cache_read_tokens = _usage_field(u, "cache_read_input_tokens") + cache_write_tokens = _usage_field(u, "cache_creation_input_tokens") elif mode == "codex_responses": - input_total = _usage_count(_usage_get(response_usage, "input_tokens", 0)) - output_tokens = _usage_count(_usage_get(response_usage, "output_tokens", 0)) - details = _usage_get(response_usage, "input_tokens_details", None) - cache_read_tokens = _usage_count( - _usage_get(details, "cached_tokens", 0) if details else 0 + input_total = _usage_field(u, "input_tokens") + output_tokens = _usage_field(u, "output_tokens") + cache_read_tokens = _usage_field(u, "input_tokens_details", "cached_tokens") + # OpenAI's documented GPT-5.6+ field is `cache_write_tokens` (billed at + # 1.25x); `cache_creation_tokens` is a fallback for older endpoints. + cache_write_tokens = _first_nonzero( + u, + ("input_tokens_details", "cache_write_tokens"), + ("input_tokens_details", "cache_creation_tokens"), ) - # OpenAI's documented field for GPT-5.6+ explicit cache writes is - # `cache_write_tokens` (billed at 1.25x); `cache_creation_tokens` is - # kept as a fallback for older/alternate Responses-compatible - # endpoints (#70543). - cache_write_tokens = _usage_count( - _usage_get(details, "cache_write_tokens", 0) if details else 0 - ) - if not cache_write_tokens: - cache_write_tokens = _usage_count( - _usage_get(details, "cache_creation_tokens", 0) if details else 0 - ) input_tokens = max(0, input_total - cache_read_tokens - cache_write_tokens) else: - # OpenAI-style names first; fall back to Anthropic-style - # (input_tokens/output_tokens). Local OpenAI-compatible servers like - # mlx_vlm.server emit the Anthropic names in chat_completions responses, - # and the OpenAI Python client preserves them as extra attributes. - prompt_total = _usage_count( - _usage_get(response_usage, "prompt_tokens", 0) - ) or _usage_count(_usage_get(response_usage, "input_tokens", 0)) - output_tokens = _usage_count( - _usage_get(response_usage, "completion_tokens", 0) - ) or _usage_count(_usage_get(response_usage, "output_tokens", 0)) - details = _usage_get(response_usage, "prompt_tokens_details", None) - # Primary: OpenAI-style prompt_tokens_details. Fallback: Anthropic-style - # top-level fields that some OpenAI-compatible proxies (OpenRouter, Vercel - # AI Gateway, Cline) expose when routing Claude models โ€” without this - # fallback, cache writes are undercounted as 0 and cache reads can be - # missed when the proxy only surfaces them at the top level. - # Port of cline/cline#10266. - cache_read_tokens = _usage_count( - _usage_get(details, "cached_tokens", 0) if details else 0 + # OpenAI-style names first, then Anthropic-style: local OpenAI-compatible + # servers (e.g. mlx_vlm.server) emit input_tokens/output_tokens and the + # OpenAI client preserves them as extra attributes. + prompt_total = _first_nonzero(u, ("prompt_tokens",), ("input_tokens",)) + output_tokens = _first_nonzero(u, ("completion_tokens",), ("output_tokens",)) + # Cache reads: nested OpenAI shape, then Anthropic-style top-level fields + # exposed by proxies routing Claude (OpenRouter, Vercel AI Gateway, Cline), + # then DeepSeek's top-level prompt_cache_hit_tokens, then Kimi/Moonshot's + # top-level cached_tokens โ€” without these, direct sessions show 0 hits + # and bill hits at the full input rate. + cache_read_tokens = _first_nonzero( + u, + ("prompt_tokens_details", "cached_tokens"), + ("cache_read_input_tokens",), + ("prompt_cache_hit_tokens",), + ("cached_tokens",), ) - if not cache_read_tokens: - cache_read_tokens = _usage_count( - _usage_get(response_usage, "cache_read_input_tokens", 0) - ) - if not cache_read_tokens: - # DeepSeek's native API (api.deepseek.com) reports context-cache - # hits as top-level prompt_cache_hit_tokens (+ the complementary - # prompt_cache_miss_tokens; prompt_tokens = hit + miss), not the - # OpenAI nested shape. Without this, direct DeepSeek sessions - # always showed 0 cache-hit tokens (#61871). - cache_read_tokens = _usage_count( - _usage_get(response_usage, "prompt_cache_hit_tokens", 0) - ) - if not cache_read_tokens: - # Kimi/Moonshot's native API (api.moonshot.cn / .ai) reports - # context-cache hits as a top-level usage.cached_tokens, not the - # OpenAI nested prompt_tokens_details.cached_tokens shape. Without - # this, direct Kimi sessions always showed 0 cache-hit tokens and - # the hits were billed at the full input rate (#65722). - cache_read_tokens = _usage_count( - _usage_get(response_usage, "cached_tokens", 0) - ) - cache_write_tokens = _usage_count( - _usage_get(details, "cache_write_tokens", 0) if details else 0 + cache_write_tokens = _first_nonzero( + u, + ("prompt_tokens_details", "cache_write_tokens"), + ("prompt_tokens_details", "cache_creation_input_tokens"), + ("cache_creation_input_tokens",), + ("cache_write_tokens",), ) - if not cache_write_tokens: - cache_write_tokens = _usage_count( - _usage_get(details, "cache_creation_input_tokens", 0) - if details else 0 - ) - if not cache_write_tokens: - cache_write_tokens = _usage_count( - _usage_get(response_usage, "cache_creation_input_tokens", 0) - ) - if not cache_write_tokens: - cache_write_tokens = _usage_count( - _usage_get(response_usage, "cache_write_tokens", 0) - ) input_tokens = max(0, prompt_total - cache_read_tokens - cache_write_tokens) - reasoning_tokens = 0 - # Responses API shape: output_tokens_details.reasoning_tokens. - # Chat Completions shape (OpenAI, OpenRouter, DeepSeek, etc.): - # completion_tokens_details.reasoning_tokens. Reading only the former - # left reasoning_tokens=0 for every chat_completions reasoning model โ€” - # hidden thinking was invisible in session accounting even though it - # dominates output spend on models like deepseek-v4-flash (measured: - # single calls burning 21K reasoning tokens to emit 500 visible tokens). - output_details = _usage_get(response_usage, "output_tokens_details", None) - if output_details: - reasoning_tokens = _usage_count(_usage_get(output_details, "reasoning_tokens", 0)) - if not reasoning_tokens: - completion_details = _usage_get(response_usage, "completion_tokens_details", None) - if completion_details: - reasoning_tokens = _usage_count( - _usage_get(completion_details, "reasoning_tokens", 0) - ) + # Responses API: output_tokens_details.reasoning_tokens. Chat Completions + # (OpenAI, OpenRouter, DeepSeek, ...): completion_tokens_details.reasoning_tokens. + # Hidden thinking dominates output spend on reasoning models, so read both. + reasoning_tokens = _first_nonzero( + u, + ("output_tokens_details", "reasoning_tokens"), + ("completion_tokens_details", "reasoning_tokens"), + ) - # Cache observability for MiniMax's Anthropic wire: on MiniMax-M3, - # usage.cache_read_input_tokens carries a constant +128 floor and - # cache_creation_input_tokens is always 0, so cache_read is NOT a - # reliable hit signal โ€” the signal that survives is the input_tokens - # drop between consecutive calls. Standard level-gated logger.debug; - # enable via logging config to confirm cache behavior. + # On MiniMax-M3's Anthropic wire, cache_read_input_tokens carries a constant + # +128 floor and cache_creation is always 0, so cache_read is not a reliable + # hit signal; the input_tokens drop between consecutive calls is. # Docs: https://platform.minimax.io/docs/api-reference/text-prompt-caching if provider_name in {"minimax", "minimax-cn"} and mode == "anthropic_messages": logger.debug( @@ -1445,6 +631,10 @@ def normalize_usage( ) +def _unknown_cost(source: CostSource, *notes: str) -> CostResult: + return CostResult(amount_usd=None, status="unknown", source=source, label="n/a", notes=notes) + + def estimate_usage_cost( model_name: str, usage: CanonicalUsage, @@ -1466,22 +656,15 @@ def estimate_usage_cost( entry = get_pricing_entry(model_name, provider=provider, base_url=base_url, api_key=api_key) if not entry: - return CostResult(amount_usd=None, status="unknown", source="none", label="n/a") + return _unknown_cost("none") - notes: list[str] = [] - amount = _ZERO - - # Whole-request context-tier selection (e.g. Gemini Pro >200k prompts): - # once the prompt (input + cache read + cache write) exceeds the entry's - # threshold, the above-threshold rates apply to the entire request. Any - # tier rate left as None falls back to the base rate. + # Whole-request context tier (e.g. Gemini Pro >200k prompts): above the + # threshold the *_above rates apply to the entire request; None falls back. input_rate = entry.input_cost_per_million output_rate = entry.output_cost_per_million cache_read_rate = entry.cache_read_cost_per_million - if ( - entry.tier_threshold_tokens is not None - and usage.prompt_tokens > entry.tier_threshold_tokens - ): + cache_write_rate = entry.cache_write_cost_per_million + if entry.tier_threshold_tokens is not None and usage.prompt_tokens > entry.tier_threshold_tokens: if entry.input_cost_per_million_above is not None: input_rate = entry.input_cost_per_million_above if entry.output_cost_per_million_above is not None: @@ -1490,39 +673,27 @@ def estimate_usage_cost( cache_read_rate = entry.cache_read_cost_per_million_above if usage.input_tokens and input_rate is None: - return CostResult(amount_usd=None, status="unknown", source=entry.source, label="n/a") + return _unknown_cost(entry.source) if usage.output_tokens and output_rate is None: - return CostResult(amount_usd=None, status="unknown", source=entry.source, label="n/a") - if usage.cache_read_tokens: - if cache_read_rate is None: - return CostResult( - amount_usd=None, - status="unknown", - source=entry.source, - label="n/a", - notes=("cache-read pricing unavailable for route",), - ) - if usage.cache_write_tokens: - if entry.cache_write_cost_per_million is None: - return CostResult( - amount_usd=None, - status="unknown", - source=entry.source, - label="n/a", - notes=("cache-write pricing unavailable for route",), - ) + return _unknown_cost(entry.source) + if usage.cache_read_tokens and cache_read_rate is None: + return _unknown_cost(entry.source, "cache-read pricing unavailable for route") + if usage.cache_write_tokens and cache_write_rate is None: + return _unknown_cost(entry.source, "cache-write pricing unavailable for route") - if input_rate is not None: - amount += Decimal(usage.input_tokens) * input_rate / _ONE_MILLION - if output_rate is not None: - amount += Decimal(usage.output_tokens) * output_rate / _ONE_MILLION - if cache_read_rate is not None: - amount += Decimal(usage.cache_read_tokens) * cache_read_rate / _ONE_MILLION - if entry.cache_write_cost_per_million is not None: - amount += Decimal(usage.cache_write_tokens) * entry.cache_write_cost_per_million / _ONE_MILLION + amount = _ZERO + for tokens, rate in ( + (usage.input_tokens, input_rate), + (usage.output_tokens, output_rate), + (usage.cache_read_tokens, cache_read_rate), + (usage.cache_write_tokens, cache_write_rate), + ): + if rate is not None: + amount += Decimal(tokens) * rate / _ONE_MILLION if entry.request_cost is not None and usage.request_count: amount += Decimal(usage.request_count) * entry.request_cost + notes: list[str] = [] status: CostStatus = "estimated" label = format_cost_label(amount) if entry.source == "none" and amount == _ZERO: @@ -1550,17 +721,11 @@ def has_known_pricing( base_url: Optional[str] = None, api_key: Optional[str] = None, ) -> bool: - """Check whether we have pricing data for this model+route. - - Uses direct lookup instead of routing through the full estimation - pipeline โ€” avoids creating dummy usage objects just to check status. - """ + """True if pricing data exists for this model+route (direct lookup, no dummy usage).""" route = resolve_billing_route(model_name, provider=provider, base_url=base_url) if route.billing_mode == "subscription_included": return True - entry = get_pricing_entry(model_name, provider=provider, base_url=base_url, api_key=api_key) - return entry is not None - + return get_pricing_entry(model_name, provider=provider, base_url=base_url, api_key=api_key) is not None def format_duration_compact(seconds: float) -> str: @@ -1573,8 +738,7 @@ def format_duration_compact(seconds: float) -> str: if hours < 24: remaining_min = int(minutes % 60) return f"{int(hours)}h {remaining_min}m" if remaining_min else f"{int(hours)}h" - days = hours / 24 - return f"{days:.1f}d" + return f"{hours / 24:.1f}d" def format_token_count_compact(value: int) -> str: @@ -1583,18 +747,10 @@ def format_token_count_compact(value: int) -> str: return str(int(value)) sign = "-" if value < 0 else "" - units = ((1_000_000_000, "B"), (1_000_000, "M"), (1_000, "K")) - for threshold, suffix in units: + for threshold, suffix in ((1_000_000_000, "B"), (1_000_000, "M"), (1_000, "K")): if abs_value >= threshold: scaled = abs_value / threshold - if scaled < 10: - text = f"{scaled:.2f}" - elif scaled < 100: - text = f"{scaled:.1f}" - else: - text = f"{scaled:.0f}" + text = f"{scaled:.2f}" if scaled < 10 else f"{scaled:.1f}" if scaled < 100 else f"{scaled:.0f}" if "." in text: text = text.rstrip("0").rstrip(".") return f"{sign}{text}{suffix}" - - return f"{value:,}" diff --git a/tests/agent/test_reasoning_effort_module.py b/tests/agent/test_reasoning_effort_module.py index dc04406a1f..16fdf1451c 100644 --- a/tests/agent/test_reasoning_effort_module.py +++ b/tests/agent/test_reasoning_effort_module.py @@ -16,7 +16,7 @@ supported vocabulary. The policy under test: import pytest from agent.reasoning_effort import ( - CODEX_RESPONSES_EFFORTS, + CODEX_GPT56_EFFORTS, EFFORT_LADDER, GLM52_EFFORTS, GLM52_OVERRIDES, @@ -137,8 +137,8 @@ class TestGlm52Vocabulary: class TestCodexVocabulary: def test_minimal_and_ultra(self): - assert clamp_effort("minimal", CODEX_RESPONSES_EFFORTS) == "low" - assert clamp_effort("ultra", CODEX_RESPONSES_EFFORTS) == "max" + assert clamp_effort("minimal", CODEX_GPT56_EFFORTS) == "low" + assert clamp_effort("ultra", CODEX_GPT56_EFFORTS) == "max" def test_per_model_max_support(self): """Live-verified (Aug 2026, #68365): 'max' is gpt-5.6-only โ€” gpt-5.5