nous_billing.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. """Nous Portal Remote Spending HTTP client.
  2. Thin, fail-loud client for the ``/api/billing/*`` endpoints the terminal billing screens drive.
  3. ``nous_account.py`` owns read-only entitlement/balance; this module owns the *write* side: buy
  4. credits, poll a charge, configure auto-reload, change plan. Money is decimal, never float: the
  5. server emits decimal STRINGS (``"142.5"``), parsed with :class:`decimal.Decimal` by callers.
  6. """
  7. from __future__ import annotations
  8. import json
  9. import os
  10. import time
  11. import urllib.error
  12. import urllib.parse
  13. import urllib.request
  14. from typing import Any, Optional
  15. DEFAULT_PORTAL_BASE_URL = "https://portal.nousresearch.com"
  16. DEFAULT_TIMEOUT = 15.0 # tight so a hung portal doesn't freeze the TUI (charge/poll calls are quick)
  17. # --- Typed errors ---
  18. class BillingError(Exception):
  19. """A billing HTTP call failed; carries server ``error`` code, HTTP ``status``, the ``portalUrl``
  20. deep-link (present on every gate denial), ``retry_after`` seconds (429/503) and the parsed ``payload``.
  21. """
  22. def __init__(
  23. self, message: str, *, status: Optional[int] = None, error: Optional[str] = None,
  24. portal_url: Optional[str] = None, retry_after: Optional[int] = None,
  25. payload: Optional[dict[str, Any]] = None, actor: Optional[str] = None,
  26. code: Optional[str] = None, recovery: Optional[str] = None,
  27. ) -> None:
  28. super().__init__(message)
  29. self.status, self.error, self.portal_url, self.retry_after = status, error, portal_url, retry_after
  30. self.payload = payload or {}
  31. # Remote-Spending contract extras: `actor` (self|admin) on a revoke, `code` (machine code
  32. # dual-emitted alongside `error`), `recovery` (reconnect|login|enable_account_toggle).
  33. # Additive — absent on older NAS / unrelated errors.
  34. self.actor, self.code, self.recovery = actor, code, recovery
  35. class BillingScopeRequired(BillingError):
  36. """``403 insufficient_scope`` — the held token lacks ``billing:manage``; the lazy step-up trigger
  37. (catching it kicks off a device-connect requesting the scope — an ADMIN must select "Allow Remote
  38. Spending"). Also fires mid-session if the scope is stripped on refresh after the user loses ADMIN.
  39. """
  40. class BillingAuthError(BillingError):
  41. """``401`` — missing/invalid bearer token (not logged in / expired)."""
  42. class BillingRemoteSpendingRevoked(BillingError):
  43. """``403 remote_spending_revoked`` — THIS terminal's spending was revoked (still logged in; only
  44. the money path is cut, unlike ``insufficient_scope``/``session_revoked``). ``actor`` is
  45. ``"admin"``/``"self"`` (absent → ``"self"``); recovery is **reconnect** (re-consent device-auth).
  46. """
  47. class BillingSessionRevoked(BillingAuthError):
  48. """``401 session_revoked`` — the whole session was logged out; recovery is **re-login**. A
  49. :class:`BillingAuthError` so 401 handling still treats it as not-logged-in, with typed copy.
  50. """
  51. class BillingTransient(BillingError):
  52. """Deterministic non-charge outcome: the request definitely did NOT complete at Stripe, so a
  53. retry after backoff is always safe — never the "maybe charged" ambiguity of a real 5xx/timeout.
  54. Covers 429 rate limiting, 503 gate-unavailable, Stripe down, and the daily upgrade cap.
  55. """
  56. class BillingRateLimited(BillingTransient):
  57. """``429 rate_limited`` or ``503 temporarily_unavailable`` — NOT a payment failure. Carries
  58. ``retry_after``; never auto-retry-spam (limiter is 5/org/hr + 5/token/hr). A 503 is the gate
  59. failing closed — back off, do NOT treat as revoked.
  60. """
  61. class BillingStripeUnavailable(BillingTransient):
  62. """``503 stripe_unavailable`` — Stripe itself is down; retry using Retry-After. Not our rate
  63. limiter: surfaces must read ``.error`` and not render "rate limited" copy.
  64. """
  65. class BillingUpgradeCapExceeded(BillingTransient):
  66. """``429 upgrade_cap_exceeded`` — the org hit its 5-upgrades/day cap. Same status as the hourly
  67. ``rate_limited`` cap but no useful short backoff; a sibling (not subclass) of BillingRateLimited.
  68. """
  69. # --- Base-URL + auth resolution ---
  70. def resolve_portal_base_url(state: Optional[dict[str, Any]] = None) -> str:
  71. """Resolve the portal base URL with login-time precedence: env, stored state, default."""
  72. from hermes_cli.auth_nous import _nous_portal_env_override
  73. env = _nous_portal_env_override()
  74. for candidate in (env, state.get("portal_base_url") if state else None):
  75. if isinstance(candidate, str) and candidate.strip():
  76. return candidate.strip().rstrip("/")
  77. return DEFAULT_PORTAL_BASE_URL
  78. def _absolutize_portal_url(portal_url: Optional[str]) -> Optional[str]:
  79. """Resolve a (possibly relative) server portalUrl against the client's portal base.
  80. The server emits ``portalUrl`` relative by design; absolute URLs pass through unchanged. urljoin
  81. needs the trailing slash on the base to join an absolute path like "/billing?..." to the host.
  82. """
  83. if not (isinstance(portal_url, str) and portal_url.strip()):
  84. return portal_url
  85. return urllib.parse.urljoin(resolve_portal_base_url().rstrip("/") + "/", portal_url)
  86. # Short-lived cache for the resolved (token, base): `resolve_nous_access_token` takes two
  87. # cross-process file locks + reads two files per call, wasteful for the 2s charge poll loop
  88. # (~150 calls per purchase). The resolver only returns tokens with >=120s of life (its refresh
  89. # skew), so a 30s cache can never hand back an about-to-expire token; a 401 still surfaces.
  90. # Keyed by hermes_home_key() so a multiplex profile never bills through a sibling's token.
  91. _TOKEN_CACHE_TTL_SECONDS = 30.0
  92. _token_cache: dict[str, tuple[float, str, str]] = {} # home key -> (cached_at, token, base)
  93. def invalidate_cached_token() -> None:
  94. """Bust the token cache so post-step-up replays use the freshly-scoped token.
  95. ``_request`` only self-busts on a 401, not on a 403 scope denial — after a step-up grant the
  96. cache would otherwise still hold the pre-grant unscoped token and the replay would 403 again.
  97. """
  98. _token_cache.clear()
  99. def _billing_not_logged_in(exc: Optional[BaseException] = None) -> BillingAuthError:
  100. """Build the canonical 'not logged in' BillingAuthError (single source)."""
  101. err = BillingAuthError("Not logged into Nous Portal — run `hermes portal` to log in.", status=401, error="invalid_token")
  102. if exc is not None:
  103. err.__cause__ = exc
  104. return err
  105. def _resolve_token_and_base(*, use_cache: bool = True) -> tuple[str, str]:
  106. """``(access_token, portal_base_url)``, cached for ``_TOKEN_CACHE_TTL_SECONDS`` unless ``use_cache=False``."""
  107. from hermes_constants import hermes_home_key
  108. cache_key = hermes_home_key()
  109. cached = _token_cache.get(cache_key) if use_cache else None
  110. if cached is not None:
  111. cached_at, token, base = cached
  112. if (time.time() - cached_at) < _TOKEN_CACHE_TTL_SECONDS:
  113. return token, base
  114. try:
  115. from hermes_cli.auth import get_provider_auth_state
  116. state = get_provider_auth_state("nous") or {}
  117. except Exception:
  118. state = {}
  119. base = resolve_portal_base_url(state)
  120. try:
  121. from hermes_cli.auth import AuthError, resolve_nous_access_token
  122. except ImportError:
  123. # auth module unavailable — fall back to the raw stored token.
  124. token = state.get("access_token")
  125. if not (isinstance(token, str) and token.strip()):
  126. raise _billing_not_logged_in()
  127. else:
  128. try:
  129. token = resolve_nous_access_token()
  130. except AuthError as exc:
  131. raise _billing_not_logged_in(exc) from exc
  132. resolved = (token.strip(), base)
  133. _token_cache[cache_key] = (time.time(), *resolved)
  134. return resolved
  135. # --- HTTP plumbing ---
  136. def _retry_after_seconds(headers: Any) -> Optional[int]:
  137. """Parse a ``Retry-After`` header (integer seconds) — None if absent/bad."""
  138. from agent.retry_utils import parse_retry_after_seconds
  139. seconds = parse_retry_after_seconds(headers)
  140. return None if seconds is None else int(seconds)
  141. # Error routing for _raise_for_error: server ``error`` code alone, then (status, error), then
  142. # status alone, then the generic fallback. Values: (exception class, fallback message when the
  143. # server sent no ``message``). Business 403s (cli_billing_disabled / role_required /
  144. # no_payment_method / monthly_cap_exceeded / …) fall through to a generic BillingError carrying
  145. # code/recovery, using the raw error code as the message.
  146. _ERRORS_BY_CODE: dict[str, tuple[type[BillingError], str]] = {
  147. "stripe_unavailable": (BillingStripeUnavailable, "Stripe is temporarily unavailable — try again shortly."),
  148. "upgrade_cap_exceeded": (BillingUpgradeCapExceeded, "Daily plan-change limit reached — try again tomorrow."),
  149. }
  150. _ERRORS_BY_STATUS_CODE: dict[tuple[int, str], tuple[type[BillingError], str]] = {
  151. (401, "session_revoked"): (BillingSessionRevoked, "Your session was logged out — log in again."),
  152. (403, "remote_spending_revoked"): (BillingRemoteSpendingRevoked, "Remote spending was stopped for this terminal."),
  153. (403, "insufficient_scope"): (BillingScopeRequired, "This action needs the billing:manage scope."),
  154. }
  155. _ERRORS_BY_STATUS: dict[int, tuple[type[BillingError], str]] = {
  156. 401: (BillingAuthError, "Authentication required."),
  157. 403: (BillingError, "Billing request denied."),
  158. 429: (BillingRateLimited, "Rate limited — try again shortly."),
  159. 503: (BillingRateLimited, "Rate limited — try again shortly."),
  160. }
  161. def _raise_for_error(status: int, payload: dict[str, Any], headers: Any = None) -> None:
  162. """Map an HTTP error response to the right typed :class:`BillingError` (see tables above).
  163. Recognizes the Remote-Spending gate contract (NAS PR #481): 403 ``remote_spending_revoked`` (this
  164. terminal's spend revoked → reconnect), 401 ``session_revoked`` (full logout → re-login), 503
  165. ``temporarily_unavailable`` (gate fail-closed → back off, NOT revoked). The business-denial codes
  166. (``cli_billing_disabled`` + dual ``code:remote_spending_disabled``, ``role_required``,
  167. ``idempotency_conflict``, …) flow through as a generic BillingError carrying
  168. ``error``/``code``/``recovery`` for the surface to map.
  169. """
  170. p = payload if isinstance(payload, dict) else {}
  171. error = p.get("error")
  172. common = {
  173. "status": status, "error": error, "portal_url": _absolutize_portal_url(p.get("portalUrl")),
  174. "retry_after": _retry_after_seconds(headers), "payload": p,
  175. "actor": p.get("actor"), "code": p.get("code"), "recovery": p.get("recovery"),
  176. }
  177. key = error if isinstance(error, str) else None
  178. cls, fallback = (
  179. _ERRORS_BY_CODE.get(key)
  180. or _ERRORS_BY_STATUS_CODE.get((status, key))
  181. or _ERRORS_BY_STATUS.get(status)
  182. or (BillingError, f"Billing request failed ({status}).")
  183. )
  184. raise cls(p.get("message") or (error if cls is BillingError else None) or fallback, **common)
  185. def _request(
  186. method: str, path: str, *, body: Optional[dict[str, Any]] = None,
  187. extra_headers: Optional[dict[str, str]] = None, timeout: float = DEFAULT_TIMEOUT, _retried_auth: bool = False,
  188. ) -> dict[str, Any]:
  189. """Authenticated billing request -> parsed JSON dict (``{}`` for an empty 2xx body).
  190. Raises a typed :class:`BillingError` on any non-2xx or transport failure. A 401 triggers exactly
  191. one retry with a freshly-resolved token so a cached-but-just-expired token self-heals.
  192. """
  193. token, base = _resolve_token_and_base(use_cache=not _retried_auth)
  194. headers = {"Authorization": f"Bearer {token}", "Accept": "application/json"}
  195. if body is not None:
  196. headers["Content-Type"] = "application/json"
  197. headers.update(extra_headers or {})
  198. data = json.dumps(body).encode("utf-8") if body is not None else None
  199. req = urllib.request.Request(f"{base}{path}", data=data, headers=headers, method=method)
  200. try:
  201. with urllib.request.urlopen(req, timeout=timeout) as resp:
  202. raw = resp.read().decode("utf-8")
  203. if not raw.strip():
  204. return {}
  205. try:
  206. return json.loads(raw)
  207. except json.JSONDecodeError as exc:
  208. # A 2xx non-JSON body (SPA/reverse-proxy fallback HTML when the route isn't
  209. # deployed) is a typed non-auth error so callers degrade to "unavailable".
  210. raise BillingError(
  211. "Billing endpoint returned a non-JSON response (it may not be available on this deployment).",
  212. error="endpoint_unavailable", status=getattr(resp, "status", None),
  213. ) from exc
  214. except urllib.error.HTTPError as exc:
  215. # 401 on a cached token → drop the cache and retry once with a fresh (refresh-aware) resolve.
  216. if exc.code == 401 and not _retried_auth:
  217. invalidate_cached_token()
  218. return _request(method, path, body=body, extra_headers=extra_headers, timeout=timeout, _retried_auth=True)
  219. try:
  220. raw = exc.read().decode("utf-8")
  221. except Exception:
  222. raw = ""
  223. try:
  224. payload = json.loads(raw) if raw.strip() else {}
  225. except json.JSONDecodeError:
  226. payload = {}
  227. _raise_for_error(exc.code, payload, getattr(exc, "headers", None))
  228. raise # unreachable; _raise_for_error always raises
  229. except urllib.error.URLError as exc:
  230. raise BillingError(f"Could not reach Nous Portal: {exc.reason}", error="network_error") from exc
  231. except TimeoutError as exc:
  232. # urlopen() wraps CONNECT-phase timeouts in URLError, but a timeout during resp.read()
  233. # surfaces as a bare TimeoutError — normalize to the typed-BillingError contract.
  234. raise BillingError("Could not reach Nous Portal: timed out", error="network_error") from exc
  235. # --- Endpoints ---
  236. def _require_str(value: Any, message: str, error: str) -> str:
  237. """Return ``value.strip()`` or raise a typed BillingError when it is not a non-blank str."""
  238. if not (isinstance(value, str) and value.strip()):
  239. raise BillingError(message, error=error)
  240. return value.strip()
  241. def _post_idempotent(path: str, body: dict[str, Any], idempotency_key: str, what: str, timeout: float) -> dict[str, Any]:
  242. """POST with a mandatory ``Idempotency-Key`` header (missing header is a server 400)."""
  243. key = _require_str(idempotency_key, f"Idempotency-Key is required for {what}.", "idempotency_key_required")
  244. return _request("POST", path, body=body, extra_headers={"Idempotency-Key": key}, timeout=timeout)
  245. def get_billing_state(*, timeout: float = DEFAULT_TIMEOUT) -> dict[str, Any]:
  246. """``GET /api/billing/state`` — role-tiered overview (no scope required)."""
  247. return _request("GET", "/api/billing/state", timeout=timeout)
  248. def patch_auto_top_up(
  249. *, enabled: bool, threshold: float | str, top_up_amount: float | str, timeout: float = DEFAULT_TIMEOUT
  250. ) -> dict[str, Any]:
  251. """``PATCH /api/billing/auto-top-up`` — configure auto-reload (scope required; strict body, JSON numbers)."""
  252. body = {"enabled": bool(enabled), "threshold": float(threshold), "topUpAmount": float(top_up_amount)}
  253. return _request("PATCH", "/api/billing/auto-top-up", body=body, timeout=timeout)
  254. def patch_keep_going_on_credits(*, enabled: bool, timeout: float = DEFAULT_TIMEOUT) -> dict[str, Any]:
  255. """``PATCH /api/billing/keep-going-on-credits``: the window plan's "Keep going on credits" setting (scope
  256. required; strict ``{enabled}`` body). Turning it off skips the spending gates."""
  257. return _request("PATCH", "/api/billing/keep-going-on-credits", body={"enabled": bool(enabled)}, timeout=timeout)
  258. def post_charge(*, amount_usd: float | str, idempotency_key: str, timeout: float = DEFAULT_TIMEOUT) -> dict[str, Any]:
  259. """``POST /api/billing/charge`` — buy credits (scope required). Reuse the UUID ``idempotency_key`` on retry.
  260. Returns ``202 {chargeId}`` — money is NOT confirmed yet; poll with :func:`get_charge_status`.
  261. """
  262. return _post_idempotent("/api/billing/charge", {"amountUsd": float(amount_usd)}, idempotency_key, "a charge", timeout)
  263. def get_charge_status(charge_id: str, *, timeout: float = DEFAULT_TIMEOUT) -> dict[str, Any]:
  264. """``GET /api/billing/charge/{id}`` — poll a charge (scope required).
  265. Returns ``{status: "pending"|"settled"|"failed", ...}``. An unknown or foreign id returns
  266. ``{status:"pending"}`` (never 404) — a ``pending`` past the 5-min cap is a *timeout*, not an error.
  267. """
  268. charge_id = _require_str(charge_id, "A charge id is required.", "invalid_charge_id")
  269. safe_id = urllib.parse.quote(charge_id, safe="") # a stray slash must not change the path shape
  270. return _request("GET", f"/api/billing/charge/{safe_id}", timeout=timeout)
  271. def get_subscription_state(*, timeout: float = DEFAULT_TIMEOUT) -> dict[str, Any]:
  272. """``GET /api/billing/subscription`` — current plan, tiers, usage (raw JSON; no scope)."""
  273. return _request("GET", "/api/billing/subscription", timeout=timeout)
  274. # --- Subscription change — preview + the pending-change resource + upgrade ---
  275. # Chargeless lane: preview (quote only) and PUT/DELETE pending-change (schedule/clear a downgrade
  276. # or cancellation, effective at period end). The ONE money route: POST upgrade (prorate + charge
  277. # + flip the plan in one Stripe op). All require ``billing:manage`` (403 insufficient_scope ->
  278. # BillingScopeRequired, driving the device step-up) — including preview, which reveals amounts.
  279. def post_subscription_preview(*, subscription_type_id: str, timeout: float = DEFAULT_TIMEOUT) -> dict[str, Any]:
  280. """``POST /api/billing/subscription/preview`` — a chargeless effect quote.
  281. ``effect`` is ``charge_now`` (upgrade; ``amountDueNowCents`` prorated), ``scheduled``
  282. (downgrade; ``effectiveAt`` period end), ``no_op``, or ``blocked`` (``reason`` says why).
  283. """
  284. return _request("POST", "/api/billing/subscription/preview", body={"subscriptionTypeId": subscription_type_id}, timeout=timeout)
  285. def put_subscription_pending_change(
  286. *, subscription_type_id: str | None = None, cancel: bool = False, timeout: float = DEFAULT_TIMEOUT
  287. ) -> dict[str, Any]:
  288. """``PUT /api/billing/subscription/pending-change`` — set the single end-of-period intent.
  289. ``cancel=True`` schedules a cancellation; ``subscription_type_id`` a downgrade / same-price change.
  290. UPGRADES are rejected here (they charge now — use :func:`post_subscription_upgrade`).
  291. """
  292. if cancel:
  293. body: dict[str, Any] = {"type": "cancellation"}
  294. else:
  295. tier = _require_str(
  296. subscription_type_id, "A subscription tier is required to schedule a plan change.", "invalid_subscription_type"
  297. )
  298. body = {"type": "tier_change", "subscriptionTypeId": tier}
  299. return _request("PUT", "/api/billing/subscription/pending-change", body=body, timeout=timeout)
  300. def delete_subscription_pending_change(*, timeout: float = DEFAULT_TIMEOUT) -> dict[str, Any]:
  301. """``DELETE /api/billing/subscription/pending-change`` — clear a scheduled downgrade/cancellation.
  302. Chargeless, but re-enables recurring spend: needs ``billing:manage`` and honors the org kill-switch.
  303. """
  304. return _request("DELETE", "/api/billing/subscription/pending-change", timeout=timeout)
  305. def post_subscription_upgrade(
  306. *, subscription_type_id: str, idempotency_key: str, timeout: float = DEFAULT_TIMEOUT
  307. ) -> dict[str, Any]:
  308. """``POST /api/billing/subscription/upgrade`` — immediate paid upgrade, the SINGLE money route.
  309. One Stripe op prorates, charges the card on file, flips the plan. Reuse ``idempotency_key`` on retry.
  310. """
  311. return _post_idempotent(
  312. "/api/billing/subscription/upgrade", {"subscriptionTypeId": subscription_type_id}, idempotency_key, "an upgrade", timeout
  313. )