billing_usage.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. """Shared dollar-denominated usage model for the ``/usage`` and ``/subscription`` bars.
  2. Terminal surfaces show **dollars**, never "credits"; the plan allowance and top-up
  3. dollars stay distinctly visible as two SEPARATE bars (a three-segment bar is
  4. unreadable at terminal widths). Source: ``NousPortalAccountInfo.paid_service_access_info``
  5. (USD floats despite the legacy ``*_credits`` names) plus ``subscription.monthly_credits``
  6. (plan bar denominator) and ``current_period_end``. Fail-open: missing/non-finite fields
  7. degrade to fewer bars; logged-out / unreachable portal yields ``available=False``.
  8. """
  9. from __future__ import annotations
  10. import logging
  11. import math
  12. import os
  13. from dataclasses import dataclass
  14. from typing import Any, Optional
  15. from hermes_time import safe_strftime
  16. logger = logging.getLogger(__name__)
  17. # Below this TOTAL spendable ($) a paid account is flagged "low" — the alert state
  18. # that nudges top-up/upgrade before a mid-run cutoff (product: "below $5 is an alert").
  19. LOW_BALANCE_THRESHOLD_USD = 5.0
  20. def _finite(value: Any) -> Optional[float]:
  21. """Float iff a real finite number (not bool/NaN/Inf); json.loads admits bare NaN, which would render ``$nan``."""
  22. if isinstance(value, bool) or not isinstance(value, (int, float)):
  23. return None
  24. f = float(value)
  25. return f if math.isfinite(f) else None
  26. def _fmt_usd(value: Optional[float]) -> str:
  27. """``$X,XXX.YY`` for display. ``None`` -> ``$0.00`` (callers gate on presence)."""
  28. return f"${(value or 0.0):,.2f}"
  29. def nous_logged_in() -> bool:
  30. """Cheap local auth-state check: a Nous access token is present. Fail-closed."""
  31. try:
  32. from hermes_cli.auth import get_provider_auth_state
  33. tok = (get_provider_auth_state("nous") or {}).get("access_token")
  34. return isinstance(tok, str) and bool(tok.strip())
  35. except Exception:
  36. return False
  37. def fetch_nous_account(timeout: float):
  38. """Wall-clock-bounded fresh portal account fetch. Raises on failure/timeout.
  39. Shares the one bounded implementation so a stalled portal releases the
  40. /billing surface at ``timeout`` too (see ``_fetch_portal_account``)."""
  41. from agent.account_usage import _fetch_portal_account
  42. return _fetch_portal_account(timeout)
  43. def format_renews(value: Optional[str]) -> Optional[str]:
  44. """ISO date/timestamp -> ``Jul 24, 2026``; unparseable input is returned unchanged."""
  45. from datetime import datetime
  46. text = str(value or "").strip()
  47. if not text:
  48. return None
  49. iso = text[:-1] + "+00:00" if text.endswith("Z") else text
  50. try:
  51. dt = datetime.fromisoformat(iso)
  52. except ValueError:
  53. try:
  54. dt = datetime.strptime(text[:10], "%Y-%m-%d")
  55. except ValueError:
  56. return text
  57. # %-d isn't portable to Windows; build the day without a leading zero.
  58. return f"{safe_strftime(dt, '%b')} {dt.day}, {dt.year}"
  59. @dataclass(frozen=True)
  60. class UsageBar:
  61. """One bar: ``spent`` of ``total`` plus remaining. ``plan`` shows % used; ``topup`` has no
  62. denominator (``spent`` is 0 and ``total == remaining`` so it renders full)."""
  63. kind: str # "plan" | "topup"
  64. remaining_usd: float
  65. total_usd: float
  66. spent_usd: float = 0.0
  67. @property
  68. def pct_used(self) -> Optional[int]:
  69. if self.kind != "plan" or self.total_usd <= 0:
  70. return None
  71. return max(0, min(100, round(self.spent_usd / self.total_usd * 100)))
  72. @property
  73. def fill_fraction(self) -> float:
  74. """Fraction of the bar that should read as 'remaining' (filled)."""
  75. return max(0.0, min(1.0, self.remaining_usd / self.total_usd)) if self.total_usd > 0 else 0.0
  76. @dataclass(frozen=True)
  77. class UsageModel:
  78. """Dollar usage model shared by /usage and /subscription. ``status``: ``free`` (no plan / no
  79. paid access), ``low`` (spendable < $5, ALERT), ``healthy`` (>= $5), ``depleted`` (paid access lost)."""
  80. available: bool
  81. status: str = "free"
  82. plan_name: Optional[str] = None
  83. renews_at: Optional[str] = None
  84. renews_display: Optional[str] = None
  85. subscription_remaining_usd: Optional[float] = None
  86. topup_remaining_usd: Optional[float] = None
  87. total_spendable_usd: Optional[float] = None
  88. plan_bar: Optional[UsageBar] = None
  89. topup_bar: Optional[UsageBar] = None
  90. @property
  91. def has_topup(self) -> bool:
  92. return bool(self.topup_remaining_usd and self.topup_remaining_usd > 0)
  93. def usage_model_from_account(account_info: Any) -> UsageModel:
  94. """Build a :class:`UsageModel` from a ``NousPortalAccountInfo``. Never raises."""
  95. try:
  96. if account_info is None or not getattr(account_info, "logged_in", False):
  97. return UsageModel(available=False)
  98. # Usage-window plans have no monthly credit grant, so the credit bars don't apply;
  99. # /usage falls through to the percent-window renderer instead. A partial/empty block is not a
  100. # window plan (same completeness rule as the credits seed).
  101. from agent.credits_tracker import _window_seed_fields
  102. if _window_seed_fields(getattr(account_info, "usage_window", None)) is not None:
  103. return UsageModel(available=False)
  104. # Sub-structs are dataclasses or None; getattr(None, ..., None) is None, so no guards needed.
  105. access = getattr(account_info, "paid_service_access_info", None)
  106. sub = getattr(account_info, "subscription", None)
  107. paid = getattr(account_info, "paid_service_access", None)
  108. sub_remaining = _finite(getattr(access, "subscription_credits_remaining", None))
  109. topup_remaining = _finite(getattr(access, "purchased_credits_remaining", None))
  110. total_usable = _finite(getattr(access, "total_usable_credits", None))
  111. plan_name = getattr(sub, "plan", None)
  112. renews_at = getattr(sub, "current_period_end", None)
  113. monthly = _finite(getattr(sub, "monthly_credits", None))
  114. has_subscription = bool(plan_name) or (monthly is not None and monthly > 0)
  115. has_topup = bool(topup_remaining and topup_remaining > 0)
  116. # Prefer the server's total; else sum the parts we have.
  117. parts = [v for v in (sub_remaining, topup_remaining) if v is not None]
  118. total_spendable = total_usable if total_usable is not None else (sum(parts) if parts else None)
  119. if paid is False:
  120. status = "depleted"
  121. elif not has_subscription and not has_topup:
  122. status = "free" # no plan and no purchased balance -> free-models-only
  123. elif total_spendable is not None and total_spendable < LOW_BALANCE_THRESHOLD_USD:
  124. status = "low"
  125. else:
  126. status = "healthy"
  127. # Plan bar needs a positive allowance AND a remaining to place on it; spent is
  128. # clamped so a debt/over-cap balance reads fully spent, not negative.
  129. plan_bar = topup_bar = None
  130. if monthly is not None and monthly > 0 and sub_remaining is not None:
  131. plan_bar = UsageBar(kind="plan", remaining_usd=max(0.0, min(monthly, sub_remaining)), total_usd=monthly,
  132. spent_usd=max(0.0, monthly - sub_remaining))
  133. # Top-up has no monthly cap, so the bar renders full = balance.
  134. if topup_remaining is not None and topup_remaining > 0:
  135. topup_bar = UsageBar(kind="topup", remaining_usd=topup_remaining, total_usd=topup_remaining, spent_usd=0.0)
  136. return UsageModel(
  137. available=True, status=status, plan_name=plan_name, renews_at=renews_at,
  138. renews_display=format_renews(renews_at), subscription_remaining_usd=sub_remaining,
  139. topup_remaining_usd=topup_remaining, total_spendable_usd=total_spendable,
  140. plan_bar=plan_bar, topup_bar=topup_bar,
  141. )
  142. except Exception:
  143. logger.debug("usage ▸ model build failed (fail-open)", exc_info=True)
  144. return UsageModel(available=False)
  145. def build_usage_model(*, timeout: float = 10.0) -> UsageModel:
  146. """Fetch account-info and build the usage model; fail-open. ``HERMES_DEV_CREDITS_FIXTURE`` short-circuits to a fixture."""
  147. fixture = _dev_fixture_usage_model()
  148. if fixture is not None:
  149. return fixture
  150. if not nous_logged_in():
  151. return UsageModel(available=False)
  152. try:
  153. return usage_model_from_account(fetch_nous_account(timeout))
  154. except Exception:
  155. logger.debug("usage ▸ portal fetch failed (fail-open)", exc_info=True)
  156. return UsageModel(available=False)
  157. def _plan_bar(remaining: float, spent: float) -> UsageBar:
  158. return UsageBar(kind="plan", remaining_usd=remaining, total_usd=20.0, spent_usd=spent)
  159. def _dev_fixture_usage_model() -> Optional[UsageModel]:
  160. """``HERMES_DEV_CREDITS_FIXTURE`` -> fixture model (``free|healthy|low|topup|depleted``), else None."""
  161. name = (os.getenv("HERMES_DEV_CREDITS_FIXTURE") or "").strip().lower()
  162. name = {"mid": "healthy", "top-up": "topup"}.get(name, name)
  163. plus = dict(available=True, plan_name="Plus", renews_at="2026-07-01")
  164. specs: dict[str, dict] = {
  165. "free": dict(available=True, status="free", plan_name=None),
  166. "healthy": dict(**plus, status="healthy", subscription_remaining_usd=14.0, total_spendable_usd=14.0, plan_bar=_plan_bar(14.0, 6.0)),
  167. "topup": dict(
  168. **plus, status="healthy", subscription_remaining_usd=14.0, topup_remaining_usd=12.0,
  169. total_spendable_usd=26.0, plan_bar=_plan_bar(14.0, 6.0),
  170. topup_bar=UsageBar(kind="topup", remaining_usd=12.0, total_usd=12.0, spent_usd=0.0),
  171. ),
  172. "low": dict(**plus, status="low", subscription_remaining_usd=3.4, total_spendable_usd=3.4, plan_bar=_plan_bar(3.4, 16.6)),
  173. "depleted": dict(**plus, status="depleted", subscription_remaining_usd=0.0, total_spendable_usd=0.0, plan_bar=_plan_bar(0.0, 20.0)),
  174. }
  175. spec = specs.get(name)
  176. return UsageModel(**spec) if spec else None