🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated
TypeScript agentic-aiagentic-frameworkagentic-workflowagentsai-agentsai-assistantai-skillsautonomous-agentsclaudecodexdsh-pluginharnessmcp-servermulti-agentmulti-agent-systemsnpmskillsswarmswarm-intelligencetypescript
feat(tui): the AI page: ask Codex (read-only, pinned) or OpenRouter, each question after a card (ADR-489 phase 3)
r7718a142b4cd
diff --git a/.github/workflows/e2e-host-matrix.yml b/.github/workflows/e2e-host-matrix.ymlindex 499672871b..dc452b7493 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,10 @@ jobs:run: |pnpm --recursive --no-bail run build || truetest -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: |+ npm install --no-save --no-package-lock --ignore-scripts --workspaces=false [email protected]+ node plugins/ruflo-console/scripts/build-tui.mjs- name: Install the pinned Codex (0.162.0)run: |npm install -g @openai/[email protected]diff --git a/docs/e2e-host-matrix.md b/docs/e2e-host-matrix.mdindex 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 Unode 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 <cli.js>` (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 <cli.js>` (test a workspacebuild; build `shared security mcp swarm cli` first), `--json <file>`, `--cap <usd>`. Exit code 1 only when a row is `fail`.## What you need for the live modediff --git a/plugins/ruflo-console/README.md b/plugins/ruflo-console/README.mdindex 48279b5a2d..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 views the mod draws, on five pages (Overview, Cost, Swarm, Events, Missions), 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).```bashnpx 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 quitnpx 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 pagenpx ruflo tui --plain | head -40 # one plain frame, exit 0: for scripts and CInpx 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`. Room is not in the terminal (it is a message box and Claude sessions); Codex and OpenRouter come next, read-only by default (decision D in the ADR). A terminal narrower than 60 columns gets a short page bar, and under 40 a one-line notice.+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:<name>=<https-base-url>|<KEY_ENV>|<model>`); 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/tests/fixtures/fake-codex.mjs b/plugins/ruflo-console/tests/fixtures/fake-codex.mjsnew file mode 100755index 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.tsnew file mode 100644index 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://[email protected]/x', POST, hosts)).toMatchObject({ ok: false })+ expect(validateHttp('https://user:[email protected]/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.tsnew file mode 100644index 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<typeof createNodeHost>[0]['ai'] = { codexBin: FAKE, allowedHosts: ['openrouter.ai'], keyEnvs: ['OPENROUTER_API_KEY'] }) => createNodeHost({ cwd: join(root, 'project'), home: root, ai })++async function drain(stream: ReturnType<ReturnType<typeof host>['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.tsnew file mode 100644index 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<ReturnType<typeof open>['ai']>, text: string) => void ai.press(text)+const frame = (session: ReturnType<typeof open>['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<typeof open>['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<string, string>; 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.tsindex 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.tsindex 92fb89067f..a9e0245999 100644--- a/plugins/ruflo-console/tests/tui-nav.spec.ts+++ b/plugins/ruflo-console/tests/tui-nav.spec.ts@@ -1,5 +1,5 @@/**- * `ruflo tui` phase 2 (ADR-489): the five pages, the page bar and keys, resize and narrow terminals, and the chrome that must not+ * `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*/@@ -64,13 +64,13 @@ const plain = (screen: string) => screen.replace(/\u001b\[[0-9;?]*[A-Za-z]/g, ''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 five pages, tab and arrows to neighbours, and ignores the rest', () => {- expect(TUI_VIEWS).toEqual(['overview', 'cost', 'swarm', 'events', 'missions'])- expect(['1', '2', '3', '4', '5'].map(keyOf)).toEqual(TUI_VIEWS.map(page => ({ page })))- expect([keyOf('o'), keyOf('c'), keyOf('s'), keyOf('e'), keyOf('m')]).toEqual([{ page: 'overview' }, { page: 'cost' }, { page: 'swarm' }, { page: 'events' }, { page: 'missions' }])+ 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('6'), keyOf('9'), keyOf('x'), keyOf(`${ESC}]0;t\u0007`)]).toEqual([null, null, null, null, null])+ 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', () => {@@ -81,26 +81,26 @@ describe('keys', () => {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 ')+ 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/5 Swarm ›')+ 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-5 page · j/k scroll · q quit')- expect(keyLine(25)).toBe('1-5 page · 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 five pages at ${columns} columns, no wider than the terminal, with none of Claude Code's chrome`, async () => {+ 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') })+ const session = openSession({ cwd: project, home: join(root, 'home'), aiPage: {} })try {session.show(view)@@ -171,7 +171,7 @@ describe('the terminal loop', () => {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/g) ?? []+ 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`)@@ -194,7 +194,7 @@ describe('the terminal loop', () => {expect(frame, `${rows} rows`).toHaveLength(rows)expect(frame[0]).toContain('4 Events')- expect(frame[rows - 1]).toMatch(/^1-5 or o c s e m page/)+ expect(frame[rows - 1]).toMatch(/^1-6 or o c s e m a page/)}})@@ -222,8 +222,8 @@ describe('the terminal loop', () => {const running = runTui({ cwd: project, home: join(root, 'home') }, narrow.io)await settle()- expect(plain(narrow.out.join(''))).toContain('‹ 1/5 Overview ›')- expect(plain(narrow.out.join(''))).toContain('1-5 page · j/k scroll · q quit')+ 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@@ -246,7 +246,7 @@ describe('the terminal loop', () => {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' }[view]}]`)+ 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/tui/ai-guard.ts b/plugins/ruflo-console/tui/ai-guard.tsnew file mode 100644index 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 <mode>] [-c sandbox_mode="<mode>"] [-m <model>] [<session>] -`.+ * `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://<allowed host>/...`: 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<string, string>; 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.tsnew file mode 100644index 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<string, unknown> = {}) => 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<string, unknown> = {}) => kit.Text({ children: clean(children), ...props })+const boxed = (color: string, children: ReturnType<typeof t>[]) => 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, unknown> = {}): 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.tsnew file mode 100644index 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:<name>=<base-url>|<KEY_ENV>|<model>;...` 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<void> {+ 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<typeof http>, 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/node-host.ts b/plugins/ruflo-console/tui/node-host.tsindex 5c1ced76a3..c476c19947 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/<pinned>-<platform>/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,19 @@ 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+const VERSION_SAYS = new RegExp('^codex-cli ' + PINNED_CODEX.replace(/\./g, '\\.') + '\\s*$')const refuse = (what: string): Promise<never> => Promise.reject(new Error(`${what}: not available in the standalone terminal`))@@ -51,6 +74,75 @@ export function cliArgv(argv: readonly string[], entry: string | undefined): strreturn 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<string>(done => execFile(bin, ['--version'], { timeout: 5_000, windowsHide: true, env: childEnv(CODEX_ENV) }, (error, stdout) => done(error === null ? String(stdout) : '')))++ if (VERSION_SAYS.test(said.trim())) 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<ProcessSpawnChunk, ProcessSpawnResult> & { readonly result: Promise<ProcessSpawnResult> }++/** 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<typeof spawnProcess>): 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<ProcessSpawnResult>(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<void>(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 +230,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 +239,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 +261,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<typeof spawnProcess> | 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<unknown>).catch(() => undefined)+ outer.return = async value => {+ isStopped = true+ ;(child as ReturnType<typeof spawnProcess> | 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.tsindex bb0378e849..7afa45cea0 100644--- a/plugins/ruflo-console/tui/run.ts+++ b/plugins/ruflo-console/tui/run.ts@@ -4,8 +4,8 @@* a test drives it without a terminal.*/import type { Depth } from './ansi'-import { cells, clean } 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@@ -24,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<string, string | undefined>; 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)@@ -37,34 +37,40 @@ export function depthOf(env: Record<string, string | undefined>): Depth {}const ESC = '\u001b'-/** Below this the frame is a short message, not a squeezed page; below NARROW the bar and the key line are the short forms. */+/** 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-export const NARROW_COLUMNS = 60-const LABELS: Record<TuiView, string> = { overview: 'Overview', cost: 'Cost', swarm: 'Swarm', events: 'Events', missions: 'Missions' }-const LETTER: Partial<Record<string, TuiView>> = { o: 'overview', c: 'cost', s: 'swarm', e: 'events', m: 'missions' }+const LABELS: Record<TuiView, string> = { overview: 'Overview', cost: 'Cost', swarm: 'Swarm', events: 'Events', missions: 'Missions', ai: 'AI' }+const LETTER: Partial<Record<string, TuiView>> = { 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/5 Swarm ›` when the terminal is narrow. Page names are ours, never from a file. */+/** 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 at = TUI_VIEWS.indexOf(view)-- if (columns < NARROW_COLUMNS) return `‹ ${at + 1}/${TUI_VIEWS.length} ${LABELS[view]} ›`-- return TUI_VIEWS.map((page, i) => {+ 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). */-export function keyLine(columns: number, place = ''): string {- const tiers = [`1-${TUI_VIEWS.length} or o c s e m page · tab next · r refresh · j/k scroll · q quit · read-only`, '1-5 page · tab next · r refresh · j/k scroll · q quit', '1-5 page · j/k scroll · q quit', '1-5 page · q quit']+/** 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 stringreturn `${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' | { page: TuiView } | 'next' | 'prev' | 'refresh' | 'down' | 'up' | 'pagedown' | 'pageup' | 'top' | 'bottom' | null@@ -112,6 +118,7 @@ export function keyOf(chunk: string): Key {}function paint(session: Session, io: TuiIO, depth: Depth, scroll: number, clear = false): number {+ const ai = session.page === 'ai' ? session.ai : nullconst raw = io.stdout.columns ?? 100const rows = Math.max(5, io.stdout.rows ?? 30)const reset = clear ? `${ESC}[2J` : ''@@ -128,17 +135,21 @@ function paint(session: Session, io: TuiIO, depth: Depth, scroll: number, clearlet 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)))+ // 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))}${depth === 'none' ? '' : `${ESC}[0m`}`+ 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(`${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}@@ -165,7 +176,7 @@ export async function runTui(options: TuiOptions, io: TuiIO): Promise<number> {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 {@@ -181,12 +192,17 @@ export async function runTui(options: TuiOptions, io: TuiIO): Promise<number> {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 (typeof key === 'object' && key !== null) (view = key.page), (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 += 1diff --git a/plugins/ruflo-console/tui/session.ts b/plugins/ruflo-console/tui/session.tsindex 3bd95c1f07..55290ff345 100644--- a/plugins/ruflo-console/tui/session.ts+++ b/plugins/ruflo-console/tui/session.ts@@ -5,32 +5,71 @@*/import { createController, type Controller } from '../hooks/controller'import type { Host } from '../hooks/host'-import { newState, type State, type ViewId } from '../hooks/state'+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: 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'] as const satisfies readonly ViewId[]+export const TUI_VIEWS = ['overview', 'cost', 'swarm', 'events', 'missions', 'ai'] as constexport 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<TuiView, 'ai'>++/** 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<NodeHostOptions, 'ai'> & {+ aiPage?: AiPageOptions & { codexBin?: string; fetch?: typeof fetch }+}++export type AiStatus = { codex: string; openrouter: string }export type Session = {state: Statecontroller: Controllerhost: 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<void>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) => voidstop: () => 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@@ -42,14 +81,26 @@ export function openSession(options: NodeHostOptions, host: Host = createNodeHosstate.pane.isFocused = truestate.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@@ -58,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++ 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.mjsindex 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 <repo cli.js> --json out.json --cap 6+// Flags: --legs claude,codex,openrouter,tui --cli-version latest|X.Y.Z --cli-path <repo cli.js> --json out.json --cap 6import { 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: setspend.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.mjsnew file mode 100644index 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> s · $<reported cost> · 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.tsindex d58bf3fb7c..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,8 +64,8 @@ describe('tui command', () => {expect(result).toMatchObject({ success: false, exitCode: 1 });});- it.skipIf(locateTuiBundle() === null)('opens each of the five pages with --plain, and refuses Room and anything else with exit 2 (real bundle)', async () => {- for (const view of ['overview', 'cost', 'swarm', 'events', 'missions']) {+ 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;@@ -77,6 +77,7 @@ describe('tui command', () => {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']) {@@ -84,6 +85,20 @@ describe('tui command', () => {}});+ 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.tsindex c31a6cc41d..8550237bbe 100644--- a/v3/@claude-flow/cli/src/commands/tui.ts+++ b/v3/@claude-flow/cli/src/commands/tui.ts@@ -2,7 +2,8 @@* `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, Cost, Swarm, Events and Missions (keys 1-5). 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).@@ -22,7 +23,7 @@ import { ownPluginDirs } from '../plugins/own-install.js';const __dirname = dirname(fileURLToPath(import.meta.url));-const VIEWS = ['overview', 'cost', 'swarm', 'events', 'missions'] as const;+const VIEWS = ['overview', 'cost', 'swarm', 'events', 'missions', 'ai'] as const;type TuiModule = { runTui: (options: Record<string, unknown>, io: Record<string, unknown>) => Promise<number>; 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<string, unknown> | 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, Cost, Swarm, Events, Missions; 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:<name>=<https-base-url>|<KEY_ENV>|<model>;... (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 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<CommandResult> {@@ -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.mdindex 3e0ff7e679..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; phase 2 (Swarm, Events and Missions, page bar and keys, resize, host capability flag) is implemented in PR 1 of the continuation; phases 3 and 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@@ -152,7 +152,12 @@ 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 (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** (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.+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-<platform>/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@@ -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**.