nous_account.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776
  1. """Normalized Nous Portal account entitlement helpers."""
  2. from __future__ import annotations
  3. import hashlib
  4. import json
  5. import logging
  6. import threading
  7. import time
  8. import urllib.request
  9. from dataclasses import dataclass, field, fields
  10. from datetime import datetime, timezone, UTC
  11. from typing import Any, Literal, Optional
  12. NousAccountInfoSource = Literal["jwt", "account_api", "inference_key", "none", "error"]
  13. # Free tool-pool coverage categories, byte-aligned with the Portal's TOOL_COVERAGE_CATEGORIES
  14. # (minted into `tool_access.coverage` on the JWT and /api/oauth/account). `fal-video` is
  15. # intentionally excluded from the pool.
  16. TOOL_COVERAGE_CATEGORIES = ("firecrawl", "fal", "fal-video", "openai-audio", "browser-use", "modal")
  17. _ACCOUNT_INFO_CACHE_TTL = 60
  18. _account_info_cache: tuple[str, float, NousPortalAccountInfo] | None = None
  19. _ACCOUNT_INFO_CACHE_LOCK = threading.Lock()
  20. # Who ``_account_info_cache`` belongs to (portal + JWT user/org), for ``cached_nous_portal_account_info``:
  21. # that read must survive a token refresh, which changes the cache key above.
  22. _account_info_identity: Optional[str] = None
  23. @dataclass(frozen=True)
  24. class NousPortalSubscriptionInfo:
  25. plan: Optional[str] = None
  26. tier: Optional[int] = None
  27. monthly_charge: Optional[float] = None
  28. monthly_credits: Optional[float] = None
  29. current_period_end: Optional[str] = None
  30. credits_remaining: Optional[float] = None
  31. rollover_credits: Optional[float] = None
  32. @dataclass(frozen=True)
  33. class NousPaidServiceAccessInfo:
  34. allowed: Optional[bool] = None
  35. paid_access: Optional[bool] = None
  36. reason: Optional[str] = None
  37. organisation_id: Optional[str] = None
  38. effective_at_ms: Optional[int] = None
  39. has_active_subscription: Optional[bool] = None
  40. active_subscription_is_paid: Optional[bool] = None
  41. subscription_tier: Optional[int] = None
  42. subscription_monthly_charge: Optional[float] = None
  43. subscription_credits_remaining: Optional[float] = None
  44. purchased_credits_remaining: Optional[float] = None
  45. total_usable_credits: Optional[float] = None
  46. member_spend_cap_exceeded: Optional[bool] = None
  47. member_spend_cap_usd: Optional[float] = None
  48. member_spend_usd: Optional[float] = None
  49. member_spend_cap_remaining_usd: Optional[float] = None
  50. @dataclass(frozen=True)
  51. class NousUsageWindowInfo:
  52. """Portal ``usage_window`` block: a usage-window plan's allowances (``gauges``, the server's list in
  53. display order; see agent/usage_gauges.py), auto top-up, a paused reason while the plan's renewal is
  54. unpaid, and the plan's picks. Absent from the account body for every other account."""
  55. # The server's allowance list (agent.usage_gauges.WindowGauge). None when the portal sends none.
  56. gauges: Optional[tuple[Any, ...]] = None
  57. # The plan's recommended picks, in order: pickers list them first, and they are the
  58. # models a limit line suggests. Every model is usable on the plan.
  59. featured_model_ids: Optional[tuple[str, ...]] = None
  60. auto_top_up_enabled: Optional[bool] = None
  61. paused_reason: Optional[str] = None
  62. # The account's "Keep going on credits" setting; None from a portal
  63. # that predates it (top-up is spent then, as before).
  64. keep_going_on_credits: Optional[bool] = None
  65. @dataclass(frozen=True)
  66. class NousToolAccessInfo:
  67. """Free tool-pool entitlement (Portal ``tool_access``), decoupled from paid/billing access.
  68. ``enabled``: a positive pool balance is live and not gated off; ``coverage``: tool category ->
  69. whether the pool funds it (FAL video is excluded).
  70. """
  71. enabled: bool = False
  72. coverage: dict[str, bool] = field(default_factory=dict)
  73. _ANON_ACCOUNT_TIER = "anonymous"
  74. # Every billing / top-up / entitlement surface says exactly this for the free tier (R-USR-1).
  75. FREE_TIER_NEEDS_ACCOUNT = "This needs a Nous account. Run `hermes auth upgrade`."
  76. FREE_TIER_NEEDS_ACCOUNT_CHAT = "This needs a Nous account. Use /login to sign in."
  77. def _is_anonymous_tier(account_info: Optional[NousPortalAccountInfo]) -> bool:
  78. return account_info is not None and account_info.is_anonymous_tier
  79. def _normalize_tier(value: object) -> str:
  80. """Tier claims arrive verbatim from the JWT claim or the account payload, neither of which
  81. strips or casefolds. Compare them normalized so casing or padding can never turn the
  82. anonymous tier into a registered one."""
  83. return value.strip().lower() if isinstance(value, str) else ""
  84. @dataclass(frozen=True)
  85. class NousPortalAccountInfo:
  86. logged_in: bool
  87. source: NousAccountInfoSource
  88. fresh: bool
  89. user_id: Optional[str] = None
  90. org_id: Optional[str] = None
  91. org_slug: Optional[str] = None
  92. org_name: Optional[str] = None
  93. client_id: Optional[str] = None
  94. product_id: Optional[str] = None
  95. nous_client: Optional[str] = None
  96. portal_base_url: Optional[str] = None
  97. inference_base_url: Optional[str] = None
  98. inference_credential_present: bool = False
  99. credential_source: Optional[str] = None
  100. expires_at: Optional[datetime] = None
  101. email: Optional[str] = None
  102. privy_did: Optional[str] = None
  103. subscription: Optional[NousPortalSubscriptionInfo] = None
  104. paid_service_access: Optional[bool] = None
  105. paid_service_access_info: Optional[NousPaidServiceAccessInfo] = None
  106. tool_access: Optional[NousToolAccessInfo] = None
  107. # Portal ``usage_window`` (account API only): None for every account not on a usage-window plan.
  108. usage_window: Optional[NousUsageWindowInfo] = None
  109. raw_claims: Optional[dict[str, Any]] = None
  110. raw_account: Optional[dict[str, Any]] = None
  111. error: Optional[str] = None
  112. # NAS account tier claim; ``"anonymous"`` is the free tier (no Nous account behind it).
  113. account_tier: Optional[str] = None
  114. # Portal ``managed_tools`` (JWT claim and account API): the portal has enabled connectors for
  115. # this account. ``None`` = the portal did not say (a token minted before the claim shipped).
  116. managed_tools: Optional[bool] = None
  117. @property
  118. def is_paid(self) -> bool:
  119. return self.paid_service_access is True
  120. @property
  121. def is_anonymous_tier(self) -> bool:
  122. """The free tier: no Nous account, so no billing, credits, or entitlement to speak of.
  123. Compared case- and whitespace-insensitively — the claim is wire data."""
  124. return _normalize_tier(self.account_tier) == _ANON_ACCOUNT_TIER
  125. @property
  126. def is_free_tier(self) -> bool:
  127. return self.paid_service_access is False
  128. @property
  129. def tool_gateway_entitled(self) -> bool:
  130. """Paid access OR a live free tool pool; use ``tool_gateway_entitled_for`` per category."""
  131. return self.paid_service_access is True or bool(self.tool_access and self.tool_access.enabled)
  132. def tool_gateway_entitled_for(self, category: str) -> bool:
  133. """Paid users are entitled everywhere; pool users only where ``coverage[category]`` is true."""
  134. ta = self.tool_access
  135. return self.paid_service_access is True or bool(ta and ta.enabled and ta.coverage.get(category) is True)
  136. @property
  137. def managed_tools_rolled_out(self) -> bool:
  138. """Only a literal ``true`` from the portal counts; absent and unknown both read as out."""
  139. return self.managed_tools is True
  140. def nous_portal_billing_url(account_info: Optional[NousPortalAccountInfo] = None) -> str:
  141. """Return the billing URL for a normalized Nous account snapshot."""
  142. try:
  143. from hermes_cli.auth import DEFAULT_NOUS_PORTAL_URL
  144. except Exception:
  145. DEFAULT_NOUS_PORTAL_URL = "https://portal.nousresearch.com"
  146. base = account_info.portal_base_url if account_info is not None else None
  147. if not _nonblank(base):
  148. base = DEFAULT_NOUS_PORTAL_URL
  149. return f"{base.rstrip('/')}/billing"
  150. def nous_portal_topup_url(account_info: Optional[NousPortalAccountInfo] = None) -> str:
  151. """Portal top-up URL (``?topup=open`` auto-opens the top-up modal).
  152. Prefers the org-pinned ``{base}/orgs/{slug}/billing`` (skips the legacy shim's multi-org
  153. re-resolution); falls back to ``{base}/billing`` when ``org_slug`` is null — never
  154. ``/orgs/None/billing``.
  155. """
  156. base = nous_portal_billing_url(account_info)[: -len("/billing")]
  157. slug = getattr(account_info, "org_slug", None) if account_info is not None else None
  158. if _nonblank(slug):
  159. from urllib.parse import quote
  160. return f"{base}/orgs/{quote(slug.strip(), safe='')}/billing?topup=open"
  161. return f"{base}/billing?topup=open"
  162. def format_usage_window_block_guidance(account_info: Optional[NousPortalAccountInfo]) -> Optional[str]:
  163. """Next step after a usage-window 402: the credits step from :func:`agent.plan_limits.credits_action`
  164. (turn on Keep going, add credits, or both), plus the auto top-up nudge when it is off. None for every
  165. account not on a usage-window plan, so the credit-grant guidance is unchanged. A paused plan points
  166. at the card, not at a top-up."""
  167. window = getattr(account_info, "usage_window", None) if account_info is not None else None
  168. # A partial/empty block is not a window plan (same completeness rule as the credits seed).
  169. from agent.credits_tracker import _window_seed_fields
  170. if _window_seed_fields(window) is None:
  171. return None
  172. if paused := getattr(window, "paused_reason", None):
  173. # A paused plan bills credits whatever the setting says: no credits is why this 402 came.
  174. from agent.usage_gauges import paused_for_payment
  175. fix = "Update your card to restore included usage" if paused_for_payment(paused) else "Included usage is paused"
  176. return f"{fix}, or add credits to keep going now: {nous_portal_billing_url(account_info)}"
  177. from agent.plan_limits import ADD_CREDITS_AND_KEEP_GOING, USE_CREDITS, credits_action
  178. purchased = getattr(account_info.paid_service_access_info, "purchased_credits_remaining", None)
  179. action = credits_action(getattr(window, "keep_going_on_credits", None),
  180. int(purchased * 1_000_000) if isinstance(purchased, (int, float)) else None)
  181. if action == USE_CREDITS:
  182. return f"Turn on Keep going in /topup to use your credits now: {nous_portal_billing_url(account_info)}"
  183. if action == ADD_CREDITS_AND_KEEP_GOING:
  184. # With the setting off the gateway refuses whatever the balance, so a top-up alone won't do.
  185. return f"Add credits and turn on Keep going in /topup to keep going now: {nous_portal_billing_url(account_info)}"
  186. lines = [f"Add credits to keep going now: {nous_portal_topup_url(account_info)}"]
  187. if getattr(window, "auto_top_up_enabled", None) is False:
  188. lines.append("Turn on auto top-up in the same place so this doesn't stop you next time.")
  189. return "\n".join(lines)
  190. def format_nous_portal_entitlement_message(
  191. account_info: Optional[NousPortalAccountInfo], *, capability: str = "this feature",
  192. include_refresh_hint: bool = True, coverage_category: Optional[str] = None,
  193. in_chat: bool = False,
  194. ) -> Optional[str]:
  195. """User-facing guidance for a missing Nous tool-gateway entitlement; ``None`` when entitled.
  196. Entitled = paid access OR a live free pool that covers it (normalized fields, not price:
  197. purchased credits without a subscription count as paid, an exhausted paid subscription does
  198. not). ``coverage_category`` scopes the check to one category; an otherwise-entitled user whose
  199. access doesn't fund it gets a neutral billing nudge, never an "exhausted" message. The
  200. pool-vs-paid distinction is never surfaced.
  201. """
  202. if _is_anonymous_tier(account_info):
  203. return FREE_TIER_NEEDS_ACCOUNT_CHAT if in_chat else FREE_TIER_NEEDS_ACCOUNT
  204. billing_url = nous_portal_billing_url(account_info)
  205. if account_info is not None:
  206. if coverage_category is not None:
  207. if account_info.tool_gateway_entitled_for(coverage_category):
  208. return None
  209. if account_info.tool_gateway_entitled:
  210. return (
  211. f"{capability} isn't included with your current Nous Portal access. "
  212. f"Add credits or a subscription to enable it at {billing_url}."
  213. )
  214. elif account_info.tool_gateway_entitled:
  215. return None
  216. if account_info is None:
  217. return (
  218. f"Hermes could not verify your Nous Portal entitlement, so {capability} is unavailable. "
  219. f"Run `hermes model` to refresh your login, or check billing at {billing_url}."
  220. )
  221. if not account_info.logged_in:
  222. if account_info.inference_credential_present:
  223. return (
  224. f"Nous inference credentials are configured, but Hermes cannot verify your Nous Portal "
  225. f"paid access for {capability}. Log in with `hermes model` to enable Portal-managed "
  226. f"features. Billing and credits are managed at {billing_url}."
  227. )
  228. return (
  229. f"Log in to Nous Portal to use {capability}: run `hermes model`. "
  230. f"Billing and credits are managed at {billing_url}."
  231. )
  232. if account_info.paid_service_access is None:
  233. detail = f"Hermes could not verify your Nous Portal paid access, so {capability} is unavailable."
  234. if account_info.error:
  235. detail += f" Account lookup failed: {account_info.error}."
  236. if include_refresh_hint:
  237. detail += " Run `hermes model` to refresh your session."
  238. return detail + f" Check billing at {billing_url}."
  239. access = account_info.paid_service_access_info
  240. reason = access.reason if access else None
  241. if reason == "account_missing":
  242. return (
  243. f"Hermes could not find a Nous Portal account or organisation for this login, so {capability} "
  244. f"is unavailable. Run `hermes model` to authenticate again; if the problem persists, contact Nous support."
  245. )
  246. if reason == "no_usable_credits" or account_info.paid_service_access is False:
  247. message = _no_paid_access_message(account_info, capability, billing_url, in_chat=in_chat)
  248. if include_refresh_hint and not account_info.fresh:
  249. message += " If you recently bought credits, run `hermes model` to refresh Hermes."
  250. return message
  251. return (
  252. f"Your Nous Portal account does not currently have paid service access, "
  253. f"so {capability} is unavailable. Add credits or update billing at {billing_url}."
  254. )
  255. def _no_paid_access_message(
  256. account_info: NousPortalAccountInfo, capability: str, billing_url: str, *, in_chat: bool = False,
  257. ) -> str:
  258. if _is_anonymous_tier(account_info):
  259. return FREE_TIER_NEEDS_ACCOUNT_CHAT if in_chat else FREE_TIER_NEEDS_ACCOUNT
  260. access = account_info.paid_service_access_info or NousPaidServiceAccessInfo()
  261. active, paid = access.has_active_subscription, access.active_subscription_is_paid
  262. labelled = (
  263. ("usable", access.total_usable_credits),
  264. ("subscription", access.subscription_credits_remaining),
  265. ("purchased", access.purchased_credits_remaining),
  266. )
  267. parts = [f"{label} ${amount:.2f}" for label, amount in labelled if amount is not None]
  268. credit_detail = f" ({', '.join(parts)})" if parts else ""
  269. if access.member_spend_cap_exceeded:
  270. cap, spent = access.member_spend_cap_usd, access.member_spend_usd
  271. cap_detail = ""
  272. if cap is not None and spent is not None:
  273. cap_detail = f" Your organisation's per-member spend cap is ${cap:.2f} and you've spent ${spent:.2f} of it."
  274. elif cap is not None:
  275. cap_detail = f" Your organisation's per-member spend cap is ${cap:.2f}."
  276. return (
  277. f"Your Nous Portal access is paused because you've exceeded the per-member spend cap set by "
  278. f"your organisation.{cap_detail}{credit_detail} Ask your organisation admin to raise the "
  279. f"member spend cap at {billing_url}, then run `hermes model` to refresh."
  280. )
  281. if active and paid:
  282. return (
  283. f"Your Nous Portal credits are exhausted{credit_detail}, so {capability} is unavailable. "
  284. f"Top up or renew credits at {billing_url}."
  285. )
  286. if active and paid is False:
  287. return (
  288. f"Your current Nous Portal plan does not include paid service access, "
  289. f"so {capability} is unavailable. Upgrade or add credits at {billing_url}."
  290. )
  291. if active is False:
  292. return (
  293. f"Your Nous Portal account has no active subscription or usable credits{credit_detail}, "
  294. f"so {capability} is unavailable. Subscribe or add credits at {billing_url}."
  295. )
  296. return (
  297. f"Your Nous Portal account has no usable paid credits{credit_detail}, so "
  298. f"{capability} is unavailable. Add credits or update billing at {billing_url}."
  299. )
  300. def reset_nous_portal_account_info_cache() -> None:
  301. """Clear the short-lived account-info cache used by tests."""
  302. global _account_info_cache, _account_info_identity
  303. _account_info_cache = None
  304. _account_info_identity = None
  305. def get_nous_portal_account_info(*, force_fresh: bool = False, min_jwt_ttl_seconds: int = 60) -> NousPortalAccountInfo:
  306. """Normalized Nous Portal account entitlement.
  307. A valid unexpired OAuth JWT serves as a local snapshot (UX gating only; the server stays
  308. authoritative). ``force_fresh=True`` always calls ``/api/oauth/account`` and bypasses the cache.
  309. """
  310. try:
  311. from hermes_cli.auth import get_provider_auth_state
  312. state = get_provider_auth_state("nous") or {}
  313. except Exception as exc:
  314. return _error_info(error=exc, logged_in=False)
  315. # A guest that has only used connectors holds just a connectors-only token (same claims). With
  316. # the free tier off a guest is not an account login: the pool and logged-out answers apply.
  317. from hermes_cli.anon_auth import guest_without_free_tier, held_connectors_token
  318. access_token = "" if guest_without_free_tier(state) else (held_connectors_token(state) or "")
  319. portal_base_url = _portal_base_url(state)
  320. if not _nonblank(access_token):
  321. return (
  322. _info_from_oauth_pool(force_fresh, min_jwt_ttl_seconds, portal_base_url)
  323. or _info_from_inference_key_pool(portal_base_url)
  324. or NousPortalAccountInfo(logged_in=False, source="none", fresh=False, portal_base_url=portal_base_url)
  325. )
  326. if not force_fresh:
  327. jwt_info = _info_from_valid_jwt(access_token, state, portal_base_url, min_jwt_ttl_seconds)
  328. if jwt_info is not None:
  329. return jwt_info
  330. return _fresh_account_info(state, force_fresh, portal_base_url)
  331. def nous_policy_present() -> Optional[bool]:
  332. """Whether the caller's org carries a restrictive model/provider policy.
  333. ``None`` is unknown (older mint / unreadable claim) and must not be reported as "no policy".
  334. """
  335. try:
  336. from hermes_cli.auth import get_provider_auth_state, _decode_jwt_claims
  337. access_token = (get_provider_auth_state("nous") or {}).get("access_token")
  338. if not _nonblank(access_token):
  339. return None
  340. claims = _decode_jwt_claims(access_token)
  341. return _coerce_bool(claims.get("policy_present")) if claims else None
  342. except Exception:
  343. return None
  344. def cached_nous_portal_account_info(*, any_age: bool = False) -> Optional[NousPortalAccountInfo]:
  345. """The account snapshot in the 60s cache, or None when empty/expired. Never a fresh fetch, never raises —
  346. for UI chrome that must not add a round trip (the pickers) after a flow has already fetched the account.
  347. ``any_age`` returns the last snapshot even past the TTL, for callers that read only the plan's shape
  348. (window or not, featured models), which rarely changes."""
  349. try:
  350. with _ACCOUNT_INFO_CACHE_LOCK:
  351. cached, identity = _account_info_cache, _account_info_identity
  352. if cached is None:
  353. return None
  354. _, cached_at, info = cached
  355. # Expiry first: it is free, while the identity check reads the auth store.
  356. if not any_age and (time.monotonic() - cached_at) >= _ACCOUNT_INFO_CACHE_TTL:
  357. return None
  358. # Another login, org or portal never reads this snapshot; a refreshed token for the same one does.
  359. if identity is None or identity != _current_account_identity():
  360. return None
  361. return info
  362. except Exception:
  363. logging.getLogger(__name__).debug("Cached Nous account info unreadable", exc_info=True)
  364. return None
  365. def _account_identity(access_token: str, portal_base_url: Optional[str]) -> str:
  366. """Portal + the token's user and org (stable across a refresh); an opaque token falls back to its hash."""
  367. from hermes_cli.auth_constants import _decode_jwt_claims
  368. claims = _decode_jwt_claims(access_token)
  369. sub, org = claims.get("sub"), claims.get("org_id")
  370. if _nonblank(sub) and _nonblank(org):
  371. identity = f"jwt:{sub}:{org}"
  372. else:
  373. identity = hashlib.sha256(access_token.encode("utf-8")).hexdigest()
  374. return f"{portal_base_url or ''}:{identity}"
  375. def _current_account_identity() -> Optional[str]:
  376. """``_account_identity`` for the persisted Nous login, without a refresh or network call. None
  377. when logged out."""
  378. from hermes_cli.auth import get_provider_auth_state
  379. state = get_provider_auth_state("nous") or {}
  380. access_token = state.get("access_token")
  381. if not _nonblank(access_token):
  382. return None
  383. return _account_identity(access_token, _portal_base_url(state))
  384. def nous_policy_notice(*, removed: bool) -> str:
  385. """One-line notice for a list the org's policy narrowed, else ``""``.
  386. Blocked models are omitted, which reads as "unsupported"; this says which it is without
  387. enumerating them. ``removed`` must reflect whether the filter actually dropped anything — the
  388. catalog read fails open, so the claim alone would label a full list as filtered.
  389. """
  390. if not removed or nous_policy_present() is not True:
  391. return ""
  392. return (
  393. "Your organization restricts which models are available — "
  394. "models outside its policy are not listed."
  395. )
  396. def _fresh_account_info(state: dict[str, Any], force_fresh: bool, portal_base_url: Optional[str]) -> NousPortalAccountInfo:
  397. global _account_info_cache, _account_info_identity
  398. try:
  399. from hermes_cli.auth import get_provider_auth_state, resolve_nous_access_token
  400. access_token = resolve_nous_access_token()
  401. refreshed_state = get_provider_auth_state("nous") or state
  402. portal_base_url = _portal_base_url(refreshed_state) or portal_base_url
  403. digest = hashlib.sha256(access_token.encode("utf-8")).hexdigest()
  404. cache_key = f"{portal_base_url or ''}:{digest}"
  405. with _ACCOUNT_INFO_CACHE_LOCK:
  406. if not force_fresh and _account_info_cache is not None:
  407. cached_key, cached_at, cached_info = _account_info_cache
  408. if cached_key == cache_key and (time.monotonic() - cached_at) < _ACCOUNT_INFO_CACHE_TTL:
  409. return cached_info
  410. info = _info_from_fetched_account(access_token, refreshed_state, portal_base_url)
  411. if info.source != "error":
  412. identity = _account_identity(access_token, portal_base_url)
  413. with _ACCOUNT_INFO_CACHE_LOCK:
  414. _account_info_cache = (cache_key, time.monotonic(), info)
  415. _account_info_identity = identity
  416. return info
  417. except Exception as exc:
  418. return _error_info(error=exc, logged_in=bool(state.get("access_token")),
  419. portal_base_url=portal_base_url, account_tier=_coerce_str(state.get("account_tier")))
  420. def _info_from_inference_key_pool(portal_base_url: Optional[str]) -> Optional[NousPortalAccountInfo]:
  421. """Return an explicit unknown-entitlement snapshot for opaque Nous keys."""
  422. try:
  423. entry = _select_nous_pool_entry()
  424. if entry is None:
  425. return None
  426. if not _nonblank(getattr(entry, "runtime_api_key", None) or getattr(entry, "access_token", "")):
  427. return None
  428. return NousPortalAccountInfo(
  429. logged_in=False, source="inference_key", fresh=False,
  430. portal_base_url=getattr(entry, "portal_base_url", None) or portal_base_url,
  431. inference_base_url=_pool_entry_inference_url(entry),
  432. inference_credential_present=True,
  433. credential_source=f"pool:{getattr(entry, 'label', 'unknown')}",
  434. error="portal_oauth_missing",
  435. )
  436. except Exception:
  437. return None
  438. def _info_from_oauth_pool(
  439. force_fresh: bool, min_jwt_ttl_seconds: int, portal_base_url: Optional[str]
  440. ) -> Optional[NousPortalAccountInfo]:
  441. try:
  442. entry = _select_nous_pool_entry()
  443. except Exception:
  444. return None
  445. if entry is None or not _pool_entry_is_portal_oauth(entry):
  446. return None
  447. access_token = entry.access_token # non-blank str: checked by _pool_entry_is_portal_oauth
  448. entry_portal_url = getattr(entry, "portal_base_url", None) or portal_base_url
  449. state = {
  450. "access_token": access_token, "client_id": getattr(entry, "client_id", None),
  451. "inference_base_url": _pool_entry_inference_url(entry), "agent_key": getattr(entry, "agent_key", None),
  452. "credential_source": f"pool:{getattr(entry, 'label', 'unknown')}",
  453. }
  454. if not force_fresh:
  455. jwt_info = _info_from_valid_jwt(access_token, state, entry_portal_url, min_jwt_ttl_seconds)
  456. if jwt_info is not None:
  457. return jwt_info
  458. try:
  459. return _info_from_fetched_account(access_token, state, entry_portal_url)
  460. except Exception as exc:
  461. return _error_info(error=exc, logged_in=True, portal_base_url=entry_portal_url,
  462. account_tier=_coerce_str(state.get("account_tier")))
  463. def _info_from_fetched_account(
  464. access_token: str, state: dict[str, Any], portal_base_url: Optional[str]
  465. ) -> NousPortalAccountInfo:
  466. """Call ``/api/oauth/account`` and normalize; empty or ``error`` payloads become error infos."""
  467. payload = _fetch_nous_account_info(access_token, portal_base_url)
  468. tier = _coerce_str(state.get("account_tier"))
  469. if not payload:
  470. return _error_info(error="empty_account_response", logged_in=True,
  471. portal_base_url=portal_base_url, account_tier=tier)
  472. if isinstance(payload.get("error"), str):
  473. return _error_info(
  474. error=payload["error"] or "account_response_error", logged_in=True,
  475. portal_base_url=portal_base_url, raw_account=payload, account_tier=tier,
  476. )
  477. return _info_from_account_payload(payload, state=state, portal_base_url=portal_base_url)
  478. def _pool_entry_inference_url(entry: Any) -> Optional[str]:
  479. return getattr(entry, "inference_base_url", None) or getattr(entry, "runtime_base_url", None) or getattr(entry, "base_url", None)
  480. def _select_nous_pool_entry() -> Optional[Any]:
  481. """Pool entry with the latest agent-key expiry, then access expiry, then lowest priority."""
  482. from agent.credential_pool import load_pool
  483. pool = load_pool("nous")
  484. if not pool or not pool.has_credentials():
  485. return None
  486. entries = list(pool.entries())
  487. if not entries:
  488. return None
  489. def _entry_sort_key(entry: Any) -> tuple[float, float, int]:
  490. agent_exp = _parse_iso_timestamp(getattr(entry, "agent_key_expires_at", None)) or 0.0
  491. access_exp = _parse_iso_timestamp(getattr(entry, "expires_at", None)) or 0.0
  492. return (agent_exp, access_exp, -int(getattr(entry, "priority", 0) or 0))
  493. return max(entries, key=_entry_sort_key)
  494. def _pool_entry_is_portal_oauth(entry: Any) -> bool:
  495. if not _nonblank(getattr(entry, "access_token", None)):
  496. return False
  497. auth_type = str(getattr(entry, "auth_type", "") or "").strip().lower()
  498. return auth_type.startswith("oauth") or bool(getattr(entry, "refresh_token", None))
  499. def _fetch_nous_account_info(access_token: str, portal_base_url: Optional[str] = None) -> dict[str, Any]:
  500. base = (portal_base_url or "https://portal.nousresearch.com").rstrip("/")
  501. headers = {"Authorization": f"Bearer {access_token}", "Accept": "application/json"}
  502. req = urllib.request.Request(f"{base}/api/oauth/account", headers=headers)
  503. with urllib.request.urlopen(req, timeout=8) as resp:
  504. payload = json.loads(resp.read().decode())
  505. return payload if isinstance(payload, dict) else {}
  506. def _info_from_valid_jwt(
  507. token: str, state: dict[str, Any], portal_base_url: Optional[str], min_jwt_ttl_seconds: int
  508. ) -> Optional[NousPortalAccountInfo]:
  509. try:
  510. from hermes_cli.auth import _decode_jwt_claims
  511. except Exception:
  512. return None
  513. claims = _decode_jwt_claims(token)
  514. if not claims:
  515. return None
  516. exp = _coerce_num(claims.get("exp"), float)
  517. if exp is None or exp <= time.time() + max(0, int(min_jwt_ttl_seconds)):
  518. return None
  519. paid_access = _coerce_bool(claims.get("paid_access"))
  520. access_info = NousPaidServiceAccessInfo(
  521. allowed=paid_access, paid_access=paid_access, organisation_id=_coerce_str(claims.get("org_id")),
  522. subscription_tier=_coerce_num(claims.get("subscription_tier"), int),
  523. )
  524. return NousPortalAccountInfo(
  525. logged_in=True, source="jwt", fresh=False,
  526. user_id=_coerce_str(claims.get("sub")),
  527. org_id=_coerce_str(claims.get("org_id")),
  528. client_id=_coerce_str(claims.get("client_id") or state.get("client_id")),
  529. product_id=_coerce_str(claims.get("product_id")),
  530. nous_client=_coerce_str(claims.get("nous_client")),
  531. portal_base_url=portal_base_url,
  532. inference_base_url=_coerce_str(state.get("inference_base_url")),
  533. inference_credential_present=True,
  534. credential_source=_coerce_str(state.get("credential_source")) or "auth_store",
  535. expires_at=datetime.fromtimestamp(exp, tz=UTC),
  536. paid_service_access=paid_access, paid_service_access_info=access_info,
  537. tool_access=_tool_access_from_value(claims.get("tool_access")),
  538. raw_claims=dict(claims),
  539. account_tier=_coerce_str(claims.get("account_tier")) or _coerce_str(state.get("account_tier")),
  540. managed_tools=_coerce_bool(claims.get("managed_tools")),
  541. )
  542. def _info_from_account_payload(
  543. payload: dict[str, Any], *, state: dict[str, Any], portal_base_url: Optional[str]
  544. ) -> NousPortalAccountInfo:
  545. user = _dict_or_empty(payload.get("user"))
  546. organisation = _dict_or_empty(payload.get("organisation"))
  547. access = _coerced_dataclass(NousPaidServiceAccessInfo, payload.get("paid_service_access"))
  548. paid_access = None
  549. if access is not None:
  550. paid_access = access.allowed if access.allowed is not None else access.paid_access
  551. return NousPortalAccountInfo(
  552. logged_in=True, source="account_api", fresh=True,
  553. org_id=_coerce_str(organisation.get("id")) or (access.organisation_id if access else None),
  554. org_slug=_coerce_str(organisation.get("slug")),
  555. org_name=_coerce_str(organisation.get("name")),
  556. client_id=_coerce_str(state.get("client_id")),
  557. portal_base_url=portal_base_url,
  558. inference_base_url=_coerce_str(state.get("inference_base_url")),
  559. inference_credential_present=bool(state.get("access_token") or state.get("agent_key")),
  560. credential_source=_coerce_str(state.get("credential_source")) or "auth_store",
  561. email=_coerce_str(user.get("email")),
  562. privy_did=_coerce_str(user.get("privy_did")),
  563. subscription=_subscription_from_payload(payload.get("subscription")),
  564. paid_service_access=paid_access, paid_service_access_info=access,
  565. tool_access=_tool_access_from_value(payload.get("tool_access")),
  566. usage_window=_coerced_dataclass(NousUsageWindowInfo, payload.get("usage_window")),
  567. raw_account=dict(payload),
  568. account_tier=_coerce_str(payload.get("account_tier")) or _coerce_str(user.get("account_tier"))
  569. or _coerce_str(state.get("account_tier")),
  570. managed_tools=_coerce_bool(payload.get("managed_tools")),
  571. )
  572. def _tool_access_from_value(value: Any) -> Optional[NousToolAccessInfo]:
  573. """Parse a Portal ``tool_access`` object (JWT claim or account API).
  574. Fails closed: a non-object yields ``None``; only literal ``true`` counts for ``enabled`` and
  575. each coverage entry.
  576. """
  577. if not isinstance(value, dict):
  578. return None
  579. coverage = {k: v is True for k, v in _dict_or_empty(value.get("coverage")).items() if isinstance(k, str)}
  580. return NousToolAccessInfo(enabled=value.get("enabled") is True, coverage=coverage)
  581. def _coerced_dataclass(cls, value: Any):
  582. """Build ``cls`` from a payload dict (field names = payload keys), coercing by declared type."""
  583. return cls(**{f.name: _COERCERS[f.type](value.get(f.name)) for f in fields(cls)}) if isinstance(value, dict) else None
  584. def _subscription_from_payload(value: Any) -> Optional[NousPortalSubscriptionInfo]:
  585. return _coerced_dataclass(NousPortalSubscriptionInfo, value)
  586. def _error_info(
  587. *, error: object, logged_in: bool, portal_base_url: Optional[str] = None,
  588. raw_account: Optional[dict[str, Any]] = None, account_tier: Optional[str] = None,
  589. ) -> NousPortalAccountInfo:
  590. """A failed-lookup snapshot. ``account_tier`` is carried through when the caller still holds the
  591. stored state, so a guest whose lookup failed still gets the "needs a Nous account" copy rather
  592. than billing or re-login guidance."""
  593. return NousPortalAccountInfo(
  594. logged_in=logged_in, source="error", fresh=False, portal_base_url=portal_base_url,
  595. raw_account=raw_account, error=str(error), account_tier=account_tier,
  596. )
  597. def _nonblank(value: Any) -> bool:
  598. return isinstance(value, str) and bool(value.strip())
  599. def _dict_or_empty(value: Any) -> dict[str, Any]:
  600. return value if isinstance(value, dict) else {}
  601. def resolve_nous_portal_base_url() -> str:
  602. from hermes_cli.auth import _nous_portal_base_url, get_provider_auth_state
  603. return _nous_portal_base_url(get_provider_auth_state("nous") or {})
  604. def _portal_base_url(state: dict[str, Any]) -> Optional[str]:
  605. from hermes_cli.auth_nous import _nous_portal_env_override
  606. value = _nous_portal_env_override() or state.get("portal_base_url")
  607. return value.strip().rstrip("/") if _nonblank(value) else None
  608. def _parse_iso_timestamp(value: Any) -> Optional[float]:
  609. if not isinstance(value, str) or not value:
  610. return None
  611. text = value.strip()
  612. if text.endswith("Z"):
  613. text = text[:-1] + "+00:00"
  614. try:
  615. return datetime.fromisoformat(text).timestamp()
  616. except Exception:
  617. return None
  618. def _coerce_str(value: Any) -> Optional[str]:
  619. return value if isinstance(value, str) and value else None
  620. def _coerce_bool(value: Any) -> Optional[bool]:
  621. return value if isinstance(value, bool) else None
  622. def _coerce_num(value: Any, cast):
  623. """``cast(value)`` or None; bools and None are rejected, not coerced."""
  624. if value is None or isinstance(value, bool):
  625. return None
  626. try:
  627. return cast(value)
  628. except (TypeError, ValueError):
  629. return None
  630. def _coerce_str_tuple(value: Any) -> Optional[tuple[str, ...]]:
  631. """A JSON array of non-empty strings → tuple (order kept, non-strings dropped); anything else → None."""
  632. if not isinstance(value, list):
  633. return None
  634. return tuple(v for v in value if isinstance(v, str) and v)
  635. # Annotations are strings (``from __future__ import annotations``).
  636. _COERCERS = {
  637. "Optional[str]": _coerce_str,
  638. "Optional[bool]": _coerce_bool,
  639. "Optional[int]": lambda v: _coerce_num(v, int),
  640. "Optional[float]": lambda v: _coerce_num(v, float),
  641. "Optional[tuple[str, ...]]": _coerce_str_tuple,
  642. "Optional[tuple[Any, ...]]": lambda v: _parse_gauges(v),
  643. }
  644. def _parse_gauges(value: Any):
  645. from agent.usage_gauges import parse_gauges
  646. return parse_gauges(value)