Files
hermes-agent/hermes_cli/cli_billing_mixin.py
Teknium 9bcbe7b5df feat(i18n): pluggable, layered language packs across core, Desktop and TUI (#126296)
* feat(i18n): layered catalogs — plugin packs and user overlay over bundled locales

* feat(tui): i18n layer — en catalog, nanostore runtime, RPC pack loader, _keys.tui.json emitter

ui-tui/src/i18n/: en.ts (facade over topical siblings under en/), types.ts
(Translations + dotted TranslationKey derived from en), runtime.ts ($locale/
$catalog atoms, translateFrom active→en→key, pack merge with string→fn
wrapping for {0}/{1} placeholders), loader.ts (display.language →
i18n.catalog {lang, surface:'tui'}, English when the method is missing),
useT()/useLocale() hooks, t() for non-React code. useConfigSync feeds the
loader from the existing config.get full hydration. `npm run i18n:keys`
writes locales/_keys.tui.json (sorted flat key list) and runs before build.

* feat(plugins): provides_locales manifest field, ctx.register_locale/register_locale_dir, manifest-only language packs

* chore(tui): split en catalog siblings by lane (slash sibling)

* feat(plugins): validate language packs — parse, text-only, key-subset WARN against en / _keys exports

* feat(tui_gateway): i18n.languages / i18n.catalog RPC + regenerated contracts

* feat(config): display.language accepts any supported_languages() id, refuses unknown ids with the list

* docs(i18n): language packs user guide, pluggable display.language, plugin developer section, AGENTS notes

* feat(plugins): report language-pack layers in the mid-run activation summary

* feat(tui): wire status bar, composer placeholders, hotkey help and approval/clarify/confirm prompts through i18n

StatusRule maps compared state values (ready/running…/summoning) to catalog
text at render via displayStatus(); hotkeys()/placeholder() resolve lazily so
a pack that arrives after boot applies. Catalog grows to 81 keys.

* feat(desktop): pluggable app locales — registry, host.i18n.registerAppLocale, backend packs, keys emitter

- Locale widens to string (BundledLocale keeps the union); TRANSLATIONS stays
  the bundled record and every consumer resolves through the registry.
- src/i18n/registry.ts: registerAppLocale(id, {endonym, rtl, translations})
  layers partial packs (nested or flat dotted) over bundled/en via
  mergeTranslations; a string over a function-valued en entry becomes a
  positional {0}/{1} formatter; $appLocaleVersion bumps so translators
  re-render; per-source disposers + replaceAppLocaleSource for atomic swaps.
- Backend packs: i18n.languages + i18n.catalog {surface:'desktop'} feed the
  registry as source 'backend' (method-not-found is silent); re-synced on
  socket open, display.language change and profile switch. A saved pack-only
  language is promoted once its pack registers.
- SDK: host.i18n.registerAppLocale / languageOptions; ctx.i18n.registerAppLocale
  tracked for unload. Docs in the desktop plugin SDK guide + skill reference.
- Language switcher lists bundled ∪ registered ∪ backend, endonym-only; RTL
  from the registry (applyDocumentLocale takes rtl).
- npm run i18n:keys emits locales/_keys.desktop.json (wired into build).

* i18n(cli): route /topup + /subscription copy through t() (cli.billing.*, cli.subscription.*)

Module-level copy tables and modal choice tuples in cli_billing_mixin.py froze
English at import, before display.language was known. They are now key tables /
builder functions evaluated at call time; every user-facing line in the /usage
balance block, /subscription and the five /topup screens reads the catalog.
Choice VALUES stay English identifiers. Fragment-assembled status lines
(Plan: … → cancels · $x left · renews …) become full templates.

* i18n(gateway): exec-approval card contract + base/run/run_busy/run_inbound replies through t()

- base_exec_approval: EA_* English constants stay; add ea_header_text()/ea_reason_label_text()/
  ea_smart_deny_line_text()/ea_default_reason_text()/ea_action_labels()/approval_timed_out_notice()
  accessors; deadline + timed-out notice resolve via gateway.exec_approval.*
- BasePlatformAdapter._EA_HEADER/_EA_REASON_LABEL/_EA_SMART_DENY_LINE/_EA_ACTION_LABELS become
  properties (adapters still shadow them with markup class attrs)
- run.py: provider error replies table holds catalog keys; _CONTEXT_OVERFLOW_REPLY -> _context_overflow_reply()
- run_busy/run_inbound: typed approval + slash-confirm matchers accept English ∪ approval.inputs.* (t())
- locales/en.yaml: gateway.exec_approval/busy/errors/... namespaces

* i18n(cli): wire modal, loops, agent-setup mixins through t() (cli.* keys)

* i18n(platforms): route Slack, Matrix and Feishu user-facing text through t()

Exec-approval markup overrides (_EA_HEADER/_EA_REASON_LABEL/_EA_SMART_DENY_LINE/
_EA_ACTION_LABELS) become per-call properties over the shared
gateway.exec_approval.* contract keys, so Slack's 3000-char section budget
measures the resolved template. Slack _APPROVAL_DECISIONS/_CONFIRM_DECISIONS,
Feishu _APPROVAL_LABEL_MAP and Matrix _EA_LEGEND/_EA_TYPED_HINT turn into
key tables resolved at click time; the Matrix typed hints become whole
sentences per offered tier instead of spliced fragments. Slack button labels
are cut to 75 chars and select placeholders to 150 after translation; the
model-facing clarify fallback answer ('choice N') stays English while the
card copy localizes.

locales/en.yaml gains the gateway.exec_approval.* contract keys plus the
platform.shared.* / platform.slack.* / platform.matrix.* / platform.feishu.*
namespaces (and the keys for the other adapters wired in follow-up commits).

* i18n(gateway): run_turn / run_turn_runner / approval-settle copy through t()

- status hints, proxy errors, background task notices, progress heartbeats, session info lines
- tool progress chrome (tool_head/tool_pending/tool_preview/tool_verbose) shared by base.format_tool_event
- run_turn_runner:1406 Chinese clarify placeholder -> gateway.clarify.native_stream_placeholder (zh text kept in zh.yaml)
- _UNEXPECTED_SILENCE_REPLY/_CLARIFY_EXPIRED_NOTICE -> accessor functions

* i18n(platforms): route Google Chat and Teams user-facing text through t()

Google Chat clarify card, typing placeholder, orphan-card labels and the whole
/setup-files reply set (module constants become platform.google_chat.setup_files.*
keys resolved at reply time). The attachment-fallback notice that shipped
hardcoded in Spanish is keyed with an English en value; es.yaml carries the
original Spanish text for those four keys.

Teams approval card header/reason use the gateway.exec_approval.* contract,
_APPROVAL_LABELS becomes a key table resolved at click time, and the meeting
summary writer resolves its section headings/fallbacks per render.

* i18n(platforms): route LINE, WeCom, email, DingTalk, IRC and Home Assistant text through t()

LINE default copy constants become catalog keys resolved in __init__ (the
LINE_*_TEXT / extra.* operator overrides still win); the busy-ack bypass
matcher keys on the leading emoji marker only, so it keeps firing once the
gateway busy heads are localized. WeCom media size/format notices that shipped
hardcoded in Chinese are keyed with English en values and zh.yaml carries the
original Chinese text. DingTalk emotion bubbles resolve per send.

* i18n(cli): route /model switch output and -q status lines through t() (cli.model.*, cli.single_query.*)

Switch-summary labels shared with the gateway reuse gateway.model.* keys
(provider/context/max-output/capabilities/prompt-caching); CLI-only variants
(glyph or no-backtick forms) live under cli.model.*. The hand-padded /model usage
block becomes a (form, description-key) table padded at render time so the
command syntax stays fixed while descriptions translate. -q 'Error:' reuses
gateway.model.error_prefix.

* i18n(cli): route TUI panel/hint/placeholder copy through t() (cli.tui.*)

_APPROVAL_CHOICE_LABELS and _TUI_MODAL_HINTS become key tables resolved at
render time; vault/sudo panel bodies are one catalog value per panel split on
newline; inline plurals use <key>_one/<key>_other. Adds the cli.* namespace
(shared/tui/voice/render/subagents/dock) to locales/en.yaml.

* i18n(cli): voice/wake-word CLI copy through t() (cli.voice.*)

RuntimeError texts raised in _voice_start_recording are human copy (callers
print {e}) and are keyed; the Termux requirement-check match stays English.
Wake state ids stay internal, only their labels localize.

* i18n(cli): live-work dock, subagent monitor and render copy through t()

cli.subagents.* / cli.dock.* / cli.render.*; count fragments pluralize via
_one/_other keys, verdict table holds keys resolved at paint time so width
clipping measures the translated text.

* i18n(gateway): unauthorized/pairing, voice, topics, shutdown, startup, notifications, kanban pings through t()

* i18n(cli): move tips + composer placeholders into the catalog (tips.tNNN / tips.placeholder.pNN)

get_random_tip()/get_random_composer_placeholder() pick a key from the English catalog
(the parity baseline, probed once per process) and resolve it through t() for the active
language, so language packs translate tips like any other string. Also lands the cli.*
en.yaml namespace consumed by the CLI info/help/error-copy wiring in the next commit.

* i18n(cli): wire chat-turn + session mixins through t(); kanban log trimmer matches t() output

* test(cli): assert TUI/dock/voice copy via t(key); prove labels resolve at render time

Pinned-English assertions in the approval-UI, live-work dock and voice tests now
go through the catalog. New test swaps the catalog after import and checks the
approval panel + hint row follow it (the reason _APPROVAL_CHOICE_LABELS and
_TUI_MODAL_HINTS became key tables).

* i18n(cli): route CLI info/help/error copy through t() (cli.* namespace)

cli_info_mixin: /help consumes CommandDef.describe() (added to commands.py: slash.<name>.description
with fallback to .description), section titles/skill/quick-command headers, /tools, /toolsets,
/usage labels, /context, /whoami, /insights, /gateway status, tool-progress labels, bang-shell
denials, MCP config-watch + /reload-mcp confirm/reload lines, /reload-skills, and the session-store
warning all read the catalog at call time (module-level label tables became functions so the
active language is honoured after startup). cli.py: worktree cleanup, tirith warning, show_config
(labels re-padded at print time), quick/plugin/skill slash-command errors, ambiguous-command hint,
stdin error, gateway start, profile warning. cli_chat_error_copy / cli_unknown_command /
cli_output / cli_init_mixin: chat error panel copy, did-you-mean lines, n-more / yes-no prompt
(localized affirmative initial alongside 'y'), unknown-toolsets warning.

* i18n(w1a): wire agent display/explainers/approval + slash registry/help through t()

- hermes_cli/commands.py: CommandDef.describe() resolves slash.<name>.description
  at call time; category labels via slash.category.*; help/alias/usage suffixes
  via slash.shared.*; gateway_help_lines and commands_platforms/slash_exec use them.
- agent/display.py: display.verb.* resolved at call time via get_tool_verb();
  bridge/spinner/thinking-verb/cute-row/failure/preview/diff text via display.*.
- agent/turn_explainers.py: exit-reason / persistence-cause tables become call-time
  lookups (explainer.exit.*, explainer.persistence.*, explainer.file_mutation.*).
- agent/background_review.py, session_activity.py, context_breakdown.py,
  status_output.py: review summaries, iteration progress, context notices.
- tools/approval.py, approval_context.py: approval.summary.*, approval.noun.*,
  approval.window.* pluralized keys.
- gateway/slash_commands*.py: remaining raw strings (busy, whoami, platform,
  bundles, memory, skills, approvals, set_home, diff, update, debug, profile,
  heartbeat, refine, review, subgoal, loop, retry, compress codex path, save,
  sessions, model guard/errors, agents rows, topup, login). HISTORY_UNREADABLE
  keeps its English constant; callers use history_unreadable() ->
  gateway.shared.history_unreadable.
- locales/en.yaml: new approval/display/explainer/slash blocks + gateway leftovers.

* i18n(telegram): route adapter chat copy through t()

Approval card (header/reason/smart-deny as HTML-escaped properties), inline
button labels, callback toasts (cut at Telegram's 200-char cap), model/choice
pickers, clarify/update/slash-confirm prompts, gmail-triage labels and the
inbound-media failure notice now come from the catalog. _UNAUTHORIZED is a
lazy _unauthorized() so the import no longer binds a language. The command
menu carries a language+payload fingerprint (forum scopes re-register on
change) and BotCommand descriptions are cut at 256.

Adds gateway.exec_approval.* (WAVE2 contract), platform.telegram.*,
platform.discord.* and the slash.*.description keys the Discord table shares
with the CLI registry to locales/en.yaml.

* i18n(gateway/platforms): whatsapp_cloud, yuanbao, weixin, signal, api_server copy through t()

- whatsapp_cloud: clarify list/buttons, approve/deny + slash-confirm labels via platform.whatsapp.* (t()-then-truncate at 20/24/72 caps); _EA_HEADER becomes a property wrapping ea_header_text()
- yuanbao: SLOW_RESPONSE_MESSAGE -> slow_response_message() (platform.yuanbao.slow_response_notice; zh keeps the original text); cron-wrapper markers centralized as module constants for strip_cron_wrapper
- api_server: PROVIDER_AUTH_FAILED_LABEL/PROVIDER_RATE_LIMITED_LABEL stay English for run.py matchers; user_text() renders via t()
- signal/_format_wait, weixin voice caption, openai_routes transformed notice
- run_turn: second _UNEXPECTED_SILENCE_REPLY consumer -> accessor

* i18n(discord): route adapter chat copy through t()

Native slash-command table becomes _NATIVE_SLASH_COMMAND_SPECS holding catalog
keys; _native_slash_commands() resolves descriptions, parameter descriptions
and Choice names for the active language, each cut at Discord's 100-char cap,
and the app-command sync fingerprint now includes get_language() so a
display.language change re-syncs. Exec-approval card (gateway.exec_approval.*
contract), slash-confirm / clarify / update views, model+choice pickers,
thread creation, forum titles, voice acks, the response-truncation notice,
the unauthorized-slash security alert and the media upload-size notices all
read from platform.discord.*. Decorator-declared button labels are relabelled
in __init__ (80-char cap); embed titles cut at 256, select placeholders at
150, option label/description at 100. _UNAUTHORIZED is a lazy _unauthorized().

* i18n(cli): wire status-bar, stream, terminal mixins + terminal_input through t(); rename kwargs that shadow t(key)

* i18n: wire hermes_cli/cli_commands_mixin.py slash-command copy through t()

- 431 new leaves under cli.commands.<cmd>.* in locales/en.yaml; 12 rows reuse
  existing gateway.* keys (rollback, diff, resume, branch, btw, model, reasoning)
  via a _gt() helper so CLI and gateway replies stay identical.
- Module-level English tables (_BUSY_MODE_*, _REASONING_TOGGLES, _HATCH_PROGRESS,
  _DIFF_LABELS, _LOCAL_ENGINE_LINES) become call-time catalog lookups keyed by id.
- Verb tables (Enabling/Disabling, Paused/Resumed/Triggered, planned/done,
  Updating/Generating) are one full template per variant; plurals use
  <key>_one/<key>_other via _tn(); hand-padded column labels (/snapshot list)
  translate the value and re-pad at the call site.
- Multi-line usage blocks are single catalog values split with _lines().
- Model-facing system notes and DB-stored reasons stay English (EXCLUDED).

* tests: assert /handoff, /worktree, /login CLI copy via t(key) instead of pinned English

* test(i18n): pin Telegram/Discord adapter catalog wiring

Lazy unauthorized notice, exec-approval contract keys, HTML escaping before
Telegram <b> wrapping, 200-char toast / 256-char BotCommand caps, Discord
100-char app-command text and 80-char button caps, and language-bearing
command-menu fingerprints on both platforms.

* i18n: reconcile cli.shared on/off vs enabled/disabled after lane merge

* i18n: describe() in TUI-gateway slash listings; localize TUI exit resume hint

* i18n(tr): translate bundled catalog + tui pack

* i18n(ja): translate bundled catalog + tui pack

* i18n(ko): translate bundled catalog + tui pack

* i18n(zh): translate bundled catalog + tui pack

* i18n(fr): translate bundled catalog + tui pack

* i18n(af): translate bundled catalog + tui pack

* i18n(uk): translate bundled catalog + tui pack

* i18n(ar): translate bundled catalog + tui pack

* i18n(pt): translate bundled catalog + tui pack

* i18n(it): translate bundled catalog + tui pack

* i18n(es): translate bundled catalog + tui pack

* i18n(zh-hant): translate bundled catalog + tui pack

* i18n(ru): translate bundled catalog + tui pack

* i18n(hu): translate bundled catalog + tui pack

* i18n(hu): translate pre-existing English-valued leftovers (kanban wake, /context, /status, fast labels)

* i18n(de): translate bundled catalog + tui pack

* i18n(ga): translate bundled catalog + tui pack

* test(i18n): fixture matches _normalize_lang(lang, home) signature

* i18n(tui): scaffold userMessages/slashCmd en siblings

* i18n(tui): wire secure prompts + content tables

* feat(tui): i18n — wire billing, subscription, connection-setup and journey overlays

Adds en siblings billing.ts / subscription.ts / connection.ts (namespaces
billing, subscription, connection, journey) and routes every user-facing
literal in billingOverlay, subscriptionOverlay, connectionSetupOverlay and
journey through useT()/messages(). Module-level label tables became lazy
(scopeStillDeniedResult(), verbOf(T, action)); auto-reload rows dispatch on
stable ids instead of label text. Regenerates locales/_keys.tui.json.

* i18n(tui): wire slash ops/wake replies

* i18n(tui): wire pickers (modelPicker, activeSessionSwitcher, petPicker)

* i18n(tui): wire slash core/debug/setup replies

* i18n(tui): wire hubs (agents overlay/panel/controls, skills, plugins)

* i18n(tui): wire slash session/topup/subscription replies

* i18n(tui): wire chat bits (branding, thinking, messageLine, loaders, todo, queued, banner, entry)

* i18n(tui): register t3 siblings (pickers, hubs, secure, content, chatBits) and regenerate keys

* i18n(tui): wire userMessages copy through the userMessages namespace

* i18n(tui): lazy-copy test for userMessages, regenerate _keys.tui.json

* i18n(tui): wire session/gateway/lib text through the TUI catalog (lane t2)

Adds en siblings session.ts, gatewayMsg.ts, libText.ts (namespaces session,
gatewayMsg, libText) and routes user-facing literals in app/{useMainApp,
useSessionLifecycle,useInputHandlers,turnController,createServerRequestHandler,
setupHandoff,createGatewayEventHandler}.ts, gatewayClient displayed reasons,
lib/*, domain/*, hooks/* through t()/messages(). Status-bar state values that
code compares against, backend-matched strings, log lines, model-bound text,
and machine 'error:' prefixes stay literal. Regenerates locales/_keys.tui.json
(232 keys).

* i18n: serve bundled locales/<lang>.tui.yaml under overlay/packs; TUI pack parity test; regen _keys.tui.json (1250)

* i18n: translate pre-existing English stubs in bundled locales (424 leaves, 14 locales)

* tui: i18n-export-en script (English templates for pack translators)

* docs(i18n): bundled TUI packs are the bottom layer of the tui surface

* i18n(ru): translate TUI pack

* i18n(ar): translate TUI pack

* i18n(es): translate TUI pack

* i18n(pt): translate TUI pack

* i18n(ko): translate TUI pack

* i18n(de): translate TUI pack

* i18n(ja): translate TUI pack

* i18n(fr): translate TUI pack

* i18n(tr): translate TUI pack

* i18n(it): translate TUI pack

* i18n(zh): translate TUI pack

* i18n(zh-hant): translate TUI pack

* i18n(hu): translate TUI pack

* i18n(uk): translate TUI pack

1,169 missing keys translated; 81 pre-existing kept byte-identical. Parity OK missing=0 extra=0 placeholder_mismatch=0 empty=0.

Deliberately identical to en: chatBits.branding.mcpSummary ({0} MCP), chatBits.thinking.agentsHint ((/agents)), session.main.voiceStt (◉ STT), session.main.voiceTtsSuffix ( [tts]), slashCmd.core.help.tuiSection (TUI), slashCmd.core.history.hermesTag (Hermes #{0}), slashCmd.debug.heapdump.heapPath (heapdump: {0}), slashCmd.debug.mem.rss (rss), subscription.stepUp.title (Remote Spending — product feature name, as in core catalog), content.faces.* (glyph-only kaomoji).

* i18n(ga): translate TUI pack

* i18n(af): translate TUI pack

* plugin_guard: locale catalogs in language packs step down the agent-config family

A translated status line such as "Updating AGENTS.md" in locales/<lang>.yaml is UI text the loader
reads as a string leaf; it cannot edit a file. The bundled en.yaml itself tripped agent_config_mod
at critical, making any faithful language pack uninstallable. Injection shapes keep full severity.

* plugin_validate_locales: read key exports with utf-8-sig (Windows footgun lint)

* i18n(relay): route relay adapter prompt copy through t(); drop dead import-bound approval header

Adds platform.relay.* (5 keys) to en and all 16 bundled locales, reusing the sibling platform
translations for the confirm buttons and the Other option.

* ci: fix TUI import order, MDX table pipe, main's overflow-warning wording in all locales; fresh-install fixture carries the i18n kernel

- ui-tui/src/i18n/en.ts: perfectionist/sort-imports (slash before slashCmd)
- docs plugins/index.md: escape the | inside the provides_locales table cell (MDX parsed <id> as JSX)
- display.notice.uncompressed_context_overflow: adopt main's wording (names compression.enabled: false
  and /compact) in en + 16 locales; the guardrail test pins that phrase
- tests/scripts/test_fresh_source_install.py: the installer tail now resolves CLI text through
  agent.i18n, so the fixture tree carries the i18n kernel + en.yaml (not the agent runtime)

* docs(desktop-plugin-sdk): double-backtick the template-literal example (MDX evaluated ${n})

* test(e2e): display.language is validated against the live language set; exclude it from the arbitrary-string set property

* commands: keep the localized COMMANDS/COMMANDS_BY_CATEGORY module __getattr__ after the compat block removal

* build: never write locales/_keys.*.json from the desktop/TUI builds; regenerate the committed desktop key export

The desktop build regenerated locales/_keys.desktop.json in the checkout, so a
hermes update that rebuilt the app left the tree dirty (Desktop update E2E:
'M locales/_keys.desktop.json'). The key exports are committed artifacts pinned
to en.ts by apps/desktop/scripts/i18n-keys.test.mjs and ui-tui i18n:keys:check;
builds read them, never write them. Regenerated after main's new desktop strings.

* test: unbreak two main-red timing tests the PR merge-ref inherits

- test_local_runtime racing fake publishes the modern state record (legacy pid-only
  records are rejected since 65ff3ad353; main has been red on this test since)
- test_run_progress_topics ManyProgressLinesAgent waits for the first bubble instead of
  a fixed 0.35s, which a loaded CI runner does not always meet

* chore(i18n): regenerate desktop key catalog for main's new strings (model pricing, copy changelog)

* test(e2e): torture-chamber fd monitor confirms a deleted sidecar is still held before calling it a leak

SQLite's WAL last-close unlinks -shm before closing its descriptor (unixShmUnmap, then
unixShmPurge), so a healthy close shows a (deleted) -shm for microseconds; the 20ms poll
occasionally caught that window on the short-lived opener and failed the episode.

* chore(i18n): regenerate desktop key catalog for main's telemetry/consent strings

* chore(i18n): regenerate desktop key catalog after main sync

---------

Co-authored-by: Teknium <teknium@nousresearch.com>
2026-09-28 14:16:18 -07:00

1086 lines
58 KiB
Python

"""Billing and subscription handlers for the interactive CLI (mixed into ``HermesCLI``).
cli.py symbols are imported LAZILY inside methods — never at module load (import cycle).
User-facing copy is looked up through ``agent.i18n.t`` at call time (never at import — the
active language is not known when this module loads), under ``cli.billing.*`` (shared /topup
copy) and ``cli.subscription.*`` (/subscription copy). Modal choice VALUES (index 0) stay
English identifiers; only labels/descriptions are translated."""
from __future__ import annotations
from agent.i18n import t
_RULE = "─" * 41
# Poll `failed` reasons → copy key (default: generic line carrying the raw reason).
_CHARGE_FAILED_KEYS = {
"authentication_required": "cli.billing.charge_failed_authentication_required",
"payment_method_expired": "cli.billing.charge_failed_payment_method_expired",
"card_declined": "cli.billing.charge_failed_card_declined"}
# Submit-time BillingError codes with a fixed copy key (no payload/type inspection).
_CHARGE_ERROR_KEYS = {
"no_payment_method": "cli.billing.charge_error_no_payment_method",
"cli_billing_disabled": "cli.billing.charge_error_remote_spending_disabled",
"remote_spending_disabled": "cli.billing.charge_error_remote_spending_disabled",
"role_required": "cli.billing.charge_error_role_required",
"idempotency_conflict": "cli.billing.charge_error_idempotency_conflict"}
# Upgrade 2xx `status` → (copy key, echo recoveryUrl as "Portal:"). Missing status → ambiguous.
_UPGRADE_STATUS_KEYS = {
"requires_action": ("cli.subscription.upgrade_requires_action", True),
"payment_failed": ("cli.subscription.upgrade_payment_failed", True)}
# Upgrade 2xx terminal statuses → dim ✓ copy key ({name} = target tier).
_UPGRADE_OK_KEYS = {
"already_on_tier": "cli.subscription.upgrade_already_on_tier",
"upgraded": "cli.subscription.upgrade_upgraded"}
# Pending-change mutations → dim ✓ copy key.
_PENDING_OK_KEYS = {
"schedule": "cli.subscription.pending_scheduled",
"cancel": "cli.subscription.pending_cancel_scheduled",
"resume": "cli.subscription.pending_resumed"}
# ── Static modal menus (value, label, description) — built at call time so labels follow the
# active language; order is the rendered order. ──
def _cancel_row(value: str = "cancel", label_key: str = "cli.billing.choice_cancel",
desc_key: str = "cli.billing.desc_do_nothing") -> tuple[str, str, str]:
return (value, t(label_key), t(desc_key))
def _portal_row(value: str = "portal") -> tuple[str, str, str]:
return (value, t("cli.billing.choice_manage_on_portal"), t("cli.billing.desc_open_billing_page"))
def _allow_remote_spending_choices() -> list[tuple[str, str, str]]:
return [
("yes", t("cli.billing.choice_allow_remote_spending"), t("cli.billing.desc_allow_remote_spending")),
("no", t("cli.billing.choice_not_now"), t("cli.billing.desc_not_now"))]
def _topup_menu_choices() -> list[tuple[str, str, str]]:
return [
("buy", t("cli.billing.choice_add_funds"), t("cli.billing.desc_add_funds")),
("auto", t("cli.billing.choice_auto_reload"), t("cli.billing.desc_auto_reload")),
("limit", t("cli.billing.choice_monthly_limit"), t("cli.billing.desc_monthly_limit")),
_portal_row(),
_cancel_row()]
def _add_card_choices() -> list[tuple[str, str, str]]:
return [
("portal", t("cli.billing.choice_add_card_on_portal"), t("cli.billing.desc_add_card_on_portal")),
("recheck", t("cli.billing.choice_recheck_card"), t("cli.billing.desc_recheck_card")),
_cancel_row(label_key="cli.billing.choice_back")]
def _auto_reload_top_choices() -> list[tuple[str, str, str]]:
return [
("edit", t("cli.billing.choice_edit_thresholds"), t("cli.billing.desc_edit_thresholds")),
("off", t("cli.billing.choice_turn_off"), t("cli.billing.desc_turn_off")),
_cancel_row()]
def _auto_reload_agree_choices() -> list[tuple[str, str, str]]:
return [
("agree", t("cli.billing.choice_agree_turn_on"), t("cli.billing.desc_agree_turn_on")),
_cancel_row()]
def _change_plan_row() -> tuple[str, str, str]:
return ("change", t("cli.subscription.choice_change_plan"), t("cli.subscription.desc_change_plan"))
def _change_menu_tail() -> list[tuple[str, str, str]]:
return [_portal_row(), _cancel_row("close", "cli.billing.choice_close")]
def _cancel_sub_choices() -> list[tuple[str, str, str]]:
return [
("yes", t("cli.subscription.choice_cancel_subscription"), t("cli.subscription.desc_cancel_subscription")),
("cancel", t("cli.billing.choice_go_back"), t("cli.subscription.desc_keep_your_plan"))]
class CLIBillingMixin:
"""Mixin holding interactive-CLI billing and subscription handlers."""
# ── Shared helpers ──
def _modal_choice(self, title, detail, choices):
"""Run the choice modal and return the normalized choice value."""
raw = self._prompt_text_input_modal(title=title, detail=detail, choices=choices)
return self._normalize_slash_confirm_choice(raw, choices)
def _block_header(self, icon, title, *, rule=True) -> None:
"""Blank line, ``<icon> <bold title>`` via _cprint, then (optionally) the rule via print."""
from cli import _cprint, _b
print()
_cprint(f" {icon} {_b(title)}")
if rule:
print(f" {_RULE}")
def _dim(self, msg, *, icon="", lead=False) -> None:
"""Dim `` <icon><msg>`` line via _cprint; ``lead`` prints a blank line first."""
from cli import _cprint, _d
if lead:
print()
_cprint(f" {icon}{_d(msg)}")
def _ok(self, msg) -> None:
"""Dim ``✓ <msg>`` success line."""
from cli import _cprint, _DIM, _RST
_cprint(f" {_DIM}✓ {msg}{_RST}")
def _print_logged_out(self, state, load_failed, cmd) -> None:
"""Logged-out / fetch-failed block shared by /subscription and /topup."""
if state.error:
self._dim(t("cli.billing.load_failed", label=load_failed, error=state.error), icon="💳 ", lead=True)
else:
self._dim(t("cli.billing.not_logged_in"), icon="💳 ", lead=True)
print(f" {t('cli.billing.run_portal_then', cmd=cmd)}")
def _print_org_line(self, state) -> None:
"""Dim ``Org: <name> · <Role>`` line (skipped when there is no org)."""
if state.org_name:
role = (state.role or "").title()
if role:
self._dim(t("cli.billing.org_line_role", org=state.org_name, role=role))
else:
self._dim(t("cli.billing.org_line", org=state.org_name))
def _try_usage_model(self):
"""Shared dollar usage model (the only source with top-up dollars); None on any failure."""
try:
from agent.billing_usage import build_usage_model
return build_usage_model()
except Exception:
return None
def _usage_bar_lines(self, usage, plan_name) -> list:
"""Plan + top-up bars as lines (filled = remaining). Caller picks the print fn: ordering differs per surface."""
lines: list = []
pb = usage.plan_bar if usage else None
if pb is not None and pb.total_usd > 0:
filled = max(0, min(10, round(pb.fill_fraction * 10)))
bar = ("█" * filled) + ("░" * (10 - filled))
pct_s = t("cli.billing.bar_pct_used", pct=pb.pct_used) if pb.pct_used is not None else ""
label = (plan_name or t("cli.billing.bar_plan_label")).ljust(8)[:8]
lines.append(" " + t("cli.billing.bar_plan", label=label, bar=bar, remaining=f"{pb.remaining_usd:,.2f}",
total=f"{pb.total_usd:,.2f}", pct=pct_s))
tb = usage.topup_bar if usage else None
if tb is not None and tb.remaining_usd > 0:
lines.append(" " + t("cli.billing.bar_topup", label=t("cli.billing.bar_topup_label").ljust(8)[:8],
bar="█" * 10, remaining=f"{tb.remaining_usd:,.2f}"))
return lines
def _print_total_spendable(self, usage, print_fn) -> None:
if usage and usage.has_topup and usage.total_spendable_usd is not None:
print_fn(f" {t('cli.billing.total_spendable', amount=f'{usage.total_spendable_usd:,.2f}')}")
def _step_up_remote_spending(self, *, explain, noninteractive_msg, declined_msg, not_granted_msg) -> bool:
""""! One-time setup" step-up (explain → confirm → device-flow). True only when granted; refusals print."""
print()
print(f" {t('cli.billing.one_time_setup')}")
self._dim(explain)
if not self._app:
print(noninteractive_msg)
return False
choice = self._modal_choice(
t("cli.billing.allow_remote_spending_title"), t("cli.billing.allow_remote_spending_detail"),
_allow_remote_spending_choices())
if choice != "yes":
print(declined_msg)
return False
print(f" {t('cli.billing.opening_browser_remote_spending')}")
try:
from hermes_cli.auth import step_up_nous_billing_scope
granted = step_up_nous_billing_scope(open_browser=True)
except Exception as exc:
print(f" {t('cli.billing.couldnt_allow_remote_spending', error=exc)}")
return False
if not granted:
print(not_granted_msg)
return bool(granted)
def _print_portal_line(self, exc) -> None:
"""``Portal: <url>`` via _cprint when the error carries a portal deep-link."""
from cli import _cprint
if exc is not None and exc.portal_url:
_cprint(f" {t('cli.billing.portal_line', url=exc.portal_url)}")
def _open_url_in_browser(self, url: str) -> bool:
"""The one portal opener. Refuses TTY-hijacking text browsers (w3m/lynx over SSH) via the auth guard."""
if not url:
return False
try:
from hermes_cli.auth import _can_open_graphical_browser, _is_remote_session
if _is_remote_session() or not _can_open_graphical_browser():
return False
except Exception:
pass # guard unavailable → plain best-effort open
try:
import webbrowser
return bool(webbrowser.open(url))
except Exception:
return False
def _open_or_print_url(self, url) -> None:
"""Open ``url`` in the browser, or print it when no graphical browser can be used."""
if not self._open_url_in_browser(url):
print(f" {t('cli.billing.open_this_url', url=url)}")
# ── /usage — Nous balance block ──
def _print_nous_credits_block(self) -> bool:
"""Nous dollar balance block (two bars); True if anything printed. Shared dollar model first, then
legacy ``nous_credits_lines``. Agent-independent (TUI slash-worker has no live agent). Fail-open."""
from cli import _cprint, _b, _d
usage = self._try_usage_model()
if usage is not None and usage.available:
from agent.billing_usage import format_renews
plan = usage.plan_name or (t("cli.billing.plan_free") if usage.status == "free" else None)
renews_display = usage.renews_display or format_renews(usage.renews_at)
renews = t("cli.billing.renews_suffix", date=renews_display) if renews_display else ""
head = [f" {_b(t('cli.billing.plan_line', plan=plan, renews=renews))}"] if plan else []
head += self._usage_bar_lines(usage, usage.plan_name)
tail = []
if usage.status == "free":
tail.append(f" {_d(t('cli.billing.free_models_only_hint'))}")
elif usage.status == "low":
_amt = f"${usage.total_spendable_usd:,.2f}" if usage.total_spendable_usd is not None else t("cli.billing.under_five")
tail.append(f" {t('cli.billing.low_balance_usage', amount=_amt)}")
# All via _cprint like the Plan line: print()/_cprint() flush to different buffers under
# patch_stdout. "Total spendable" alone does not count as printed (legacy lines still follow).
if plan:
print()
for ln in head:
_cprint(ln)
self._print_total_spendable(usage, _cprint)
for ln in tail:
_cprint(ln)
if head or tail:
return True
from agent.account_usage import nous_credits_lines
lines = nous_credits_lines()
if not lines:
return False
print()
for line in lines:
print(f" {line}")
return True
def _print_usage_cta(self) -> None:
"""The `/usage` call-to-action; mirrors the TUI's ``USAGE_CTA``. Nous-account only."""
self._dim(t("cli.billing.usage_cta"))
# ── /subscription — view plan + change it (CLI surface) ──
def _show_subscription(self):
"""`/subscription` (alias `/upgrade`). Deep-links NAS's ``/manage-subscription`` (NOT Stripe); never charges."""
from agent.subscription_view import build_subscription_state, subscription_manage_url
state = build_subscription_state()
if not state.logged_in:
self._print_logged_out(state, t("cli.subscription.load_failed_label"), "/subscription")
return
if state.context == "team": # no personal plan — teams run on a shared balance
self._block_header("☤", t("cli.subscription.team_header"))
self._print_org_line(state)
print(f" {t('cli.subscription.team_connected', org=state.org_name or t('cli.subscription.a_team_org'))}")
self._dim(t("cli.subscription.personal_note"))
return
self._subscription_overview(state, subscription_manage_url(state))
def _subscription_overview(self, state, manage_url):
"""Plan read block, then the action: portal hand-off (member / non-interactive), catalog (Free), change menu."""
from cli import _cprint, _b, _d
from agent.billing_usage import format_renews
usage = self._try_usage_model()
c = state.current
is_free = not (c and c.tier_id)
can_change = state.can_change_plan
plan_name = (c.tier_name or c.tier_id) if c else (usage.plan_name if usage else None)
u_status = usage.status if usage else None
_spend = usage.total_spendable_usd if usage else None
renews_display = usage.renews_display if usage else None
if not renews_display and c and c.cycle_ends_at:
renews_display = format_renews(c.cycle_ends_at)
# Headline flags the pending change ("→ Plus" / "→ cancels"); the banner (cancel > downgrade)
# leads so it can't read as "nothing happened".
_flip, _trans = "", None
_your_plan = t("cli.subscription.your_plan")
if c and c.cancel_at_period_end:
_flip = t("cli.subscription.status_flip_cancels")
_trans = (c.tier_name or _your_plan, t("cli.subscription.cancels"),
format_renews(c.cancellation_effective_at) or t("cli.subscription.end_of_billing_period"))
elif c and c.pending_downgrade_tier_name:
_flip = t("cli.subscription.status_flip_to", tier=c.pending_downgrade_tier_name)
_trans = (c.tier_name or _your_plan, c.pending_downgrade_tier_name,
format_renews(c.pending_downgrade_at) or t("cli.subscription.end_of_cycle"))
_left = t("cli.subscription.status_left", amount=f"{_spend:,.2f}") if _spend is not None else ""
if u_status == "low" and _spend is not None:
_tail = ""
elif not can_change:
_tail = t("cli.subscription.status_view_only")
else:
_tail = t("cli.subscription.status_renews", date=renews_display) if renews_display else ""
if plan_name:
status = t("cli.subscription.status_line", plan=plan_name, flip=_flip, left=_left, tail=_tail)
else:
status = t("cli.subscription.status_free")
# All-_cprint (blanks included) so the block orders deterministically even when piped.
_cprint("")
if _trans:
_from, _to, _when = _trans
_cprint(f" ⏳ {_b(t('cli.subscription.scheduled_change'))}")
_cprint(" " + t("cli.subscription.scheduled_change_line", from_plan=_from, to_plan=_to,
when=_d(t("cli.subscription.scheduled_when", when=_when))))
self._dim(t("cli.subscription.keep_until_then", plan=_from))
_cprint("")
_cprint(f" ☤ {_b(status)}")
print(f" {_RULE}")
for _bar_ln in self._usage_bar_lines(usage, plan_name):
print(_bar_ln)
self._print_total_spendable(usage, print)
if is_free:
self._dim(t("cli.subscription.paid_models_need_subscription"))
elif u_status == "low":
_amt = f"${_spend:,.2f}" if _spend is not None else t("cli.billing.under_five")
_cprint(f" {t('cli.subscription.low_balance', amount=_amt)}")
self._print_org_line(state)
print(f" {_RULE}")
if not can_change:
self._dim(t("cli.subscription.plan_changes_need_admin"), lead=True)
if manage_url:
print(f" {t('cli.billing.manage_on_portal_url', url=manage_url)}")
elif not self._app: # non-interactive (TUI slash-worker / piped): the modal can't run
print()
if manage_url:
print(f" {t('cli.subscription.manage_url_line', url=manage_url)}")
print(f" {t('cli.subscription.open_then_rerun')}")
elif is_free: # a NEW subscription needs a fresh card → catalog + portal deep-link only
self._subscription_free_catalog(state, manage_url)
else:
self._subscription_change_menu(state, manage_url)
def _subscription_free_catalog(self, state, manage_url):
"""Free + admin + interactive: catalog → pick → portal deep-link ``plan=<tier_id>`` (a new sub needs a card)."""
from agent.subscription_view import format_tier_row, selectable_tiers, subscription_manage_url
tiers = selectable_tiers(state)
if not tiers:
self._subscription_open_portal(state, manage_url, verb=t("cli.subscription.start_subscription"))
return
self._block_header("☤", t("cli.subscription.choose_plan"))
for i, tier in enumerate(tiers, 1):
print(f" {i}. {format_tier_row(tier)}")
self._dim(t("cli.subscription.start_opens_portal"))
choices = [(tier.tier_id, format_tier_row(tier), t("cli.subscription.desc_start_on_portal", name=tier.name))
for tier in tiers]
choices.append(_cancel_row())
raw = self._prompt_text_input_modal(
title=t("cli.subscription.start_subscription"), detail=t("cli.subscription.pick_plan_detail"), choices=choices)
# Rows are numbered → accept a bare number (the normalizer only knows confirm-dialog digits).
_digit = (raw or "").strip()
_by_row = tiers[int(_digit) - 1] if _digit.isdigit() and 1 <= int(_digit) <= len(tiers) else None
choice = _by_row.tier_id if _by_row else self._normalize_slash_confirm_choice(raw, choices)
if not choice or choice == "cancel":
print(f" {t('cli.subscription.cancelled_no_plan_started')}")
return
tier_url = subscription_manage_url(state, tier_id=choice) or manage_url
if not tier_url:
self._dim(t("cli.billing.no_manage_url"))
return
picked = next((tier for tier in tiers if tier.tier_id == choice), None)
label = picked.name if picked else t("cli.subscription.your_plan")
if self._open_url_in_browser(tier_url):
print(f" {t('cli.subscription.opening_portal_to_start', plan=label)}")
else:
print(f" {t('cli.subscription.open_url_to_start', plan=label, url=tier_url)}")
print(f" {t('cli.subscription.finish_in_browser')}")
def _subscription_open_portal(self, state, manage_url, *, verb=None):
"""Open / copy the manage-subscription URL — the portal hand-off."""
verb = verb or t("cli.subscription.manage_your_subscription")
print()
if not manage_url:
self._dim(t("cli.billing.no_manage_url"))
return
choices = [
("open", verb, t("cli.subscription.desc_open_subscription_page")),
("copy", t("cli.subscription.choice_copy_link"), t("cli.subscription.desc_copy_link")),
_cancel_row()]
choice = self._modal_choice(verb, "", choices)
if choice == "open":
self._open_or_print_url(manage_url)
print()
print(f" {t('cli.subscription.finish_in_browser')}")
elif choice == "copy":
try:
self._write_osc52_clipboard(manage_url)
print(f" {t('cli.subscription.copied', url=manage_url)}")
except Exception:
print(f" {t('cli.subscription.manage_url', url=manage_url)}")
else:
print(f" {t('cli.billing.cancelled_yellow')}")
def _subscription_change_menu(self, state, manage_url):
"""The in-terminal change menu for a paid admin/owner (interactive)."""
c = state.current
# A scheduled change makes undo the likeliest intent → promote it first. The Close row is
# "close" (not "cancel") so typing "cancel" can't be confused with "Cancel subscription".
if c and (c.cancel_at_period_end or c.pending_downgrade_tier_name):
keep_name = c.tier_name or t("cli.subscription.your_plan")
head = [("keep", t("cli.subscription.choice_keep_plan", plan=keep_name), t("cli.subscription.desc_keep_plan")),
_change_plan_row()]
else:
head = [_change_plan_row(),
("cancel_sub", t("cli.subscription.choice_cancel_subscription"), t("cli.subscription.desc_cancel_subscription"))]
choice = self._modal_choice(t("cli.subscription.manage_your_subscription"), "", head + _change_menu_tail())
action = {
"change": lambda: self._subscription_pick_tier(state),
"keep": lambda: self._subscription_apply(state, ("resume", None)),
"cancel_sub": lambda: self._subscription_confirm_cancel(state),
"portal": lambda: self._subscription_open_portal(state, manage_url)}.get(choice)
if action:
action()
else:
print(f" {t('cli.subscription.closed_no_change')}")
def _subscription_pick_tier(self, state):
"""Tier picker → preview → confirm. Paid tiers other than current (dropping to free = cancellation)."""
from agent.subscription_view import format_tier_row, is_upgrade, selectable_tiers
c = state.current
selectable = selectable_tiers(state)
if not selectable:
print(f" {t('cli.subscription.no_other_plans')}")
return
choices = []
for tier in selectable:
direction = t("cli.subscription.direction_upgrade") if is_upgrade(state, tier.tier_id) else t("cli.subscription.direction_downgrade")
choices.append((tier.tier_id, t("cli.subscription.tier_row", row=format_tier_row(tier), direction=direction),
t("cli.subscription.desc_switch_to", name=tier.name)))
choices.append(_cancel_row(label_key="cli.billing.choice_back"))
choice = self._modal_choice(
t("cli.subscription.change_plan_title"),
t("cli.subscription.current_pick_detail", plan=c.tier_name if c else t("cli.billing.plan_free")), choices)
if not choice or choice == "cancel":
print(f" {t('cli.subscription.cancelled_no_plan_change')}")
return
self._subscription_preview_and_confirm(state, choice)
def _subscription_preview_and_confirm(self, state, tier_id, *, allow_stepup=True):
"""Preview → effect → confirm+apply. ``allow_stepup=False`` (post-grant replay) never re-prompts a step-up."""
from cli import _cprint, _b, _d
from agent.subscription_view import is_upgrade, subscription_change_preview_from_payload, subscription_manage_url
from hermes_cli.nous_billing import BillingError, BillingScopeRequired, post_subscription_preview
self._dim(t("cli.subscription.checking_change"))
try:
payload = post_subscription_preview(subscription_type_id=tier_id)
except BillingScopeRequired:
if allow_stepup:
self._subscription_handle_scope_required(state, retry=("preview", tier_id))
else:
print(f" {t('cli.billing.stepup_stale')}")
return
except BillingError as exc:
self._subscription_render_error(state, exc)
return
p = subscription_change_preview_from_payload(payload)
effect = p.effect
target = p.target_tier_name or t("cli.subscription.the_selected_plan")
print()
if effect == "no_op":
self._dim(t("cli.subscription.already_on_nothing_to_change", plan=target))
return
if effect not in ("charge_now", "scheduled"):
# blocked OR unknown effect → fail SAFE (never schedule on an unrecognized string) and
# re-offer the portal. plan= rides along only for an UPGRADE hand-off (downgrades stay native).
_cprint(f" 🟡 {p.reason or t('cli.subscription.cannot_confirm_here')}")
_plan = tier_id if is_upgrade(state, tier_id) else None
_mu = subscription_manage_url(state, tier_id=_plan)
if _mu:
print(f" {t('cli.billing.manage_on_portal_url', url=_mu)}")
return
_tag = t("cli.subscription.tag_charged_now") if effect == "charge_now" else t("cli.subscription.tag_scheduled_not_today")
_cprint(f" {_b(t('cli.subscription.confirm_plan_change'))} {_d(_tag)}")
if effect == "charge_now":
_amt = f"${p.amount_due_now_cents / 100:.2f}" if p.amount_due_now_cents is not None else None
_charged = t("cli.subscription.charged_amount_now", amount=_amt) if _amt else t("cli.subscription.charged_prorated_now")
_cprint(f" {t('cli.subscription.upgrade_will_be_charged', plan=target, charged=_charged)}")
# Best-effort: name the exact card, but only when the resolver rung matches what a
# subscription charge actually uses (subPin / customerDefault — Stripe's precedence).
_card_line = t("cli.subscription.card_on_subscription_charged")
try:
from agent.billing_view import build_billing_state
_bs = build_billing_state(timeout=6.0)
_c = _bs.card if _bs.logged_in else None
if _c is not None and _c.resolved_via in ("subPin", "customerDefault"):
_card_line = t("cli.subscription.named_card_on_subscription_charged", card=_c.masked)
except Exception:
pass
self._dim(_card_line)
pay_label = (t("cli.subscription.choice_pay_and_upgrade", amount=_amt) if _amt
else t("cli.subscription.choice_upgrade_now_prorated"))
action = ("upgrade", tier_id)
# The money-moving row is NOT the default — a bare Enter hits "Go back", so a stray keystroke can't charge.
confirm_choices = [
_cancel_row(label_key="cli.billing.choice_go_back", desc_key="cli.billing.desc_do_not_charge"),
("yes", pay_label, t("cli.subscription.desc_charge_and_upgrade"))]
else: # scheduled (whitelisted above)
_when = (p.effective_at[:10] if (p.effective_at and len(p.effective_at) >= 10)
else t("cli.subscription.end_of_billing_period"))
_cprint(f" {t('cli.subscription.change_takes_effect', plan=target, when=_when)}")
pay_label = t("cli.subscription.choice_schedule_change", plan=target)
action = ("schedule", tier_id)
confirm_choices = [
("yes", pay_label, t("cli.subscription.desc_apply_change")),
_cancel_row(label_key="cli.billing.choice_go_back", desc_key="cli.subscription.desc_do_not_change")]
if p.monthly_credits_delta:
self._dim(t("cli.subscription.monthly_credits_change", delta=p.monthly_credits_delta))
if self._modal_choice(pay_label, "", confirm_choices) != "yes":
print(f" {t('cli.subscription.cancelled_no_plan_change')}")
return
self._subscription_apply(state, action, allow_stepup=allow_stepup)
def _subscription_confirm_cancel(self, state):
"""Confirm, then schedule a cancellation at period end."""
from cli import _cprint, _b, _d
from agent.billing_usage import format_renews
c = state.current
_end = ((format_renews(c.cycle_ends_at) if (c and c.cycle_ends_at) else None)
or t("cli.subscription.end_of_billing_period"))
print()
_cprint(f" {_b(t('cli.subscription.confirm_cancellation'))} {_d(t('cli.subscription.tag_scheduled_not_today'))}")
_cprint(" " + t("cli.subscription.cancel_stays_active_until",
plan=(c.tier_name if c else t("cli.subscription.your_plan")), end=_end))
self._dim(t("cli.subscription.keep_remaining_credits"))
if self._modal_choice(t("cli.subscription.cancel_subscription_question"), "", _cancel_sub_choices()) != "yes":
print(f" {t('cli.subscription.cancelled_plan_unchanged')}")
return
self._subscription_apply(state, ("cancel", None))
def _subscription_apply(self, state, action, idempotency_key=None, *, allow_stepup=True):
"""Run ("upgrade"|"schedule", tier_id) / ("cancel"|"resume", None); scope denial → step-up + ONE replay, same key."""
from cli import _cprint
from hermes_cli.nous_billing import (
BillingError, BillingTransient, BillingRemoteSpendingRevoked, BillingScopeRequired, BillingSessionRevoked,
delete_subscription_pending_change, post_subscription_upgrade, put_subscription_pending_change)
kind, arg = action
key = None
if kind == "upgrade":
from agent.billing_view import new_idempotency_key
key = idempotency_key or new_idempotency_key()
try:
if kind == "upgrade":
res = post_subscription_upgrade(subscription_type_id=arg, idempotency_key=key) or {}
status = res.get("status")
name = res.get("targetTierName") or t("cli.subscription.your_new_plan")
if status in _UPGRADE_OK_KEYS:
self._ok(t(_UPGRADE_OK_KEYS[status], name=name))
elif status in _UPGRADE_STATUS_KEYS:
line_key, echo_url = _UPGRADE_STATUS_KEYS[status]
_cprint(f" {t(line_key)}")
if echo_url and res.get("recoveryUrl"):
_cprint(f" {t('cli.billing.portal_line', url=res.get('recoveryUrl'))}")
else: # unknown / absent 2xx status → also ambiguous, not a flat failure
self._subscription_render_upgrade_ambiguous(None)
return
pending = {
"schedule": (put_subscription_pending_change, {"subscription_type_id": arg}),
"cancel": (put_subscription_pending_change, {"cancel": True}),
"resume": (delete_subscription_pending_change, {})}.get(kind)
if pending:
pending[0](**pending[1])
self._ok(t(_PENDING_OK_KEYS[kind]))
self._dim(t("cli.subscription.rerun_to_review"))
except BillingScopeRequired: # rejects BEFORE charging → route to the step-up
if allow_stepup:
self._subscription_handle_scope_required(state, retry=action, idempotency_key=key)
else:
print(f" {t('cli.billing.stepup_stale')}")
except BillingError as exc:
# Upgrade only: deterministic PRE-charge rejections (Transient/401/403 types, 4xx codes)
# never reached Stripe → recovery copy. Transport / 5xx is INDETERMINATE (NAS may have
# charged) → steer to a re-check, never a blind retry (a fresh key can't dedup).
_pre_charge = (BillingTransient, BillingSessionRevoked, BillingRemoteSpendingRevoked)
_ambiguous = (exc.error in ("network_error", "endpoint_unavailable")
or exc.status is None or exc.status >= 500)
if kind == "upgrade" and _ambiguous and not isinstance(exc, _pre_charge):
self._subscription_render_upgrade_ambiguous(exc)
else:
self._subscription_render_error(state, exc)
def _subscription_handle_scope_required(self, state, *, retry, idempotency_key=None):
"""insufficient_scope → step-up, then replay `retry` ONCE so the user never re-runs the command."""
granted = self._step_up_remote_spending(
explain=t("cli.subscription.stepup_explain"),
noninteractive_msg=f" {t('cli.subscription.stepup_noninteractive')}",
declined_msg=f" {t('cli.subscription.stepup_declined')}",
not_granted_msg=f" {t('cli.subscription.stepup_not_granted')}")
if not granted:
return
self._ok(t("cli.billing.remote_spending_allowed"))
# Bust the 30s token cache (it still holds the pre-grant token; _request only busts on 401).
try:
from hermes_cli import nous_billing as _nb
_nb.invalidate_cached_token()
except Exception:
pass
# Re-fetch fresh state, then replay the held action ONCE (allow_stepup=False).
from agent.subscription_view import build_subscription_state
try:
fresh = build_subscription_state()
except Exception:
fresh = state
if retry[0] == "preview":
self._subscription_preview_and_confirm(fresh, retry[1], allow_stepup=False)
else:
self._subscription_apply(fresh, retry, idempotency_key=idempotency_key, allow_stepup=False)
def _subscription_render_error(self, state, exc):
"""Render a subscription BillingError (a lighter _billing_render_charge_error)."""
from cli import _cprint
msg = str(exc) or t("cli.billing.something_went_wrong")
if exc.error == "insufficient_scope": # defensive: the flow routes scope to the step-up before here
_cprint(f" {t('cli.subscription.remote_spending_not_allowed_yet')}")
elif exc.error in ("subscription_mutation_rejected", "preview_rejected"):
_cprint(f" 🟡 {msg}")
else:
_cprint(f" 🔴 {msg}")
self._print_portal_line(exc)
def _subscription_render_upgrade_ambiguous(self, exc):
"""AMBIGUOUS outcome (NAS may have charged) → steer to a re-check, never a blind retry (key isn't persisted)."""
from cli import _cprint
_cprint(f" {t('cli.subscription.upgrade_ambiguous')}")
self._dim(t("cli.subscription.rerun_to_check_plan"))
self._print_portal_line(exc)
# ── /topup — Remote Spending (CLI surface, all 5 screens) ──
def _show_billing(self, command: str = "/topup"):
"""`/topup` — ZERO sub-commands (argument ignored; Overview is the only route). Non-interactive never
prompts. Money is Decimal end-to-end; the terminal never collects card details."""
from agent.billing_view import build_billing_state
state = build_billing_state()
if not state.logged_in:
self._print_logged_out(state, t("cli.billing.load_failed_label"), "/topup")
return
self._billing_overview(state)
def _billing_portal_hint(self, state, *, reason: str = "") -> None:
"""Print a portal deep-link line (the funnel for portal-only actions)."""
if not state.portal_url:
return
if reason:
print(f" {reason}")
print(f" {t('cli.billing.manage_on_portal_url', url=state.portal_url)}")
def _billing_require_admin(self, state, *, icon="💳 ", off_reason_key="cli.billing.killswitch_reason_buy") -> bool:
"""Admin + org kill-switch gate; portal funnel + False when blocked. ``icon`` adds a blank line + prefix."""
if state.can_change_plan and state.cli_billing_enabled:
return True
if icon:
print()
if not state.can_change_plan:
self._dim(t("cli.billing.actions_require_admin"), icon=icon)
self._billing_portal_hint(state)
else:
self._dim(t("cli.billing.remote_spending_off_for_org"), icon=icon)
self._billing_portal_hint(state, reason=t(off_reason_key))
return False
def _billing_overview(self, state):
"""Screen 1 — balance, bars, menu. No scope preflight (a charge 403s); a missing card does NOT gate it."""
from cli import _cprint, _b
from agent.billing_view import format_money
usage = self._try_usage_model()
print()
_cprint(f" 💳 {_b(t('cli.billing.topup_header', balance=format_money(state.balance_usd)))}")
self._print_org_line(state)
print(f" {_RULE}")
for _bar_ln in self._usage_bar_lines(usage, usage.plan_name if usage else None):
print(_bar_ln)
ar = state.auto_reload
if ar is not None:
if ar.enabled:
print(f" {t('cli.billing.auto_reload_on_line', threshold=format_money(ar.threshold_usd), reload_to=format_money(ar.reload_to_usd))}")
else:
print(f" {t('cli.billing.auto_reload_off_line')}")
if state.can_change_plan and state.cli_billing_enabled: # card at a glance, full-menu case only
if state.card is not None:
print(f" {t('cli.billing.card_line', card=state.card.display)}")
else:
self._dim(t("cli.billing.no_saved_card_add_funds_hint"))
print(f" {_RULE}")
# Action gating: admin + kill-switch for charge/auto-reload; everyone gets portal.
if not self._billing_require_admin(state, icon="", off_reason_key="cli.billing.killswitch_reason_overview"):
return
if not self._app: # non-interactive: no modal, just the portal funnel
self._billing_portal_hint(state)
return
# One-time vs automatic — the distinction stated up front in each first sentence.
self._dim(t("cli.billing.add_funds_now_hint"))
_amounts = [ar.reload_to_usd, ar.threshold_usd] if ar is not None and ar.enabled else [None]
if all(a is not None and a.is_finite() for a in _amounts):
_auto_line = t("cli.billing.refill_when_low_amounts", reload_to=format_money(ar.reload_to_usd),
threshold=format_money(ar.threshold_usd))
else:
_auto_line = t("cli.billing.refill_when_low_generic")
self._dim(_auto_line)
print(f" {_RULE}")
# No "Allow Remote Spending" item — discovered at pay time. "Add funds" charges the org's
# portal-saved card (server-held; no card ref leaves the client).
action = {
"buy": self._billing_buy_flow,
"auto": self._billing_auto_reload_flow,
"limit": self._billing_limit_screen,
"portal": self._billing_open_portal}.get(self._modal_choice(t("cli.billing.topup_title"), "", _topup_menu_choices()))
if action:
action(state)
else:
print(f" {t('cli.billing.cancelled')}")
def _billing_open_portal(self, state):
if not state.portal_url:
print(f" {t('cli.billing.no_portal_url')}")
return
self._open_or_print_url(state.portal_url)
print(f" {t('cli.billing.complete_in_browser')}")
def _billing_add_card_flow(self, state):
"""No card → add it on the portal (never in-terminal), bounded re-check loop. Refreshed state, or None."""
from cli import _cprint
self._block_header("💳", t("cli.billing.add_card_first"), rule=False)
_cprint(f" {t('cli.billing.no_saved_card')}")
self._dim(t("cli.billing.add_card_once_hint"))
for _ in range(8): # bounded: portal-open plus a handful of re-checks
choice = self._modal_choice(t("cli.billing.add_card_title"), "", _add_card_choices())
if choice == "portal":
self._billing_open_portal(state)
self._dim(t("cli.billing.add_card_then_recheck"))
elif choice == "recheck":
from agent.billing_view import build_billing_state
try:
fresh = build_billing_state()
except Exception:
fresh = None
if fresh is not None and fresh.logged_in:
state = fresh
if state.card is not None:
self._ok(t("cli.billing.card_found_continuing", card=state.card.display))
return state
print(f" {t('cli.billing.still_no_card')}")
else:
break
print(f" {t('cli.billing.cancelled_no_funds')}")
return None
def _billing_buy_flow(self, state):
"""Screen 2 (presets) → Screen 3 (confirm+charge+poll). No scope preflight: react to the server's 403s."""
from agent.billing_view import format_money, validate_charge_amount
if not self._billing_require_admin(state):
return
if not self._app:
self._block_header("💳", t("cli.billing.add_funds"), rule=False)
print(f" {t('cli.billing.presets', presets=', '.join(format_money(p) for p in state.charge_presets))}")
print(f" {t('cli.billing.run_interactive_to_purchase')}")
self._billing_portal_hint(state)
return
if state.card is None: # guided add-card path first, so the amount pick can't 403
state = self._billing_add_card_flow(state)
if state is None or state.card is None:
return
preset_choices = [(str(p), format_money(p), t("cli.billing.desc_one_time_purchase")) for p in state.charge_presets]
preset_choices.append(("custom", t("cli.billing.choice_custom_amount"), t("cli.billing.desc_custom_amount")))
preset_choices.append(_cancel_row())
card = state.card
choice = self._modal_choice(
t("cli.billing.add_funds"),
t("cli.billing.payment_line", card=card.display) if card else t("cli.billing.no_saved_card_short"),
preset_choices)
if not choice or choice == "cancel":
print(f" {t('cli.billing.cancelled_no_funds')}")
return
from decimal import Decimal
if choice == "custom":
entered = self._prompt_text_input(f" {t('cli.billing.amount_prompt')} ")
if entered is None: # cancelled (e.g. slash-worker can't prompt off-thread)
print(f" {t('cli.billing.cancelled_no_funds')}")
return
v = validate_charge_amount(entered or "", min_usd=state.min_usd, max_usd=state.max_usd)
if not v.ok:
print(f" 🔴 {v.error}")
return
amount = v.amount
else:
try:
amount = Decimal(choice)
except Exception:
print(f" {t('cli.billing.invalid_selection')}")
return
self._billing_confirm_and_charge(state, amount)
def _billing_confirm_and_charge(self, state, amount):
"""Screen 3 — confirm total + consent, charge, then poll to settlement."""
from agent.billing_view import format_money, new_idempotency_key
card = state.card
self._block_header("💳", t("cli.billing.confirm_purchase"))
print(f" {t('cli.billing.total_line', amount=format_money(amount))}")
if card:
print(f" {t('cli.billing.payment_line', card=card.display)}")
if card.provenance is None: # older NAS without provenance → generic line
self._dim(t("cli.billing.portal_card_will_be_charged"))
print(f" {_RULE}")
self._dim(t("cli.billing.consent_charge"))
confirm_choices = [
("pay", t("cli.billing.choice_pay_now", amount=format_money(amount)), t("cli.billing.desc_submit_charge")),
("portal", t("cli.billing.choice_manage_on_portal"), t("cli.billing.desc_manage_card_billing")),
_cancel_row(label_key="cli.billing.choice_go_back", desc_key="cli.billing.desc_do_not_charge")]
if not self._app:
print(f" {t('cli.billing.run_interactive_to_confirm')}")
return
choice = self._modal_choice(
t("cli.billing.pay_question", amount=format_money(amount)),
card.display if card else t("cli.billing.no_saved_card_lower"), confirm_choices)
if choice == "portal":
self._billing_open_portal(state)
return
if choice != "pay":
print(f" {t('cli.billing.cancelled_no_funds')}")
return
key = new_idempotency_key() # reused on the post-step-up resume so a double-submit collapses
self._billing_submit_and_poll(
state, amount, key, missing_msg=f" 🔴 {t('cli.billing.no_charge_id')}",
status_msg=t("cli.billing.charge_submitted"),
on_scope=lambda: self._billing_handle_scope_required(state, amount=amount, idempotency_key=key))
def _billing_submit_and_poll(self, state, amount, key, *, missing_msg, status_msg, on_scope=None):
"""POST the charge, then poll. ``on_scope`` handles a scope denial (first submit); else it renders."""
from cli import _cprint, _d
from hermes_cli.nous_billing import BillingError, BillingScopeRequired, post_charge
try:
result = post_charge(amount_usd=amount, idempotency_key=key)
except BillingError as exc:
if on_scope is not None and isinstance(exc, BillingScopeRequired):
on_scope()
else:
self._billing_render_charge_error(state, exc)
return
charge_id = result.get("chargeId")
if not charge_id:
print(missing_msg)
return
_cprint(f" {_d(status_msg)}")
self._billing_poll_charge(state, charge_id, amount)
def _billing_poll_charge(self, state, charge_id, amount):
"""Poll loop: 2s interval, 5-min cap, cancellable. settled = ledger truth."""
import time as _time
from agent.billing_view import format_money, parse_money
from hermes_cli.nous_billing import BillingError, BillingTransient, get_charge_status
deadline = _time.time() + 300
while _time.time() < deadline:
try:
status = get_charge_status(charge_id)
except BillingTransient as exc: # retry-after, NOT a failure — back off and keep polling
_time.sleep(min(exc.retry_after or 5, 30))
continue
except BillingError as exc:
print(f" {t('cli.billing.could_not_check_charge', error=exc)}")
return
state_str = status.get("status")
if state_str == "settled":
amt = status.get("amountUsd")
_added = format_money(parse_money(amt)) if amt else format_money(amount)
print(f" {t('cli.billing.added_to_balance', amount=_added)}")
return
if state_str == "failed":
self._billing_render_charge_failed(state, status.get("reason"))
return
_time.sleep(2.0) # pending
print(f" {t('cli.billing.still_processing')}")
self._billing_portal_hint(state)
def _billing_render_charge_failed(self, state, reason):
"""Poll `failed` reasons → the right copy + portal funnel."""
reason = (reason or "").strip()
key = _CHARGE_FAILED_KEYS.get(reason)
print(f" {t(key)}" if key else f" {t('cli.billing.charge_failed_generic', reason=reason or 'processing_error')}")
self._billing_portal_hint(state)
def _billing_render_charge_error(self, state, exc):
"""Submit-time BillingError. Order matters: revoked/session before code lookups; Transient before scope."""
from hermes_cli.nous_billing import BillingTransient, BillingRemoteSpendingRevoked, BillingSessionRevoked
code = exc.error
portal_url = exc.portal_url or state.portal_url
if isinstance(exc, BillingRemoteSpendingRevoked) or code == "remote_spending_revoked":
# This terminal's spend was revoked; recovery is reconnect.
who = t("cli.billing.revoked_by_admin") if exc.actor == "admin" else t("cli.billing.revoked_by_you")
print(f" {t('cli.billing.revoked_reconnect', who=who)}")
elif isinstance(exc, BillingSessionRevoked) or code == "session_revoked":
print(f" {t('cli.billing.session_logged_out')}")
elif code in _CHARGE_ERROR_KEYS or exc.code == "remote_spending_disabled":
# Fixed copy by `error`; the gate's dual error/code payload may carry it in `.code` only.
print(f" {t(_CHARGE_ERROR_KEYS.get(code) or _CHARGE_ERROR_KEYS['cli_billing_disabled'])}")
elif code == "monthly_cap_exceeded":
remaining = (exc.payload or {}).get("remainingUsd")
if remaining is not None:
print(f" {t('cli.billing.monthly_cap_reached_headroom', remaining=remaining)}")
else:
print(f" {t('cli.billing.monthly_cap_reached')}")
elif isinstance(exc, BillingTransient):
wait = exc.retry_after
mins = t("cli.billing.try_again_in_min", minutes=max(1, round(wait / 60))) if wait else ""
print(f" {t('cli.billing.too_many_charges', mins=mins)}")
elif code == "insufficient_scope":
# Never leak the raw billing:manage scope (a raced post-grant replay can re-raise it).
print(f" {t('cli.billing.remote_spending_needs_approval')}")
else:
print(f" 🔴 {exc}")
if portal_url:
print(f" {t('cli.billing.portal_line', url=portal_url)}")
def _billing_handle_scope_required(self, state, *, amount=None, idempotency_key=None):
"""403 insufficient_scope → reauth, then resume ``amount`` on explicit confirm, reusing the idempotency key."""
from agent.billing_view import build_billing_state, format_money, new_idempotency_key
amount_str = format_money(amount) if amount is not None else t("cli.billing.your_topup")
granted = self._step_up_remote_spending(
explain=t("cli.billing.charge_stepup_explain", amount=amount_str),
noninteractive_msg=f" {t('cli.billing.charge_stepup_noninteractive')}",
declined_msg=f" {t('cli.billing.charge_stepup_declined')}",
not_granted_msg=f" {t('cli.billing.charge_stepup_not_granted')}")
if not granted:
return
# The token now has the scope, but the ORG kill-switch is a separate gate — re-fetch /state.
fresh = build_billing_state()
if not (fresh.logged_in and fresh.cli_billing_enabled):
print(f" {t('cli.billing.allowed_but_org_off')}")
self._billing_portal_hint(fresh)
return
if fresh.card is None: # half-done state: say so rather than a bare "✓ enabled"
print(f" ✓ {t('cli.billing.allowed_no_card')}")
self._dim(t("cli.billing.topup_on_portal_to_continue"))
self._billing_portal_hint(fresh)
return
if amount is None: # scope-required hit outside a charge (e.g. auto-reload config)
print(f" ✓ {t('cli.billing.allowed_run_topup')}")
return
print(f" ✓ {t('cli.billing.remote_spending_allowed')}")
resume_choices = [
("resume", t("cli.billing.choice_resume_topup", amount=format_money(amount)), t("cli.billing.desc_resume_topup")),
_cancel_row(desc_key="cli.billing.desc_do_not_charge")]
if self._modal_choice(
t("cli.billing.resume_topup_title"),
t("cli.billing.resume_topup_detail", amount=format_money(amount)), resume_choices) != "resume":
print(f" {t('cli.billing.cancelled_no_funds')}")
return
self._billing_submit_and_poll(
fresh, amount, idempotency_key or new_idempotency_key(),
missing_msg=f" {t('cli.billing.no_charge_id')}",
status_msg=t("cli.billing.resuming_topup"))
def _billing_auto_reload_flow(self, state):
"""Screen 4 — threshold + reload-to → PATCH. Prefills; validates ``reload_to > threshold``; "Turn off" if on."""
from agent.billing_view import format_money, validate_charge_amount
if not self._billing_require_admin(state):
return
card = state.card
ar = state.auto_reload
currently_on = bool(ar and ar.enabled)
self._block_header("💳", t("cli.billing.auto_reload"))
self._dim(t("cli.billing.auto_reload_hint"))
if card:
print(f" {t('cli.billing.card_on_file', card=card.masked)}")
else:
print(f" {t('cli.billing.no_saved_card_manage_portal')}")
self._billing_portal_hint(state)
return
_current = (t("cli.billing.auto_reload_rule", threshold=format_money(ar.threshold_usd), reload_to=format_money(ar.reload_to_usd))
if currently_on else "")
if currently_on:
print(f" {t('cli.billing.currently', rule=_current)}")
if not self._app:
print(f" {t('cli.billing.run_interactive_to_configure')}")
self._billing_portal_hint(state)
return
if currently_on: # let the user turn it off without re-entering values
top = self._modal_choice(t("cli.billing.auto_reload"), t("cli.billing.auto_reload_on_detail", rule=_current),
_auto_reload_top_choices())
if top == "off":
self._billing_auto_reload_disable(state)
return
if top != "edit":
print(f" {t('cli.billing.cancelled_yellow')}")
return
_CANCELLED = object()
def _ask_amount(label, current):
"""One amount; empty keeps `current` when editing. Decimal / kept value, or _CANCELLED (already printed)."""
cur = format_money(current) if currently_on else None
prompt = f" {t('cli.billing.amount_prompt_labeled', label=label)}" + (f" [{cur}]: " if cur else ": ")
raw = self._prompt_text_input(prompt)
if raw is None: # cancelled (e.g. slash-worker can't prompt off-thread)
print(f" {t('cli.billing.cancelled_yellow')}")
return _CANCELLED
if not (raw or "").strip() and currently_on:
return current
v = validate_charge_amount(raw or "", min_usd=state.min_usd, max_usd=state.max_usd)
if not v.ok or v.amount is None:
print(f" 🔴 {v.error}")
return _CANCELLED
return v.amount
threshold_amt = _ask_amount(t("cli.billing.threshold_label"), ar.threshold_usd if currently_on else None)
if threshold_amt is _CANCELLED:
return
reload_amt = _ask_amount(t("cli.billing.reload_to_label"), ar.reload_to_usd if currently_on else None)
if reload_amt is _CANCELLED:
return
if reload_amt is None or threshold_amt is None or reload_amt <= threshold_amt:
print(f" {t('cli.billing.reload_must_exceed_threshold')}")
return
self._dim(t("cli.billing.auto_reload_consent", card=card.masked, threshold=format_money(threshold_amt)), lead=True)
if self._modal_choice(
t("cli.billing.turn_on_auto_reload_question"),
t("cli.billing.auto_reload_rule_cap", threshold=format_money(threshold_amt), reload_to=format_money(reload_amt)),
_auto_reload_agree_choices()) != "agree":
print(f" {t('cli.billing.cancelled_yellow')}")
return
if self._billing_patch_auto_top_up(state, enabled=True, threshold=float(threshold_amt), top_up_amount=float(reload_amt)):
print(f" {t('cli.billing.auto_reload_enabled', threshold=format_money(threshold_amt), reload_to=format_money(reload_amt))}")
def _billing_patch_auto_top_up(self, state, **kwargs) -> bool:
"""PATCH auto-top-up; scope denials → step-up, other errors → renderer. True on success."""
from hermes_cli.nous_billing import BillingError, BillingScopeRequired, patch_auto_top_up
try:
patch_auto_top_up(**kwargs)
except BillingScopeRequired:
self._billing_handle_scope_required(state)
return False
except BillingError as exc:
self._billing_render_charge_error(state, exc)
return False
return True
def _billing_auto_reload_disable(self, state):
"""PATCH ``enabled:false``; the endpoint still requires threshold/topUpAmount → echo current (or 0)."""
ar = state.auto_reload
thr = float(ar.threshold_usd) if ar and ar.threshold_usd is not None else 0.0
rel = float(ar.reload_to_usd) if ar and ar.reload_to_usd is not None else 0.0
if self._billing_patch_auto_top_up(state, enabled=False, threshold=thr, top_up_amount=rel):
print(f" {t('cli.billing.auto_reload_disabled')}")
def _billing_limit_screen(self, state):
"""Screen 5 — monthly spend limit (read-only; cap is portal-only)."""
from agent.billing_view import format_money
self._block_header("💳", t("cli.billing.monthly_spend_limit"))
cap = state.monthly_cap
if cap is None or cap.limit_usd is None:
self._dim(t("cli.billing.no_monthly_cap"))
else:
ceiling = t("cli.billing.default_ceiling_suffix") if cap.is_default_ceiling else ""
print(f" {t('cli.billing.used_this_month', spent=format_money(cap.spent_this_month_usd), limit=format_money(cap.limit_usd), ceiling=ceiling)}")
self._dim(t("cli.billing.monthly_limit_read_only"))
self._billing_portal_hint(state)