hermes-agent/ui-tui/src/gatewayTypes.ts
Siddharth Balyan 7ba5df0d52
feat(billing): /credits command — balance + portal top-up handoff (#44776)
* feat(billing): /usage → portal top-up browser handoff

Add the terminal side of the billing slice (phase 2a): start a top-up by
throwing the user to the portal billing page with the top-up modal open. The
terminal does not confirm, poll, or track payment — checkout completes in the
browser and the next /usage shows the new balance.

- nous_account.py: parse organisation.slug/name from /api/oauth/account into
  NousPortalAccountInfo; add nous_portal_topup_url() building the org-pinned
  {base}/orgs/{slug}/billing?topup=open with a null-slug fallback to the legacy
  {base}/billing?topup=open (never /orgs/None/...).
- portal_cli.py: 'hermes portal topup' — fresh account fetch, identity line
  (Topping up as <email> / org <name>), browser open with printed-URL fallback,
  no-wait closing copy. No polling/confirmation (deferred to 2b).
- account_usage.py: the shared /usage credits block now links the org-pinned
  top-up URL (auto-opens the modal) + points to the command.

Depends on NAS #409 (organisation.slug/name + ?topup=open). Do not merge until
that is live on the target env; until then /api/oauth/account returns
organisation: { id } only and the URL falls back to legacy.

* feat(billing): /credits command for balance + top-up handoff

Replace the standalone `hermes portal topup` subcommand with an in-session
/credits slash command — a focused money surface (balance in, top-up out) that
works in the CLI, TUI, and every messaging platform from one registry entry.

- commands.py: register /credits (Info category). Slack is at its 50-slash cap,
  so /credits is routed via /hermes credits on Slack only (new
  _SLACK_VIA_HERMES_ONLY set) to avoid clamping a canonical command off the
  native list and breaking Telegram parity; native everywhere else.
- account_usage.py: build_credits_view() — one portal fetch → balance lines +
  identity line + org-pinned top-up URL + depleted flag, consumed by all
  surfaces. Reuses the same snapshot/URL builder as /usage so numbers match.
- cli.py: _show_credits() — balance block + identity line + 3-button panel
  (Open top-up / Copy link / Cancel) via the existing prompt_toolkit modal.
  ASK, never auto-launch; headless falls back to printing the URL.
- gateway/slash_commands.py: _handle_credits_command() — renders the block +
  tappable top-up URL + no-wait copy; works on button and plain-text platforms.
- /usage credits line now points to /credits.
- Retire `hermes portal topup` (portal_cli.py back to baseline); the engine
  (slug/name parse + nous_portal_topup_url) stays as the shared core.

No polling, no payment confirmation (billing phase 2a). Depends on NAS #409.

* fix(credits): /credits works in the TUI slash-worker (non-interactive)

In the TUI, /credits runs in the slash-worker subprocess where there is no
live prompt_toolkit app and stdin is the JSON-RPC pipe. _show_credits called
the 3-button modal unconditionally, which fell back to reading stdin →
exception → slash.exec rejected → the command produced no output (only the
pre-existing 'Credit access paused' banner showed).

- _show_credits: when self._app is None (TUI worker / piped / non-interactive),
  render the text variant — balance block + tappable top-up URL + no-wait line,
  same affordance as the messaging surfaces — and skip the modal entirely. The
  3-button panel still renders in the interactive CLI.
- Depleted banner copy: 'run /usage for balance' → 'run /credits to top up'
  now that /credits is the dedicated money surface (+ tests).
- Regression tests: _show_credits with self._app=None renders text and never
  invokes the modal; logged-out path.

* feat(tui): credits.view RPC for the /credits tappable top-up button

Add a credits.view JSON-RPC method returning the structured CreditsView
(logged_in, balance_lines, identity_line, topup_url, depleted) so the TUI can
render a clickable <Link> top-up button instead of plain text. Account-
independent (portal fetch gated on a logged-in Nous account), fail-open to
{logged_in: false} on any hiccup. Mirrors session.usage's credits-block pattern.

Frontend (TUI-local /credits command + Ink component) lands separately.

* feat(tui): /credits command with keyboard-driven top-up confirm

TUI-local /credits: fetches the structured balance via the credits.view RPC,
prints the balance + identity + top-up URL, then arms the EXISTING confirm
overlay (Enter = open top-up in browser via openExternalUrl, Esc = cancel).
Reuses ConfirmReq — no new overlay component/state/input handler. Headless
(openExternalUrl returns false) falls back to printing the URL.

- gatewayTypes.ts: CreditsViewResponse.
- commands/credits.ts: the command (mirrors /status's rpc+guarded pattern).
- registry.ts: register creditsCommands.
- test: balance+overlay armed, headless fallback, no-url, logged-out (4 cases).

Matches the CLI /credits 'Enter to open' affordance. Phase 2a: no polling.
2026-06-12 08:51:10 +00:00

603 lines
16 KiB
TypeScript

import type { SessionInfo, SlashCategory, SubagentStatus, Usage } from './types.js'
export interface GatewaySkin {
banner_hero?: string
banner_logo?: string
branding?: Record<string, string>
colors?: Record<string, string>
help_header?: string
tool_prefix?: string
}
export interface GatewayCompletionItem {
display: string
meta?: string
text: string
}
export interface GatewayTranscriptMessage {
context?: string
name?: string
role: 'assistant' | 'system' | 'tool' | 'user'
text?: string
}
// ── Commands / completion ────────────────────────────────────────────
export interface CommandsCatalogResponse {
canon?: Record<string, string>
categories?: SlashCategory[]
pairs?: [string, string][]
skill_count?: number
sub?: Record<string, string[]>
warning?: string
}
export interface CompletionResponse {
items?: GatewayCompletionItem[]
replace_from?: number
}
export interface SlashExecResponse {
output?: string
warning?: string
}
// ── Credits / top-up ─────────────────────────────────────────────────
export interface CreditsViewResponse {
balance_lines: string[]
depleted: boolean
identity_line: string | null
logged_in: boolean
topup_url: string | null
}
export type CommandDispatchResponse =
| { output?: string; type: 'exec' | 'plugin' }
| { target: string; type: 'alias' }
| { message?: string; name: string; type: 'skill' }
| { message: string; notice?: string; type: 'send' }
| { message: string; notice?: string; type: 'prefill' }
// ── Config ───────────────────────────────────────────────────────────
export interface ConfigDisplayConfig {
bell_on_complete?: boolean
busy_input_mode?: string
details_mode?: string
inline_diffs?: boolean
mouse_tracking?: boolean | null | number | string
sections?: Record<string, string>
show_cost?: boolean
show_reasoning?: boolean
streaming?: boolean
thinking_mode?: string
/**
* Nudge the user toward the /agents spawn-tree dashboard the first time a
* turn starts delegating, via a one-time transient activity hint. Opens
* nothing — just advertises the command. Default true.
*/
tui_agents_nudge?: boolean
tui_auto_resume_recent?: boolean
tui_compact?: boolean
/** Legacy alias for display.mouse_tracking. */
tui_mouse?: boolean | null | number | string
// Forward-compat: backend may send styles this client doesn't know yet —
// `normalizeIndicatorStyle` falls back to 'kaomoji' for those — but the
// wire type is documented as `string` so consumers don't get a false
// narrowing-and-autocomplete contract on a value that requires runtime
// validation anyway.
tui_status_indicator?: string
tui_statusbar?: 'bottom' | 'off' | 'on' | 'top' | boolean
}
export interface ConfigVoiceConfig {
// Raw `yaml.safe_load()` value from config; may be non-string if hand-edited.
// Callers must normalize/validate at runtime (parseVoiceRecordKey()).
record_key?: unknown
}
export interface ConfigFullResponse {
config?: { display?: ConfigDisplayConfig; voice?: ConfigVoiceConfig; paste_collapse_threshold?: number; paste_collapse_char_threshold?: number }
}
export interface ConfigMtimeResponse {
mtime?: number
}
export interface ConfigGetValueResponse {
display?: string
home?: string
value?: string
}
export interface ConfigSetResponse {
confirm_message?: string
confirm_required?: boolean
credential_warning?: string
history_reset?: boolean
info?: SessionInfo
value?: string
warning?: string
}
export interface SetupStatusResponse {
provider_configured?: boolean
}
// ── Session lifecycle ────────────────────────────────────────────────
export interface SessionCreateResponse {
info?: SessionInfo & { config_warning?: string; credential_warning?: string }
session_id: string
}
export interface SessionResumeResponse {
inflight?: null | SessionInflightTurn
info?: SessionInfo
message_count?: number
messages: GatewayTranscriptMessage[]
resumed?: string
running?: boolean
session_id: string
started_at?: number
status?: LiveSessionStatus
}
export type LiveSessionStatus = 'idle' | 'starting' | 'waiting' | 'working'
export interface SessionActiveItem {
current?: boolean
id: string
last_active?: number
message_count?: number
model?: string
preview?: string
session_key?: string
started_at?: number
status: LiveSessionStatus
title?: string
}
export interface SessionActiveListResponse {
sessions?: SessionActiveItem[]
}
export interface SessionInflightTurn {
assistant?: string
streaming?: boolean
user?: string
}
export interface SessionActivateResponse {
inflight?: null | SessionInflightTurn
info?: SessionInfo
message_count?: number
messages: GatewayTranscriptMessage[]
running?: boolean
session_id: string
session_key?: string
started_at?: number
status?: LiveSessionStatus
}
export interface SessionListItem {
id: string
message_count: number
preview: string
source?: string
started_at: number
title: string
}
export interface SessionListResponse {
sessions?: SessionListItem[]
}
export interface SessionDeleteResponse {
deleted: string
}
export interface SessionMostRecentResponse {
session_id?: null | string
source?: string
started_at?: number
title?: string
}
export interface SessionTitleResponse {
pending?: boolean
session_key?: string
title?: string
}
export interface SessionSaveResponse {
file?: string
}
export interface SessionUndoResponse {
removed?: number
}
export interface SessionUsageResponse {
cache_read?: number
cache_write?: number
calls?: number
compressions?: number
context_max?: number
context_percent?: number
context_used?: number
cost_status?: 'estimated' | 'exact'
cost_usd?: number
credits_lines?: string[]
input?: number
model?: string
output?: number
total?: number
}
export interface SessionStatusResponse {
output?: string
}
export interface SessionCompressResponse {
after_messages?: number
after_tokens?: number
before_messages?: number
before_tokens?: number
info?: SessionInfo
messages?: GatewayTranscriptMessage[]
removed?: number
summary?: {
headline?: string
noop?: boolean
note?: null | string
token_line?: string
}
usage?: Usage
}
export interface SessionBranchResponse {
session_id?: string
title?: string
}
export interface SessionCloseResponse {
closed?: boolean
ok?: boolean
}
export interface SessionInterruptResponse {
ok?: boolean
}
export interface SessionSteerResponse {
status?: 'queued' | 'rejected'
text?: string
}
// ── Prompt / submission ──────────────────────────────────────────────
export interface PromptSubmitResponse {
ok?: boolean
}
export interface BackgroundStartResponse {
task_id?: string
}
export interface ClarifyRespondResponse {
ok?: boolean
}
export interface ApprovalRespondResponse {
ok?: boolean
}
export interface SudoRespondResponse {
ok?: boolean
}
export interface SecretRespondResponse {
ok?: boolean
}
// ── Shell / clipboard / input ────────────────────────────────────────
export interface ShellExecResponse {
code: number
stderr?: string
stdout?: string
}
export interface ClipboardPasteResponse {
attached?: boolean
count?: number
height?: number
message?: string
token_estimate?: number
width?: number
}
export interface InputDetectDropResponse {
height?: number
is_image?: boolean
matched?: boolean
name?: string
text?: string
token_estimate?: number
width?: number
}
export interface TerminalResizeResponse {
ok?: boolean
}
// ── Image attach ─────────────────────────────────────────────────────
export interface ImageAttachResponse {
height?: number
name?: string
remainder?: string
token_estimate?: number
width?: number
}
// ── Voice ────────────────────────────────────────────────────────────
export interface VoiceToggleResponse {
audio_available?: boolean
available?: boolean
details?: string
enabled?: boolean
record_key?: string
stt_available?: boolean
tts?: boolean
}
export interface VoiceRecordResponse {
status?: 'busy' | 'recording' | 'stopped'
text?: string
}
// ── Tools (TS keeps configure since it resets local history) ─────────
export interface ToolsConfigureResponse {
changed?: string[]
enabled_toolsets?: string[]
info?: SessionInfo
missing_servers?: string[]
reset?: boolean
unknown?: string[]
}
// ── Model picker ─────────────────────────────────────────────────────
export interface ModelOptionProvider {
auth_type?: string
authenticated?: boolean
is_current?: boolean
key_env?: string
models?: string[]
name: string
slug: string
total_models?: number
warning?: string
}
export interface ModelOptionsResponse {
model?: string
provider?: string
providers?: ModelOptionProvider[]
}
// ── MCP ──────────────────────────────────────────────────────────────
export interface ReloadMcpResponse {
status?: string
message?: string
}
export interface ReloadEnvResponse {
updated?: number
}
export interface ProcessStopResponse {
killed?: number
}
export interface BrowserManageResponse {
connected?: boolean
messages?: string[]
url?: string
}
export interface RollbackCheckpoint {
hash: string
message?: string
timestamp?: string
}
export interface RollbackListResponse {
checkpoints?: RollbackCheckpoint[]
enabled?: boolean
}
export interface RollbackDiffResponse {
diff?: string
rendered?: string
stat?: string
}
export interface RollbackRestoreResponse {
error?: string
history_removed?: number
message?: string
reason?: string
restored_to?: string
success?: boolean
}
// ── Subagent events ──────────────────────────────────────────────────
export interface SubagentEventPayload {
api_calls?: number
cost_usd?: number
depth?: number
duration_seconds?: number
files_read?: string[]
files_written?: string[]
goal: string
input_tokens?: number
iteration?: number
model?: string
output_tail?: { is_error?: boolean; preview?: string; tool?: string }[]
output_tokens?: number
parent_id?: null | string
reasoning_tokens?: number
status?: SubagentStatus
subagent_id?: string
summary?: string
task_count?: number
task_index: number
text?: string
tool_count?: number
tool_name?: string
tool_preview?: string
toolsets?: string[]
}
// ── Delegation control RPCs ──────────────────────────────────────────
export interface DelegationStatusResponse {
active?: {
depth?: number
goal?: string
model?: null | string
parent_id?: null | string
started_at?: number
status?: string
subagent_id?: string
tool_count?: number
}[]
max_concurrent_children?: number
max_spawn_depth?: number
paused?: boolean
}
export interface DelegationPauseResponse {
paused?: boolean
}
export interface SubagentInterruptResponse {
found?: boolean
subagent_id?: string
}
// ── Spawn-tree snapshots ─────────────────────────────────────────────
export interface SpawnTreeListEntry {
count: number
finished_at?: number
label?: string
path: string
session_id?: string
started_at?: number | null
}
export interface SpawnTreeListResponse {
entries?: SpawnTreeListEntry[]
}
export interface SpawnTreeLoadResponse {
finished_at?: number
label?: string
session_id?: string
started_at?: null | number
subagents?: unknown[]
}
export type GatewayEvent =
| { payload?: { skin?: GatewaySkin }; session_id?: string; type: 'gateway.ready' }
| { payload?: GatewaySkin; session_id?: string; type: 'skin.changed' }
| { payload: SessionInfo; session_id?: string; type: 'session.info' }
| { payload?: { text?: string }; session_id?: string; type: 'thinking.delta' }
| { payload?: undefined; session_id?: string; type: 'message.start' }
| { payload?: { kind?: string; text?: string }; session_id?: string; type: 'status.update' }
| {
payload?: {
id?: string
key?: string
kind?: 'sticky' | 'ttl'
level?: 'error' | 'info' | 'success' | 'warn'
text?: string
ttl_ms?: null | number
}
session_id?: string
type: 'notification.show'
}
| { payload?: { key?: string }; session_id?: string; type: 'notification.clear' }
| { payload?: { state?: 'idle' | 'listening' | 'transcribing' }; session_id?: string; type: 'voice.status' }
| { payload?: { no_speech_limit?: boolean; text?: string }; session_id?: string; type: 'voice.transcript' }
| { payload: { line: string }; session_id?: string; type: 'gateway.stderr' }
| {
payload?: { level?: 'info' | 'warn' | 'error'; message?: string }
session_id?: string
type: 'browser.progress'
}
| {
payload?: { cwd?: string; python?: string; stderr_tail?: string }
session_id?: string
type: 'gateway.start_timeout'
}
| { payload?: { preview?: string }; session_id?: string; type: 'gateway.protocol_error' }
| { payload?: { text?: string; verbose?: boolean }; session_id?: string; type: 'reasoning.delta' | 'reasoning.available' }
| { payload: { name?: string; preview?: string }; session_id?: string; type: 'tool.progress' }
| { payload: { name?: string }; session_id?: string; type: 'tool.generating' }
| {
payload: { args_text?: string; context?: string; name?: string; tool_id: string; todos?: unknown[] }
session_id?: string
type: 'tool.start'
}
| {
payload: {
duration_s?: number
error?: string
inline_diff?: string
name?: string
result_text?: string
summary?: string
tool_id: string
todos?: unknown[]
}
session_id?: string
type: 'tool.complete'
}
| {
payload: { choices: string[] | null; question: string; request_id: string }
session_id?: string
type: 'clarify.request'
}
| {
payload: { allow_permanent?: boolean; command: string; description: string }
session_id?: string
type: 'approval.request'
}
| { payload: { request_id: string }; session_id?: string; type: 'sudo.request' }
| { payload: { env_var: string; prompt: string; request_id: string }; session_id?: string; type: 'secret.request' }
| { payload: { task_id: string; text: string }; session_id?: string; type: 'background.complete' }
| { payload?: { text?: string }; session_id?: string; type: 'review.summary' }
| { payload: SubagentEventPayload; session_id?: string; type: 'subagent.spawn_requested' }
| { payload: SubagentEventPayload; session_id?: string; type: 'subagent.start' }
| { payload: SubagentEventPayload; session_id?: string; type: 'subagent.thinking' }
| { payload: SubagentEventPayload; session_id?: string; type: 'subagent.tool' }
| { payload: SubagentEventPayload; session_id?: string; type: 'subagent.progress' }
| { payload: SubagentEventPayload; session_id?: string; type: 'subagent.complete' }
| { payload: { rendered?: string; text?: string }; session_id?: string; type: 'message.delta' }
| {
payload?: { reasoning?: string; rendered?: string; text?: string; usage?: Usage }
session_id?: string
type: 'message.complete'
}
| { payload?: { message?: string }; session_id?: string; type: 'error' }