cli_billing_mixin.py 62 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159
  1. """Billing and subscription handlers for the interactive CLI (mixed into ``HermesCLI``).
  2. cli.py symbols are imported LAZILY inside methods — never at module load (import cycle).
  3. User-facing copy is looked up through ``agent.i18n.t`` at call time (never at import — the
  4. active language is not known when this module loads), under ``cli.billing.*`` (shared /topup
  5. copy) and ``cli.subscription.*`` (/subscription copy). Modal choice VALUES (index 0) stay
  6. English identifiers; only labels/descriptions are translated."""
  7. from __future__ import annotations
  8. from agent.i18n import t
  9. _RULE = "─" * 41
  10. # Poll `failed` reasons → copy key (default: generic line carrying the raw reason).
  11. _CHARGE_FAILED_KEYS = {
  12. "authentication_required": "cli.billing.charge_failed_authentication_required",
  13. "payment_method_expired": "cli.billing.charge_failed_payment_method_expired",
  14. "card_declined": "cli.billing.charge_failed_card_declined"}
  15. # Submit-time BillingError codes with a fixed copy key (no payload/type inspection).
  16. _CHARGE_ERROR_KEYS = {
  17. "no_payment_method": "cli.billing.charge_error_no_payment_method",
  18. "cli_billing_disabled": "cli.billing.charge_error_remote_spending_disabled",
  19. "remote_spending_disabled": "cli.billing.charge_error_remote_spending_disabled",
  20. "role_required": "cli.billing.charge_error_role_required",
  21. "idempotency_conflict": "cli.billing.charge_error_idempotency_conflict"}
  22. # Upgrade 2xx `status` → (copy key, echo recoveryUrl as "Portal:"). Missing status → ambiguous.
  23. _UPGRADE_STATUS_KEYS = {
  24. "requires_action": ("cli.subscription.upgrade_requires_action", True),
  25. "payment_failed": ("cli.subscription.upgrade_payment_failed", True)}
  26. # Upgrade 2xx terminal statuses → dim ✓ copy key ({name} = target tier).
  27. _UPGRADE_OK_KEYS = {
  28. "already_on_tier": "cli.subscription.upgrade_already_on_tier",
  29. "upgraded": "cli.subscription.upgrade_upgraded"}
  30. # Pending-change mutations → dim ✓ copy key.
  31. _PENDING_OK_KEYS = {
  32. "schedule": "cli.subscription.pending_scheduled",
  33. "cancel": "cli.subscription.pending_cancel_scheduled",
  34. "resume": "cli.subscription.pending_resumed"}
  35. # ── Static modal menus (value, label, description) — built at call time so labels follow the
  36. # active language; order is the rendered order. ──
  37. def _cancel_row(value: str = "cancel", label_key: str = "cli.billing.choice_cancel",
  38. desc_key: str = "cli.billing.desc_do_nothing") -> tuple[str, str, str]:
  39. return (value, t(label_key), t(desc_key))
  40. def _portal_row(value: str = "portal") -> tuple[str, str, str]:
  41. return (value, t("cli.billing.choice_manage_on_portal"), t("cli.billing.desc_open_billing_page"))
  42. def _allow_remote_spending_choices() -> list[tuple[str, str, str]]:
  43. return [
  44. ("yes", t("cli.billing.choice_allow_remote_spending"), t("cli.billing.desc_allow_remote_spending")),
  45. ("no", t("cli.billing.choice_not_now"), t("cli.billing.desc_not_now"))]
  46. def _topup_menu_choices() -> list[tuple[str, str, str]]:
  47. return [
  48. ("buy", t("cli.billing.choice_add_funds"), t("cli.billing.desc_add_funds")),
  49. ("auto", t("cli.billing.choice_auto_reload"), t("cli.billing.desc_auto_reload")),
  50. ("limit", t("cli.billing.choice_monthly_limit"), t("cli.billing.desc_monthly_limit")),
  51. _portal_row(),
  52. _cancel_row()]
  53. def _add_card_choices() -> list[tuple[str, str, str]]:
  54. return [
  55. ("portal", t("cli.billing.choice_add_card_on_portal"), t("cli.billing.desc_add_card_on_portal")),
  56. ("recheck", t("cli.billing.choice_recheck_card"), t("cli.billing.desc_recheck_card")),
  57. _cancel_row(label_key="cli.billing.choice_back")]
  58. def _auto_reload_top_choices() -> list[tuple[str, str, str]]:
  59. return [
  60. ("edit", t("cli.billing.choice_edit_thresholds"), t("cli.billing.desc_edit_thresholds")),
  61. ("off", t("cli.billing.choice_turn_off"), t("cli.billing.desc_turn_off")),
  62. _cancel_row()]
  63. def _auto_reload_agree_choices() -> list[tuple[str, str, str]]:
  64. return [
  65. ("agree", t("cli.billing.choice_agree_turn_on"), t("cli.billing.desc_agree_turn_on")),
  66. _cancel_row()]
  67. def _change_plan_row() -> tuple[str, str, str]:
  68. return ("change", t("cli.subscription.choice_change_plan"), t("cli.subscription.desc_change_plan"))
  69. def _change_menu_tail() -> list[tuple[str, str, str]]:
  70. return [_portal_row(), _cancel_row("close", "cli.billing.choice_close")]
  71. def _cancel_sub_choices() -> list[tuple[str, str, str]]:
  72. return [
  73. ("yes", t("cli.subscription.choice_cancel_subscription"), t("cli.subscription.desc_cancel_subscription")),
  74. ("cancel", t("cli.billing.choice_go_back"), t("cli.subscription.desc_keep_your_plan"))]
  75. # Keep going on credits: window plans only (the portal sends the setting only there).
  76. def _keep_going_row() -> tuple[str, str, str]:
  77. return ("hermes", t("cli.billing.keep_going_choice"), t("cli.billing.keep_going_desc"))
  78. def _keep_going_agree_choices() -> list[tuple[str, str, str]]:
  79. return [
  80. ("agree", t("cli.billing.keep_going_turn_on"), t("cli.billing.keep_going_desc")),
  81. _cancel_row(desc_key="cli.billing.keep_going_keep_off_desc")]
  82. def _keep_going_off_choices() -> list[tuple[str, str, str]]:
  83. return [
  84. ("off", t("cli.billing.keep_going_turn_off"), t("cli.billing.keep_going_turn_off_desc")),
  85. _cancel_row(label_key="cli.billing.keep_going_leave_on")]
  86. class CLIBillingMixin:
  87. """Mixin holding interactive-CLI billing and subscription handlers."""
  88. # ── Shared helpers ──
  89. def _modal_choice(self, title, detail, choices):
  90. """Run the choice modal and return the normalized choice value."""
  91. raw = self._prompt_text_input_modal(title=title, detail=detail, choices=choices)
  92. return self._normalize_slash_confirm_choice(raw, choices)
  93. def _block_header(self, icon, title, *, rule=True) -> None:
  94. """Blank line, ``<icon> <bold title>`` via _cprint, then (optionally) the rule via print."""
  95. from cli import _cprint, _b
  96. print()
  97. _cprint(f" {icon} {_b(title)}")
  98. if rule:
  99. print(f" {_RULE}")
  100. def _dim(self, msg, *, icon="", lead=False) -> None:
  101. """Dim `` <icon><msg>`` line via _cprint; ``lead`` prints a blank line first."""
  102. from cli import _cprint, _d
  103. if lead:
  104. print()
  105. _cprint(f" {icon}{_d(msg)}")
  106. def _ok(self, msg) -> None:
  107. """Dim ``✓ <msg>`` success line."""
  108. from cli import _cprint, _DIM, _RST
  109. _cprint(f" {_DIM}✓ {msg}{_RST}")
  110. def _print_logged_out(self, state, load_failed, cmd) -> None:
  111. """Logged-out / fetch-failed block shared by /subscription and /topup."""
  112. if state.error:
  113. self._dim(t("cli.billing.load_failed", label=load_failed, error=state.error), icon="💳 ", lead=True)
  114. else:
  115. self._dim(t("cli.billing.not_logged_in"), icon="💳 ", lead=True)
  116. print(f" {t('cli.billing.run_portal_then', cmd=cmd)}")
  117. def _print_org_line(self, state) -> None:
  118. """Dim ``Org: <name> · <Role>`` line (skipped when there is no org)."""
  119. if state.org_name:
  120. role = (state.role or "").title()
  121. if role:
  122. self._dim(t("cli.billing.org_line_role", org=state.org_name, role=role))
  123. else:
  124. self._dim(t("cli.billing.org_line", org=state.org_name))
  125. def _try_usage_model(self):
  126. """Shared dollar usage model (the only source with top-up dollars); None on any failure."""
  127. try:
  128. from agent.billing_usage import build_usage_model
  129. return build_usage_model()
  130. except Exception:
  131. return None
  132. def _usage_bar_lines(self, usage, plan_name) -> list:
  133. """Plan + top-up bars as lines (filled = remaining). Caller picks the print fn: ordering differs per surface."""
  134. lines: list = []
  135. pb = usage.plan_bar if usage else None
  136. if pb is not None and pb.total_usd > 0:
  137. filled = max(0, min(10, round(pb.fill_fraction * 10)))
  138. bar = ("█" * filled) + ("░" * (10 - filled))
  139. pct_s = t("cli.billing.bar_pct_used", pct=pb.pct_used) if pb.pct_used is not None else ""
  140. label = (plan_name or t("cli.billing.bar_plan_label")).ljust(8)[:8]
  141. lines.append(" " + t("cli.billing.bar_plan", label=label, bar=bar, remaining=f"{pb.remaining_usd:,.2f}",
  142. total=f"{pb.total_usd:,.2f}", pct=pct_s))
  143. tb = usage.topup_bar if usage else None
  144. if tb is not None and tb.remaining_usd > 0:
  145. lines.append(" " + t("cli.billing.bar_topup", label=t("cli.billing.bar_topup_label").ljust(8)[:8],
  146. bar="█" * 10, remaining=f"{tb.remaining_usd:,.2f}"))
  147. return lines
  148. def _print_total_spendable(self, usage, print_fn) -> None:
  149. if usage and usage.has_topup and usage.total_spendable_usd is not None:
  150. print_fn(f" {t('cli.billing.total_spendable', amount=f'{usage.total_spendable_usd:,.2f}')}")
  151. def _step_up_remote_spending(self, *, explain, noninteractive_msg, declined_msg, not_granted_msg) -> bool:
  152. """"! One-time setup" step-up (explain → confirm → device-flow). True only when granted; refusals print."""
  153. print()
  154. print(f" {t('cli.billing.one_time_setup')}")
  155. self._dim(explain)
  156. if not self._app:
  157. print(noninteractive_msg)
  158. return False
  159. choice = self._modal_choice(
  160. t("cli.billing.allow_remote_spending_title"), t("cli.billing.allow_remote_spending_detail"),
  161. _allow_remote_spending_choices())
  162. if choice != "yes":
  163. print(declined_msg)
  164. return False
  165. print(f" {t('cli.billing.opening_browser_remote_spending')}")
  166. try:
  167. from hermes_cli.auth import step_up_nous_billing_scope
  168. granted = step_up_nous_billing_scope(open_browser=True)
  169. except Exception as exc:
  170. print(f" {t('cli.billing.couldnt_allow_remote_spending', error=exc)}")
  171. return False
  172. if not granted:
  173. print(not_granted_msg)
  174. return bool(granted)
  175. def _print_portal_line(self, exc) -> None:
  176. """``Portal: <url>`` via _cprint when the error carries a portal deep-link."""
  177. from cli import _cprint
  178. if exc is not None and exc.portal_url:
  179. _cprint(f" {t('cli.billing.portal_line', url=exc.portal_url)}")
  180. def _open_url_in_browser(self, url: str) -> bool:
  181. """The one portal opener. Refuses TTY-hijacking text browsers (w3m/lynx over SSH) via the auth guard."""
  182. if not url:
  183. return False
  184. try:
  185. from hermes_cli.auth import _can_open_graphical_browser, _is_remote_session
  186. if _is_remote_session() or not _can_open_graphical_browser():
  187. return False
  188. except Exception:
  189. pass # guard unavailable → plain best-effort open
  190. try:
  191. import webbrowser
  192. return bool(webbrowser.open(url))
  193. except Exception:
  194. return False
  195. def _open_or_print_url(self, url) -> None:
  196. """Open ``url`` in the browser, or print it when no graphical browser can be used."""
  197. if not self._open_url_in_browser(url):
  198. print(f" {t('cli.billing.open_this_url', url=url)}")
  199. # ── /usage — Nous balance block ──
  200. def _print_nous_credits_block(self) -> bool:
  201. """Nous dollar balance block (two bars); True if anything printed. Shared dollar model first, then
  202. legacy ``nous_credits_lines``. Agent-independent (TUI slash-worker has no live agent). Fail-open."""
  203. from cli import _cprint, _b, _d
  204. usage = self._try_usage_model()
  205. if usage is not None and usage.available:
  206. from agent.billing_usage import format_renews
  207. plan = usage.plan_name or (t("cli.billing.plan_free") if usage.status == "free" else None)
  208. renews_display = usage.renews_display or format_renews(usage.renews_at)
  209. renews = t("cli.billing.renews_suffix", date=renews_display) if renews_display else ""
  210. head = [f" {_b(t('cli.billing.plan_line', plan=plan, renews=renews))}"] if plan else []
  211. head += self._usage_bar_lines(usage, usage.plan_name)
  212. tail = []
  213. if usage.status == "free":
  214. tail.append(f" {_d(t('cli.billing.free_models_only_hint'))}")
  215. elif usage.status == "low":
  216. _amt = f"${usage.total_spendable_usd:,.2f}" if usage.total_spendable_usd is not None else t("cli.billing.under_five")
  217. tail.append(f" {t('cli.billing.low_balance_usage', amount=_amt)}")
  218. # All via _cprint like the Plan line: print()/_cprint() flush to different buffers under
  219. # patch_stdout. "Total spendable" alone does not count as printed (legacy lines still follow).
  220. if plan:
  221. print()
  222. for ln in head:
  223. _cprint(ln)
  224. self._print_total_spendable(usage, _cprint)
  225. for ln in tail:
  226. _cprint(ln)
  227. if head or tail:
  228. return True
  229. from agent.account_usage import nous_credits_lines
  230. lines = nous_credits_lines(
  231. credits_state=getattr(getattr(self, "agent", None), "_credits_state", None),
  232. )
  233. if not lines:
  234. return False
  235. print()
  236. for line in lines:
  237. print(f" {line}")
  238. return True
  239. def _print_usage_cta(self) -> None:
  240. """The `/usage` call-to-action; mirrors the TUI's ``USAGE_CTA``. Nous-account only."""
  241. self._dim(t("cli.billing.usage_cta"))
  242. # ── /subscription — view plan + change it (CLI surface) ──
  243. def _show_subscription(self):
  244. """`/subscription` (alias `/upgrade`). Deep-links NAS's ``/manage-subscription`` (NOT Stripe); never charges."""
  245. from agent.subscription_view import build_subscription_state, subscription_manage_url
  246. state = build_subscription_state()
  247. if not state.logged_in:
  248. self._print_logged_out(state, t("cli.subscription.load_failed_label"), "/subscription")
  249. return
  250. if state.context == "team": # no personal plan — teams run on a shared balance
  251. self._block_header("☤", t("cli.subscription.team_header"))
  252. self._print_org_line(state)
  253. print(f" {t('cli.subscription.team_connected', org=state.org_name or t('cli.subscription.a_team_org'))}")
  254. self._dim(t("cli.subscription.personal_note"))
  255. return
  256. self._subscription_overview(state, subscription_manage_url(state))
  257. def _subscription_overview(self, state, manage_url):
  258. """Plan read block, then the action: portal hand-off (member / non-interactive), catalog (Free), change menu."""
  259. from cli import _cprint, _b, _d
  260. from agent.billing_usage import format_renews
  261. usage = self._try_usage_model()
  262. c = state.current
  263. is_free = not (c and c.tier_id)
  264. can_change = state.can_change_plan
  265. plan_name = (c.tier_name or c.tier_id) if c else (usage.plan_name if usage else None)
  266. u_status = usage.status if usage else None
  267. _spend = usage.total_spendable_usd if usage else None
  268. renews_display = usage.renews_display if usage else None
  269. if not renews_display and c and c.cycle_ends_at:
  270. renews_display = format_renews(c.cycle_ends_at)
  271. # Headline flags the pending change ("→ Plus" / "→ cancels"); the banner (cancel > downgrade)
  272. # leads so it can't read as "nothing happened".
  273. _flip, _trans = "", None
  274. _your_plan = t("cli.subscription.your_plan")
  275. if c and c.cancel_at_period_end:
  276. _flip = t("cli.subscription.status_flip_cancels")
  277. _trans = (c.tier_name or _your_plan, t("cli.subscription.cancels"),
  278. format_renews(c.cancellation_effective_at) or t("cli.subscription.end_of_billing_period"))
  279. elif c and c.pending_downgrade_tier_name:
  280. _flip = t("cli.subscription.status_flip_to", tier=c.pending_downgrade_tier_name)
  281. _trans = (c.tier_name or _your_plan, c.pending_downgrade_tier_name,
  282. format_renews(c.pending_downgrade_at) or t("cli.subscription.end_of_cycle"))
  283. _left = t("cli.subscription.status_left", amount=f"{_spend:,.2f}") if _spend is not None else ""
  284. if u_status == "low" and _spend is not None:
  285. _tail = ""
  286. elif not can_change:
  287. _tail = t("cli.subscription.status_view_only")
  288. else:
  289. _tail = t("cli.subscription.status_renews", date=renews_display) if renews_display else ""
  290. if plan_name:
  291. status = t("cli.subscription.status_line", plan=plan_name, flip=_flip, left=_left, tail=_tail)
  292. else:
  293. status = t("cli.subscription.status_free")
  294. # All-_cprint (blanks included) so the block orders deterministically even when piped.
  295. _cprint("")
  296. if _trans:
  297. _from, _to, _when = _trans
  298. _cprint(f" ⏳ {_b(t('cli.subscription.scheduled_change'))}")
  299. _cprint(" " + t("cli.subscription.scheduled_change_line", from_plan=_from, to_plan=_to,
  300. when=_d(t("cli.subscription.scheduled_when", when=_when))))
  301. self._dim(t("cli.subscription.keep_until_then", plan=_from))
  302. _cprint("")
  303. _cprint(f" ☤ {_b(status)}")
  304. print(f" {_RULE}")
  305. for _bar_ln in self._usage_bar_lines(usage, plan_name):
  306. print(_bar_ln)
  307. self._print_total_spendable(usage, print)
  308. if is_free:
  309. self._dim(t("cli.subscription.paid_models_need_subscription"))
  310. elif u_status == "low":
  311. _amt = f"${_spend:,.2f}" if _spend is not None else t("cli.billing.under_five")
  312. _cprint(f" {t('cli.subscription.low_balance', amount=_amt)}")
  313. self._print_org_line(state)
  314. print(f" {_RULE}")
  315. if not can_change:
  316. self._dim(t("cli.subscription.plan_changes_need_admin"), lead=True)
  317. if manage_url:
  318. print(f" {t('cli.billing.manage_on_portal_url', url=manage_url)}")
  319. elif not self._app: # non-interactive (TUI slash-worker / piped): the modal can't run
  320. print()
  321. if manage_url:
  322. print(f" {t('cli.subscription.manage_url_line', url=manage_url)}")
  323. print(f" {t('cli.subscription.open_then_rerun')}")
  324. elif is_free: # a NEW subscription needs a fresh card → catalog + portal deep-link only
  325. self._subscription_free_catalog(state, manage_url)
  326. else:
  327. self._subscription_change_menu(state, manage_url)
  328. def _subscription_free_catalog(self, state, manage_url):
  329. """Free + admin + interactive: catalog → pick → portal deep-link ``plan=<tier_id>`` (a new sub needs a card)."""
  330. from agent.subscription_view import format_tier_row, selectable_tiers, subscription_manage_url
  331. tiers = selectable_tiers(state)
  332. if not tiers:
  333. self._subscription_open_portal(state, manage_url, verb=t("cli.subscription.start_subscription"))
  334. return
  335. self._block_header("☤", t("cli.subscription.choose_plan"))
  336. for i, tier in enumerate(tiers, 1):
  337. print(f" {i}. {format_tier_row(tier)}")
  338. self._dim(t("cli.subscription.start_opens_portal"))
  339. choices = [(tier.tier_id, format_tier_row(tier), t("cli.subscription.desc_start_on_portal", name=tier.name))
  340. for tier in tiers]
  341. choices.append(_cancel_row())
  342. raw = self._prompt_text_input_modal(
  343. title=t("cli.subscription.start_subscription"), detail=t("cli.subscription.pick_plan_detail"), choices=choices)
  344. # Rows are numbered → accept a bare number (the normalizer only knows confirm-dialog digits).
  345. _digit = (raw or "").strip()
  346. _by_row = tiers[int(_digit) - 1] if _digit.isdigit() and 1 <= int(_digit) <= len(tiers) else None
  347. choice = _by_row.tier_id if _by_row else self._normalize_slash_confirm_choice(raw, choices)
  348. if not choice or choice == "cancel":
  349. print(f" {t('cli.subscription.cancelled_no_plan_started')}")
  350. return
  351. tier_url = subscription_manage_url(state, tier_id=choice) or manage_url
  352. if not tier_url:
  353. self._dim(t("cli.billing.no_manage_url"))
  354. return
  355. picked = next((tier for tier in tiers if tier.tier_id == choice), None)
  356. label = picked.name if picked else t("cli.subscription.your_plan")
  357. if self._open_url_in_browser(tier_url):
  358. print(f" {t('cli.subscription.opening_portal_to_start', plan=label)}")
  359. else:
  360. print(f" {t('cli.subscription.open_url_to_start', plan=label, url=tier_url)}")
  361. print(f" {t('cli.subscription.finish_in_browser')}")
  362. def _subscription_open_portal(self, state, manage_url, *, verb=None):
  363. """Open / copy the manage-subscription URL — the portal hand-off."""
  364. verb = verb or t("cli.subscription.manage_your_subscription")
  365. print()
  366. if not manage_url:
  367. self._dim(t("cli.billing.no_manage_url"))
  368. return
  369. choices = [
  370. ("open", verb, t("cli.subscription.desc_open_subscription_page")),
  371. ("copy", t("cli.subscription.choice_copy_link"), t("cli.subscription.desc_copy_link")),
  372. _cancel_row()]
  373. choice = self._modal_choice(verb, "", choices)
  374. if choice == "open":
  375. self._open_or_print_url(manage_url)
  376. print()
  377. print(f" {t('cli.subscription.finish_in_browser')}")
  378. elif choice == "copy":
  379. try:
  380. self._write_osc52_clipboard(manage_url)
  381. print(f" {t('cli.subscription.copied', url=manage_url)}")
  382. except Exception:
  383. print(f" {t('cli.subscription.manage_url', url=manage_url)}")
  384. else:
  385. print(f" {t('cli.billing.cancelled_yellow')}")
  386. def _subscription_change_menu(self, state, manage_url):
  387. """The in-terminal change menu for a paid admin/owner (interactive)."""
  388. c = state.current
  389. # A scheduled change makes undo the likeliest intent → promote it first. The Close row is
  390. # "close" (not "cancel") so typing "cancel" can't be confused with "Cancel subscription".
  391. if c and (c.cancel_at_period_end or c.pending_downgrade_tier_name):
  392. keep_name = c.tier_name or t("cli.subscription.your_plan")
  393. head = [("keep", t("cli.subscription.choice_keep_plan", plan=keep_name), t("cli.subscription.desc_keep_plan")),
  394. _change_plan_row()]
  395. else:
  396. head = [_change_plan_row(),
  397. ("cancel_sub", t("cli.subscription.choice_cancel_subscription"), t("cli.subscription.desc_cancel_subscription"))]
  398. choice = self._modal_choice(t("cli.subscription.manage_your_subscription"), "", head + _change_menu_tail())
  399. action = {
  400. "change": lambda: self._subscription_pick_tier(state),
  401. "keep": lambda: self._subscription_apply(state, ("resume", None)),
  402. "cancel_sub": lambda: self._subscription_confirm_cancel(state),
  403. "portal": lambda: self._subscription_open_portal(state, manage_url)}.get(choice)
  404. if action:
  405. action()
  406. else:
  407. print(f" {t('cli.subscription.closed_no_change')}")
  408. def _subscription_pick_tier(self, state):
  409. """Tier picker → preview → confirm. Paid tiers other than current (dropping to free = cancellation)."""
  410. from agent.subscription_view import format_tier_row, is_upgrade, selectable_tiers
  411. c = state.current
  412. selectable = selectable_tiers(state)
  413. if not selectable:
  414. print(f" {t('cli.subscription.no_other_plans')}")
  415. return
  416. choices = []
  417. for tier in selectable:
  418. direction = t("cli.subscription.direction_upgrade") if is_upgrade(state, tier.tier_id) else t("cli.subscription.direction_downgrade")
  419. choices.append((tier.tier_id, t("cli.subscription.tier_row", row=format_tier_row(tier), direction=direction),
  420. t("cli.subscription.desc_switch_to", name=tier.name)))
  421. choices.append(_cancel_row(label_key="cli.billing.choice_back"))
  422. choice = self._modal_choice(
  423. t("cli.subscription.change_plan_title"),
  424. t("cli.subscription.current_pick_detail", plan=c.tier_name if c else t("cli.billing.plan_free")), choices)
  425. if not choice or choice == "cancel":
  426. print(f" {t('cli.subscription.cancelled_no_plan_change')}")
  427. return
  428. self._subscription_preview_and_confirm(state, choice)
  429. def _subscription_preview_and_confirm(self, state, tier_id, *, allow_stepup=True):
  430. """Preview → effect → confirm+apply. ``allow_stepup=False`` (post-grant replay) never re-prompts a step-up."""
  431. from cli import _cprint, _b, _d
  432. from agent.subscription_view import is_upgrade, subscription_change_preview_from_payload, subscription_manage_url
  433. from hermes_cli.nous_billing import BillingError, BillingScopeRequired, post_subscription_preview
  434. self._dim(t("cli.subscription.checking_change"))
  435. try:
  436. payload = post_subscription_preview(subscription_type_id=tier_id)
  437. except BillingScopeRequired:
  438. if allow_stepup:
  439. self._subscription_handle_scope_required(state, retry=("preview", tier_id))
  440. else:
  441. print(f" {t('cli.billing.stepup_stale')}")
  442. return
  443. except BillingError as exc:
  444. self._subscription_render_error(state, exc)
  445. return
  446. p = subscription_change_preview_from_payload(payload)
  447. effect = p.effect
  448. target = p.target_tier_name or t("cli.subscription.the_selected_plan")
  449. print()
  450. if effect == "no_op":
  451. self._dim(t("cli.subscription.already_on_nothing_to_change", plan=target))
  452. return
  453. if effect not in ("charge_now", "scheduled"):
  454. # blocked OR unknown effect → fail SAFE (never schedule on an unrecognized string) and
  455. # re-offer the portal. plan= rides along only for an UPGRADE hand-off (downgrades stay native).
  456. _cprint(f" 🟡 {p.reason or t('cli.subscription.cannot_confirm_here')}")
  457. _plan = tier_id if is_upgrade(state, tier_id) else None
  458. _mu = subscription_manage_url(state, tier_id=_plan)
  459. if _mu:
  460. print(f" {t('cli.billing.manage_on_portal_url', url=_mu)}")
  461. return
  462. _tag = t("cli.subscription.tag_charged_now") if effect == "charge_now" else t("cli.subscription.tag_scheduled_not_today")
  463. _cprint(f" {_b(t('cli.subscription.confirm_plan_change'))} {_d(_tag)}")
  464. if effect == "charge_now":
  465. _amt = f"${p.amount_due_now_cents / 100:.2f}" if p.amount_due_now_cents is not None else None
  466. _charged = t("cli.subscription.charged_amount_now", amount=_amt) if _amt else t("cli.subscription.charged_prorated_now")
  467. _cprint(f" {t('cli.subscription.upgrade_will_be_charged', plan=target, charged=_charged)}")
  468. # Best-effort: name the exact card, but only when the resolver rung matches what a
  469. # subscription charge actually uses (subPin / customerDefault — Stripe's precedence).
  470. _card_line = t("cli.subscription.card_on_subscription_charged")
  471. try:
  472. from agent.billing_view import build_billing_state
  473. _bs = build_billing_state(timeout=6.0)
  474. _c = _bs.card if _bs.logged_in else None
  475. if _c is not None and _c.resolved_via in ("subPin", "customerDefault"):
  476. _card_line = t("cli.subscription.named_card_on_subscription_charged", card=_c.masked)
  477. except Exception:
  478. pass
  479. self._dim(_card_line)
  480. pay_label = (t("cli.subscription.choice_pay_and_upgrade", amount=_amt) if _amt
  481. else t("cli.subscription.choice_upgrade_now_prorated"))
  482. action = ("upgrade", tier_id)
  483. # The money-moving row is NOT the default — a bare Enter hits "Go back", so a stray keystroke can't charge.
  484. confirm_choices = [
  485. _cancel_row(label_key="cli.billing.choice_go_back", desc_key="cli.billing.desc_do_not_charge"),
  486. ("yes", pay_label, t("cli.subscription.desc_charge_and_upgrade"))]
  487. else: # scheduled (whitelisted above)
  488. _when = (p.effective_at[:10] if (p.effective_at and len(p.effective_at) >= 10)
  489. else t("cli.subscription.end_of_billing_period"))
  490. _cprint(f" {t('cli.subscription.change_takes_effect', plan=target, when=_when)}")
  491. pay_label = t("cli.subscription.choice_schedule_change", plan=target)
  492. action = ("schedule", tier_id)
  493. confirm_choices = [
  494. ("yes", pay_label, t("cli.subscription.desc_apply_change")),
  495. _cancel_row(label_key="cli.billing.choice_go_back", desc_key="cli.subscription.desc_do_not_change")]
  496. if p.monthly_credits_delta:
  497. self._dim(t("cli.subscription.monthly_credits_change", delta=p.monthly_credits_delta))
  498. if self._modal_choice(pay_label, "", confirm_choices) != "yes":
  499. print(f" {t('cli.subscription.cancelled_no_plan_change')}")
  500. return
  501. self._subscription_apply(state, action, allow_stepup=allow_stepup)
  502. def _subscription_confirm_cancel(self, state):
  503. """Confirm, then schedule a cancellation at period end."""
  504. from cli import _cprint, _b, _d
  505. from agent.billing_usage import format_renews
  506. c = state.current
  507. _end = ((format_renews(c.cycle_ends_at) if (c and c.cycle_ends_at) else None)
  508. or t("cli.subscription.end_of_billing_period"))
  509. print()
  510. _cprint(f" {_b(t('cli.subscription.confirm_cancellation'))} {_d(t('cli.subscription.tag_scheduled_not_today'))}")
  511. _cprint(" " + t("cli.subscription.cancel_stays_active_until",
  512. plan=(c.tier_name if c else t("cli.subscription.your_plan")), end=_end))
  513. self._dim(t("cli.subscription.keep_remaining_credits"))
  514. if self._modal_choice(t("cli.subscription.cancel_subscription_question"), "", _cancel_sub_choices()) != "yes":
  515. print(f" {t('cli.subscription.cancelled_plan_unchanged')}")
  516. return
  517. self._subscription_apply(state, ("cancel", None))
  518. def _subscription_apply(self, state, action, idempotency_key=None, *, allow_stepup=True):
  519. """Run ("upgrade"|"schedule", tier_id) / ("cancel"|"resume", None); scope denial → step-up + ONE replay, same key."""
  520. from cli import _cprint
  521. from hermes_cli.nous_billing import (
  522. BillingError, BillingTransient, BillingRemoteSpendingRevoked, BillingScopeRequired, BillingSessionRevoked,
  523. delete_subscription_pending_change, post_subscription_upgrade, put_subscription_pending_change)
  524. kind, arg = action
  525. key = None
  526. if kind == "upgrade":
  527. from agent.billing_view import new_idempotency_key
  528. key = idempotency_key or new_idempotency_key()
  529. try:
  530. if kind == "upgrade":
  531. res = post_subscription_upgrade(subscription_type_id=arg, idempotency_key=key) or {}
  532. status = res.get("status")
  533. name = res.get("targetTierName") or t("cli.subscription.your_new_plan")
  534. if status in _UPGRADE_OK_KEYS:
  535. self._ok(t(_UPGRADE_OK_KEYS[status], name=name))
  536. elif status in _UPGRADE_STATUS_KEYS:
  537. line_key, echo_url = _UPGRADE_STATUS_KEYS[status]
  538. _cprint(f" {t(line_key)}")
  539. if echo_url and res.get("recoveryUrl"):
  540. _cprint(f" {t('cli.billing.portal_line', url=res.get('recoveryUrl'))}")
  541. else: # unknown / absent 2xx status → also ambiguous, not a flat failure
  542. self._subscription_render_upgrade_ambiguous(None)
  543. return
  544. pending = {
  545. "schedule": (put_subscription_pending_change, {"subscription_type_id": arg}),
  546. "cancel": (put_subscription_pending_change, {"cancel": True}),
  547. "resume": (delete_subscription_pending_change, {})}.get(kind)
  548. if pending:
  549. pending[0](**pending[1])
  550. self._ok(t(_PENDING_OK_KEYS[kind]))
  551. self._dim(t("cli.subscription.rerun_to_review"))
  552. except BillingScopeRequired: # rejects BEFORE charging → route to the step-up
  553. if allow_stepup:
  554. self._subscription_handle_scope_required(state, retry=action, idempotency_key=key)
  555. else:
  556. print(f" {t('cli.billing.stepup_stale')}")
  557. except BillingError as exc:
  558. # Upgrade only: deterministic PRE-charge rejections (Transient/401/403 types, 4xx codes)
  559. # never reached Stripe → recovery copy. Transport / 5xx is INDETERMINATE (NAS may have
  560. # charged) → steer to a re-check, never a blind retry (a fresh key can't dedup).
  561. _pre_charge = (BillingTransient, BillingSessionRevoked, BillingRemoteSpendingRevoked)
  562. _ambiguous = (exc.error in ("network_error", "endpoint_unavailable")
  563. or exc.status is None or exc.status >= 500)
  564. if kind == "upgrade" and _ambiguous and not isinstance(exc, _pre_charge):
  565. self._subscription_render_upgrade_ambiguous(exc)
  566. else:
  567. self._subscription_render_error(state, exc)
  568. def _subscription_handle_scope_required(self, state, *, retry, idempotency_key=None):
  569. """insufficient_scope → step-up, then replay `retry` ONCE so the user never re-runs the command."""
  570. granted = self._step_up_remote_spending(
  571. explain=t("cli.subscription.stepup_explain"),
  572. noninteractive_msg=f" {t('cli.subscription.stepup_noninteractive')}",
  573. declined_msg=f" {t('cli.subscription.stepup_declined')}",
  574. not_granted_msg=f" {t('cli.subscription.stepup_not_granted')}")
  575. if not granted:
  576. return
  577. self._ok(t("cli.billing.remote_spending_allowed"))
  578. # Bust the 30s token cache (it still holds the pre-grant token; _request only busts on 401).
  579. try:
  580. from hermes_cli import nous_billing as _nb
  581. _nb.invalidate_cached_token()
  582. except Exception:
  583. pass
  584. # Re-fetch fresh state, then replay the held action ONCE (allow_stepup=False).
  585. from agent.subscription_view import build_subscription_state
  586. try:
  587. fresh = build_subscription_state()
  588. except Exception:
  589. fresh = state
  590. if retry[0] == "preview":
  591. self._subscription_preview_and_confirm(fresh, retry[1], allow_stepup=False)
  592. else:
  593. self._subscription_apply(fresh, retry, idempotency_key=idempotency_key, allow_stepup=False)
  594. def _subscription_render_error(self, state, exc):
  595. """Render a subscription BillingError (a lighter _billing_render_charge_error)."""
  596. from cli import _cprint
  597. msg = str(exc) or t("cli.billing.something_went_wrong")
  598. if exc.error == "insufficient_scope": # defensive: the flow routes scope to the step-up before here
  599. _cprint(f" {t('cli.subscription.remote_spending_not_allowed_yet')}")
  600. elif exc.error in ("subscription_mutation_rejected", "preview_rejected"):
  601. _cprint(f" 🟡 {msg}")
  602. else:
  603. _cprint(f" 🔴 {msg}")
  604. self._print_portal_line(exc)
  605. def _subscription_render_upgrade_ambiguous(self, exc):
  606. """AMBIGUOUS outcome (NAS may have charged) → steer to a re-check, never a blind retry (key isn't persisted)."""
  607. from cli import _cprint
  608. _cprint(f" {t('cli.subscription.upgrade_ambiguous')}")
  609. self._dim(t("cli.subscription.rerun_to_check_plan"))
  610. self._print_portal_line(exc)
  611. # ── /topup — Remote Spending (CLI surface, all 5 screens) ──
  612. def _show_billing(self, command: str = "/topup"):
  613. """`/topup` — ZERO sub-commands (argument ignored; Overview is the only route). Non-interactive never
  614. prompts. Money is Decimal end-to-end; the terminal never collects card details."""
  615. from agent.billing_view import build_billing_state
  616. state = build_billing_state()
  617. if not state.logged_in:
  618. self._print_logged_out(state, t("cli.billing.load_failed_label"), "/topup")
  619. return
  620. self._billing_overview(state)
  621. def _billing_portal_hint(self, state, *, reason: str = "") -> None:
  622. """Print a portal deep-link line (the funnel for portal-only actions)."""
  623. if not state.portal_url:
  624. return
  625. if reason:
  626. print(f" {reason}")
  627. print(f" {t('cli.billing.manage_on_portal_url', url=state.portal_url)}")
  628. def _billing_require_admin(self, state, *, icon="💳 ", off_reason_key="cli.billing.killswitch_reason_buy") -> bool:
  629. """Admin + org kill-switch gate; portal funnel + False when blocked. ``icon`` adds a blank line + prefix."""
  630. if state.can_change_plan and state.cli_billing_enabled:
  631. return True
  632. if icon:
  633. print()
  634. if not state.can_change_plan:
  635. self._dim(t("cli.billing.actions_require_admin"), icon=icon)
  636. self._billing_portal_hint(state)
  637. else:
  638. self._dim(t("cli.billing.remote_spending_off_for_org"), icon=icon)
  639. self._billing_portal_hint(state, reason=t(off_reason_key))
  640. return False
  641. def _billing_overview(self, state):
  642. """Screen 1 — balance, bars, menu. No scope preflight (a charge 403s); a missing card does NOT gate it."""
  643. from cli import _cprint, _b
  644. from agent.billing_view import format_money
  645. usage = self._try_usage_model()
  646. print()
  647. _cprint(f" 💳 {_b(t('cli.billing.topup_header', balance=format_money(state.balance_usd)))}")
  648. self._print_org_line(state)
  649. print(f" {_RULE}")
  650. for _bar_ln in self._usage_bar_lines(usage, usage.plan_name if usage else None):
  651. print(_bar_ln)
  652. ar = state.auto_reload
  653. if ar is not None:
  654. if ar.enabled:
  655. print(f" {t('cli.billing.auto_reload_on_line', threshold=format_money(ar.threshold_usd), reload_to=format_money(ar.reload_to_usd))}")
  656. else:
  657. print(f" {t('cli.billing.auto_reload_off_line')}")
  658. if state.keep_going_on_credits is not None:
  659. print(f" {t('cli.billing.keep_going_on_line' if state.keep_going_on_credits else 'cli.billing.keep_going_off_line')}")
  660. if state.can_change_plan and state.cli_billing_enabled: # card at a glance, full-menu case only
  661. if state.card is not None:
  662. print(f" {t('cli.billing.card_line', card=state.card.display)}")
  663. else:
  664. self._dim(t("cli.billing.no_saved_card_add_funds_hint"))
  665. print(f" {_RULE}")
  666. # Action gating: admin + kill-switch for charge/auto-reload; everyone gets portal.
  667. if not self._billing_require_admin(state, icon="", off_reason_key="cli.billing.killswitch_reason_overview"):
  668. self._billing_offer_keep_going_off(state)
  669. return
  670. if not self._app: # non-interactive: no modal, just the portal funnel
  671. self._billing_portal_hint(state)
  672. return
  673. # One-time vs automatic — the distinction stated up front in each first sentence.
  674. self._dim(t("cli.billing.add_funds_now_hint"))
  675. _amounts = [ar.reload_to_usd, ar.threshold_usd] if ar is not None and ar.enabled else [None]
  676. if all(a is not None and a.is_finite() for a in _amounts):
  677. _auto_line = t("cli.billing.refill_when_low_amounts", reload_to=format_money(ar.reload_to_usd),
  678. threshold=format_money(ar.threshold_usd))
  679. else:
  680. _auto_line = t("cli.billing.refill_when_low_generic")
  681. self._dim(_auto_line)
  682. print(f" {_RULE}")
  683. # No "Allow Remote Spending" item — discovered at pay time. "Add funds" charges the org's
  684. # portal-saved card (server-held; no card ref leaves the client).
  685. # "hermes" only on window plans (the portal sends the setting only there).
  686. choices = _topup_menu_choices()
  687. if state.keep_going_on_credits is not None:
  688. choices.insert(2, _keep_going_row()) # after Auto-reload
  689. action = {
  690. "buy": self._billing_buy_flow,
  691. "auto": self._billing_auto_reload_flow,
  692. "hermes": self._billing_keep_going_on_credits_flow,
  693. "limit": self._billing_limit_screen,
  694. "portal": self._billing_open_portal}.get(self._modal_choice(t("cli.billing.topup_title"), "", choices))
  695. if action:
  696. action(state)
  697. else:
  698. print(f" {t('cli.billing.cancelled')}")
  699. def _billing_open_portal(self, state):
  700. if not state.portal_url:
  701. print(f" {t('cli.billing.no_portal_url')}")
  702. return
  703. self._open_or_print_url(state.portal_url)
  704. print(f" {t('cli.billing.complete_in_browser')}")
  705. def _billing_add_card_flow(self, state):
  706. """No card → add it on the portal (never in-terminal), bounded re-check loop. Refreshed state, or None."""
  707. from cli import _cprint
  708. self._block_header("💳", t("cli.billing.add_card_first"), rule=False)
  709. _cprint(f" {t('cli.billing.no_saved_card')}")
  710. self._dim(t("cli.billing.add_card_once_hint"))
  711. for _ in range(8): # bounded: portal-open plus a handful of re-checks
  712. choice = self._modal_choice(t("cli.billing.add_card_title"), "", _add_card_choices())
  713. if choice == "portal":
  714. self._billing_open_portal(state)
  715. self._dim(t("cli.billing.add_card_then_recheck"))
  716. elif choice == "recheck":
  717. from agent.billing_view import build_billing_state
  718. try:
  719. fresh = build_billing_state()
  720. except Exception:
  721. fresh = None
  722. if fresh is not None and fresh.logged_in:
  723. state = fresh
  724. if state.card is not None:
  725. self._ok(t("cli.billing.card_found_continuing", card=state.card.display))
  726. return state
  727. print(f" {t('cli.billing.still_no_card')}")
  728. else:
  729. break
  730. print(f" {t('cli.billing.cancelled_no_funds')}")
  731. return None
  732. def _billing_buy_flow(self, state):
  733. """Screen 2 (presets) → Screen 3 (confirm+charge+poll). No scope preflight: react to the server's 403s."""
  734. from agent.billing_view import format_money, validate_charge_amount
  735. if not self._billing_require_admin(state):
  736. return
  737. if not self._app:
  738. self._block_header("💳", t("cli.billing.add_funds"), rule=False)
  739. print(f" {t('cli.billing.presets', presets=', '.join(format_money(p) for p in state.charge_presets))}")
  740. print(f" {t('cli.billing.run_interactive_to_purchase')}")
  741. self._billing_portal_hint(state)
  742. return
  743. if state.card is None: # guided add-card path first, so the amount pick can't 403
  744. state = self._billing_add_card_flow(state)
  745. if state is None or state.card is None:
  746. return
  747. preset_choices = [(str(p), format_money(p), t("cli.billing.desc_one_time_purchase")) for p in state.charge_presets]
  748. preset_choices.append(("custom", t("cli.billing.choice_custom_amount"), t("cli.billing.desc_custom_amount")))
  749. preset_choices.append(_cancel_row())
  750. card = state.card
  751. choice = self._modal_choice(
  752. t("cli.billing.add_funds"),
  753. t("cli.billing.payment_line", card=card.display) if card else t("cli.billing.no_saved_card_short"),
  754. preset_choices)
  755. if not choice or choice == "cancel":
  756. print(f" {t('cli.billing.cancelled_no_funds')}")
  757. return
  758. from decimal import Decimal
  759. if choice == "custom":
  760. entered = self._prompt_text_input(f" {t('cli.billing.amount_prompt')} ")
  761. if entered is None: # cancelled (e.g. slash-worker can't prompt off-thread)
  762. print(f" {t('cli.billing.cancelled_no_funds')}")
  763. return
  764. v = validate_charge_amount(entered or "", min_usd=state.min_usd, max_usd=state.max_usd)
  765. if not v.ok:
  766. print(f" 🔴 {v.error}")
  767. return
  768. amount = v.amount
  769. else:
  770. try:
  771. amount = Decimal(choice)
  772. except Exception:
  773. print(f" {t('cli.billing.invalid_selection')}")
  774. return
  775. self._billing_confirm_and_charge(state, amount)
  776. def _billing_confirm_and_charge(self, state, amount):
  777. """Screen 3 — confirm total + consent, charge, then poll to settlement."""
  778. from agent.billing_view import format_money, new_idempotency_key
  779. card = state.card
  780. self._block_header("💳", t("cli.billing.confirm_purchase"))
  781. print(f" {t('cli.billing.total_line', amount=format_money(amount))}")
  782. if card:
  783. print(f" {t('cli.billing.payment_line', card=card.display)}")
  784. if card.provenance is None: # older NAS without provenance → generic line
  785. self._dim(t("cli.billing.portal_card_will_be_charged"))
  786. print(f" {_RULE}")
  787. self._dim(t("cli.billing.consent_charge"))
  788. confirm_choices = [
  789. ("pay", t("cli.billing.choice_pay_now", amount=format_money(amount)), t("cli.billing.desc_submit_charge")),
  790. ("portal", t("cli.billing.choice_manage_on_portal"), t("cli.billing.desc_manage_card_billing")),
  791. _cancel_row(label_key="cli.billing.choice_go_back", desc_key="cli.billing.desc_do_not_charge")]
  792. if not self._app:
  793. print(f" {t('cli.billing.run_interactive_to_confirm')}")
  794. return
  795. choice = self._modal_choice(
  796. t("cli.billing.pay_question", amount=format_money(amount)),
  797. card.display if card else t("cli.billing.no_saved_card_lower"), confirm_choices)
  798. if choice == "portal":
  799. self._billing_open_portal(state)
  800. return
  801. if choice != "pay":
  802. print(f" {t('cli.billing.cancelled_no_funds')}")
  803. return
  804. key = new_idempotency_key() # reused on the post-step-up resume so a double-submit collapses
  805. self._billing_submit_and_poll(
  806. state, amount, key, missing_msg=f" 🔴 {t('cli.billing.no_charge_id')}",
  807. status_msg=t("cli.billing.charge_submitted"),
  808. on_scope=lambda: self._billing_handle_scope_required(state, amount=amount, idempotency_key=key))
  809. def _billing_submit_and_poll(self, state, amount, key, *, missing_msg, status_msg, on_scope=None):
  810. """POST the charge, then poll. ``on_scope`` handles a scope denial (first submit); else it renders."""
  811. from cli import _cprint, _d
  812. from hermes_cli.nous_billing import BillingError, BillingScopeRequired, post_charge
  813. try:
  814. result = post_charge(amount_usd=amount, idempotency_key=key)
  815. except BillingError as exc:
  816. if on_scope is not None and isinstance(exc, BillingScopeRequired):
  817. on_scope()
  818. else:
  819. self._billing_render_charge_error(state, exc)
  820. return
  821. charge_id = result.get("chargeId")
  822. if not charge_id:
  823. print(missing_msg)
  824. return
  825. _cprint(f" {_d(status_msg)}")
  826. self._billing_poll_charge(state, charge_id, amount)
  827. def _billing_poll_charge(self, state, charge_id, amount):
  828. """Poll loop: 2s interval, 5-min cap, cancellable. settled = ledger truth."""
  829. import time as _time
  830. from agent.billing_view import format_money, parse_money
  831. from hermes_cli.nous_billing import BillingError, BillingTransient, get_charge_status
  832. deadline = _time.time() + 300
  833. while _time.time() < deadline:
  834. try:
  835. status = get_charge_status(charge_id)
  836. except BillingTransient as exc: # retry-after, NOT a failure — back off and keep polling
  837. _time.sleep(min(exc.retry_after or 5, 30))
  838. continue
  839. except BillingError as exc:
  840. print(f" {t('cli.billing.could_not_check_charge', error=exc)}")
  841. return
  842. state_str = status.get("status")
  843. if state_str == "settled":
  844. amt = status.get("amountUsd")
  845. _added = format_money(parse_money(amt)) if amt else format_money(amount)
  846. print(f" {t('cli.billing.added_to_balance', amount=_added)}")
  847. return
  848. if state_str == "failed":
  849. self._billing_render_charge_failed(state, status.get("reason"))
  850. return
  851. _time.sleep(2.0) # pending
  852. print(f" {t('cli.billing.still_processing')}")
  853. self._billing_portal_hint(state)
  854. def _billing_render_charge_failed(self, state, reason):
  855. """Poll `failed` reasons → the right copy + portal funnel."""
  856. reason = (reason or "").strip()
  857. key = _CHARGE_FAILED_KEYS.get(reason)
  858. print(f" {t(key)}" if key else f" {t('cli.billing.charge_failed_generic', reason=reason or 'processing_error')}")
  859. self._billing_portal_hint(state)
  860. def _billing_render_charge_error(self, state, exc):
  861. """Submit-time BillingError. Order matters: revoked/session before code lookups; Transient before scope."""
  862. from hermes_cli.nous_billing import BillingTransient, BillingRemoteSpendingRevoked, BillingSessionRevoked
  863. code = exc.error
  864. portal_url = exc.portal_url or state.portal_url
  865. if isinstance(exc, BillingRemoteSpendingRevoked) or code == "remote_spending_revoked":
  866. # This terminal's spend was revoked; recovery is reconnect.
  867. who = t("cli.billing.revoked_by_admin") if exc.actor == "admin" else t("cli.billing.revoked_by_you")
  868. print(f" {t('cli.billing.revoked_reconnect', who=who)}")
  869. elif isinstance(exc, BillingSessionRevoked) or code == "session_revoked":
  870. print(f" {t('cli.billing.session_logged_out')}")
  871. elif code in _CHARGE_ERROR_KEYS or exc.code == "remote_spending_disabled":
  872. # Fixed copy by `error`; the gate's dual error/code payload may carry it in `.code` only.
  873. print(f" {t(_CHARGE_ERROR_KEYS.get(code) or _CHARGE_ERROR_KEYS['cli_billing_disabled'])}")
  874. elif code == "monthly_cap_exceeded":
  875. remaining = (exc.payload or {}).get("remainingUsd")
  876. if remaining is not None:
  877. print(f" {t('cli.billing.monthly_cap_reached_headroom', remaining=remaining)}")
  878. else:
  879. print(f" {t('cli.billing.monthly_cap_reached')}")
  880. elif isinstance(exc, BillingTransient):
  881. wait = exc.retry_after
  882. mins = t("cli.billing.try_again_in_min", minutes=max(1, round(wait / 60))) if wait else ""
  883. print(f" {t('cli.billing.too_many_charges', mins=mins)}")
  884. elif code == "insufficient_scope":
  885. # Never leak the raw billing:manage scope (a raced post-grant replay can re-raise it).
  886. print(f" {t('cli.billing.remote_spending_needs_approval')}")
  887. else:
  888. print(f" 🔴 {exc}")
  889. if portal_url:
  890. print(f" {t('cli.billing.portal_line', url=portal_url)}")
  891. def _billing_handle_scope_required(self, state, *, amount=None, idempotency_key=None):
  892. """403 insufficient_scope → reauth, then resume ``amount`` on explicit confirm, reusing the idempotency key."""
  893. from agent.billing_view import build_billing_state, format_money, new_idempotency_key
  894. amount_str = format_money(amount) if amount is not None else t("cli.billing.your_topup")
  895. granted = self._step_up_remote_spending(
  896. explain=t("cli.billing.charge_stepup_explain", amount=amount_str),
  897. noninteractive_msg=f" {t('cli.billing.charge_stepup_noninteractive')}",
  898. declined_msg=f" {t('cli.billing.charge_stepup_declined')}",
  899. not_granted_msg=f" {t('cli.billing.charge_stepup_not_granted')}")
  900. if not granted:
  901. return
  902. # The token now has the scope, but the ORG kill-switch is a separate gate — re-fetch /state.
  903. fresh = build_billing_state()
  904. if not (fresh.logged_in and fresh.cli_billing_enabled):
  905. print(f" {t('cli.billing.allowed_but_org_off')}")
  906. self._billing_portal_hint(fresh)
  907. return
  908. if fresh.card is None: # half-done state: say so rather than a bare "✓ enabled"
  909. print(f" ✓ {t('cli.billing.allowed_no_card')}")
  910. self._dim(t("cli.billing.topup_on_portal_to_continue"))
  911. self._billing_portal_hint(fresh)
  912. return
  913. if amount is None: # scope-required hit outside a charge (e.g. auto-reload config)
  914. print(f" ✓ {t('cli.billing.allowed_run_topup')}")
  915. return
  916. print(f" ✓ {t('cli.billing.remote_spending_allowed')}")
  917. resume_choices = [
  918. ("resume", t("cli.billing.choice_resume_topup", amount=format_money(amount)), t("cli.billing.desc_resume_topup")),
  919. _cancel_row(desc_key="cli.billing.desc_do_not_charge")]
  920. if self._modal_choice(
  921. t("cli.billing.resume_topup_title"),
  922. t("cli.billing.resume_topup_detail", amount=format_money(amount)), resume_choices) != "resume":
  923. print(f" {t('cli.billing.cancelled_no_funds')}")
  924. return
  925. self._billing_submit_and_poll(
  926. fresh, amount, idempotency_key or new_idempotency_key(),
  927. missing_msg=f" {t('cli.billing.no_charge_id')}",
  928. status_msg=t("cli.billing.resuming_topup"))
  929. def _billing_auto_reload_flow(self, state):
  930. """Screen 4 — threshold + reload-to → PATCH. Prefills; validates ``reload_to > threshold``; "Turn off" if on."""
  931. from agent.billing_view import format_money, validate_charge_amount
  932. if not self._billing_require_admin(state):
  933. return
  934. card = state.card
  935. ar = state.auto_reload
  936. currently_on = bool(ar and ar.enabled)
  937. self._block_header("💳", t("cli.billing.auto_reload"))
  938. self._dim(t("cli.billing.auto_reload_hint"))
  939. if card:
  940. print(f" {t('cli.billing.card_on_file', card=card.masked)}")
  941. else:
  942. print(f" {t('cli.billing.no_saved_card_manage_portal')}")
  943. self._billing_portal_hint(state)
  944. return
  945. _current = (t("cli.billing.auto_reload_rule", threshold=format_money(ar.threshold_usd), reload_to=format_money(ar.reload_to_usd))
  946. if currently_on else "")
  947. if currently_on:
  948. print(f" {t('cli.billing.currently', rule=_current)}")
  949. if not self._app:
  950. print(f" {t('cli.billing.run_interactive_to_configure')}")
  951. self._billing_portal_hint(state)
  952. return
  953. if currently_on: # let the user turn it off without re-entering values
  954. top = self._modal_choice(t("cli.billing.auto_reload"), t("cli.billing.auto_reload_on_detail", rule=_current),
  955. _auto_reload_top_choices())
  956. if top == "off":
  957. self._billing_auto_reload_disable(state)
  958. return
  959. if top != "edit":
  960. print(f" {t('cli.billing.cancelled_yellow')}")
  961. return
  962. _CANCELLED = object()
  963. def _ask_amount(label, current):
  964. """One amount; empty keeps `current` when editing. Decimal / kept value, or _CANCELLED (already printed)."""
  965. cur = format_money(current) if currently_on else None
  966. prompt = f" {t('cli.billing.amount_prompt_labeled', label=label)}" + (f" [{cur}]: " if cur else ": ")
  967. raw = self._prompt_text_input(prompt)
  968. if raw is None: # cancelled (e.g. slash-worker can't prompt off-thread)
  969. print(f" {t('cli.billing.cancelled_yellow')}")
  970. return _CANCELLED
  971. if not (raw or "").strip() and currently_on:
  972. return current
  973. v = validate_charge_amount(raw or "", min_usd=state.min_usd, max_usd=state.max_usd)
  974. if not v.ok or v.amount is None:
  975. print(f" 🔴 {v.error}")
  976. return _CANCELLED
  977. return v.amount
  978. threshold_amt = _ask_amount(t("cli.billing.threshold_label"), ar.threshold_usd if currently_on else None)
  979. if threshold_amt is _CANCELLED:
  980. return
  981. reload_amt = _ask_amount(t("cli.billing.reload_to_label"), ar.reload_to_usd if currently_on else None)
  982. if reload_amt is _CANCELLED:
  983. return
  984. if reload_amt is None or threshold_amt is None or reload_amt <= threshold_amt:
  985. print(f" {t('cli.billing.reload_must_exceed_threshold')}")
  986. return
  987. self._dim(t("cli.billing.auto_reload_consent", card=card.masked, threshold=format_money(threshold_amt)), lead=True)
  988. if self._modal_choice(
  989. t("cli.billing.turn_on_auto_reload_question"),
  990. t("cli.billing.auto_reload_rule_cap", threshold=format_money(threshold_amt), reload_to=format_money(reload_amt)),
  991. _auto_reload_agree_choices()) != "agree":
  992. print(f" {t('cli.billing.cancelled_yellow')}")
  993. return
  994. if self._billing_patch_auto_top_up(state, enabled=True, threshold=float(threshold_amt), top_up_amount=float(reload_amt)):
  995. print(f" {t('cli.billing.auto_reload_enabled', threshold=format_money(threshold_amt), reload_to=format_money(reload_amt))}")
  996. def _billing_patch_auto_top_up(self, state, **kwargs) -> bool:
  997. """PATCH auto-top-up; scope denials → step-up, other errors → renderer. True on success."""
  998. from hermes_cli.nous_billing import patch_auto_top_up
  999. return self._billing_patch(state, patch_auto_top_up, **kwargs)
  1000. def _billing_patch(self, state, call, **kwargs) -> bool:
  1001. from hermes_cli.nous_billing import BillingError, BillingScopeRequired
  1002. try:
  1003. call(**kwargs)
  1004. except BillingScopeRequired:
  1005. self._billing_handle_scope_required(state)
  1006. return False
  1007. except BillingError as exc:
  1008. self._billing_render_charge_error(state, exc)
  1009. return False
  1010. return True
  1011. def _billing_offer_keep_going_off(self, state):
  1012. """Turning "Keep going on credits" off only stops spending, so an admin can still do it with
  1013. Remote Spending off (the portal and the server allow it too)."""
  1014. if not (state.can_change_plan and state.keep_going_on_credits and getattr(self, "_app", None)):
  1015. return
  1016. if self._modal_choice(t("cli.billing.keep_going_is_on_title"), "", _keep_going_off_choices()) == "off":
  1017. self._billing_keep_going_on_credits_flow(state)
  1018. def _billing_keep_going_on_credits_flow(self, state):
  1019. """Window plans: flip "Keep going on credits". Turning it on spends money later, so it asks
  1020. first; turning it off does not."""
  1021. turn_on = not state.keep_going_on_credits
  1022. if turn_on and self._modal_choice(
  1023. t("cli.billing.keep_going_confirm_title"), t("cli.billing.keep_going_confirm_body"),
  1024. _keep_going_agree_choices()) != "agree":
  1025. print(f" {t('cli.billing.cancelled_yellow')}")
  1026. return
  1027. self._billing_set_keep_going(state, turn_on, allow_stepup=True)
  1028. def _billing_set_keep_going(self, state, turn_on: bool, *, allow_stepup: bool) -> None:
  1029. """PATCH the setting. A scope denial runs the step-up, then sends the same change ONCE (no card or
  1030. org Remote Spending check: the setting is not a charge, and turning it off must always work)."""
  1031. from hermes_cli.nous_billing import BillingError, BillingScopeRequired, patch_keep_going_on_credits
  1032. try:
  1033. patch_keep_going_on_credits(enabled=turn_on)
  1034. except BillingScopeRequired as exc:
  1035. if not allow_stepup:
  1036. self._billing_render_charge_error(state, exc)
  1037. return
  1038. if self._step_up_remote_spending(
  1039. explain=t("cli.subscription.stepup_explain"),
  1040. noninteractive_msg=f" {t('cli.subscription.stepup_noninteractive')}",
  1041. declined_msg=f" {t('cli.subscription.stepup_declined')}",
  1042. not_granted_msg=f" {t('cli.subscription.stepup_not_granted')}"):
  1043. self._billing_set_keep_going(state, turn_on, allow_stepup=False)
  1044. return
  1045. except BillingError as exc:
  1046. self._billing_render_charge_error(state, exc)
  1047. return
  1048. print(f" {t('cli.billing.keep_going_turned_on' if turn_on else 'cli.billing.keep_going_turned_off')}")
  1049. from agent.credits_tracker import apply_keep_going_change
  1050. apply_keep_going_change(getattr(self, "agent", None), turn_on)
  1051. def _billing_auto_reload_disable(self, state):
  1052. """PATCH ``enabled:false``; the endpoint still requires threshold/topUpAmount → echo current (or 0)."""
  1053. ar = state.auto_reload
  1054. thr = float(ar.threshold_usd) if ar and ar.threshold_usd is not None else 0.0
  1055. rel = float(ar.reload_to_usd) if ar and ar.reload_to_usd is not None else 0.0
  1056. if self._billing_patch_auto_top_up(state, enabled=False, threshold=thr, top_up_amount=rel):
  1057. print(f" {t('cli.billing.auto_reload_disabled')}")
  1058. def _billing_limit_screen(self, state):
  1059. """Screen 5 — monthly spend limit (read-only; cap is portal-only)."""
  1060. from agent.billing_view import format_money
  1061. self._block_header("💳", t("cli.billing.monthly_spend_limit"))
  1062. cap = state.monthly_cap
  1063. if cap is None or cap.limit_usd is None:
  1064. self._dim(t("cli.billing.no_monthly_cap"))
  1065. else:
  1066. ceiling = t("cli.billing.default_ceiling_suffix") if cap.is_default_ceiling else ""
  1067. print(f" {t('cli.billing.used_this_month', spent=format_money(cap.spent_this_month_usd), limit=format_money(cap.limit_usd), ceiling=ceiling)}")
  1068. self._dim(t("cli.billing.monthly_limit_read_only"))
  1069. self._billing_portal_hint(state)