diff --git a/.github/workflows/e2e-host-matrix.yml b/.github/workflows/e2e-host-matrix.yml index 499672871b..5bed3ab340 100644 --- a/.github/workflows/e2e-host-matrix.yml +++ b/.github/workflows/e2e-host-matrix.yml @@ -11,6 +11,8 @@ on: - 'v3/@claude-flow/cli/bin/**' - 'v3/@claude-flow/cli/src/mcp-server.ts' - 'v3/@claude-flow/codex/src/**' + - 'plugins/ruflo-console/tui/**' + - 'plugins/ruflo-console/hooks/views/standalone-pane.ts' - '.github/workflows/e2e-host-matrix.yml' schedule: - cron: '23 5 * * 1' @@ -39,6 +41,11 @@ jobs: run: | pnpm --recursive --no-bail run build || true test -f @claude-flow/cli/dist/src/index.js || { echo "::error::the CLI did not build"; exit 1; } + - name: Build the TUI bundle (esbuild only, no root install; the tui leg skips cleanly without it) + run: | + mkdir -p "$RUNNER_TEMP/esb" + npm install --prefix "$RUNNER_TEMP/esb" --ignore-scripts esbuild@0.27.2 + RUFLO_ESBUILD_DIR="$RUNNER_TEMP/esb" node plugins/ruflo-console/scripts/build-tui.mjs - name: Install the pinned Codex (0.162.0) run: | npm install -g @openai/codex@0.162.0 diff --git a/docs/e2e-host-matrix.md b/docs/e2e-host-matrix.md index a3003845ba..942c73abe8 100644 --- a/docs/e2e-host-matrix.md +++ b/docs/e2e-host-matrix.md @@ -8,7 +8,7 @@ RUFLO_E2E_LIVE=1 npm run e2e:live # also real sessions, capped at 6 U node scripts/e2e/host-matrix.mjs --legs codex --cli-path "$PWD/v3/@claude-flow/cli/bin/cli.js" --json out.json ``` -Flags: `--legs claude,codex,openrouter`, `--cli-version latest|X.Y.Z` (default: the published `ruflo`), `--cli-path ` (test a workspace +Flags: `--legs claude,codex,openrouter,tui` (the `tui` leg runs the standalone `ruflo tui` bundle in process, so build it first: `node plugins/ruflo-console/scripts/build-tui.mjs`; keyless it covers the six pages, the not-a-terminal exit and the AI page against a stub fetch; live it asks OpenRouter and the pinned Codex one trivial question each after a card), `--cli-version latest|X.Y.Z` (default: the published `ruflo`), `--cli-path ` (test a workspace build; build `shared security mcp swarm cli` first), `--json `, `--cap `. Exit code 1 only when a row is `fail`. ## What you need for the live mode diff --git a/plugins/ruflo-console/.claude-plugin/plugin.json b/plugins/ruflo-console/.claude-plugin/plugin.json index b1b744a676..b11ff5353c 100644 --- a/plugins/ruflo-console/.claude-plugin/plugin.json +++ b/plugins/ruflo-console/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "ruflo-console", "description": "ruflo's cockpit inside Claude Code and the one /ruflo command for every ruflo mod (function hooks, early access). Views: overview with health alerts, swarm topology graph, claims flow with TTL rings, federation map, plugin health matrix, learning curve and pipeline, MetaHarness radar and audit trend, memory, cost gauge, agent timeline, approvals queue, event stream, a main menu, an x.ruv.io federation board, an AI terminal (codex, claude or both in remembered sessions, streamed), Skills (npx skills), a Hive-Mind view, a MetaHarness lab, agent drill-down; a command palette for confirm-gated actions through the ruflo CLI; a band above the prompt. Reads ruflo's files and the CLI's local JSON; anything not measured reads n/a. The one network call it makes by itself is a daily read of the published plugin.json at github.com/ruvnet/ruflo to offer an update (Settings → Updates: ask, auto, or off); it installs only through Claude Code's own claude plugin update, and never a new major version without asking.", - "version": "0.42.6", + "version": "0.42.7", "author": { "name": "ruvnet", "url": "https://github.com/ruvnet" diff --git a/plugins/ruflo-console/CHANGELOG.md b/plugins/ruflo-console/CHANGELOG.md index df9b047452..9d94411de1 100644 --- a/plugins/ruflo-console/CHANGELOG.md +++ b/plugins/ruflo-console/CHANGELOG.md @@ -2,6 +2,11 @@ Newest first. One `## — ` heading per version, then `feat:`, `fix:`, `breaking:` and `chore:` bullets (ADR-478). Built from git history; older versions: `git log -- plugins/ruflo-console`. +## 0.42.7 — 2026-10-11 +- feat: `ruflo tui` has five pages: Overview, Cost, Swarm, Events and Missions (keys 1 to 5, or o c s e m; Tab and Shift-Tab cycle). A page bar shows where you are, a key line says what the keys are, and the terminal redraws on a resize (a short bar under 60 columns, a one-line notice under 40). Room is left out on purpose: it is a message box and Claude sessions this host does not have (ADR-489) +- fix: on the standalone terminal the shared chrome no longer draws what only Claude Code can do: no tab bar, footer buttons, Launch section, Ask Claude buttons or Claude control card, and buttons that nobody can press are not drawn (a state chip such as `● all 0` and a section title are). Under Claude Code nothing changes: every new branch is behind `state.isStandalone` +- fix: Missions on the standalone terminal reads the mission record only (ADR-406); the goal field, plan and research launch are Claude turns and are not shown + ## 0.42.6 — 2026-10-10 - fix: the Plugin Catalog says "mod synced here, plugin not installed" (and marks the row ◇) for a mod Claude Code loaded by sync, such as ruflo-arena@synced, instead of a flat "not installed" that contradicted the Plugins page; the install button stays (#3979) - chore: work-in-progress and merge lines are dropped from the console and mods changelogs shown on What's new (#3979) diff --git a/plugins/ruflo-console/README.md b/plugins/ruflo-console/README.md index 3bd0c1cbcd..2f25972579 100644 --- a/plugins/ruflo-console/README.md +++ b/plugins/ruflo-console/README.md @@ -47,16 +47,18 @@ CONSOLE_DRIVE_INSTALL="$PWD:ruflo-mods@ruflo" RUFLO_E2E_LIVE=1 bash plugins/rufl ## In a terminal of its own: `ruflo tui` (ADR-489) -The same Overview and Cost views, drawn by a small standalone terminal host instead of Claude Code. Read-only; `npx ruflo tui` (the `ruflo` package and `@claude-flow/cli` carry the bundle). +The same views the mod draws, on five pages (Overview, Cost, Swarm, Events, Missions), drawn by a small standalone terminal host instead of Claude Code, and a sixth, AI, that asks Codex or OpenRouter. The five are read-only; the AI page shows a card of exactly what would be sent and sends only after a `y`; `npx ruflo tui` (the `ruflo` package and `@claude-flow/cli` carry the bundle). ```bash -npx ruflo tui # interactive: o overview, c cost, Tab, j/k, PgUp/PgDn, g/G, r refresh, q quit -npx ruflo tui --view cost # start on the Cost page +npx ruflo tui # interactive: 1-5 or o c s e m pick a page, Tab/Shift-Tab cycle, j/k, PgUp/PgDn, g/G, r refresh, q quit +npx ruflo tui --view swarm # start on the Swarm page +npx ruflo tui --view ai --model openai/gpt-4o-mini --max-spend-usd 0.1 # ask OpenRouter on a cheap model, stopping at $0.10 reported (key in $OPENROUTER_API_KEY, never shown) +npx ruflo tui --no-ai # without the AI page npx ruflo tui --plain | head -40 # one plain frame, exit 0: for scripts and CI npx ruflo tui | cat # no terminal and no --plain: a one-line hint on stderr, exit 2 ``` -From a checkout, build the bundle first: `node plugins/ruflo-console/scripts/build-tui.mjs`. Swarm, Events, Missions and Room come next, in that order; Codex and OpenRouter later, read-only by default (decisions C and D in the ADR). +From a checkout, build the bundle first: `node plugins/ruflo-console/scripts/build-tui.mjs`. Room is not in the terminal (it is a message box and Claude sessions). **AI page:** Ctrl-T picks Codex or OpenRouter, Enter shows the card, `y` sends, `n` or Esc cancels, Ctrl-S stops a running answer, Esc hands the keys back to the page bar. Codex runs read-only and only as the pinned 0.162.0 release (never `current` or PATH); OpenRouter goes to `openrouter.ai` over https, or to a host a `--convo-targets` entry names (`endpoint:=||`); a key is read by its variable name and never drawn. Details and what is not done yet: ADR-489 section 4. A terminal narrower than 60 columns gets a short page bar, and under 40 a one-line notice. ## Toasts (ADR-477) diff --git a/plugins/ruflo-console/hooks/state.ts b/plugins/ruflo-console/hooks/state.ts index dd35fc3a37..15a341cd04 100644 --- a/plugins/ruflo-console/hooks/state.ts +++ b/plugins/ruflo-console/hooks/state.ts @@ -197,6 +197,8 @@ export type State = { configDir: string | null /** False in a session with no pane to show (claude -p, an SDK host): views are then answered as text. */ isInteractive: boolean + /** True on the standalone terminal host (ADR-489): there is no Claude session, prompt box, tab bar or mouse, so the shared chrome and the Claude-only controls are not drawn. False under Claude Code. */ + isStandalone: boolean /** When this module loaded: "since the console loaded" series and stall times count from here. */ loadedAtMs: number view: ViewId @@ -343,6 +345,7 @@ export function newState(raw: PluginOptions | undefined): State { nostrKeyVerifiedAtMs: null, configDir: null, isInteractive: true, + isStandalone: false, loadedAtMs: Date.now(), view: 'overview', back: 'overview', diff --git a/plugins/ruflo-console/hooks/version.ts b/plugins/ruflo-console/hooks/version.ts index 4152115a56..4dedca65dd 100644 --- a/plugins/ruflo-console/hooks/version.ts +++ b/plugins/ruflo-console/hooks/version.ts @@ -2,4 +2,4 @@ * The console's version, shown on the header so a person can tell which build is running. Kept equal to the plugin's manifest * (`.claude-plugin/plugin.json`); tests/version.spec.ts fails if the two drift. */ -export const CONSOLE_VERSION = '0.42.6' +export const CONSOLE_VERSION = '0.42.7' diff --git a/plugins/ruflo-console/hooks/views/control.ts b/plugins/ruflo-console/hooks/views/control.ts index 98545f5718..1c488ff638 100644 --- a/plugins/ruflo-console/hooks/views/control.ts +++ b/plugins/ruflo-console/hooks/views/control.ts @@ -8,7 +8,7 @@ const MARK = { ok: '✓', waiting: '…', denied: '✕', error: '!' } as const const COLOR = { ok: THEME.ok, waiting: THEME.warn, denied: THEME.bad, error: THEME.bad } as const /** True while control is on or Claude has acted this session: then the dashboard leads the page, so it is never below the fold. */ -export const isControlActive = (ctx: Ctx): boolean => levelOf(settingsOf(ctx.state).ai.modelControl) !== 'off' || ctx.state.control.log.length > 0 +export const isControlActive = (ctx: Ctx): boolean => !ctx.state.isStandalone && levelOf(settingsOf(ctx.state).ai.modelControl) !== 'off' || ctx.state.control.log.length > 0 /** * The "Claude control" dashboard (ADR-444): whether Claude may drive the console and how far, what it has done this session, and the @@ -16,6 +16,9 @@ export const isControlActive = (ctx: Ctx): boolean => levelOf(settingsOf(ctx.sta */ export function controlRows(ctx: Ctx): RenderElement[] { const { state } = ctx + + // The standalone terminal has no Claude session to control the console: the card would describe a thing that cannot happen here. + if (state.isStandalone) return [] const ai = settingsOf(state).ai const level = levelOf(ai.modelControl) const control = state.control diff --git a/plugins/ruflo-console/hooks/views/events-parts.ts b/plugins/ruflo-console/hooks/views/events-parts.ts index 65a71a2712..9acc51b3ac 100644 --- a/plugins/ruflo-console/hooks/views/events-parts.ts +++ b/plugins/ruflo-console/hooks/views/events-parts.ts @@ -74,7 +74,7 @@ export function detailRows(ctx: Ctx, entry: Row, around: readonly ConsoleEvent[] else if (ref !== undefined) out.push(line(ctx, 'now: nothing in the last read for this ref', { dimColor: true })) const buttons: Btn[] = [ - { key: 'ev-ask', label: ' ✦ ask Claude ', onPress: () => act.ask(event) }, + ...(ctx.state.isStandalone ? [] : [{ key: 'ev-ask', label: ' ✦ ask Claude ', onPress: () => act.ask(event) }]), { key: 'ev-pin', label: ' 📌 pin ', onPress: () => act.pin(event) }, { key: 'ev-copy', label: ' ⧉ copy line ', onPress: () => act.copy(event) }, { key: 'ev-mute-kind', label: ` mute ${event.kind} `, onPress: () => act.muteKind(event.kind) }, diff --git a/plugins/ruflo-console/hooks/views/mission-control.ts b/plugins/ruflo-console/hooks/views/mission-control.ts index 38f618bf10..81ba5d2029 100644 --- a/plugins/ruflo-console/hooks/views/mission-control.ts +++ b/plugins/ruflo-console/hooks/views/mission-control.ts @@ -223,6 +223,9 @@ const flowRows = (ctx: Ctx): RenderElement[] => wrap(FLOW, Math.max(20, ctx.colu * mission or starts a Claude turn; ▶ auto-run is the person's opt-in to skip that confirm for the next ready task. */ export function missionControlView(ctx: Ctx): RenderElement { + // The standalone terminal reads the mission record (ADR-406) and nothing else: planning, launching and research start a Claude turn. + if (ctx.state.isStandalone) return col(ctx, observationRows(ctx), 'mission-record') + const mc = mcOf(ctx.state) const mission = activeMission(ctx.state) const rows: RenderElement[] = [rule(ctx, 'Mission Control', mission === null ? 'goal → SPARC plan → tasks → Claude' : `${mission.id.slice(0, 12)}…`)] diff --git a/plugins/ruflo-console/hooks/views/missions.ts b/plugins/ruflo-console/hooks/views/missions.ts index 97145e82fd..1644308359 100644 --- a/plugins/ruflo-console/hooks/views/missions.ts +++ b/plugins/ruflo-console/hooks/views/missions.ts @@ -48,7 +48,7 @@ export function observationRows(ctx: Ctx): RenderElement[] { rows.push(...researchRows(ctx)) if (observation === null) { - rows.push(text(ctx, ' No mission record yet (ADR-406): create one from a goal in Plan.', { color: THEME.warn })) + rows.push(text(ctx, ctx.state.isStandalone ? ' No mission record yet (ADR-406). Missions are made from a goal in the Claude Code console; this page shows the record once one exists.' : ' No mission record yet (ADR-406): create one from a goal in Plan.', { color: THEME.warn })) return rows } diff --git a/plugins/ruflo-console/hooks/views/optimizer.ts b/plugins/ruflo-console/hooks/views/optimizer.ts index fe4445a730..82580f9ea8 100644 --- a/plugins/ruflo-console/hooks/views/optimizer.ts +++ b/plugins/ruflo-console/hooks/views/optimizer.ts @@ -21,7 +21,8 @@ function findingRows(ctx: Ctx, finding: Finding): RenderElement[] { return [ row(ctx, [ctx.kit.Text({ bold: true, color: COLOR[finding.level](), children: ` ${GLYPH[finding.level]} ${clip(finding.title, Math.max(20, ctx.columns - 34))} ` }), ctx.kit.Text({ dimColor: true, children: `· ${finding.area} · ${finding.metric}` })], `opt-head-${finding.id}`), text(ctx, ` ${clip(finding.why, Math.max(20, ctx.columns - 6))}`, { dimColor: true }), - row( + // The standalone terminal has no buttons, so a row of fixes (or "no button for this one") would say something false there. + ...(ctx.state.isStandalone ? [] : [row( ctx, [ ...fixes.map(item => ctx.kit.Button({ key: `opt-fix-${finding.id}-${item.id}`, label: ` ▸ ${item.label} `, plain: true, onPress: () => ctx.act.optimizer.fix(finding.id, item.id) })), @@ -29,7 +30,7 @@ function findingRows(ctx: Ctx, finding: Finding): RenderElement[] { ctx.kit.Button({ key: `opt-ask-${finding.id}`, label: ' ✦ ask Claude ', plain: true, dimColor: true, onPress: () => ctx.act.optimizer.ask(finding.id) }), ], `opt-fixes-${finding.id}`, - ), + )]), ...(before === undefined ? [] : [text(ctx, ` after ${cfg.ran.get(finding.id) ?? 'a fix'}: ${before} → now ${now ?? 'resolved (no longer a finding)'} (refresh r re-reads)`, { color: now === null ? THEME.ok : THEME.info })]), ] } diff --git a/plugins/ruflo-console/hooks/views/pane.ts b/plugins/ruflo-console/hooks/views/pane.ts index e22a156eaa..1eab9b168e 100644 --- a/plugins/ruflo-console/hooks/views/pane.ts +++ b/plugins/ruflo-console/hooks/views/pane.ts @@ -66,7 +66,7 @@ const NETWORKS: readonly (readonly [string, ViewId])[] = [['x.ruv.io', 'xruv'], /** Width from which every tab spells its name beside its emoji (the 1-9 row is about 128 columns with names). */ const WIDE_TABS = 140 -const BODIES: Record RenderElement> = { +export const BODIES: Record RenderElement> = { menu: menuView, overview: overviewView, swarm: swarmView, diff --git a/plugins/ruflo-console/hooks/views/standalone-pane.ts b/plugins/ruflo-console/hooks/views/standalone-pane.ts new file mode 100644 index 0000000000..c55ec2bc50 --- /dev/null +++ b/plugins/ruflo-console/hooks/views/standalone-pane.ts @@ -0,0 +1,26 @@ +/** + * The page on the standalone terminal host (ADR-489): the view's own body in its cards, under one line that says what the page is + * for. Everything else paneView draws is Claude Code's surface and is left out here: the tab bar, the icon row, the footer buttons, + * the BBS furniture and the plugin Launch section are all mouse controls or Claude turns, and this host has neither. The terminal + * shell (tui/run.ts) draws its own page bar and key line in their place. + */ +import type { RenderElement } from 'claude-code' + +import { isCompactPane, VIEWS } from '../state' +import { CARD_COLUMNS, hasCards, withCards } from './card' +import { col, setLook, text, THEME, type Ctx } from './common' +import { stepsRows } from './steps' + +export function standalonePane(base: Ctx, body: (ctx: Ctx) => RenderElement): RenderElement { + setLook(base.state.options.look) + + const ctx = base + const cardsOn = hasCards(ctx.columns, isCompactPane(ctx.state)) + const bodyCtx: Ctx = cardsOn ? { ...ctx, columns: ctx.columns - CARD_COLUMNS, cards: true, kit: withCards(ctx.kit, undefined) } : ctx + const view = VIEWS.find(entry => entry.id === ctx.state.view) + // The purpose line, minus what only Claude Code can do: Missions here is the record, and Events has no filter key. + const purpose = view === undefined ? '' : view.id === 'missions' ? 'the mission record ruflo wrote: state, tasks and evidence as recorded (read-only)' : view.blurb.replace(/\s*\(f filters them\)/, '') + const about = view === undefined ? [] : [text(ctx, `${view.icon} ${view.label} — ${purpose}`, { color: THEME.head, bold: true })] + + return col(ctx, [...about, ...(cardsOn ? stepsRows(bodyCtx) : []), body(bodyCtx)], 'standalone-pane') +} diff --git a/plugins/ruflo-console/scripts/build-tui.mjs b/plugins/ruflo-console/scripts/build-tui.mjs index ab953e146a..bb2e5dbd86 100644 --- a/plugins/ruflo-console/scripts/build-tui.mjs +++ b/plugins/ruflo-console/scripts/build-tui.mjs @@ -11,11 +11,18 @@ const root = resolve(dirname(fileURLToPath(import.meta.url)), '..') const flag = name => process.argv.includes(name) ? process.argv[process.argv.indexOf(name) + 1] : undefined const outfile = resolve(flag('--outfile') ?? join(root, 'dist', 'tui.mjs')) +// The repo's own esbuild (npm install at the root), or the one in RUFLO_ESBUILD_DIR (a directory with node_modules/esbuild: CI installs it alone, since a root install is heavy). let esbuild -try { - esbuild = createRequire(join(root, '..', '..', 'package.json'))('esbuild') -} catch { - console.error('build-tui: esbuild is not installed (run npm install at the repo root).') +for (const base of [join(root, '..', '..', 'package.json'), ...(process.env.RUFLO_ESBUILD_DIR ? [join(process.env.RUFLO_ESBUILD_DIR, 'package.json')] : [])]) { + try { + esbuild = createRequire(base)('esbuild') + break + } catch { + // try the next place + } +} +if (esbuild === undefined) { + console.error('build-tui: esbuild is not installed (run npm install at the repo root, or set RUFLO_ESBUILD_DIR to a directory that has node_modules/esbuild).') process.exit(1) } diff --git a/plugins/ruflo-console/scripts/smoke.sh b/plugins/ruflo-console/scripts/smoke.sh index f09288217f..56b7dcec88 100755 --- a/plugins/ruflo-console/scripts/smoke.sh +++ b/plugins/ruflo-console/scripts/smoke.sh @@ -11,9 +11,9 @@ step() { printf "→ %s ... " "$1"; } ok() { printf "PASS\n"; PASS=$((PASS+1)); } bad() { printf "FAIL: %s\n" "$1"; FAIL=$((FAIL+1)); } -step "1. plugin.json declares ruflo-console 0.42.6" +step "1. plugin.json declares ruflo-console 0.42.7" grep -q '"name": "ruflo-console"' "$ROOT/.claude-plugin/plugin.json" \ - && grep -q '"version": "0.42.6"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version" + && grep -q '"version": "0.42.7"' "$ROOT/.claude-plugin/plugin.json" && ok || bad "name/version" step "2. hooks.json names exactly one module and no classic hook commands" grep -q '"modules": \["./register.ts"\]' "$HOOKS/hooks.json" && ! grep -q '"command"' "$HOOKS/hooks.json" \ diff --git a/plugins/ruflo-console/tests/fixtures/fake-codex.mjs b/plugins/ruflo-console/tests/fixtures/fake-codex.mjs new file mode 100755 index 0000000000..d2c776ad39 --- /dev/null +++ b/plugins/ruflo-console/tests/fixtures/fake-codex.mjs @@ -0,0 +1,27 @@ +#!/usr/bin/env node +// A stand-in for the pinned Codex (ADR-489 phase 3 tests): `--version` says the pinned version; `exec --json ... -` reads the prompt on stdin +// and streams the events the real CLI writes (thread.started, an agent message, turn.completed). What it was started with goes to the file +// `fake-codex.log` in CODEX_HOME (the one variable besides PATH and HOME the host lets a child see), so a test can assert the exact argv, that +// the prompt came on stdin, and what the child's environment held. +import { appendFileSync } from 'node:fs' + +const args = process.argv.slice(2) + +if (args[0] === '--version') { + console.log('codex-cli 0.162.0') + process.exit(0) +} + +let input = '' + +process.stdin.setEncoding('utf8') +process.stdin.on('data', chunk => (input += chunk)) +process.stdin.on('end', () => { + if (process.env.CODEX_HOME) appendFileSync(`${process.env.CODEX_HOME}/fake-codex.log`, JSON.stringify({ args, input, codexHome: process.env.CODEX_HOME, hasOpenRouterKey: process.env.OPENROUTER_API_KEY !== undefined, hasOtherSecret: process.env.SOME_OTHER_SECRET !== undefined }) + '\n') + + const event = e => console.log(JSON.stringify(e)) + + event({ type: 'thread.started', thread_id: '019f0000-aaaa-bbbb-cccc-000000000001' }) + event({ type: 'item.completed', item: { type: 'agent_message', text: `echo: ${input.trim()}\n\u001b]0;pwned\u0007and a second line` } }) + event({ type: 'turn.completed', usage: { input_tokens: 12, output_tokens: 7 } }) +}) diff --git a/plugins/ruflo-console/tests/tui-ai-guard.spec.ts b/plugins/ruflo-console/tests/tui-ai-guard.spec.ts new file mode 100644 index 0000000000..e96233c8b6 --- /dev/null +++ b/plugins/ruflo-console/tests/tui-ai-guard.spec.ts @@ -0,0 +1,87 @@ +/** + * What the AI page may run and send (ADR-489 decision D): every refusal pinned. Pure, so no process and no network. + * npx vitest run plugins/ruflo-console/tests/tui-ai-guard.spec.ts + */ +import { describe, expect, it } from 'vitest' + +import { allowedHostsOf, PINNED_CODEX, validateCodexArgv, validateHttp } from '../tui/ai-guard' + +const NEW = ['codex', 'exec', '--json', '--sandbox', 'read-only', '--skip-git-repo-check', '-'] +const RESUME = ['codex', 'exec', 'resume', '--json', '--skip-git-repo-check', '-c', 'sandbox_mode="read-only"', '019f0000-aaaa-bbbb-cccc-000000000001', '-'] + +describe('codex argv', () => { + it('accepts exactly what the console builds for a new thread and for a resumed one, read-only', () => { + expect(validateCodexArgv(NEW)).toEqual({ ok: true, args: ['exec', '--json', '--sandbox', 'read-only', '--skip-git-repo-check', '-'], sandbox: 'read-only' }) + expect(validateCodexArgv(RESUME)).toEqual({ ok: true, args: ['exec', 'resume', '--json', '--skip-git-repo-check', '-c', 'sandbox_mode="read-only"', '019f0000-aaaa-bbbb-cccc-000000000001', '-'], sandbox: 'read-only' }) + expect(validateCodexArgv(['codex', 'exec', '-s', 'read-only', '--ephemeral', '-m', 'gpt-5-codex', '-'])).toMatchObject({ ok: true }) + }) + + it('refuses another program, another subcommand, and a missing explicit sandbox', () => { + expect(validateCodexArgv(['bash', 'exec', '-'])).toMatchObject({ ok: false }) + expect(validateCodexArgv(['codex', 'login'])).toMatchObject({ ok: false }) + expect(validateCodexArgv(['codex', 'exec', '--json', '-'])).toMatchObject({ ok: false, why: expect.stringMatching(/explicit sandbox/) }) + expect(validateCodexArgv(['codex', 'exec', '--sandbox', 'read-only'])).toMatchObject({ ok: false, why: expect.stringMatching(/must end with -/) }) + expect(validateCodexArgv([...NEW, '--yolo'])).toMatchObject({ ok: false }) + }) + + it('refuses danger-full-access and every way to widen the sandbox, whatever the opt-in', () => { + for (const allow of [false, true]) { + expect(validateCodexArgv(['codex', 'exec', '--sandbox', 'danger-full-access', '-'], allow)).toMatchObject({ ok: false }) + expect(validateCodexArgv(['codex', 'exec', '-c', 'sandbox_mode="danger-full-access"', '-'], allow)).toMatchObject({ ok: false }) + expect(validateCodexArgv(['codex', 'exec', '--dangerously-bypass-approvals-and-sandbox', '--sandbox', 'read-only', '-'], allow)).toMatchObject({ ok: false }) + expect(validateCodexArgv(['codex', 'exec', '--sandbox', 'read-only', '-c', 'approval_policy="never"', '-'], allow)).toMatchObject({ ok: false }) + expect(validateCodexArgv(['codex', 'exec', '--sandbox', 'read-only', '-p', 'unsafe', '-'], allow)).toMatchObject({ ok: false }) + expect(validateCodexArgv(['codex', 'exec', '--sandbox', 'read-only', '--add-dir', '/', '-'], allow)).toMatchObject({ ok: false }) + expect(validateCodexArgv(['codex', 'exec', '--full-auto', '--sandbox', 'read-only', '-'], allow)).toMatchObject({ ok: false }) + } + }) + + it('allows workspace-write only after the per-session opt-in, and never two different modes', () => { + const write = ['codex', 'exec', '--sandbox', 'workspace-write', '-'] + + expect(validateCodexArgv(write)).toMatchObject({ ok: false }) + expect(validateCodexArgv(write, true)).toMatchObject({ ok: true, sandbox: 'workspace-write' }) + expect(validateCodexArgv(['codex', 'exec', '--sandbox', 'read-only', '-c', 'sandbox_mode="workspace-write"', '-'], true)).toMatchObject({ ok: false, why: expect.stringMatching(/two different/) }) + }) + + it('refuses a model name that is not a plain name, a stray token, and anything after the stdin marker', () => { + expect(validateCodexArgv(['codex', 'exec', '--sandbox', 'read-only', '-m', 'a b; rm -rf /', '-'])).toMatchObject({ ok: false }) + expect(validateCodexArgv(['codex', 'exec', '--sandbox', 'read-only', 'some prompt text', '-'])).toMatchObject({ ok: false }) + expect(validateCodexArgv(['codex', 'exec', '--sandbox', 'read-only', '-', 'x'])).toMatchObject({ ok: false }) + }) + + it('pins the version the tests and the host check against', () => { + expect(PINNED_CODEX).toBe('0.162.0') + }) +}) + +const POST = { method: 'POST', headers: { 'content-type': 'application/json', authorization: 'Bearer k' }, body: '{}' } + +describe('http', () => { + const hosts = ['openrouter.ai', 'llm.example.com'] + + it('accepts https POST to a listed host with the two chat headers', () => { + expect(validateHttp('https://openrouter.ai/api/v1/chat/completions', POST, hosts)).toMatchObject({ ok: true }) + expect(validateHttp('https://llm.example.com:443/v1/chat/completions', POST, hosts)).toMatchObject({ ok: true }) + }) + + it('refuses http, other hosts, look-alike hosts, userinfo, other ports, other methods and other headers', () => { + expect(validateHttp('http://openrouter.ai/x', POST, hosts)).toMatchObject({ ok: false, why: 'https only' }) + expect(validateHttp('https://evil.example.com/x', POST, hosts)).toMatchObject({ ok: false }) + expect(validateHttp('https://evil.openrouter.ai/x', POST, hosts)).toMatchObject({ ok: false }) + expect(validateHttp('https://openrouter.ai.evil.com/x', POST, hosts)).toMatchObject({ ok: false }) + expect(validateHttp('https://openrouter.ai@evil.com/x', POST, hosts)).toMatchObject({ ok: false }) + expect(validateHttp('https://user:pw@openrouter.ai/x', POST, hosts)).toMatchObject({ ok: false, why: 'no credentials in the URL' }) + expect(validateHttp('https://openrouter.ai:8443/x', POST, hosts)).toMatchObject({ ok: false }) + expect(validateHttp('https://169.254.169.254/latest', POST, hosts)).toMatchObject({ ok: false }) + expect(validateHttp('https://openrouter.ai/x', { ...POST, method: 'GET' }, hosts)).toMatchObject({ ok: false }) + expect(validateHttp('https://openrouter.ai/x', { ...POST, headers: { ...POST.headers, cookie: 'a=b' } }, hosts)).toMatchObject({ ok: false }) + expect(validateHttp('https://openrouter.ai/x', { ...POST, body: 'x'.repeat(100_001) }, hosts)).toMatchObject({ ok: false }) + expect(validateHttp('not a url', POST, hosts)).toMatchObject({ ok: false }) + }) + + it('builds the host list from openrouter.ai and the https hosts a convoTargets entry names, never an address or an http host', () => { + expect(allowedHostsOf(['https://llm.example.com/v1', 'http://plain.example.com/v1', 'https://10.0.0.5/v1', 'https://box.internal/v1', 'https://localhost.local/v1', 'garbage'])).toEqual(['openrouter.ai', 'llm.example.com']) + expect(allowedHostsOf([])).toEqual(['openrouter.ai']) + }) +}) diff --git a/plugins/ruflo-console/tests/tui-ai-host.spec.ts b/plugins/ruflo-console/tests/tui-ai-host.spec.ts new file mode 100644 index 0000000000..5054002a6d --- /dev/null +++ b/plugins/ruflo-console/tests/tui-ai-host.spec.ts @@ -0,0 +1,173 @@ +/** + * The standalone Node host with the AI doors open (ADR-489 phase 3): the pinned Codex only (a fake one here), HTTPS to a listed host only + * (an injected fetch), a model key read by NAME. Nothing reaches the real network or a real Codex. + * npx vitest run plugins/ruflo-console/tests/tui-ai-host.spec.ts + */ +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync, chmodSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest' + +import { createNodeHost, resolveCodex } from '../tui/node-host' + +const FAKE = join(__dirname, 'fixtures', 'fake-codex.mjs') +const isWin = process.platform === 'win32' +const NEW = ['codex', 'exec', '--json', '--sandbox', 'read-only', '--skip-git-repo-check', '-'] +let root: string +let codexHome: string + +beforeAll(() => { + root = mkdtempSync(join(tmpdir(), 'tui-ai-host-')) + codexHome = join(root, 'codex-home') + mkdirSync(join(root, 'project'), { recursive: true }) + mkdirSync(codexHome, { recursive: true }) +}) +afterAll(() => { + rmSync(root, { recursive: true, force: true }) +}) + +const host = (ai: Parameters[0]['ai'] = { codexBin: FAKE, allowedHosts: ['openrouter.ai'], keyEnvs: ['OPENROUTER_API_KEY'] }) => createNodeHost({ cwd: join(root, 'project'), home: root, ai }) + +async function drain(stream: ReturnType['spawn']>): Promise<{ out: string; err: string; code: number | null }> { + let out = '' + let err = '' + + for await (const chunk of stream) { + if (chunk.stream === 'stdout') out += chunk.text + else err += chunk.text + } + + return { out, err, code: (await stream.result).code } +} + +describe('the pinned Codex', () => { + it.skipIf(isWin)('resolves only a program whose --version says exactly the pinned version', async () => { + expect(await resolveCodex(root, FAKE)).toEqual({ ok: true, bin: FAKE }) + + const newer = join(root, 'newer-codex.mjs') + + writeFileSync(newer, '#!/usr/bin/env node\nconsole.log("codex-cli 0.162.1")\n') + chmodSync(newer, 0o755) + expect(await resolveCodex(root, newer)).toMatchObject({ ok: false, why: expect.stringMatching(/pinned Codex 0\.162\.0 is not installed/) }) + }) + + it('finds the release directory named for the pinned version, never current and never PATH', async () => { + const releases = join(root, '.codex', 'packages', 'standalone', 'releases') + + mkdirSync(join(releases, '0.162.1-x86_64-unknown-linux-musl', 'bin'), { recursive: true }) + mkdirSync(join(root, '.codex', 'packages', 'standalone', 'current'), { recursive: true }) + // Another version on disk, and a codex on PATH that claims the pinned version: neither is used. + writeFileSync(join(releases, '0.162.1-x86_64-unknown-linux-musl', 'bin', 'codex'), '#!/bin/sh\necho "codex-cli 0.162.0"\n') + chmodSync(join(releases, '0.162.1-x86_64-unknown-linux-musl', 'bin', 'codex'), 0o755) + expect(await resolveCodex(root)).toMatchObject({ ok: false, why: expect.stringMatching(/never uses current or PATH/) }) + }) + + it.skipIf(isWin)('finds the exact release when it is there', async () => { + const dir = join(root, '.codex', 'packages', 'standalone', 'releases', '0.162.0-x86_64-unknown-linux-musl', 'bin') + + mkdirSync(dir, { recursive: true }) + writeFileSync(join(dir, 'codex'), readFileSync(FAKE)) + chmodSync(join(dir, 'codex'), 0o755) + expect(await resolveCodex(root)).toEqual({ ok: true, bin: join(dir, 'codex') }) + }) + + it('spawn refuses anything but a read-only codex exec, before a process starts, and with no AI options at all', () => { + expect(() => host().spawn(['bash', '-c', 'echo hi'])).toThrow(/only `codex exec` runs here/) + expect(() => host().spawn(['codex', 'exec', '--sandbox', 'danger-full-access', '-'])).toThrow(/not allowed/) + expect(() => createNodeHost({ cwd: join(root, 'project'), home: root }).spawn(NEW)).toThrow(/AI page is not enabled/) + }) + + it.skipIf(isWin)('streams the child, sends the prompt on stdin, and keeps our API keys out of its environment', async () => { + process.env.OPENROUTER_API_KEY = 'sk-or-v1-0123456789abcdef0123456789abcdef' + process.env.SOME_OTHER_SECRET = 'do-not-leak' + process.env.CODEX_HOME = codexHome + + try { + const { out, code } = await drain(host().spawn(NEW, 'hello codex')) + const ran = JSON.parse(readFileSync(join(codexHome, 'fake-codex.log'), 'utf8').trim().split('\n').pop() as string) as { args: string[]; input: string; codexHome: string | null; hasOpenRouterKey: boolean; hasOtherSecret: boolean } + + expect(code).toBe(0) + expect(out).toContain('thread.started') + expect(ran.args).toEqual(['exec', '--json', '--sandbox', 'read-only', '--skip-git-repo-check', '-']) + expect(ran.input).toBe('hello codex') + expect(ran.codexHome).toBe(codexHome) + expect(ran.hasOpenRouterKey).toBe(false) + expect(ran.hasOtherSecret).toBe(false) + } finally { + delete process.env.OPENROUTER_API_KEY + delete process.env.SOME_OTHER_SECRET + delete process.env.CODEX_HOME + } + }) + + it('a missing pinned program is a failed start in the stream, with the reason, not a crash', async () => { + const stream = host({ codexBin: join(root, 'nope', 'codex'), allowedHosts: [], keyEnvs: [] }).spawn(NEW, 'x') + + await expect(drain(stream)).rejects.toThrow(/pinned Codex 0\.162\.0 is not installed/) + }) + + it.skipIf(isWin)('returning from the stream stops the child', async () => { + const slow = join(root, 'slow-codex.mjs') + + writeFileSync(slow, '#!/usr/bin/env node\nif (process.argv[2] === "--version") { console.log("codex-cli 0.162.0"); process.exit(0) }\nprocess.stdin.resume(); setInterval(() => console.log("tick"), 50)\n') + chmodSync(slow, 0o755) + + const stream = host({ codexBin: slow, allowedHosts: [], keyEnvs: [] }).spawn(NEW, 'x') + const first = await stream.next() + + expect(first.done).toBe(false) + await stream.return(undefined as never) + await expect(stream.result).resolves.toMatchObject({ signal: 'SIGTERM' }) + }) +}) + +describe('https', () => { + const sent = () => vi.fn(async (_url: unknown, _init?: unknown) => new Response('{"ok":true}', { status: 200 })) + + it('sends a POST to a listed host with redirects off, and nothing else leaves', async () => { + const fetchSpy = sent() + const h = host({ allowedHosts: ['openrouter.ai'], keyEnvs: [], fetch: fetchSpy as never }) + const reply = await h.httpSend!('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', headers: { 'content-type': 'application/json', authorization: 'Bearer k' }, body: '{}' }) + + expect(reply).toEqual({ ok: true, status: 200, text: '{"ok":true}' }) + expect(fetchSpy).toHaveBeenCalledTimes(1) + expect((fetchSpy.mock.calls[0]?.[1] as { redirect: string }).redirect).toBe('manual') + + for (const url of ['http://openrouter.ai/x', 'https://evil.example.com/x', 'https://openrouter.ai.evil.com/x', 'https://169.254.169.254/x']) { + expect(await h.httpSend!(url, { method: 'POST', headers: {}, body: '{}' })).toMatchObject({ ok: false, status: 0 }) + } + expect(await h.httpSend!('https://openrouter.ai/x', { method: 'GET', headers: {}, body: '' })).toMatchObject({ ok: false, status: 0 }) + expect(fetchSpy).toHaveBeenCalledTimes(1) + }) + + it('a redirect is an error, never followed (it could carry the key to another host)', async () => { + const h = host({ allowedHosts: ['openrouter.ai'], keyEnvs: [], fetch: (async () => new Response('', { status: 302, headers: { location: 'https://evil.example.com/' } })) as never }) + + expect(await h.httpSend!('https://openrouter.ai/x', { method: 'POST', headers: {}, body: '{}' })).toMatchObject({ ok: false, status: 302, text: expect.stringMatching(/does not follow redirects/) }) + }) + + it('with no AI options the host sends nothing', async () => { + const fetchSpy = sent() + + expect(await createNodeHost({ cwd: join(root, 'project'), home: root }).httpSend!('https://openrouter.ai/x', { method: 'POST', headers: {}, body: '{}' })).toMatchObject({ ok: false, status: 0 }) + expect(fetchSpy).not.toHaveBeenCalled() + }) + + it('reads a model key by name, only a name it was given, and any other command stays refused', async () => { + process.env.OPENROUTER_API_KEY = 'sk-or-v1-0123456789abcdef0123456789abcdef' + process.env.SOME_OTHER_SECRET = 'do-not-read' + + try { + const h = host({ allowedHosts: ['openrouter.ai'], keyEnvs: ['OPENROUTER_API_KEY'] }) + + expect((await h.run(['printenv', 'OPENROUTER_API_KEY'], 1000)).stdout.trim()).toBe(process.env.OPENROUTER_API_KEY) + expect((await h.run(['printenv', 'MISSING_KEY_VAR'], 1000).catch(() => ({ exitCode: -1 }))).exitCode).not.toBe(0) + await expect(h.run(['printenv', 'SOME_OTHER_SECRET'], 1000)).rejects.toThrow(/not available/) + await expect(h.run(['printenv'], 1000)).rejects.toThrow(/not available/) + await expect(h.run(['sh', '-c', 'echo $HOME'], 1000)).rejects.toThrow(/not available/) + } finally { + delete process.env.OPENROUTER_API_KEY + delete process.env.SOME_OTHER_SECRET + } + }) +}) diff --git a/plugins/ruflo-console/tests/tui-ai-page.spec.ts b/plugins/ruflo-console/tests/tui-ai-page.spec.ts new file mode 100644 index 0000000000..e4db52ec0a --- /dev/null +++ b/plugins/ruflo-console/tests/tui-ai-page.spec.ts @@ -0,0 +1,315 @@ +/** + * The AI page (ADR-489 phase 3, decision D) end to end without a network or a real Codex: a stub fetch for OpenRouter and the fake pinned + * Codex. Every send waits for a card that was drawn; a key is read by name and never reaches a frame; the reply's cost is the provider's. + * npx vitest run plugins/ruflo-console/tests/tui-ai-page.spec.ts + */ +import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' + +import { widthOf } from '../tui/ansi' +import { runTui, type TuiIO } from '../tui/run' +import { openSession } from '../tui/session' + +const FAKE = join(__dirname, 'fixtures', 'fake-codex.mjs') +const KEY = 'sk-or-v1-0123456789abcdef0123456789abcdef' +const ESC = '\u001b' +const isWin = process.platform === 'win32' +let root: string +let project: string +let codexHome: string + +beforeAll(() => { + root = mkdtempSync(join(tmpdir(), 'tui-ai-page-')) + project = join(root, 'project') + codexHome = join(root, 'codex-home') + mkdirSync(project, { recursive: true }) + mkdirSync(codexHome, { recursive: true }) +}) +afterAll(() => rmSync(root, { recursive: true, force: true })) +beforeEach(() => void (process.env.OPENROUTER_API_KEY = KEY)) +afterEach(() => { + delete process.env.OPENROUTER_API_KEY + delete process.env.CODEX_HOME + vi.useRealTimers() +}) + +const reply = (content: string, cost = 0.004) => ({ choices: [{ message: { content } }], usage: { prompt_tokens: 5, completion_tokens: 7, cost }, model: 'stub/model' }) + +function open(extra: { maxSpendUsd?: number; model?: string; body?: unknown; status?: number } = {}) { + const fetchSpy = vi.fn(async (_url: unknown, _init?: unknown) => new Response(JSON.stringify(extra.body ?? reply('hello from the stub')), { status: extra.status ?? 200 })) + const session = openSession({ cwd: project, home: root, aiPage: { codexBin: FAKE, fetch: fetchSpy as never, ...(extra.maxSpendUsd !== undefined && { maxSpendUsd: extra.maxSpendUsd }), ...(extra.model !== undefined && { model: extra.model }) } }) + + session.show('ai') + + return { session, ai: session.ai!, fetchSpy } +} + +const type = (ai: NonNullable['ai']>, text: string) => void ai.press(text) +const frame = (session: ReturnType['session'], columns = 100, rows = 30) => session.frame(columns, 'none', rows).join('\n') +/** A frame with the card's border and wrapping folded away, so a phrase that wrapped is still found. */ +const flat = (text: string) => text.replace(/[│╭╮╰╯─]/g, ' ').replace(/\s+/g, ' ') +const until = async (check: () => boolean, ms = 4000) => { + const end = Date.now() + ms + + while (!check() && Date.now() < end) await new Promise(resolve => setTimeout(resolve, 20)) + expect(check()).toBe(true) +} +const body = (spy: ReturnType['fetchSpy']) => JSON.parse((spy.mock.calls[0]?.[1] as { body: string }).body) as { model: string; messages: { content: string }[] } + +describe('OpenRouter', () => { + it('Enter shows a card of exactly what would be sent and sends nothing', () => { + const { session, ai, fetchSpy } = open({ model: 'stub/model' }) + + ai.press('\u0014') + type(ai, 'what is two plus two') + ai.press('\r') + + const text = frame(session) + + expect(ai.card).toMatchObject({ target: 'openrouter', text: 'what is two plus two' }) + expect(text).toContain('Ask first, #1') + expect(flat(text)).toContain('POST https://openrouter.ai/api/v1/chat/completions') + expect(flat(text)).toContain('Authorization: Bearer ‹from $OPENROUTER_API_KEY›') + expect(flat(text)).toContain('"model":"stub/model"') + expect(text).toContain('y sends it') + expect(text).not.toContain(KEY) + expect(fetchSpy).not.toHaveBeenCalled() + session.stop() + }) + + it('a y before the card was on screen answers nothing; once drawn, it sends one request with the key in one header', async () => { + const { session, ai, fetchSpy } = open({ model: 'stub/model' }) + + ai.press('\u0014') + type(ai, 'hello') + ai.press('\r') + ai.press('y') + expect(ai.notice).toMatch(/not on screen yet/) + expect(fetchSpy).not.toHaveBeenCalled() + + frame(session) + ai.drawn() + ai.press('y') + await until(() => fetchSpy.mock.calls.length === 1 && session.state.terminal.lines.some(line => line.kind === 'end')) + + const [url, init] = fetchSpy.mock.calls[0] as [URL, { method: string; headers: Record; redirect: string }] + + expect(String(url)).toBe('https://openrouter.ai/api/v1/chat/completions') + expect(init.method).toBe('POST') + expect(init.redirect).toBe('manual') + expect(init.headers.authorization).toBe(`Bearer ${KEY}`) + expect(body(fetchSpy)).toMatchObject({ model: 'stub/model', messages: [{ role: 'user', content: 'hello' }] }) + + const text = frame(session) + + expect(text).toContain('hello from the stub') + expect(text).toContain('$0.004000') + expect(text).not.toContain(KEY) + expect(ai.spentUsd).toBeCloseTo(0.004, 6) + session.stop() + }) + + it('masks the key if the provider echoes it, and strips escape sequences from a reply', async () => { + const { session, ai } = open({ body: reply(`your key is ${KEY} ${ESC}]0;pwned\u0007 and ${ESC}[2J gone`) }) + + ai.press('\u0014') + type(ai, 'echo it') + ai.press('\r') + frame(session) + ai.drawn() + ai.press('y') + await until(() => session.state.terminal.lines.some(line => line.kind === 'end')) + + const text = frame(session) + + expect(text).not.toContain(KEY) + expect(text).not.toContain(']0;pwned') + expect(frame(session, 100, 30)).not.toContain(ESC) + session.stop() + }) + + it('stops at the spend cap using the provider-reported cost, and says why', async () => { + const { session, ai, fetchSpy } = open({ maxSpendUsd: 0.004 }) + + ai.press('\u0014') + type(ai, 'one') + ai.press('\r') + frame(session) + ai.drawn() + ai.press('y') + await until(() => session.state.terminal.lines.some(line => line.kind === 'end')) + type(ai, 'two') + ai.press('\r') + expect(ai.card).toBeNull() + expect(ai.notice).toMatch(/spend cap is reached \(reported \$0\.004000 of \$0\.004000\)/) + expect(fetchSpy).toHaveBeenCalledTimes(1) + session.stop() + }) + + it('refuses without a key, naming the variable and never a value', async () => { + delete process.env.OPENROUTER_API_KEY + + const { session, ai, fetchSpy } = open() + + ai.press('\u0014') + type(ai, 'hi') + ai.press('\r') + frame(session) + ai.drawn() + ai.press('y') + await until(() => session.state.terminal.lines.some(line => line.kind === 'err')) + expect(session.state.terminal.lines.map(line => line.text).join('\n')).toMatch(/\$OPENROUTER_API_KEY is not set/) + expect(fetchSpy).not.toHaveBeenCalled() + session.stop() + }) + + it('a card expires after 60 s with no answer and then runs nothing', () => { + vi.useFakeTimers({ toFake: ['Date'] }) + + const { session, ai, fetchSpy } = open() + + ai.press('\u0014') + type(ai, 'late') + ai.press('\r') + frame(session) + ai.drawn() + vi.setSystemTime(Date.now() + 61_000) + ai.press('y') + expect(ai.card).toBeNull() + expect(ai.notice).toMatch(/expired after 60 s/) + expect(fetchSpy).not.toHaveBeenCalled() + session.stop() + }) + + it('n and Esc cancel, a replaced card is the only one a y answers, and pasted text is never an answer', () => { + const { session, ai, fetchSpy } = open() + + ai.press('\u0014') + type(ai, 'first') + ai.press('\r') + ai.press('n') + expect(ai.card).toBeNull() + type(ai, 'second') + ai.press('\r') + expect(ai.card?.id).toBe(2) + ai.press(ESC) + expect(ai.card).toBeNull() + // A paste with a newline and a y in it is text, not an Enter and not an answer. + type(ai, 'pasted\ry') + expect(ai.draft).toBe('pastedy') + expect(ai.card).toBeNull() + expect(fetchSpy).not.toHaveBeenCalled() + session.stop() + }) + + it('refuses a message that looks like a credential before a card is made', () => { + const { session, ai } = open() + + ai.press('\u0014') + type(ai, `use this ${KEY} please`) + ai.press('\r') + expect(ai.card).toBeNull() + expect(ai.notice).not.toBeNull() + expect(frame(session)).not.toContain(KEY) + session.stop() + }) +}) + +describe('Codex', () => { + it.skipIf(isWin)('Ctrl-T picks Codex; the card shows a read-only argv; y runs the pinned fake with the prompt on stdin and streams its answer', async () => { + process.env.CODEX_HOME = codexHome + + const { session, ai } = open() + + expect(ai.target).toBe('codex') + type(ai, 'summarize this repo') + ai.press('\r') + + const card = flat(frame(session)) + + expect(card).toContain('Ask first, #1') + expect(card).toContain('codex exec --json --sandbox read-only --skip-git-repo-check -') + expect(card).toContain('prompt on stdin: "summarize this repo"') + expect(card).toContain('Codex 0.162.0, read-only') + expect(card).not.toMatch(/danger-full-access|--yolo|workspace-write/) + ai.drawn() + ai.press('y') + await until(() => session.state.terminal.lines.some(line => line.kind === 'end')) + + const ran = JSON.parse(readFileSync(join(codexHome, 'fake-codex.log'), 'utf8').trim().split('\n').pop() as string) as { args: string[]; input: string } + const text = frame(session) + + expect(ran.args).toEqual(['exec', '--json', '--sandbox', 'read-only', '--skip-git-repo-check', '-']) + expect(ran.input).toBe('summarize this repo') + expect(text).toContain('echo: summarize this repo') + expect(text).toContain('and a second line') + expect(text).not.toContain(']0;pwned') + expect(session.state.terminal.sessions.codex).toBe('019f0000-aaaa-bbbb-cccc-000000000001') + session.stop() + }) + + it('without the pinned release the answer says so and nothing falls back to PATH or current', async () => { + const session = openSession({ cwd: project, home: join(root, 'no-codex-here'), aiPage: { fetch: vi.fn() as never } }) + + session.show('ai') + + const ai = session.ai! + + type(ai, 'hi') + ai.press('\r') + frame(session) + ai.drawn() + ai.press('y') + await until(() => session.state.terminal.lines.some(line => line.kind === 'end')) + expect(session.state.terminal.lines.map(line => line.text).join('\n')).toMatch(/pinned Codex 0\.162\.0 is not installed/) + session.stop() + }) +}) + +describe('the page', () => { + it('Esc hands the keys back to the shell and i takes them again; Ctrl-C is never typed', () => { + const { session, ai } = open() + + expect(ai.press('7').consumed).toBe(true) + expect(ai.draft).toBe('7') + expect(ai.press(ESC).consumed).toBe(true) + expect(ai.mode).toBe('nav') + expect(ai.press('3').consumed).toBe(false) + expect(ai.press('i').consumed).toBe(true) + expect(ai.mode).toBe('type') + expect(ai.press('\u0003').consumed).toBe(false) + expect(ai.draft).toBe('7') + session.stop() + }) + + it('fits every width and height: no line wider than the terminal, no more rows than it has', () => { + const { session, ai } = open() + + ai.press('\u0014') + type(ai, 'a long question '.repeat(20)) + ai.press('\r') + + for (const [columns, rows] of [[40, 12], [60, 20], [80, 24], [120, 40]] as const) { + const lines = session.frame(columns, 'none', rows) + + expect(lines.length, `${columns}x${rows}`).toBeLessThanOrEqual(rows - 2) + for (const line of lines) expect(widthOf(line), line).toBeLessThanOrEqual(columns) + } + session.stop() + }) + + it('--plain prints the status and an empty conversation, and is off with no AI options', async () => { + const out: string[] = [] + const io = (): TuiIO => ({ stdin: { on: () => undefined, off: () => undefined, resume: () => undefined, pause: () => undefined }, stdout: { columns: 100, rows: 30, write: text => void out.push(text) }, stderr: { write: () => undefined }, env: {} }) + + expect(await runTui({ cwd: project, home: root, plain: true, view: 'ai', aiPage: { codexBin: FAKE } }, io())).toBe(0) + expect(out.join('')).toMatch(/codex .*ready|codex .*pinned/) + expect(out.join('')).toContain('openrouter') + expect(out.join('')).not.toContain(KEY) + out.length = 0 + expect(await runTui({ cwd: project, home: root, plain: true, view: 'ai' }, io())).toBe(0) + expect(out.join('')).toContain('The AI page is off') + }) +}) diff --git a/plugins/ruflo-console/tests/tui-host.spec.ts b/plugins/ruflo-console/tests/tui-host.spec.ts index 94a6643d2f..b63c0490f7 100644 --- a/plugins/ruflo-console/tests/tui-host.spec.ts +++ b/plugins/ruflo-console/tests/tui-host.spec.ts @@ -103,7 +103,8 @@ describe('the Claude Code engine is refused, not faked', () => { for (const refused of [host.fetchText('https://example.com'), host.askChoice('ok?', ['yes']), host.openPane({} as never), host.panes(), host.settings(), host.rufloSnapshot(), host.submitPrompt('hi'), host.runSlash('x', '')]) await expect(refused).rejects.toThrow(/not available in the standalone terminal/) expect(() => host.spawn(['ruflo'])).toThrow() expect(host.toolCall).toBeUndefined() - expect(host.httpSend).toBeUndefined() + // httpSend exists for the AI page but sends nothing unless the host was built with the AI options (host tests in tui-ai-host.spec.ts). + await expect(host.httpSend!('https://openrouter.ai/x', { method: 'POST', headers: {}, body: '{}' })).resolves.toMatchObject({ ok: false, status: 0 }) await expect(host.fillPrompt('x')).resolves.toBe(false) }) diff --git a/plugins/ruflo-console/tests/tui-nav.spec.ts b/plugins/ruflo-console/tests/tui-nav.spec.ts new file mode 100644 index 0000000000..a9e0245999 --- /dev/null +++ b/plugins/ruflo-console/tests/tui-nav.spec.ts @@ -0,0 +1,252 @@ +/** + * `ruflo tui` phase 2 (ADR-489): the six pages, the page bar and keys, resize and narrow terminals, and the chrome that must not + * be drawn on a host with no Claude session and no mouse. Real ruflo files on disk, an injected terminal, no engine. + * npx vitest run plugins/ruflo-console/tests/tui-nav.spec.ts + */ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { dirname, join } from 'node:path' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' + +import { widthOf } from '../tui/ansi' +import { keyLine, keyOf, MIN_COLUMNS, navLine, runTui, type TuiIO } from '../tui/run' +import { openSession, TUI_VIEWS } from '../tui/session' +import { RUFLO_FILES } from './fixtures/ruflo-run' + +const ESC = '\u001b' +let root: string +let project: string +let hostile: string + +const put = (base: string, files: Record) => { + for (const [path, body] of Object.entries(files)) { + mkdirSync(dirname(join(base, path)), { recursive: true }) + writeFileSync(join(base, path), body) + } +} + +beforeAll(() => { + root = mkdtempSync(join(tmpdir(), 'tui-nav-')) + project = join(root, 'project') + hostile = join(root, 'hostile') + put(project, RUFLO_FILES) + // A mission record whose objective and blocked reason carry an escape sequence and a token: the Missions page must show words only. + put(hostile, { + ...RUFLO_FILES, + '.claude-flow/missions/observation.json': JSON.stringify({ + schemaVersion: 1, + contract: 'ruflo.mission-observation/1', + observedAt: new Date().toISOString(), + missions: [{ missionId: 'msn_one', objective: `ship it ${ESC}]0;pwned\u0007 ghp_abcdefghijklmnopqrstuvwxyz0123456789`, state: 'blocked', blockedReason: `needs ${ESC}[31mred${ESC}[0m review`, revision: 2, plan: { revision: 1, taskCount: 1, tasks: [{ id: 't1', title: `do ${ESC}[2Jthings`, status: 'ready' }] }, evidence: { count: 1, verified: 0 } }], + }), + }) +}) +afterAll(() => rmSync(root, { recursive: true, force: true })) + +function terminal(columns = 100, rows = 30) { + const out: string[] = [] + const listeners: Array<(chunk: string) => void> = [] + const resizers: Array<() => void> = [] + const stdout = { isTTY: true, columns, rows, write: (text: string) => void out.push(text), on: (_e: 'resize', fn: () => void) => void resizers.push(fn), off: () => void resizers.splice(0) } + const io: TuiIO = { + stdin: { isTTY: true, setRawMode: () => undefined, on: (_e, fn) => void listeners.push(fn as never), off: () => void listeners.splice(0), resume: () => undefined, pause: () => undefined }, + stdout, + stderr: { write: () => undefined }, + env: { TERM: 'xterm-256color' }, + } + + return { io, out, stdout, press: (key: string) => listeners.forEach(fn => fn(key)), resize: (c: number, r = rows) => { stdout.columns = c; stdout.rows = r; resizers.forEach(fn => fn()) } } +} + +const settle = (ms = 200) => new Promise(resolve => setTimeout(resolve, ms)) +const plain = (screen: string) => screen.replace(/\u001b\[[0-9;?]*[A-Za-z]/g, '') +/** The lines of the last frame drawn (a frame starts at cursor-home), as plain text. */ +const lastFrame = (chunks: string[]) => plain((chunks.join('').split(`${ESC}[H`).pop() ?? '').replace(/\r/g, '')).split('\n') + +describe('keys', () => { + it('maps digits and letters to the pages, tab and arrows to neighbours, and ignores the rest', () => { + expect(TUI_VIEWS).toEqual(['overview', 'cost', 'swarm', 'events', 'missions', 'ai']) + expect(['1', '2', '3', '4', '5', '6'].map(keyOf)).toEqual(TUI_VIEWS.map(page => ({ page }))) + expect([keyOf('o'), keyOf('c'), keyOf('s'), keyOf('e'), keyOf('m'), keyOf('a')]).toEqual([{ page: 'overview' }, { page: 'cost' }, { page: 'swarm' }, { page: 'events' }, { page: 'missions' }, { page: 'ai' }]) + expect([keyOf('\t'), keyOf(`${ESC}[C`), keyOf('l')]).toEqual(['next', 'next', 'next']) + expect([keyOf(`${ESC}[Z`), keyOf(`${ESC}[D`), keyOf('h')]).toEqual(['prev', 'prev', 'prev']) + expect([keyOf('0'), keyOf('7'), keyOf('9'), keyOf('x'), keyOf(`${ESC}]0;t\u0007`)]).toEqual([null, null, null, null, null]) + }) + + it('has no key for Room: its content is a message box and Claude sessions this host does not have', () => { + expect(keyOf('R')).toBeNull() + expect(TUI_VIEWS as readonly string[]).not.toContain('room') + }) +}) + +describe('page bar and key line', () => { + it('lists the pages with the current one marked, and shortens to a position when narrow', () => { + expect(navLine('swarm', 100, 'none')).toBe(' 1 Overview 2 Cost [3 Swarm] 4 Events 5 Missions 6 AI ') + expect(navLine('swarm', 100, '256')).toContain(`${ESC}[7m 3 Swarm ${ESC}[0m`) + expect(navLine('swarm', 59, 'none')).toBe('‹ 3/6 Swarm ›') + expect(widthOf(navLine('missions', 60, '256'))).toBeLessThanOrEqual(60) + }) + + it('has a short key line for a narrow terminal and says read-only on a wide one', () => { + expect(keyLine(100)).toContain('read-only') + expect(keyLine(100)).toContain('q quit') + expect(keyLine(50)).toBe('1-6 page · j/k scroll · q quit') + expect(keyLine(25)).toBe('1-6 page · q quit') + for (const columns of [40, 50, 59, 60, 70, 80, 99, 120]) for (const place of ['', ' · 1-18/42']) expect(widthOf(keyLine(columns, place)), `${columns}${place}`).toBeLessThanOrEqual(columns) + }) +}) + +describe('every page, on a host with no Claude session and no mouse', () => { + for (const columns of [80, 120]) { + it(`draws all six pages at ${columns} columns, no wider than the terminal, with none of Claude Code's chrome`, async () => { + for (const view of TUI_VIEWS) { + const session = openSession({ cwd: project, home: join(root, 'home'), aiPage: {} }) + + try { + session.show(view) + await session.refresh() + + const lines = session.frame(columns, 'none') + const text = lines.join('\n') + + expect(lines.length, view).toBeGreaterThan(3) + for (const line of lines) expect(widthOf(line), `${view}: ${line}`).toBeLessThanOrEqual(columns) + // Claude Code's surface: Ask Claude, the Claude-control card, the footer and tab buttons, hotkey brackets. + expect(text, view).not.toMatch(/ask claude|✦|Claude control|Take back control/i) + expect(text, view).not.toMatch(/Palette|Actions\]|\bClose\b|\[\s*[0-9a-z]\s{2}/) + expect(text, view).not.toMatch(/\[[^\]\n]*[▸▶⇩⧉🔔★][^\]\n]*\]/) + } finally { + session.stop() + } + } + }) + } + + it('the Missions page reads the mission record only: no goal field, no plan, no research launch', async () => { + const session = openSession({ cwd: project, home: join(root, 'home') }) + + try { + session.show('missions') + await session.refresh() + + const text = session.frame(100, 'none').join('\n') + + expect(text).toContain('Mission record') + expect(text).not.toMatch(/goal:|Plan options|Start research|use the palette/i) + } finally { + session.stop() + } + }) + + it('hostile mission text: words only reach the screen (no escape, no token)', async () => { + const session = openSession({ cwd: hostile, home: join(root, 'home') }) + + try { + session.show('missions') + await session.refresh() + + const text = session.frame(120, '256').join('\n') + + expect(text).toContain('msn_one') + expect(text).not.toContain(']0;pwned') + expect(text).not.toContain('ghp_abcdefghijklmnopqrstuvwxyz0123456789') + expect(text.replace(/\u001b\[[0-9;]*m/g, '')).not.toContain(ESC) + } finally { + session.stop() + } + }) +}) + +describe('the terminal loop', () => { + it('jumps to a page on a digit, cycles with tab and shift-tab, and the page bar follows', async () => { + const t = terminal() + const running = runTui({ cwd: project, home: join(root, 'home') }, t.io) + + await settle() + t.press('3') + t.press('\t') + t.press(`${ESC}[Z`) + t.press('e') + t.press('5') + t.press('q') + await expect(running).resolves.toBe(0) + + const bars = plain(t.out.join('')).match(/1 Overview {1,3}2 Cost {1,3}3 Swarm {1,3}4 Events {1,3}5 Missions {1,3}6 AI/g) ?? [] + + expect(bars.length).toBeGreaterThanOrEqual(5) + expect(t.out.join('')).toContain(`${ESC}[7m 3 Swarm ${ESC}[0m`) + expect(t.out.join('')).toContain(`${ESC}[7m 4 Events ${ESC}[0m`) + expect(t.out.join('')).toContain(`${ESC}[7m 5 Missions ${ESC}[0m`) + }) + + it('fills the terminal exactly: the page bar on the first row, the key line on the last', async () => { + for (const rows of [24, 40]) { + const t = terminal(100, rows) + const running = runTui({ cwd: project, home: join(root, 'home') }, t.io) + + await settle() + t.press('4') + await settle(50) + t.press('q') + await running + + const frame = lastFrame(t.out) + + expect(frame, `${rows} rows`).toHaveLength(rows) + expect(frame[0]).toContain('4 Events') + expect(frame[rows - 1]).toMatch(/^1-6 or o c s e m a page/) + } + }) + + it('redraws at the new width on a resize, clearing the screen first', async () => { + const t = terminal(120, 30) + const running = runTui({ cwd: project, home: join(root, 'home') }, t.io) + + await settle() + + const before = t.out.length + + t.resize(70, 20) + await settle(50) + + const after = t.out.slice(before).join('') + + expect(after.startsWith(`${ESC}[2J`)).toBe(true) + for (const line of lastFrame(t.out)) expect(widthOf(line), line).toBeLessThanOrEqual(70) + t.press('q') + await running + }) + + it('under 60 columns it draws the position bar and the short key line; under 40 it says how wide it needs to be', async () => { + const narrow = terminal(52, 24) + const running = runTui({ cwd: project, home: join(root, 'home') }, narrow.io) + + await settle() + expect(plain(narrow.out.join(''))).toContain('‹ 1/6 Overview ›') + expect(plain(narrow.out.join(''))).toContain('1-6 page · j/k scroll · q quit') + for (const line of lastFrame(narrow.out)) expect(widthOf(line), line).toBeLessThanOrEqual(52) + + const before = narrow.out.length + + narrow.resize(MIN_COLUMNS - 1) + await settle(50) + expect(plain(narrow.out.slice(before).join(''))).toContain('Too narrow: need 40 columns') + narrow.press('q') + await expect(running).resolves.toBe(0) + }) + + it('--plain prints the page bar then the frame, with no escapes, for any page', async () => { + for (const view of TUI_VIEWS) { + const out: string[] = [] + const code = await runTui( + { cwd: project, home: join(root, 'home'), plain: true, view }, + { stdin: { on: () => undefined, off: () => undefined, resume: () => undefined, pause: () => undefined }, stdout: { columns: 90, rows: 30, write: text => void out.push(text) }, stderr: { write: () => undefined }, env: {} }, + ) + const text = out.join('') + + expect(code).toBe(0) + expect(text).not.toContain(ESC) + expect(text.split('\n')[0]).toContain(`[${{ overview: '1 Overview', cost: '2 Cost', swarm: '3 Swarm', events: '4 Events', missions: '5 Missions', ai: '6 AI' }[view]}]`) + } + }) +}) diff --git a/plugins/ruflo-console/tests/tui-render.spec.ts b/plugins/ruflo-console/tests/tui-render.spec.ts index c4477a55b5..5ba69ea4bb 100644 --- a/plugins/ruflo-console/tests/tui-render.spec.ts +++ b/plugins/ruflo-console/tests/tui-render.spec.ts @@ -88,8 +88,14 @@ describe('render', () => { expect(widthOf(render(text('🏠'.repeat(20), { wrap: 'truncate-end' }), 11, 'none')[0] as string)).toBeLessThanOrEqual(11) }) - it('draws a button as an inert bracketed label and skips hidden boxes', () => { - expect(render(kit.Button({ key: 'k', label: 'Refresh' } as never), 30, 'none')).toEqual(['[Refresh]']) + it('draws only a state chip from a button (a control nobody can press is not drawn), and skips hidden boxes', () => { + expect(render(kit.Button({ key: 'k', label: 'Refresh' } as never), 30, 'none')).toEqual([]) + expect(render(kit.Button({ key: 'k', label: ' ✦ ask Claude ' } as never), 30, 'none')).toEqual([]) + expect(render(kit.Button({ key: 'k', label: ' ● all 3 ', hotkey: 'a' } as never), 30, 'none')).toEqual(['● all 3 ']) + expect(render(kit.Button({ key: 'k', label: ' ○ bad 0 ' } as never), 30, 'none')).toEqual(['○ bad 0 ']) + // A section title stays, without the fold mark (nothing folds in a terminal). + expect(render(kit.Button({ key: 'sec-optimizer', label: '▾ Optimizer' } as never), 30, 'none')).toEqual(['Optimizer']) + expect(render(kit.Button({ key: 'sec-plan', label: '▸ Plan options' } as never), 30, 'none')).toEqual(['Plan options']) expect(render(box([text('gone')], { hidden: true }), 30, 'none')).toEqual([]) }) diff --git a/plugins/ruflo-console/tests/tui-session.spec.ts b/plugins/ruflo-console/tests/tui-session.spec.ts index 82f766426a..822d2ca16e 100644 --- a/plugins/ruflo-console/tests/tui-session.spec.ts +++ b/plugins/ruflo-console/tests/tui-session.spec.ts @@ -1,6 +1,6 @@ /** * `ruflo tui` end to end without a terminal (ADR-489): real ruflo files on disk, the mod's own controller and views over the Node - * host, drawn by the mod's own paneView, headless and with an injected terminal. Run with + * host, drawn by the mod's own page bodies in the standalone pane, headless and with an injected terminal. Run with * npx vitest run plugins/ruflo-console/tests/tui-session.spec.ts */ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' @@ -199,7 +199,7 @@ describe('interactive', () => { expect(screen.startsWith(`${ESC}[?1049h`)).toBe(true) expect(screen).toContain('Where it goes') - expect(screen).toContain('cost ·') + expect(screen).toContain('2 Cost') expect(screen.endsWith(`${ESC}[?25h${ESC}[?1049l`)).toBe(true) expect(raw).toEqual([true, false]) }) @@ -219,7 +219,7 @@ describe('interactive', () => { describe('keys and colour depth', () => { it('maps the documented keys and ignores the rest', () => { - expect([keyOf('q'), keyOf('\u0003'), keyOf('o'), keyOf('c'), keyOf('r'), keyOf('j'), keyOf(`${ESC}[A`), keyOf(' ')]).toEqual(['quit', 'quit', 'overview', 'cost', 'refresh', 'down', 'up', 'pagedown']) + expect([keyOf('q'), keyOf('\u0003'), keyOf('o'), keyOf('c'), keyOf('r'), keyOf('j'), keyOf(`${ESC}[A`), keyOf(' ')]).toEqual(['quit', 'quit', { page: 'overview' }, { page: 'cost' }, 'refresh', 'down', 'up', 'pagedown']) expect([keyOf('x'), keyOf(`${ESC}]0;t\u0007`), keyOf('')]).toEqual([null, null, null]) }) diff --git a/plugins/ruflo-console/tui/ai-guard.ts b/plugins/ruflo-console/tui/ai-guard.ts new file mode 100644 index 0000000000..d2327a41af --- /dev/null +++ b/plugins/ruflo-console/tui/ai-guard.ts @@ -0,0 +1,120 @@ +/** + * What the standalone terminal lets the AI page run and send (ADR-489 decision D). Pure: strings in, a verdict out, so a test + * pins every refusal. Two doors, both narrow on purpose: + * - Codex: one program (the PINNED release, never `current` and never PATH: 0.162.1 crashes with a #GP), `exec` only, an explicit + * read-only sandbox, and a fixed list of flags. Anything else (a profile, an extra config key, danger-full-access, --yolo, an + * added directory) is refused before a process starts. + * - HTTPS to a short list of hosts: openrouter.ai and the hosts a convoTargets entry names; POST only, no redirects, no headers but + * the two a chat request needs. + */ +export const PINNED_CODEX = '0.162.0' + +const SESSION = /^[0-9A-Za-z][0-9A-Za-z-]{7,63}$/ +const MODEL = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,80}$/ +const SANDBOX = /^sandbox_mode="(read-only|workspace-write)"$/ + +export type CodexVerdict = { ok: true; args: string[]; sandbox: 'read-only' | 'workspace-write' } | { ok: false; why: string } + +/** + * `codex exec [resume] [--json] [--skip-git-repo-check] [--ephemeral] [--sandbox|-s ] [-c sandbox_mode=""] [-m ] [] -`. + * `workspace-write` is accepted only when the person opted in for the session (`allowWrite`); danger-full-access never is. + */ +export function validateCodexArgv(argv: readonly string[], allowWrite = false): CodexVerdict { + if (argv[0] !== 'codex' || argv[1] !== 'exec') return { ok: false, why: 'only `codex exec` runs here' } + + const rest = argv.slice(2) + const args: string[] = ['exec'] + let sandbox: 'read-only' | 'workspace-write' | null = null + let isLast = false + let hasSession = false + + const mode = (value: string | undefined): 'read-only' | 'workspace-write' | null => (value === 'read-only' || (allowWrite && value === 'workspace-write') ? value : null) + + for (let i = 0; i < rest.length; i += 1) { + const token = rest[i] as string + + if (isLast) return { ok: false, why: 'nothing may follow the stdin marker' } + + if (token === 'resume' && i === 0) args.push(token) + else if (token === '--json' || token === '--skip-git-repo-check' || token === '--ephemeral') args.push(token) + else if (token === '--sandbox' || token === '-s') { + const value = mode(rest[i + 1]) + + if (value === null) return { ok: false, why: `sandbox "${String(rest[i + 1]).slice(0, 30)}" is not allowed: read-only only${allowWrite ? ' (or workspace-write, opted in)' : ''}` } + if (sandbox !== null && sandbox !== value) return { ok: false, why: 'two different sandbox modes' } + sandbox = value + args.push('--sandbox', value) + i += 1 + } else if (token === '-c') { + const found = SANDBOX.exec(rest[i + 1] ?? '') + const value = mode(found?.[1]) + + if (value === null) return { ok: false, why: `config "${String(rest[i + 1]).slice(0, 40)}" is not allowed: only a read-only sandbox_mode` } + if (sandbox !== null && sandbox !== value) return { ok: false, why: 'two different sandbox modes' } + sandbox = value + args.push('-c', `sandbox_mode="${value}"`) + i += 1 + } else if (token === '-m' || token === '--model') { + const value = rest[i + 1] ?? '' + + if (!MODEL.test(value)) return { ok: false, why: 'the model name is not a plain name' } + args.push(token, value) + i += 1 + } else if (token === '-') { + args.push('-') + isLast = true + } else if (rest[0] === 'resume' && !hasSession && SESSION.test(token)) { + hasSession = true + args.push(token) + } else return { ok: false, why: `"${token.slice(0, 40)}" is not a flag the terminal passes to codex` } + } + + if (sandbox === null) return { ok: false, why: 'no explicit sandbox: the terminal never relies on the default (a config file may widen it)' } + if (!isLast) return { ok: false, why: 'the prompt goes on stdin: the argument list must end with -' } + + return { ok: true, args, sandbox } +} + +export type HttpVerdict = { ok: true; url: URL } | { ok: false; why: string } +const HEADERS = new Set(['content-type', 'authorization']) +export const HTTP_BODY_MAX = 100_000 + +/** `https:///...`: https, no credentials in the URL, the default port, a host from the list exactly, POST, two headers, a bounded body. */ +export function validateHttp(url: string, init: { method: string; headers: Record; body: string }, allowedHosts: readonly string[]): HttpVerdict { + let parsed: URL + + try { + parsed = new URL(url) + } catch { + return { ok: false, why: 'not a URL' } + } + + if (parsed.protocol !== 'https:') return { ok: false, why: 'https only' } + if (parsed.username !== '' || parsed.password !== '') return { ok: false, why: 'no credentials in the URL' } + if (parsed.port !== '' && parsed.port !== '443') return { ok: false, why: 'the default https port only' } + if (!allowedHosts.includes(parsed.hostname.toLowerCase())) return { ok: false, why: `${parsed.hostname.slice(0, 60)} is not a host the terminal may send to (openrouter.ai and the hosts a convoTargets entry names)` } + if (init.method !== 'POST') return { ok: false, why: 'POST only' } + + for (const name of Object.keys(init.headers)) if (!HEADERS.has(name.toLowerCase())) return { ok: false, why: `header "${name.slice(0, 30)}" is not sent` } + + if (init.body.length > HTTP_BODY_MAX) return { ok: false, why: 'the request is too large' } + + return { ok: true, url: parsed } +} + +/** The hosts the AI page may send to: openrouter.ai and each https host a convoTargets entry names. Other schemes and addresses are left out. */ +export function allowedHostsOf(endpointUrls: readonly string[]): string[] { + const hosts = new Set(['openrouter.ai']) + + for (const raw of endpointUrls) { + try { + const url = new URL(raw) + + if (url.protocol === 'https:' && /^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/i.test(url.hostname) && !/^\d+(\.\d+){3}$/.test(url.hostname) && !/\.(internal|local)$/i.test(url.hostname)) hosts.add(url.hostname.toLowerCase()) + } catch { + // an unreadable entry adds nothing + } + } + + return [...hosts] +} diff --git a/plugins/ruflo-console/tui/ai-page.ts b/plugins/ruflo-console/tui/ai-page.ts new file mode 100644 index 0000000000..357dffad27 --- /dev/null +++ b/plugins/ruflo-console/tui/ai-page.ts @@ -0,0 +1,88 @@ +/** + * The AI page as terminal lines (ADR-489 phase 3): a status block, the conversation (the console's own `screenOf`, so Codex's streamed + * events look as they do in the Claude Code console), the question card when one is waiting, a notice, and the input line. Every string + * goes through `cleanText` (credential shapes masked) and then `render`, whose Text path is the one chokepoint for escapes and secrets. + * + * A card is only answerable if the person can see ALL of what would be sent: on a terminal too small for that, the page says so and the + * card stays unanswerable (`fits` false), so a `y` can never approve something that was cut off. + */ +import { cleanText } from '../hooks/data/wf-clean' +import type { State } from '../hooks/state' +import { screenOf } from '../hooks/views/terminal' +import type { Ai } from './ai' +import { CARD_TTL_MS, usd } from './ai' +import { PINNED_CODEX } from './ai-guard' +import { cells, clean, render, terminalKit, type Depth } from './ansi' +import type { AiStatus } from './session' + +const kit = terminalKit() +const t = (children: string, props: Record = {}) => kit.Text({ children: cleanText(clean(children)), ...props }) +/** Text the page built itself from a vetted request (the card): escapes out, but not run through the credential mask, which would hide the words "Bearer ‹from $KEY›" that tell the person where the key comes from. The user's own text in it was already refused if it looked like a credential. */ +const own = (children: string, props: Record = {}) => kit.Text({ children: clean(children), ...props }) +const boxed = (color: string, children: ReturnType[]) => kit.Box({ borderStyle: 'round', borderColor: color, paddingX: 1, flexDirection: 'column', children }) + +/** The tail of a line that fits `width` cells, with a leading ellipsis when it was cut (the end of a draft is where the cursor is). */ +function tail(line: string, width: number): string { + if (cells(line) <= width) return line + + let out = '' + + for (const ch of [...line].reverse()) { + if (cells(out + ch) > width - 1) break + out = ch + out + } + + return `…${out}` +} + +export type AiFrame = { lines: string[]; fits: boolean } + +export function aiFrame(state: State, ai: Ai | null, status: AiStatus, columns: number, depth: Depth, rows: number): AiFrame { + const draw = (nodes: unknown[]): string[] => render(nodes, columns, depth) + const one = (text: string, props: Record = {}): string[] => draw([t(tail(text, columns), props)]) + const head = one('💻 AI — ask Codex (read-only) or OpenRouter; every question asks first', { color: '#d78700', bold: true }) + + if (ai === null) return { lines: [...head, ...one(' The AI page is off in this run (started with --no-ai).', { dimColor: true })], fits: true } + + const max = Math.max(3, rows - 2) + const spent = `${usd(ai.spentUsd)} of ${usd(ai.capUsd)} reported` + const turns = state.terminal.turns.codex + const codex = `${ai.target === 'codex' ? '▸' : ' '} codex ${status.codex}${turns > 0 ? ` · ${turns} turn${turns === 1 ? '' : 's'}, no dollars reported` : ''}` + const router = `${ai.target === 'openrouter' ? '▸' : ' '} openrouter ${status.openrouter} · spend ${spent}` + // The status lines are ours (a variable's NAME, never its value), so they skip the credential mask, which reads "key: …" as a secret. + const full = draw([boxed('#8787ff', [own(codex, { bold: ai.target === 'codex' }), own(router, { bold: ai.target === 'openrouter' })])]) + const compact = draw([own(tail(codex, columns), { bold: ai.target === 'codex' }), own(tail(router, columns), { bold: ai.target === 'openrouter' })]) + const card = ai.card + const left = card === null ? 0 : Math.max(0, Math.ceil((CARD_TTL_MS - (Date.now() - card.atMs)) / 1000)) + const title = card === null ? '' : `Ask first, #${card.id}: this goes to ${card.target === 'codex' ? `Codex ${PINNED_CODEX}, read-only` : 'OpenRouter'}` + const keys = `y sends it · n cancels · it expires in ${left} s` + const cardFull = card === null ? [] : draw([boxed('#d7af00', [own(title, { bold: true, color: '#d7af00' }), own(card.shows), own(card.note, { dimColor: true }), own(keys, { bold: true })])]) + const cardCompact = card === null ? [] : draw([boxed('#d7af00', [own(title, { bold: true, color: '#d7af00' }), own(card.shows), own(keys, { bold: true })])]) + const cardMin = card === null ? [] : draw([own(title, { bold: true, color: '#d7af00' }), own(card.shows), own(keys, { bold: true })]) + const notice = ai.notice === null ? [] : one(` ${ai.notice}`, { color: '#d75f5f' }) + const input = one(`${ai.target === 'codex' ? 'codex' : 'openrouter'} › ${ai.draft}${ai.mode === 'type' && card === null ? '█' : ''}`, { bold: true }) + // The roomiest layout that fits; a card is never trimmed, only its decoration (the note, the border, the status box) goes first. + const choices: { top: string[]; status: string[]; card: string[] }[] = [ + { top: head, status: full, card: cardFull }, + { top: head, status: full, card: cardCompact }, + { top: head, status: compact, card: cardCompact }, + { top: head, status: compact, card: cardMin }, + { top: [], status: compact, card: cardMin }, + { top: [], status: [], card: cardMin }, + ] + const need = (choice: (typeof choices)[number]) => choice.top.length + choice.status.length + choice.card.length + notice.length + input.length + const pick = choices.find(choice => need(choice) + (card === null ? 3 : 0) <= max) + + // Not even the question and its keys fit: say so, and the card cannot be answered (`fits` false) until the terminal is taller or wider. + if (card !== null && pick === undefined) return { lines: [...one(' Enlarge the terminal: the whole question has to be on screen before it can be answered (n cancels).', { color: '#d75f5f' }), ...input].slice(-max), fits: false } + + const use = pick ?? { top: head, status: compact, card: [] as string[] } + const room = Math.max(0, max - need(use)) + const conversation = screenOf(state.terminal.lines, Math.max(20, columns - 6)).flatMap(row => draw([kit.Box({ flexDirection: 'row', children: [t(row.gutter, { color: row.gutterColor }), t(row.text, row.style)] })])) + const end = Math.max(0, conversation.length - state.terminal.scroll) + const shown = room === 0 ? [] : conversation.slice(Math.max(0, end - room), end) + const empty = conversation.length === 0 && room > 0 ? one(' Nothing yet. Type a question and press Enter: the card shows what would be sent before anything is.', { dimColor: true }).slice(0, room) : [] + const body = shown.length > 0 ? shown : empty + + return { lines: [...use.top, ...use.status, ...body, ...Array.from({ length: Math.max(0, room - body.length) }, () => ''), ...use.card, ...notice, ...input].slice(-max), fits: true } +} diff --git a/plugins/ruflo-console/tui/ai.ts b/plugins/ruflo-console/tui/ai.ts new file mode 100644 index 0000000000..fd34563c24 --- /dev/null +++ b/plugins/ruflo-console/tui/ai.ts @@ -0,0 +1,269 @@ +/** + * The AI page of the standalone terminal (ADR-489 phase 3, decision D): ask Codex (read-only, the pinned release) or OpenRouter + * (https, an allow-listed host) from the terminal. It reuses the console's own parts, not a second harness: `harness.send` runs + * Codex and streams its events into the same scrollback the console draws, and `sendTo` (the conversation bridge, ADR-465) builds + * and sends the OpenRouter request and reads back the cost the provider itself billed. + * + * Nothing is sent without a card: Enter shows exactly what would leave this machine, and only a `y` while that card is on screen + * runs it (#3983: the answer is bound to the card the person was shown, and a card that was never drawn, was replaced, or has + * expired answers nothing). A reply's cost is the provider's own figure, never one worked out here; the spend cap stops the next + * send once the reported total reaches it. Codex reports no dollars, so its turns are counted and its cost reads n/a. + */ +import { argvOf, send as sendToCodex, whyNotRun } from '../hooks/harness' +import { parseConfig, targetsOf, type Config, type Endpoint, endpointsOf } from '../hooks/data/wf-targets' +import { payloadOf, sendTo, type SendDeps } from '../hooks/data/wf-send' +import type { Host } from '../hooks/host' +import type { State, TermLine } from '../hooks/state' +import { allowedHostsOf, PINNED_CODEX } from './ai-guard' +import { cleanText } from '../hooks/data/wf-clean' +import { clean } from './ansi' + +export type AiTarget = 'codex' | 'openrouter' +export type AiCard = { id: number; target: AiTarget; text: string; shows: string; note: string; atMs: number } +export type AiMode = 'type' | 'nav' +export type AiOptions = { + /** `endpoint:=||;...` exactly as the console's convoTargets option. */ + convoTargets?: string + /** The OpenRouter model for this session (a plain model name); default is the console's `openrouter/auto`. */ + model?: string + /** Stop sending once the provider-reported spend reaches this many USD (default 0.5). */ + maxSpendUsd?: number + allowWrite?: boolean +} + +export type Ai = { + readonly mode: AiMode + readonly draft: string + readonly target: AiTarget + readonly card: AiCard | null + readonly spentUsd: number + readonly capUsd: number + readonly notice: string | null + readonly config: Config + /** The hosts the host may send to and the key variables it may read: what the Node host is built with. */ + readonly allowedHosts: string[] + readonly keyEnvs: string[] + /** One keypress on the AI page. `consumed` false means the shell may treat it as a page key (quit, a page number, tab). */ + press: (chunk: string) => { consumed: boolean } + /** The shell opened this page: typing is on again (a person who left with Esc comes back to a field that takes keys). */ + enter: () => void + /** Called by the shell after a frame that showed the card was written: only then may `y` answer it. */ + drawn: () => void + stop: () => void + isBusy: () => boolean +} + +export const CARD_TTL_MS = 60_000 +/** Dollars as the provider reported them: a cheap turn costs a few millionths, so under a cent the figure keeps six places and is never rounded to $0. */ +export const usd = (value: number): string => `$${value >= 0.01 ? value.toFixed(4) : value.toFixed(6)}` +const DRAFT_MAX = 4_000 +const ESC = '\u001b' +const MODEL = /^[A-Za-z0-9][A-Za-z0-9._:/@+-]{0,80}$/ + +const lineAdd = (state: State, kind: TermLine['kind'], text: string, from: TermLine['from']): void => { + state.terminal.lines.push({ kind, text: cleanText(clean(text)).slice(0, 2_000), ...(from !== undefined && { from }) }) + if (state.terminal.lines.length > 600) state.terminal.lines.splice(0, state.terminal.lines.length - 600) +} + +/** The config the page sends with: the console's convoTargets, with this session's model put on the OpenRouter entry. */ +export function aiConfigOf(options: AiOptions): { config: Config; errors: string[] } { + const model = options.model !== undefined && MODEL.test(options.model) ? options.model : undefined + const base = parseConfig(options.convoTargets ?? '') + const config = model === undefined ? base : parseConfig(`endpoint:openrouter=https://openrouter.ai/api/v1|OPENROUTER_API_KEY|${model};${options.convoTargets ?? ''}`) + + return { config, errors: [...config.errors, ...(options.model !== undefined && model === undefined ? ['the model name is not a plain name: openrouter/auto is used'] : [])] } +} + +export function openAi(state: State, host: Host, options: AiOptions = {}): Ai { + const { config, errors } = aiConfigOf(options) + const endpoints: Endpoint[] = endpointsOf(config) + const openrouter = endpoints.find(endpoint => endpoint.name === 'openrouter') as Endpoint + const targets = targetsOf({ agents: [], peers: [], config, hasHive: false, hasCodex: true }) + const http = targets.find(target => target.id === 'openrouter') + const capUsd = options.maxSpendUsd !== undefined && Number.isFinite(options.maxSpendUsd) && options.maxSpendUsd >= 0 ? options.maxSpendUsd : 0.5 + const deps = (): SendDeps => ({ run: host.run, httpSend: host.httpSend, submitPrompt: host.submitPrompt, cli: [], helper: '', trustedPeers: new Set(), cwd: state.cwd, hive: null, config } as unknown as SendDeps) + let mode: AiMode = 'type' + let draft = '' + let target: AiTarget = 'codex' + let card: AiCard | null = null + let shown: number | null = null + let counter = 0 + let spentUsd = 0 + let notice: string | null = errors[0] ?? null + let isSending = false + + const note = (text: string | null) => void (notice = text) + const busy = () => isSending || state.terminal.runs.size > 0 + + /** What leaves this machine, said before it goes (the card), or why this cannot be sent. */ + function cardFor(text: string): { ok: true; card: AiCard } | { ok: false; why: string } { + const id = (counter += 1) + + if (target === 'codex') { + state.terminal.harness = 'codex' + + const why = whyNotRun(state, text) + + if (why !== null) return { ok: false, why } + + const argv = argvOf(state, 'codex', text.trim()) ?? [] + + return { ok: true, card: { id, target, text: text.trim(), shows: `${argv.join(' ')} (prompt on stdin: ${JSON.stringify(text.trim())})`, note: `Read-only sandbox, the pinned Codex ${PINNED_CODEX} (never current or PATH). The prompt goes to OpenAI through the codex CLI. Codex does not report dollars: its turns are counted, its cost reads n/a.`, atMs: Date.now() } } + } + + if (http === undefined) return { ok: false, why: 'no openrouter target' } + if (spentUsd >= capUsd) return { ok: false, why: `the spend cap is reached (reported ${usd(spentUsd)} of ${usd(capUsd)}): restart with a higher --max-spend-usd` } + + const made = payloadOf(http, text, deps()) + + return made.ok ? { ok: true, card: { id, target, text: made.body, shows: made.payload.shows, note: made.payload.note, atMs: Date.now() } } : { ok: false, why: made.why } + } + + async function run(chosen: AiCard): Promise { + if (chosen.target === 'codex') { + state.terminal.harness = 'codex' + sendToCodex(state, host, chosen.text) + + return + } + + isSending = true + lineAdd(state, 'in', chosen.text, 'ruflo') + lineAdd(state, 'head', 'openrouter', 'ruflo') + + const started = Date.now() + + try { + const result = await sendTo(deps(), http as NonNullable, chosen.text) + + for (const line of result.text.split('\n')) lineAdd(state, result.ok ? 'out' : 'err', line, 'ruflo') + + if (result.costUsd !== undefined) { + spentUsd += result.costUsd + state.terminal.costUsd += result.costUsd + state.terminal.costReports += 1 + } + + const secs = Math.round((Date.now() - started) / 1000) + const tokens = (result.tokensIn ?? 0) + (result.tokensOut ?? 0) + + lineAdd(state, 'end', result.ok ? `✓ ${secs} s${result.costUsd !== undefined ? ` · ${usd(result.costUsd)}` : ' · cost not reported'}${tokens > 0 ? ` · ${tokens.toLocaleString('en-US')} tokens` : ''}${result.model !== undefined ? ` · ${clean(result.model)}` : ''}` : '✗ not sent or failed', 'ruflo') + } finally { + isSending = false + host.invalidate() + } + } + + function confirm(): void { + const chosen = card + + if (chosen === null) return + + // Only the card that was drawn, still current and not stale: a card made and answered before a frame showed it answers nothing. + if (shown !== chosen.id) return note('that question was not on screen yet: look at it, then answer') + if (Date.now() - chosen.atMs > CARD_TTL_MS) { + card = null + + return note(`that question expired after ${CARD_TTL_MS / 1000} s with no answer, so it did not run: ask again`) + } + if (busy()) return note('an answer is still coming: wait, or stop it (Ctrl-S)') + + card = null + shown = null + note(null) + void run(chosen) + } + + function submit(): void { + if (draft.trim() === '') return note('type something first') + if (busy()) return note('an answer is still coming: wait, or stop it (Ctrl-S)') + + const made = cardFor(draft) + + if (!made.ok) { + // A message that looks like a credential is dropped, not kept in the field: it is neither shown again nor held. + if (cleanText(draft) !== draft) draft = '' + + return note(made.why) + } + + card = made.card + shown = null + draft = '' + note(null) + } + + const scroll = (by: number) => void (state.terminal.scroll = Math.max(0, state.terminal.scroll + by)) + + return { + get mode() { + return mode + }, + get draft() { + return draft + }, + get target() { + return target + }, + get card() { + return card + }, + get spentUsd() { + return spentUsd + }, + capUsd, + get notice() { + return notice + }, + config, + allowedHosts: allowedHostsOf(endpoints.map(endpoint => endpoint.baseUrl)), + keyEnvs: [...new Set(endpoints.map(endpoint => endpoint.keyEnv).filter(name => name !== 'NONE'))], + enter: () => void (mode = 'type'), + drawn: () => void (shown = card === null ? null : card.id), + isBusy: busy, + stop, + press: chunk => { + // A question is on screen: only a lone y (or Enter) answers it, a lone n (or Esc) drops it. Pasted text is never an answer. + if (card !== null) { + if (chunk === 'y' || chunk === 'Y' || chunk === '\r') confirm() + else if (chunk === 'n' || chunk === 'N' || chunk === ESC) (card = null), (shown = null), note('cancelled: nothing was sent') + else if (chunk === '\u0003' || chunk === '\u0004') return { consumed: false } + + return { consumed: true } + } + + if (mode === 'nav') { + if (chunk === 'i' || chunk === '\r') { + mode = 'type' + + return { consumed: true } + } + + return { consumed: false } + } + + if (chunk === '\u0003' || chunk === '\u0004') return { consumed: false } + if (chunk === ESC) return void (mode = 'nav'), { consumed: true } + if (chunk === '\r') return submit(), { consumed: true } + if (chunk === '\u007f' || chunk === '\b') return void (draft = [...draft].slice(0, -1).join('')), { consumed: true } + if (chunk === '\u0015') return void (draft = ''), { consumed: true } + if (chunk === '\u0014') return void ((target = target === 'codex' ? 'openrouter' : 'codex'), note(null)), { consumed: true } + if (chunk === '\u0013') return stop(), { consumed: true } + if (chunk === `${ESC}[5~`) return scroll(10), { consumed: true } + if (chunk === `${ESC}[6~`) return scroll(-10), { consumed: true } + if (chunk.startsWith(ESC)) return { consumed: true } + + // Typed or pasted text: printable characters only, never a newline (a paste with one does not submit), capped. + const text = chunk.replace(/[\u0000-\u001f\u007f-\u009f]/g, '') + + if (text !== '') draft = (draft + text).slice(0, DRAFT_MAX) + + return { consumed: true } + }, + } + + function stop(): void { + for (const running of state.terminal.runs.values()) running.stop() + note(state.terminal.runs.size > 0 ? 'stopping…' : 'nothing is running') + } +} diff --git a/plugins/ruflo-console/tui/ansi.ts b/plugins/ruflo-console/tui/ansi.ts index 190c1595c2..285d657f4d 100644 --- a/plugins/ruflo-console/tui/ansi.ts +++ b/plugins/ruflo-console/tui/ansi.ts @@ -176,10 +176,18 @@ export function render(node: unknown, width: number, depth: Depth): string[] { return lines.map(line => (open === '' ? line : `${open}${line}${RESET}`)) } + // A Button is a mouse or hotkey control of the Claude Code host, and this terminal has neither: a control that would act is not drawn + // (a bracketed "button" nobody can press is a lie), and one that starts a Claude turn (✦) never is. What stays is information: + // a section title (key `sec-…`, without its fold mark since nothing folds here), and a chip that shows a state, such as `● all 0` + // against `○ bad 0`, with a gap after it so neighbours do not run together. if (type === 'Button') { - const label = clean(props.label) + const label = clean(props.label).trim() - return [cut(`${sgr({ dimColor: true }, depth)}[${props.hotkey === undefined ? '' : `${clean(props.hotkey)} `}${label}]${depth === 'none' ? '' : RESET}`, width)] + if (label.includes('✦')) return [] + + if (typeof props.key === 'string' && props.key.startsWith('sec-')) return [cut(`${sgr({ bold: true }, depth)}${label.replace(/^[▾▸]\s*/, '')}${depth === 'none' ? '' : RESET}`, width)] + + return /^[●○]/.test(label) ? [cut(`${sgr({ dimColor: true }, depth)}${label} ${depth === 'none' ? '' : RESET}`, width)] : [] } if (type !== 'Box') return [] diff --git a/plugins/ruflo-console/tui/node-host.ts b/plugins/ruflo-console/tui/node-host.ts index 5c1ced76a3..2330cb3965 100644 --- a/plugins/ruflo-console/tui/node-host.ts +++ b/plugins/ruflo-console/tui/node-host.ts @@ -8,13 +8,28 @@ * box, tool calls, network, a spawned process, a dialog) is refused, which the Host contract already allows: a refusal is a * missing fact, never a crash. A write phase must port the confirm gate (#3983) before it lifts any of these. */ -import { execFile } from 'node:child_process' +import { execFile, spawn as spawnProcess } from 'node:child_process' import { readdir, readFile, realpath, stat } from 'node:fs/promises' import { homedir } from 'node:os' import { dirname, isAbsolute, join, resolve, sep } from 'node:path' -import type { ProcessRunResult, Timer } from 'claude-code' +import type { ProcessRunResult, ProcessSpawnChunk, ProcessSpawnResult, Timer } from 'claude-code' import type { Host } from '../hooks/host' +import { PINNED_CODEX, validateCodexArgv, validateHttp } from './ai-guard' + +/** What the AI page may reach (ADR-489 decision D). Absent: the host refuses every spawn, send and key read, as in phase 2. */ +export type AiOptions = { + /** The pinned Codex program, when it is not under `~/.codex/packages/standalone/releases/-/bin/codex` (a test passes a fake). Its `--version` must still say the pinned version. */ + codexBin?: string + /** Hosts an HTTPS request may go to (see allowedHostsOf). */ + allowedHosts?: readonly string[] + /** Environment variable NAMES whose value may be read as a model key (the OpenRouter default and each convoTargets entry's keyEnv). The value goes to one request header and nowhere else. */ + keyEnvs?: readonly string[] + /** The person opted in, for this session, to Codex writing in the workspace. */ + allowWrite?: boolean + /** A fetch for a test; the real one is Node's. */ + fetch?: typeof fetch +} export type NodeHostOptions = { cwd: string @@ -26,11 +41,20 @@ export type NodeHostOptions = { cliEntry?: string /** Where the console's own files are (its catalog); informational in this host. */ pluginRoot?: string + ai?: AiOptions + /** Something changed that the screen should show (a stream wrote, a request answered). */ + onInvalidate?: () => void } const MAX_OUT = 1_000_000 /** Variables a child may see: enough to run node and find the project, none of the API keys in the parent's environment. */ const CHILD_ENV = /^(PATH|HOME|USERPROFILE|SystemRoot|TMPDIR|TEMP|TMP|LANG|LC_[A-Z]+|TERM|NO_COLOR|CLAUDE_CONFIG_DIR|CLAUDE_FLOW_[A-Z_]+|RUFLO_[A-Z_]+)$/ +/** What the Codex child may also see: where its own login lives. No API key of ours reaches it. */ +const CODEX_ENV = /^CODEX_HOME$/ +const HTTP_WAIT_MS = 120_000 +const HTTP_BODY_CAP = 1_000_000 +/** What the pinned program's --version must print, exactly. */ +const VERSION_SAYS = 'codex-cli ' + PINNED_CODEX const refuse = (what: string): Promise => Promise.reject(new Error(`${what}: not available in the standalone terminal`)) @@ -51,6 +75,75 @@ export function cliArgv(argv: readonly string[], entry: string | undefined): str return head === undefined ? null : [process.execPath, entry, ...argv.slice(head.length)] } +const childEnv = (...extra: RegExp[]): NodeJS.ProcessEnv => Object.fromEntries(Object.entries(process.env).filter(([key]) => CHILD_ENV.test(key) || extra.some(pattern => pattern.test(key)))) + +/** The pinned Codex program, or the reason there is none. Never `current`, never PATH: its `--version` must say exactly the pinned version. */ +export async function resolveCodex(home: string, explicit?: string): Promise<{ ok: true; bin: string } | { ok: false; why: string }> { + const candidates: string[] = [] + + if (explicit !== undefined) candidates.push(explicit) + else { + const releases = join(home, '.codex', 'packages', 'standalone', 'releases') + const names = await readdir(releases).catch(() => [] as string[]) + + for (const name of names) if (name.startsWith(PINNED_CODEX + '-') && /^[0-9.]+-[A-Za-z0-9_-]+$/.test(name)) candidates.push(join(releases, name, 'bin', 'codex')) + } + + for (const bin of candidates) { + const said = await new Promise(done => execFile(bin, ['--version'], { timeout: 5_000, windowsHide: true, env: childEnv(CODEX_ENV) }, (error, stdout) => done(error === null ? String(stdout) : ''))) + + if (said.trim() === VERSION_SAYS) return { ok: true, bin } + } + + return { ok: false, why: 'the pinned Codex ' + PINNED_CODEX + ' is not installed under ~/.codex/packages/standalone/releases (the terminal never uses current or PATH: 0.162.1 crashes)' } +} + +type Streamed = AsyncGenerator & { readonly result: Promise } + +/** A child's output as the Host's stream: chunks of stdout and stderr in order, then its exit as the result. */ +function streamOf(child: ReturnType): Streamed { + const queue: ProcessSpawnChunk[] = [] + let wake: (() => void) | null = null + let isDone = false + let exit: ProcessSpawnResult = { code: null, signal: null } + let settle: (value: ProcessSpawnResult) => void = () => undefined + const result = new Promise(resolve => void (settle = resolve)) + const push = (stream: 'stdout' | 'stderr') => (data: Buffer) => { + const text = data.toString('utf8') + + if (text !== '') queue.push({ stream, text }) + wake?.() + } + const finish = (value: ProcessSpawnResult) => { + exit = value + isDone = true + settle(value) + wake?.() + } + + child.stdout?.on('data', push('stdout')) + child.stderr?.on('data', push('stderr')) + child.once('error', error => { + queue.push({ stream: 'stderr', text: error.message + '\n' }) + finish({ code: 1, signal: null }) + }) + child.once('close', (code, signal) => finish({ code, signal })) + + const generator = (async function* () { + for (;;) { + const next = queue.shift() + + if (next !== undefined) yield next + else if (isDone) return exit + else await new Promise(resolve => void (wake = resolve)) + } + })() as Streamed + + Object.defineProperty(generator, 'result', { value: result }) + + return generator +} + export function createNodeHost(options: NodeHostOptions): Host { const cwd = resolve(options.cwd) const home = options.home ?? homedir() @@ -138,7 +231,7 @@ export function createNodeHost(options: NodeHostOptions): Host { fetchText: () => refuse('network'), askChoice: () => refuse('a dialog'), toast: () => undefined, - invalidate: () => undefined, + invalidate: () => options.onInvalidate?.(), scrollTop: () => undefined, focus: () => refuse('focus'), blit: () => undefined, @@ -147,6 +240,13 @@ export function createNodeHost(options: NodeHostOptions): Host { panes: () => refuse('panes'), registerCommand: () => refuse('slash commands'), run: (argv, timeoutMs, stdin) => { + // A model key is read by NAME from this process's environment, and only a name the AI page was configured with. + if (argv[0] === 'printenv' && argv.length === 2 && options.ai?.keyEnvs?.includes(argv[1] as string) === true) { + const value = process.env[argv[1] as string] + + return Promise.resolve({ exitCode: value === undefined || value === '' ? 1 : 0, stdout: value === undefined ? '' : value + '\n', stderr: '', isStdoutTruncated: false, isStderrTruncated: false }) + } + const command = cliArgv(argv, options.cliEntry) if (command === null) return refuse('running a program other than the ruflo CLI') @@ -162,8 +262,66 @@ export function createNodeHost(options: NodeHostOptions): Host { child.stdin?.end(stdin ?? '') }) }, - spawn: () => { - throw new Error('spawning a process: not available in the standalone terminal') + spawn: (argv, input) => { + const ai = options.ai + const verdict = ai === undefined ? ({ ok: false, why: 'the AI page is not enabled' } as const) : validateCodexArgv(argv, ai.allowWrite === true) + + if (!verdict.ok) throw new Error('spawning ' + String(argv[0]).slice(0, 30) + ': ' + verdict.why) + + // Nothing starts until the first read, so the pinned program is resolved (and refused, if absent) in the stream's own turn, as a failed start. + let child: ReturnType | null = null + let isStopped = false + let inner: Streamed | null = null + const started = (async () => { + const found = await resolveCodex(home, ai?.codexBin) + + if (!found.ok) throw new Error(found.why) + if (isStopped) throw new Error('stopped before it started') + + child = spawnProcess(found.bin, verdict.args, { cwd, env: childEnv(CODEX_ENV), windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] }) + child.stdin?.on('error', () => undefined) + child.stdin?.end(input ?? '') + inner = streamOf(child) + + return inner + })() + + started.catch(() => undefined) + + const outer = (async function* () { + const stream = await started + + return yield* stream + })() as Streamed + const close = outer.return.bind(outer) + + Object.defineProperty(outer, 'result', { value: started.then(stream => stream.result) }) + ;(outer.result as Promise).catch(() => undefined) + outer.return = async value => { + isStopped = true + ;(child as ReturnType | null)?.kill('SIGTERM') + + return close(value) + } + + return outer + }, + httpSend: async (url, init) => { + const ai = options.ai + const verdict = ai === undefined ? ({ ok: false, why: 'the AI page is not enabled' } as const) : validateHttp(url, init, ai.allowedHosts ?? ['openrouter.ai']) + + if (!verdict.ok) return { ok: false, status: 0, text: verdict.why } + + try { + const response = await (ai?.fetch ?? fetch)(verdict.url, { method: 'POST', headers: init.headers, body: init.body, redirect: 'manual', signal: AbortSignal.timeout(HTTP_WAIT_MS) }) + + // A redirect is never followed (it could carry the key to another host): it is an error. + if (response.status >= 300 && response.status < 400) return { ok: false, status: response.status, text: 'the server redirected: the terminal does not follow redirects' } + + return { ok: response.ok, status: response.status, text: (await response.text()).slice(0, HTTP_BODY_CAP) } + } catch (error) { + return { ok: false, status: 0, text: error instanceof Error ? error.message.slice(0, 160) : 'the request failed' } + } }, usage: async () => ({}), rufloTools: async () => ({ tools: 0, servers: [] }), diff --git a/plugins/ruflo-console/tui/run.ts b/plugins/ruflo-console/tui/run.ts index bd26c0153a..7afa45cea0 100644 --- a/plugins/ruflo-console/tui/run.ts +++ b/plugins/ruflo-console/tui/run.ts @@ -4,7 +4,8 @@ * a test drives it without a terminal. */ import type { Depth } from './ansi' -import { openSession, TUI_VIEWS, type Session, type TuiView } from './session' +import { cells, clean, widthOf } from './ansi' +import { openSession, TUI_VIEWS, type Session, type SessionOptions, type TuiView } from './session' export type TuiInput = { isTTY?: boolean @@ -23,7 +24,7 @@ export type TuiOutput = { off?: (event: 'resize', fn: () => void) => unknown } export type TuiIO = { stdin: TuiInput; stdout: TuiOutput; stderr: { write: (text: string) => unknown }; env: Record; signal?: AbortSignal } -export type TuiOptions = { cwd: string; view?: TuiView; plain?: boolean; cliEntry?: string; configDir?: string; home?: string; pluginRoot?: string; refreshMs?: number } +export type TuiOptions = { cwd: string; view?: TuiView; plain?: boolean; cliEntry?: string; configDir?: string; home?: string; pluginRoot?: string; refreshMs?: number; /** The AI page's settings; absent: the page is off. */ aiPage?: SessionOptions['aiPage'] } export const isTuiView = (value: unknown): value is TuiView => typeof value === 'string' && (TUI_VIEWS as readonly string[]).includes(value) @@ -35,11 +36,43 @@ export function depthOf(env: Record): Depth { return env.COLORTERM === 'truecolor' || env.COLORTERM === '24bit' ? 'truecolor' : '256' } -const KEYS = 'o overview · c cost · r refresh · j/k scroll · q quit' const ESC = '\u001b' +/** Below this the frame is a short message, not a squeezed page. The page bar and the key line shorten to what fits. */ +export const MIN_COLUMNS = 40 + +const LABELS: Record = { overview: 'Overview', cost: 'Cost', swarm: 'Swarm', events: 'Events', missions: 'Missions', ai: 'AI' } +const LETTER: Partial> = { o: 'overview', c: 'cost', s: 'swarm', e: 'events', m: 'missions', a: 'ai' } + +/** The page bar: every page with its number (the current one in reverse), or `‹ 3/6 Swarm ›` when the terminal is too narrow for all of them. Page names are ours, never from a file. */ +export function navLine(view: TuiView, columns: number, depth: Depth): string { + const wide = TUI_VIEWS.map((page, i) => { + const text = ` ${i + 1} ${LABELS[page]} ` + + return page === view && depth !== 'none' ? `${ESC}[7m${text}${ESC}[0m` : page === view ? `[${text.trim()}]` : text + }).join(' ') + + return widthOf(wide) <= columns ? wide : `‹ ${TUI_VIEWS.indexOf(view) + 1}/${TUI_VIEWS.length} ${LABELS[view]} ›` +} + +/** The key line under the page: every key when there is room, fewer keys as the terminal narrows, always inside `columns` (the scroll position, when there is one, is counted in). `own` replaces the page keys (the AI page has its own). */ +export function keyLine(columns: number, place = '', own?: readonly string[]): string { + const pages = `1-${TUI_VIEWS.length}` + const tiers = own ?? [`${pages} or o c s e m a page · tab next · r refresh · j/k scroll · q quit · read-only`, `${pages} page · tab next · r refresh · j/k scroll · q quit`, `${pages} page · j/k scroll · q quit`, `${pages} page · q quit`] + const fits = tiers.find(line => cells(line + place) <= columns) ?? tiers[tiers.length - 1] as string + + return `${fits}${place}`.slice(0, columns) +} + +/** The AI page's key line: what a typed key does now (typing, a card waiting, or after Esc). */ +export function aiKeyTiers(mode: 'type' | 'nav', hasCard: boolean): string[] { + if (hasCard) return ['y send it · n cancel · Ctrl-C quit', 'y send · n cancel'] + if (mode === 'nav') return ['1-6 page · tab next · i or Enter back to typing · q quit', '1-6 page · i type · q quit'] + + return ['type · Enter ask · Ctrl-T codex/openrouter · Ctrl-S stop · PgUp/PgDn scroll · Esc keys · Ctrl-C quit', 'Enter ask · Ctrl-T target · Ctrl-S stop · Esc keys', 'Enter ask · Esc keys'] +} /** One keypress as an action, from the bytes a terminal sends. Anything else is ignored. */ -export type Key = 'quit' | 'overview' | 'cost' | 'next' | 'refresh' | 'down' | 'up' | 'pagedown' | 'pageup' | 'top' | 'bottom' | null +export type Key = 'quit' | { page: TuiView } | 'next' | 'prev' | 'refresh' | 'down' | 'up' | 'pagedown' | 'pageup' | 'top' | 'bottom' | null export function keyOf(chunk: string): Key { switch (chunk) { @@ -47,12 +80,14 @@ export function keyOf(chunk: string): Key { case '\u0003': case '\u0004': return 'quit' - case 'o': - return 'overview' - case 'c': - return 'cost' case '\t': + case 'l': + case `${ESC}[C`: return 'next' + case `${ESC}[Z`: + case 'h': + case `${ESC}[D`: + return 'prev' case 'r': return 'refresh' case 'j': @@ -73,27 +108,47 @@ export function keyOf(chunk: string): Key { case 'G': case `${ESC}[F`: return 'bottom' - default: - return null + default: { + const digit = /^[1-9]$/.test(chunk) ? TUI_VIEWS[Number(chunk) - 1] : undefined + const page = digit ?? LETTER[chunk] + + return page === undefined ? null : { page } + } } } -function paint(session: Session, io: TuiIO, depth: Depth, scroll: number): number { - const columns = Math.max(40, Math.min(200, io.stdout.columns ?? 100)) +function paint(session: Session, io: TuiIO, depth: Depth, scroll: number, clear = false): number { + const ai = session.page === 'ai' ? session.ai : null + const raw = io.stdout.columns ?? 100 const rows = Math.max(5, io.stdout.rows ?? 30) - const room = rows - 1 + const reset = clear ? `${ESC}[2J` : '' + + // Too narrow for a page: say so in a line that fits, rather than a squeezed frame of broken cards. + if (raw < MIN_COLUMNS) { + io.stdout.write(`${reset}${ESC}[H${'Too narrow: need 40 columns (q quits)'.slice(0, Math.max(1, raw))}${ESC}[K${ESC}[J`) + + return 0 + } + + const columns = Math.min(200, raw) + const room = rows - 2 let lines: string[] try { - lines = session.frame(columns, depth) + lines = session.frame(columns, depth, room) } catch { lines = ['The page could not be drawn. Press r to read again, q to quit.'] } - const top = Math.max(0, Math.min(scroll, Math.max(0, lines.length - room))) - const footer = `${depth === 'none' ? '' : `${ESC}[7m`} ${session.state.view} · ${top + 1}-${Math.min(lines.length, top + room)}/${lines.length} · ${KEYS} · read-only ${depth === 'none' ? '' : `${ESC}[0m`}` + // The AI page fits its own conversation to the room and follows the tail; the others scroll. + const top = session.page === 'ai' ? 0 : Math.max(0, Math.min(scroll, Math.max(0, lines.length - room))) + const place = lines.length > room ? ` · ${top + 1}-${Math.min(lines.length, top + room)}/${lines.length}` : '' + const footer = `${depth === 'none' ? '' : `${ESC}[2m`}${clean(keyLine(columns, place, session.page === 'ai' && session.ai !== null ? aiKeyTiers(session.ai.mode, session.ai.card !== null) : undefined))}${depth === 'none' ? '' : `${ESC}[0m`}` - io.stdout.write(`${ESC}[H${lines.slice(top, top + room).map(line => `${line}${ESC}[K`).join('\r\n')}${ESC}[J\r\n${footer.slice(0, columns + 12)}`) + io.stdout.write(`${reset}${ESC}[H${navLine(session.state.view as TuiView, columns, depth)}${ESC}[K\r\n${[...lines.slice(top, top + room), ...Array.from({ length: Math.max(0, room - (lines.length - top)) }, () => '')].map(line => `${line}${ESC}[K`).join('\r\n')}${ESC}[J\r\n${footer}`) + + // The question card is on screen now: from here a `y` may answer it, and not before (#3983). + if (session.cardFits) ai?.drawn() return top } @@ -102,7 +157,9 @@ function paint(session: Session, io: TuiIO, depth: Depth, scroll: number): numbe async function once(session: Session, io: TuiIO, view: TuiView): Promise { session.show(view) await session.refresh() - io.stdout.write(`${session.frame(Math.max(40, Math.min(200, io.stdout.columns ?? 100)), 'none').join('\n')}\n`) + const columns = Math.max(MIN_COLUMNS, Math.min(200, io.stdout.columns ?? 100)) + + io.stdout.write(`${navLine(view, columns, 'none')}\n${session.frame(columns, 'none').join('\n')}\n`) return 0 } @@ -119,7 +176,7 @@ export async function runTui(options: TuiOptions, io: TuiIO): Promise { return 2 } - const session = openSession({ cwd: options.cwd, ...(options.cliEntry !== undefined && { cliEntry: options.cliEntry }), ...(options.configDir !== undefined && { configDir: options.configDir }), ...(options.home !== undefined && { home: options.home }), ...(options.pluginRoot !== undefined && { pluginRoot: options.pluginRoot }) }) + const session = openSession({ cwd: options.cwd, ...(options.cliEntry !== undefined && { cliEntry: options.cliEntry }), ...(options.configDir !== undefined && { configDir: options.configDir }), ...(options.home !== undefined && { home: options.home }), ...(options.pluginRoot !== undefined && { pluginRoot: options.pluginRoot }), ...(options.aiPage !== undefined && { aiPage: options.aiPage }) }) let view: TuiView = options.view ?? 'overview' try { @@ -135,13 +192,19 @@ export async function runTui(options: TuiOptions, io: TuiIO): Promise { await session.refresh() if (!isDone) draw() } + session.onChange(() => void (isDone || draw())) + const onKey = (chunk: Buffer | string) => { + // The AI page takes the keys while you type (digits and letters are text there): Esc hands them back to the shell, and Ctrl-C always quits. + if (view === 'ai' && session.ai !== null && session.ai.press(chunk.toString()).consumed) return draw() + const key = keyOf(chunk.toString()) const page = Math.max(1, (io.stdout.rows ?? 30) - 2) if (key === 'quit') return finish() - if (key === 'overview' || key === 'cost') (view = key), (scroll = 0), session.show(view) + if (typeof key === 'object' && key !== null) (view = key.page), (scroll = 0), session.show(view), view === 'ai' && session.ai?.enter() else if (key === 'next') (view = TUI_VIEWS[(TUI_VIEWS.indexOf(view) + 1) % TUI_VIEWS.length] as TuiView), (scroll = 0), session.show(view) + else if (key === 'prev') (view = TUI_VIEWS[(TUI_VIEWS.indexOf(view) + TUI_VIEWS.length - 1) % TUI_VIEWS.length] as TuiView), (scroll = 0), session.show(view) else if (key === 'down') scroll += 1 else if (key === 'up') scroll = Math.max(0, scroll - 1) else if (key === 'pagedown') scroll += page @@ -159,7 +222,9 @@ export async function runTui(options: TuiOptions, io: TuiIO): Promise { io.stdin.setRawMode(true) io.stdin.resume() io.stdin.on('data', onKey) - io.stdout.on?.('resize', draw) + const resize = () => void (scroll = paint(session, io, depth, scroll, true)) + + io.stdout.on?.('resize', resize) io.signal?.addEventListener('abort', finish, { once: true }) draw() @@ -173,7 +238,7 @@ export async function runTui(options: TuiOptions, io: TuiIO): Promise { isDone = true clearInterval(timer) io.stdin.off('data', onKey) - io.stdout.off?.('resize', draw) + io.stdout.off?.('resize', resize) io.stdin.setRawMode(false) io.stdin.pause() io.stdout.write(`${ESC}[?25h${ESC}[?1049l`) diff --git a/plugins/ruflo-console/tui/session.ts b/plugins/ruflo-console/tui/session.ts index c31d7193e6..55290ff345 100644 --- a/plugins/ruflo-console/tui/session.ts +++ b/plugins/ruflo-console/tui/session.ts @@ -1,49 +1,106 @@ /** - * One standalone console session (ADR-489): the mod's own state and controller over the Node host, drawn by the mod's own - * `paneView` into terminal lines. This is the "same code path": nothing below `paneView` is forked; only the Host and the Kit differ. + * One standalone console session (ADR-489): the mod's own state and controller over the Node host, with the mod's own page bodies + * (`BODIES`, the same functions `paneView` calls) drawn by `standalonePane` into terminal lines. This is the "same code path": no view is + * forked; only the Host, the Kit and the pane around the body differ (Claude Code's tab bar, footer and Launch section are not drawn here). */ import { createController, type Controller } from '../hooks/controller' import type { Host } from '../hooks/host' -import { newState, type State, type ViewId } from '../hooks/state' -import { paneView } from '../hooks/views/pane' +import { newState, type State } from '../hooks/state' +import { BODIES } from '../hooks/views/pane' +import { standalonePane } from '../hooks/views/standalone-pane' import { render, terminalKit, type Depth } from './ansi' -import { createNodeHost, type NodeHostOptions } from './node-host' +import { aiConfigOf, openAi, type Ai, type AiOptions as AiPageOptions } from './ai' +import { aiFrame } from './ai-page' +import { allowedHostsOf } from './ai-guard' +import { createNodeHost, resolveCodex, type NodeHostOptions } from './node-host' -/** The pages the standalone shell opens in this phase: the rest need the Claude Code host's panes, prompt or dialogs. */ -export const TUI_VIEWS = ['overview', 'cost'] as const satisfies readonly ViewId[] +/** + * The pages the standalone shell opens: Overview and Cost, then Swarm, Events and Missions (ADR-489 decision C). Room is left out on purpose: + * its content is what people said to Claude in a session and a message box, neither of which this host has, so it could only draw empty cards. + */ +export const TUI_VIEWS = ['overview', 'cost', 'swarm', 'events', 'missions', 'ai'] as const export type TuiView = (typeof TUI_VIEWS)[number] +/** The pages that are the console's own views. `ai` is the terminal's own page (ADR-489 phase 3): ask Codex or OpenRouter. */ +export type ConsoleView = Exclude + +/** What the AI page may do. Absent: the page says it is off and the host refuses every spawn, send and key read (phase 2). */ +export type SessionOptions = Omit & { + aiPage?: AiPageOptions & { codexBin?: string; fetch?: typeof fetch } +} + +export type AiStatus = { codex: string; openrouter: string } export type Session = { state: State controller: Controller host: Host + /** The terminal's own AI page (null: off). */ + ai: Ai | null + aiStatus: AiStatus + /** True when the last AI frame had the whole question card on screen: only then may a y answer it. */ + cardFits: boolean + /** The page now showing. */ + page: TuiView /** Reads the disk again and runs the page's read-only probes, then returns. Never throws. */ refresh: () => Promise show: (view: TuiView) => void - /** The page as terminal lines, `columns` wide. */ - frame: (columns: number, depth: Depth) => string[] + /** The page as terminal lines, `columns` wide. `rows` is how many the terminal has for it (the AI page fits its conversation to them). */ + frame: (columns: number, depth: Depth, rows?: number) => string[] + /** Something changed that the screen should show (streamed output): the shell redraws. */ + onChange: (fn: () => void) => void stop: () => void } -export function openSession(options: NodeHostOptions, host: Host = createNodeHost(options)): Session { +export function openSession(options: SessionOptions, host?: Host): Session { + let listener: (() => void) | null = null + const page = options.aiPage + const aiConfig = page === undefined ? null : aiConfigOf(page).config + const endpoints = aiConfig === null ? [] : aiConfig.endpoints.length > 0 ? aiConfig.endpoints : [] + const hostOptions: NodeHostOptions = { + ...options, + onInvalidate: () => listener?.(), + ...(page !== undefined && aiConfig !== null && { + ai: { + ...(page.codexBin !== undefined && { codexBin: page.codexBin }), + ...(page.fetch !== undefined && { fetch: page.fetch }), + ...(page.allowWrite === true && { allowWrite: true }), + allowedHosts: allowedHostsOf([...endpoints.map(endpoint => endpoint.baseUrl), 'https://openrouter.ai/api/v1']), + keyEnvs: [...new Set([...endpoints.map(endpoint => endpoint.keyEnv), 'OPENROUTER_API_KEY'].filter(name => name !== 'NONE'))], + }, + }), + } + const node = host ?? createNodeHost(hostOptions) const state = newState({ look: 'plain', fps: 0, boot: false, panel: 'off', eventsPersist: false } as never) state.cwd = options.cwd state.isInteractive = true + state.isStandalone = true // The controller draws and probes only for a pane that is open and shown; here the whole terminal is that pane. state.pane.isOpen = true state.pane.isShown = true state.pane.isFocused = true state.pane.bootAtMs = 0 - const controller = createController(state, host) + const controller = createController(state, node) + const ai = page === undefined ? null : openAi(state, node, page) + const aiStatus: AiStatus = { codex: ai === null ? 'off' : 'checking…', openrouter: ai === null ? 'off' : 'checking…' } + let current: TuiView = 'overview' + let cardFits = false - const ready = Promise.all([host.home().then(home => void (state.home = home ?? null), () => undefined), host.configDir().then(dir => void (state.configDir = dir ?? null), () => undefined)]) + const ready = Promise.all([node.home().then(home => void (state.home = home ?? null), () => undefined), node.configDir().then(dir => void (state.configDir = dir ?? null), () => undefined)]) return { state, controller, - host, + host: node, + ai, + aiStatus, + get cardFits() { + return cardFits + }, + get page() { + return current + }, refresh: async () => { try { await ready @@ -52,17 +109,39 @@ export function openSession(options: NodeHostOptions, host: Host = createNodeHos } catch { // A read that fails is a page that says n/a, never a crashed terminal. } + + if (ai !== null) { + const home = (await node.home()) ?? '' + const found = await resolveCodex(home, page?.codexBin).catch(() => ({ ok: false as const, why: 'could not check' })) + + aiStatus.codex = found.ok ? 'ready: the pinned release, read-only' : found.why + aiStatus.openrouter = ai.keyEnvs.some(name => (process.env[name] ?? '') !== '') ? `ready (${ai.keyEnvs.filter(name => (process.env[name] ?? '') !== '').join(', ')} is set)` : `not ready: $${ai.keyEnvs[0] ?? 'OPENROUTER_API_KEY'} is not set` + } }, show: view => { - state.view = view - state.back = view + current = view + + if (view !== 'ai') { + state.view = view + state.back = view + } }, - frame: (columns, depth) => { + frame: (columns, depth, rows = 30) => { state.pane.columns = columns - const tree = paneView({ kit: terminalKit(), state, nowMs: Date.now(), columns, pictures: new Map(), act: controller.actions }) + + if (current === 'ai') { + const drawn = aiFrame(state, ai, aiStatus, columns, depth, rows) + + cardFits = drawn.fits + + return drawn.lines + } + + const tree = standalonePane({ kit: terminalKit(), state, nowMs: Date.now(), columns, pictures: new Map(), act: controller.actions }, BODIES[state.view]) return render(tree, columns, depth) }, + onChange: fn => void (listener = fn), stop: () => controller.stop(), } } diff --git a/scripts/e2e/host-matrix.mjs b/scripts/e2e/host-matrix.mjs index ad485c59af..121bab5485 100644 --- a/scripts/e2e/host-matrix.mjs +++ b/scripts/e2e/host-matrix.mjs @@ -2,12 +2,13 @@ // Three-host e2e loop (ADR-490): Claude Code, Codex and OpenRouter against the real ruflo CLI/MCP/mods, host x assertion matrix. // node scripts/e2e/host-matrix.mjs keyless + stubbed assertions only (what CI runs): $0, no model call // RUFLO_E2E_LIVE=1 node scripts/e2e/host-matrix.mjs --live also run the live legs (spend-incurring, capped at --cap USD, default 6) -// Flags: --legs claude,codex,openrouter --cli-version latest|X.Y.Z --cli-path --json out.json --cap 6 +// Flags: --legs claude,codex,openrouter,tui --cli-version latest|X.Y.Z --cli-path --json out.json --cap 6 import { writeFileSync } from 'node:fs' import { spend, renderTable, redact } from './lib.mjs' import { claudeLeg } from './leg-claude.mjs' import { codexLeg } from './leg-codex.mjs' import { openrouterLeg } from './leg-openrouter.mjs' +import { tuiLeg } from './leg-tui.mjs' const arg = (k, d) => { const i = process.argv.indexOf(`--${k}`); return i > 0 ? process.argv[i + 1] : d } const live = process.argv.includes('--live') && process.env.RUFLO_E2E_LIVE === '1' @@ -15,9 +16,9 @@ if (process.argv.includes('--live') && !live) console.error('--live ignored: set spend.cap = Number(arg('cap', '6')) const cliPath = arg('cli-path', process.env.RUFLO_E2E_CLI_PATH) const cli = cliPath ? { cmd: process.execPath, args: [cliPath], label: `path:${cliPath}` } : { cmd: 'npx', args: ['-y', `ruflo@${arg('cli-version', process.env.RUFLO_E2E_CLI_VERSION ?? 'latest')}`], label: `ruflo@${arg('cli-version', process.env.RUFLO_E2E_CLI_VERSION ?? 'latest')}` } -const legs = (arg('legs', 'claude,codex,openrouter')).split(',') +const legs = (arg('legs', 'claude,codex,openrouter,tui')).split(',') const ctx = { cli, live, spend } -const fns = { claude: claudeLeg, codex: codexLeg, openrouter: openrouterLeg } +const fns = { claude: claudeLeg, codex: codexLeg, openrouter: openrouterLeg, tui: tuiLeg } const rows = [] for (const leg of legs) { diff --git a/scripts/e2e/leg-tui.mjs b/scripts/e2e/leg-tui.mjs new file mode 100644 index 0000000000..c04f357db4 --- /dev/null +++ b/scripts/e2e/leg-tui.mjs @@ -0,0 +1,126 @@ +// TUI leg (ADR-490 + ADR-489 phase 3): the standalone `ruflo tui` bundle, in this process, with an injected terminal. Keyless part ($0, what CI +// runs): the six pages, the not-a-terminal exit, the AI page's card and refusals against a stub fetch and no Codex. Live part (RUFLO_E2E_LIVE=1): +// one cheap OpenRouter question and one read-only turn on the pinned Codex, each after a card, capped by the shared spend cap. +import { existsSync } from 'node:fs' +import { fileURLToPath, pathToFileURL } from 'node:url' +import { recorder, sandbox, addSecret, redact } from './lib.mjs' +import { findOpenRouterKey } from './leg-openrouter.mjs' + +const ESC = '\u001b' +const strip = s => s.replace(/\u001b\[[0-9;?]*[A-Za-z]/g, '') + +/** An injected terminal: keys in, the last drawn frame out. */ +function terminal(columns = 100, rows = 32) { + const out = [] + const keys = [] + const io = { + stdin: { isTTY: true, setRawMode: () => undefined, on: (_e, fn) => void keys.push(fn), off: () => void keys.splice(0), resume: () => undefined, pause: () => undefined }, + stdout: { isTTY: true, columns, rows, write: t => void out.push(t), on: () => undefined, off: () => undefined }, + stderr: { write: () => undefined }, + env: { TERM: 'xterm-256color' }, + } + const frame = () => strip((out.join('').split(`${ESC}[H`).pop() ?? '').replace(/\r/g, '')) + const press = k => keys.forEach(fn => fn(k)) + const waitFor = async (re, ms = 8000) => { + const end = Date.now() + ms + while (Date.now() < end) { if (re.test(frame())) return true; await new Promise(r => setTimeout(r, 25)) } + return false + } + return { io, press, frame, waitFor, all: () => strip(out.join('')) } +} + +async function ask(mod, options, text, { target = 'codex', env = {} } = {}) { + const t = terminal() + t.io.env = { ...t.io.env, ...env } + const running = mod.runTui({ ...options, view: 'ai' }, t.io) + await t.waitFor(/codex ›|openrouter ›/) + if (target === 'openrouter') t.press('\u0014') + t.press(text) + t.press('\r') + const card = await t.waitFor(/Ask first, #\d+/) + const cardText = t.frame() + if (card) t.press('y') + return { t, running, card, cardText } +} + +export async function tuiLeg({ live, spend }) { + const rec = recorder('tui') + const bundle = fileURLToPath(new URL('../../plugins/ruflo-console/dist/tui.mjs', import.meta.url)) + if (!existsSync(bundle)) { rec.skipped('tui bundle present', 'plugins/ruflo-console/dist/tui.mjs is not built (node plugins/ruflo-console/scripts/build-tui.mjs)'); return rec.rows } + const mod = await import(pathToFileURL(bundle).href) + const sb = sandbox('e2e-tui.') + const project = sb.project('proj') + const SENTINEL = 'sk-or-v1-e2esentinel0123456789abcdef0123456789' + addSecret(SENTINEL) + + try { + rec.check('six pages: overview cost swarm events missions ai', JSON.stringify(mod.TUI_VIEWS) === JSON.stringify(['overview', 'cost', 'swarm', 'events', 'missions', 'ai']), JSON.stringify(mod.TUI_VIEWS)) + + for (const view of mod.TUI_VIEWS) { + const out = [] + const code = await mod.runTui({ cwd: project, home: sb.home, plain: true, view, aiPage: {} }, { stdin: { on() {}, off() {}, resume() {}, pause() {} }, stdout: { columns: 100, rows: 30, write: t => void out.push(t) }, stderr: { write() {} }, env: {} }) + const text = out.join('') + rec.check(`--plain ${view}: exit 0, page bar with the page marked, no escapes, no key`, code === 0 && /\[\d [A-Za-z]+\]/.test(text.split('\n')[0]) && !text.includes(ESC) && !text.includes(SENTINEL), text.split('\n')[0]) + } + + const err = [] + const code = await mod.runTui({ cwd: project, home: sb.home }, { stdin: { isTTY: false, on() {}, off() {}, resume() {}, pause() {} }, stdout: { isTTY: false, write() {} }, stderr: { write: t => void err.push(t) }, env: {} }) + rec.check('no terminal and no --plain: one-line hint on stderr and exit 2', code === 2 && /not an interactive terminal/.test(err.join('')), err.join('').trim()) + + // Keyless AI: OpenRouter against a stub fetch (the host allows only https openrouter.ai; the stub stands in for it). + process.env.OPENROUTER_API_KEY = SENTINEL + const calls = [] + const stub = async (url, init) => { calls.push({ url: String(url), redirect: init.redirect, auth: init.headers.authorization }); return new Response(JSON.stringify({ choices: [{ message: { content: 'STUB-PONG' } }], usage: { prompt_tokens: 5, completion_tokens: 2, cost: 0.00003 }, model: 'stub/model' }), { status: 200 }) } + const one = await ask(mod, { cwd: project, home: sb.home, aiPage: { fetch: stub, model: 'stub/model' } }, 'say pong', { target: 'openrouter' }) + rec.check('ai: Enter shows a card naming the host, the model and the key variable, and sends nothing before y', one.card && /openrouter\.ai\/api\/v1\/chat\/completions/.test(one.cardText.replace(/\s+/g, ' ')) && /\$OPENROUTER_API_KEY/.test(one.cardText.replace(/\s+/g, ' ')) && !one.cardText.includes(SENTINEL), one.cardText.split('\n').find(l => /Ask first/.test(l)) ?? '') + const answered = await one.t.waitFor(/STUB-PONG/) + rec.check('ai: after y exactly one request went to openrouter.ai, redirects off, key in one header, reply drawn with the reported cost, key never drawn', answered && calls.length === 1 && calls[0].url.startsWith('https://openrouter.ai/') && calls[0].redirect === 'manual' && calls[0].auth === `Bearer ${SENTINEL}` && /\$0\.000030/.test(one.t.frame()) && !one.t.all().includes(SENTINEL), JSON.stringify({ n: calls.length, url: calls[0]?.url })) + one.t.press('\u0003') + await one.running + + // Keyless AI: no pinned Codex under this HOME, so a Codex question fails with the reason and nothing falls back to PATH or current. + const two = await ask(mod, { cwd: project, home: sb.home, aiPage: { fetch: stub } }, 'hello', { target: 'codex' }) + // The answer row (✗ codex: …), not the status line above it, which says the same thing before any question is asked. + const refused = await two.t.waitFor(/✗ codex: .*pinned Codex 0\.162\.0 is not installed/s) + rec.check('ai: without the pinned Codex release the answer says so (never current, never PATH)', refused, two.t.frame().split('\n').find(l => /✗ codex/.test(l)) ?? '') + two.t.press('\u0003') + await two.running + delete process.env.OPENROUTER_API_KEY + } catch (e) { rec.fail('keyless tui leg ran to completion', redact(String(e?.stack ?? e)).slice(0, 400)) } + + if (!live) { rec.skipped('live: OpenRouter and Codex through the TUI', 'RUFLO_E2E_LIVE not set'); sb.cleanup(); return rec.rows } + + const key = findOpenRouterKey() + if (!key) rec.blocked('live: OpenRouter question through the TUI', 'no OPENROUTER_API_KEY in env or GCP Secret Manager') + else { + try { + process.env.OPENROUTER_API_KEY = key + const run = await ask(mod, { cwd: project, home: sb.home, aiPage: { model: 'openai/gpt-4o-mini', maxSpendUsd: Math.min(0.25, spend.left()) } }, 'Reply with exactly the single word: PONG', { target: 'openrouter' }) + const ok = await run.t.waitFor(/PONG/, 60_000) + // The answer arrives before its end row (✓ s · $ · tokens): wait for that row, then read the cost off it. + await run.t.waitFor(/✓ \d+ s/, 10_000) + + const frame = run.t.frame() + const cost = Number(/✓ \d+ s · \$([0-9.]+)/.exec(frame)?.[1] ?? NaN) + if (Number.isFinite(cost)) spend.add(cost) + rec.check('live: OpenRouter answered PONG through the TUI after a card; key never drawn', ok && !run.t.all().includes(key), redact(frame.split('\n').find(l => /PONG|✓/.test(l)) ?? ''), { long: false }) + rec.check('live: the provider reported a cost (not computed here)', Number.isFinite(cost) && cost > 0, `reported $${cost}`) + run.t.press('\u0003') + await run.running + } catch (e) { rec.fail('live OpenRouter leg ran to completion', redact(String(e?.message ?? e))) } finally { delete process.env.OPENROUTER_API_KEY } + } + + // The pinned Codex under the real HOME, read-only, one trivial turn (a ChatGPT plan turn, no dollars). Run in a throwaway working directory. + try { + const realHome = process.env.HOME ?? sb.home + const run = await ask(mod, { cwd: sb.project('codex-live'), home: realHome, aiPage: {} }, 'Reply with exactly the single word: PONG', { target: 'codex' }) + const done = await run.t.waitFor(/PONG|not installed|✗/, 120_000) + const frame = run.t.frame() + rec.check('live: the pinned Codex answered PONG through the TUI, read-only', done && /PONG/.test(frame) && /sandbox read-only/.test(run.cardText.replace(/\s+/g, ' ')), redact(frame.split('\n').find(l => /PONG|✗|not installed/.test(l)) ?? '').slice(0, 200)) + run.t.press('\u0003') + await run.running + } catch (e) { rec.fail('live Codex leg ran to completion', redact(String(e?.message ?? e))) } + + sb.cleanup() + return rec.rows +} diff --git a/v3/@claude-flow/cli/__tests__/tui-command.test.ts b/v3/@claude-flow/cli/__tests__/tui-command.test.ts index 4691544c3f..ae89781286 100644 --- a/v3/@claude-flow/cli/__tests__/tui-command.test.ts +++ b/v3/@claude-flow/cli/__tests__/tui-command.test.ts @@ -8,7 +8,7 @@ import { dirname, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { afterEach, describe, expect, it } from 'vitest'; -import { locateTuiBundle, tuiCommand } from '../src/commands/tui.js'; +import { aiPage, locateTuiBundle, tuiCommand } from '../src/commands/tui.js'; /** The command names capability-brain.ts lists, read from the source so the test fails if `tui` is dropped. */ const COMMANDS_FOR_BRAIN = [...readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'src', 'mcp-tools', 'capability-brain.ts'), 'utf8').matchAll(/'([a-z][a-z-]*)'/g)].map(match => match[1]); @@ -64,6 +64,41 @@ describe('tui command', () => { expect(result).toMatchObject({ success: false, exitCode: 1 }); }); + it.skipIf(locateTuiBundle() === null)('opens each of the six pages with --plain, and refuses Room and anything else with exit 2 (real bundle)', async () => { + for (const view of ['overview', 'cost', 'swarm', 'events', 'missions', 'ai']) { + const lines: string[] = []; + const real = process.stdout.write.bind(process.stdout); + process.stdout.write = ((chunk: string | Uint8Array) => (lines.push(String(chunk)), true)) as typeof process.stdout.write; + try { + const result = await tuiCommand.action!({ args: [], flags: { view, plain: true }, cwd: tmp() } as never); + + expect(result, view).toMatchObject({ success: true, exitCode: 0 }); + } finally { + process.stdout.write = real; + } + expect(lines.join(''), view).toContain('1 Overview'); + expect(lines.join(''), view).not.toContain(process.env.OPENROUTER_API_KEY ?? '\u0000never'); + } + + for (const view of ['room', 'nope']) { + expect(await tuiCommand.action!({ args: [], flags: { view, plain: true }, cwd: tmp() } as never), view).toMatchObject({ success: false, exitCode: 2 }); + } + }); + + it('reads the AI flags: a model, a numeric cap (a bad one is dropped), the endpoint list from a flag or the environment', () => { + expect(aiPage({})).toEqual({}); + expect(aiPage({ model: 'openai/gpt-4o-mini', maxSpendUsd: 0.1, convoTargets: 'endpoint:a=https://x.example/v1|A_KEY|m' })).toEqual({ model: 'openai/gpt-4o-mini', maxSpendUsd: 0.1, convoTargets: 'endpoint:a=https://x.example/v1|A_KEY|m' }); + expect(aiPage({ 'max-spend-usd': '0.25' })).toEqual({ maxSpendUsd: 0.25 }); + expect(aiPage({ maxSpendUsd: -1 })).toEqual({}); + expect(aiPage({ maxSpendUsd: 'lots' })).toEqual({}); + expect(aiPage({ model: '' })).toEqual({}); + }); + + it('declares --ai (default on, --no-ai turns it off), --model, --max-spend-usd and --convo-targets', () => { + expect(tuiCommand.options?.find(option => option.name === 'ai')).toMatchObject({ type: 'boolean', default: true }); + for (const name of ['model', 'max-spend-usd', 'convo-targets']) expect(tuiCommand.options?.some(option => option.name === name), name).toBe(true); + }); + it('declares --plain as a boolean option and lists it in the examples', () => { expect(tuiCommand.options?.find(option => option.name === 'plain')).toMatchObject({ type: 'boolean', default: false }); expect(tuiCommand.examples?.some(example => example.command.includes('--plain'))).toBe(true); diff --git a/v3/@claude-flow/cli/src/commands/tui.ts b/v3/@claude-flow/cli/src/commands/tui.ts index 373539f7f0..8550237bbe 100644 --- a/v3/@claude-flow/cli/src/commands/tui.ts +++ b/v3/@claude-flow/cli/src/commands/tui.ts @@ -2,13 +2,14 @@ * `ruflo tui` — the ruflo console in a terminal of its own (ADR-489). * * Runs the same views the Claude Code mod (plugins/ruflo-console) draws, over a Node host instead of the mod host. Read-only in - * this phase: Overview and Cost. The bundle is built from the plugin's source (scripts/build-tui.mjs) and loaded from this + * the pages: Overview, Cost, Swarm, Events and Missions are read-only; AI (key 6) asks Codex (read-only, the pinned 0.162.0) or OpenRouter + * (https, openrouter.ai or a convoTargets host), and every question shows a card first. The bundle is built from the plugin's source (scripts/build-tui.mjs) and loaded from this * CLI's OWN install only (never from the working directory: opening a repository must not run code that repository supplies). * No bundle is a message and exit 1, never a crash; ruflo stays operational without it. Without a terminal (a pipe, CI) the live view cannot run: * a one-line hint and exit 2, unless --plain asks for one frame as plain text and exit 0 (ADR-489 decision E). * * npx ruflo tui # interactive, in a terminal - * npx ruflo tui --view cost # start on the Cost page + * npx ruflo tui --view swarm # start on the Swarm page (keys 1-5 or o c s e m switch pages) * npx ruflo tui --plain | head # one plain frame, exit 0 (scripts, CI) * npx ruflo tui | cat # not a terminal and no --plain: a hint on stderr, exit 2 */ @@ -22,7 +23,7 @@ import { ownPluginDirs } from '../plugins/own-install.js'; const __dirname = dirname(fileURLToPath(import.meta.url)); -const VIEWS = ['overview', 'cost'] as const; +const VIEWS = ['overview', 'cost', 'swarm', 'events', 'missions', 'ai'] as const; type TuiModule = { runTui: (options: Record, io: Record) => Promise; isTuiView: (value: unknown) => boolean }; @@ -41,16 +42,31 @@ function cliEntry(): string | undefined { return existsSync(entry) ? entry : undefined; } +/** The AI page's settings from the flags (and one environment variable for the endpoint list). Absent flags leave the defaults; a bad number is ignored, never passed on. */ +export function aiPage(flags: Record | undefined): { model?: string; maxSpendUsd?: number; convoTargets?: string } { + const model = typeof flags?.model === 'string' && flags.model !== '' ? flags.model : undefined; + const cap = flags?.maxSpendUsd ?? flags?.['max-spend-usd']; + const maxSpendUsd = typeof cap === 'number' && Number.isFinite(cap) && cap >= 0 ? cap : typeof cap === 'string' && /^\d+(\.\d+)?$/.test(cap) ? Number(cap) : undefined; + const targets = flags?.convoTargets ?? flags?.['convo-targets'] ?? process.env.RUFLO_TUI_CONVO_TARGETS; + + return { ...(model !== undefined && { model }), ...(maxSpendUsd !== undefined && { maxSpendUsd }), ...(typeof targets === 'string' && targets !== '' && { convoTargets: targets.slice(0, 2000) }) }; +} + export const tuiCommand: Command = { name: 'tui', - description: 'The ruflo console in your terminal (Overview and Cost, read-only). Same views as the Claude Code mod.', + description: 'The ruflo console in your terminal: Overview, Cost, Swarm, Events, Missions (read-only) and an AI page that asks Codex or OpenRouter, each question after a card.', options: [ { name: 'view', description: `Page to open: ${VIEWS.join(' | ')}`, type: 'string' as const, default: 'overview' }, + { name: 'ai', description: 'The AI page (ask Codex read-only or OpenRouter, each question after a confirm card). --no-ai turns it off', type: 'boolean' as const, default: true }, + { name: 'model', description: 'OpenRouter model for this session (default openrouter/auto)', type: 'string' as const }, + { name: 'max-spend-usd', description: 'Stop sending to OpenRouter once the provider-reported spend reaches this (default 0.5)', type: 'number' as const }, + { name: 'convo-targets', description: 'Extra OpenAI-compatible endpoints, the console convoTargets syntax: endpoint:=||;... (a key is named by its environment variable). Also RUFLO_TUI_CONVO_TARGETS', type: 'string' as const }, { name: 'plain', description: 'Print one frame as plain text and exit 0 (scripts and CI). Without it, a non-terminal gets a hint and exit 2', type: 'boolean' as const, default: false }, ], examples: [ { command: 'npx ruflo tui', description: 'Open the console in this terminal' }, - { command: 'npx ruflo tui --view cost', description: 'Start on the Cost page' }, + { command: 'npx ruflo tui --view swarm', description: 'Start on the Swarm page (keys 1-5 switch pages, tab cycles, q quits)' }, + { command: 'npx ruflo tui --view ai --model openai/gpt-4o-mini --max-spend-usd 0.1', description: 'The AI page on a cheap OpenRouter model, stopping at $0.10 reported (key in $OPENROUTER_API_KEY, never shown)' }, { command: 'npx ruflo tui --plain | head -40', description: 'One plain frame, exit 0: for scripts and CI (no terminal needed)' }, ], async action(context: CommandContext): Promise { @@ -84,7 +100,7 @@ export const tuiCommand: Command = { try { const code = await mod.runTui( - { cwd: ctx.cwd ?? process.cwd(), view: wanted, ...(ctx.flags?.plain === true && { plain: true }), ...(cliEntry() !== undefined && { cliEntry: cliEntry() }), ...(process.env.CLAUDE_CONFIG_DIR !== undefined && { configDir: process.env.CLAUDE_CONFIG_DIR }) }, + { cwd: ctx.cwd ?? process.cwd(), view: wanted, ...(ctx.flags?.plain === true && { plain: true }), ...(ctx.flags?.ai !== false && { aiPage: aiPage(ctx.flags) }), ...(cliEntry() !== undefined && { cliEntry: cliEntry() }), ...(process.env.CLAUDE_CONFIG_DIR !== undefined && { configDir: process.env.CLAUDE_CONFIG_DIR }) }, { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr, env: process.env, signal: stop.signal }, ); return { success: code === 0, exitCode: code }; diff --git a/v3/docs/adr/ADR-489-ruflo-tui-standalone-console.md b/v3/docs/adr/ADR-489-ruflo-tui-standalone-console.md index cb3862bc31..e70034f7f2 100644 --- a/v3/docs/adr/ADR-489-ruflo-tui-standalone-console.md +++ b/v3/docs/adr/ADR-489-ruflo-tui-standalone-console.md @@ -1,6 +1,6 @@ # ADR 489: `ruflo tui`: the console in a terminal of its own, over the same views -Status: Accepted. The owner accepted decisions A to E on 2026-10-11 (section 8). Phase 1 (read-only Overview and Cost, `--plain`, publish wiring) is implemented in PR #4059; phases 2 to 4 are a roadmap that must follow those decisions. +Status: Accepted. The owner accepted decisions A to E on 2026-10-11 (section 8). Phase 1 (read-only Overview and Cost, `--plain`, publish wiring) is implemented in PR #4059; phase 2 (Swarm, Events and Missions, page bar and keys, resize, host capability flag) is implemented in PR #4075; phase 3 (the AI page: Codex and OpenRouter, each question after a card) is implemented in PR 2 of the continuation; phase 4 (actions) is a roadmap that must follow those decisions. Date: 2026-10-11 @@ -151,14 +151,19 @@ not a replacement and not a second implementation. 1. **Phase 1 (PR #4059): the vertical slice.** `ruflo tui [--view overview|cost] [--plain]`; alternate screen, keys `o c Tab r j k PgUp PgDn g G q`, auto-refresh every 3 s; `--plain` prints one plain frame and exits 0, and without a terminal and without `--plain` it prints a one-line hint and exits 2 (decision E); read-only; the boundary and security tests; ADR. 1b. **Publish wiring (done in PR #4059, decisions A and B).** `prepare-publish.mjs` builds and stages the bundle and `esbuild` is a declared devDependency. Still to do: a CI job that runs `ruflo tui --plain` from the packed tarball. -2. **Host capabilities and more pages.** `Host.capabilities` so chrome and rows that need Claude Code are hidden, not drawn inert; pages in the accepted order (decision C): Swarm, then Events, then Missions, then Room, all read-only; Raster to half-block cells; Windows and tmux verification; `NO_COLOR` and width (CJK, emoji) handling. -3. **Drive Codex and OpenRouter** (3.5) behind the confirm gate, with #3983's tests ported; the AI terminal page; per-provider spend read from the CLIs' own reports and the ledger. +2. **Host capabilities and more pages (done).** `state.isStandalone` is the capability flag: the shared chrome and the Claude-only rows are not drawn on this host (no tab bar, footer buttons, Launch section, Ask Claude, Claude control card; a button that cannot be pressed is not drawn, a state chip and a section title are). Pages in the accepted order (decision C): Overview, Cost, **Swarm, Events, Missions**, all read-only; keys `1`-`5`, `o c s e m`, Tab and Shift-Tab, a page bar, a key line that shortens with the width, a clear-and-redraw on resize, a position bar under 60 columns and a one-line notice under 40. **Room is not shipped, on purpose:** its content is what people said to Claude in a session plus a message box, neither of which this host has, so it could only draw empty cards; it comes back if a host source for it exists. Missions shows the ADR-406 mission record only (goal entry, planning and research start a Claude turn). Still open: Raster to half-block cells, Windows verification, CJK and emoji width beyond the table in `ansi.ts`. +3. **Drive Codex and OpenRouter (done).** Page 6, `AI` (`tui/ai.ts`, `ai-page.ts`, `ai-guard.ts`; keys `6`/`a`). Reuse, not a second harness: `harness.send` runs Codex and streams its events into the scrollback the console already draws, and `sendTo` (the conversation bridge, ADR-465) builds and sends the OpenRouter request. What is new is the doors and the gate: + - **Codex.** `Host.spawn` accepts one program: the **pinned release** found under `~/.codex/packages/standalone/releases/0.162.0-/bin/codex` whose `--version` says exactly `codex-cli 0.162.0`. `current` and PATH are never used (0.162.1 crashes with a #GP); if the release is absent the answer says so and nothing falls back. The argument list is validated against a fixed allow-list (`exec`, `--json`, `--skip-git-repo-check`, `--ephemeral`, an explicit `--sandbox read-only` or `-c sandbox_mode="read-only"`, a plain model name, a session id after `resume`, the `-` stdin marker): no profile, no extra config key, no `--yolo`, no `danger-full-access`, no added directory, and **no run without an explicit sandbox** (a config file could widen the default). The child sees PATH, HOME and `CODEX_HOME` only: none of our API keys. + - **OpenRouter.** `Host.httpSend` sends only **https POST to `openrouter.ai` or a host a `convoTargets` entry names** (exact host, default port, no userinfo, two headers, a bounded body) and **never follows a redirect** (a 3xx is an error: it could carry the key to another host). A key is read by **variable name** (`printenv NAME`, only for names the page was configured with), rides one header, and is masked out of anything drawn, including the provider's own echo. Cost is the figure the provider reported (six places under a cent), never one computed here. + - **The gate (#3983).** Enter makes a card showing exactly what would leave the machine (the Codex argv and prompt, or the POST, the model and the key variable's name); only a lone `y` while that card has been **drawn in full** answers it; `n` or Esc drops it; it expires after 60 s; a paste is text, never an answer; a terminal too small to show the whole card cannot answer it. A message that looks like a credential is refused and dropped. + - **Spend.** `--max-spend-usd` (default 0.5) stops the next OpenRouter question once the provider-reported total reaches it. Codex reports no dollars: its turns are counted and its cost reads n/a. The multi-provider ledger (ADR-437) reads Codex's own rollouts and OpenRouter's key usage; this page adds no writer to it. + - **Not in this PR:** the per-session **workspace-write opt-in**. The host accepts `workspace-write` when built with `allowWrite` and the guard pins it (tests), but the page offers no toggle and the console's Codex argv is read-only, so no write path exists yet; it needs a card that names the files Codex may change, which is phase 4. 4. **Actions.** Pressable buttons and fields (an optional lazily loaded input dependency, or hand-rolled), the confirm card, the palette; each write goes through `Runner` as in the mod. ## 5. Risks - **Cell width.** Width is counted in terminal cells with a small table (CJK, fullwidth, the emoji blocks, combining marks); a symbol the table does not list, or a terminal that draws an emoji at another width, can still shift a border. Tested for the emoji the pane header uses. -- **Chrome that lies.** Inert Claude-only controls are visible until phase 2. They are dimmed and the footer says read-only; still a rough edge. +- **Chrome that lies (closed in phase 2).** The Claude-only controls are no longer drawn. Residual: some page text still names a button (a hint such as "open Memory"), because the view's words are shared with Claude Code. - **Drift.** A new view may import something engine-specific. Mitigation: `tui-boundary.spec.ts` (imports) and a headless smoke over the pages the TUI opens. - **Bundle size.** 437 KiB gzip for a feature many will not use. It loads lazily, only for `tui`. Dropping the unused pages from the bundle (tree-shaking by an explicit page list) is a phase 2 option. - **A second place to sanitise.** The engine's escape handling is not inherited. `clean` is one function with a test; any new drawing path must go through `render`. @@ -192,7 +197,7 @@ The owner delegated these to be optimised and recorded; each is **Accepted**. A, - **A. Accepted, done.** `esbuild` is a root devDependency (`^0.27.2`, build-time only; `package-lock.json` changed by one line, proven with `npm ci --dry-run`). - **B. Accepted, done.** `prepare-publish.mjs` builds and stages `plugins/ruflo-console/dist/tui.mjs` into the CLI tarball now (+449,345 bytes gzip-packed, measured), so `npx ruflo tui` works from the registry package, not only a checkout. - **C. Accepted (phase 2).** Pages after Overview and Cost, all read-only, in this order: **Swarm, then Events, then Missions, then Room last.** -- **D. Accepted (phase 3).** Codex: read-only sandbox by default through the pinned-by-path binary (never the 0.162.1 build), an explicit per-session opt-in for workspace-write, and **no `danger-full-access` path in the TUI**. +- **D. Accepted, implemented in phase 3 except the workspace-write toggle (section 4, item 3).** Codex: read-only sandbox by default through the pinned-by-path binary (never the 0.162.1 build), an explicit per-session opt-in for workspace-write, and **no `danger-full-access` path in the TUI**. OpenRouter: `httpSend` only to `https://openrouter.ai` plus hosts named in `convoTargets`, https only, no redirects to other hosts, keys referenced by environment variable name only and never rendered or logged, model output sanitised through `ansi.ts` `clean` before drawing, and the confirm-gate binding (#3983) required for any write action. Detail in section 3.5. - **E. Accepted, done.** `ruflo tui --plain` prints one frame as plain text and exits 0 (`ruflo tui --plain | head`). **Without a TTY and without `--plain`** it prints a one-line hint on stderr and exits **2**.