Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Isolate Claude Code and Codex question navigation (#1040)

Dee4787889866e2
diff --git a/cli/AGENTS.md b/cli/AGENTS.md
index b2522246a..ebcd450c4 100644
--- a/cli/AGENTS.md
+++ b/cli/AGENTS.md
@@ -25,7 +25,7 @@ they show as `harnessd`, `harnessd-core` and `harnessd-<process>` (`src/harnessd
|---|---|---|
| master | supervision only (`src/harnessd/`) | by `harness start`, `harness start -f`, or launchd or systemd after `harness service install` |
| core | sessions (`src/core/`) | always |
-| engine-claude, engine-codex | history, last-turn readers, live transcript parsers, runtime profiles/catalogs, screen interpretation and model control | on demand: an attach or read for that engine |
+| engine-claude, engine-codex | history, last-turn readers, live transcript parsers, runtime profiles/catalogs, screen interpretation, model control and question navigation | on demand: an attach or read for that engine |
| search | session search | always |
| viewers | the harness viewers, their remote streams and rendered surfaces, and the Store | always |
| edge | the shell service, workspaces, usage, the monitor, the project readers, the change-agent handoff, the recaps | always |
diff --git a/cli/ci-e2e-durations.json b/cli/ci-e2e-durations.json
index 0d5e17318..c7f273da1 100644
--- a/cli/ci-e2e-durations.json
+++ b/cli/ci-e2e-durations.json
@@ -9,6 +9,7 @@
"e2e/compaction.e2e.ts": 50000,
"e2e/core.e2e.ts": 121200,
"e2e/enginehomes.e2e.ts": 131900,
+ "e2e/engineQuestionControl.e2e.ts": 172000,
"e2e/history.e2e.ts": 113000,
"e2e/races.e2e.ts": 264300,
"e2e/recovery.e2e.ts": 28700,
diff --git a/cli/e2e/endurance.e2e.ts b/cli/e2e/endurance.e2e.ts
index 037a14dfc..28c54237d 100644
--- a/cli/e2e/endurance.e2e.ts
+++ b/cli/e2e/endurance.e2e.ts
@@ -16,6 +16,12 @@
* the service comes back and serves again. At the end every turn sent was started once, in the order
* sent, and no tmux client or process of the daemon outlives it.
*
+ * Questions are answered as the app answers them (e2e/harness/questionWork.ts): Claude Code a choice, a
+ * multiSelect through its review, a typed answer and a permission, Codex a choice and a permission. Each
+ * answer's result is awaited; a refused one is retried as a new intent, and every refusal is reported (a
+ * finding in the soak; in chaos, where an engine worker can be killed mid-answer, only an answer that never
+ * goes in is). At the end each engine's transcript must hold every answer that went in, once, in order.
+ *
* `SOAK_OUT=<folder>` keeps the samples (CSV) and the report (JSON). `SOAK_SEED` picks the run.
*/
import { mkdirSync, mkdtempSync, writeFileSync } from 'node:fs'
@@ -26,6 +32,7 @@ import { LocalClient, type Frame } from './harness/client.js'
import { IsolatedDaemon, until } from './harness/daemon.js'
import { Desk } from './harness/desk.js'
import { alive, everyPid, forget, harnessdProcesses, slopes, startSampler, strays, tmuxClients, TurnLedger, type Sample } from './harness/endurance.js'
+import { askAndAnswer, compareAnswers, engineAnswers, QUESTION_KINDS, summarizeAnswers, type QuestionEngine, type QuestionOutcome } from './harness/questionWork.js'
const ON = process.env.SOAK === '1'
function knob(name: string, fallback: number, min: number, max: number): number {
@@ -105,6 +112,28 @@ async function wakeServices(client: LocalClient): Promise<void> {
}
interface Findings { lines: string[] }
+/** Every question asked in a run, and whether a refused answer is a finding (the soak) or expected (chaos). */
+interface Questions { outcomes: Array<QuestionOutcome & { agentId: string; at: string }>; refusalsAreFindings: boolean }
+
+/** What the questions came to: answered, refused, never answered, and each engine's own record of them. */
+async function questionReport(d: IsolatedDaemon, client: LocalClient, questions: Questions, engines: Map<string, QuestionEngine>) {
+ const rows = (await client.request('agents_list', {}, 30_000)).agents as Array<Record<string, any>>
+ const ledger = [...engines].map(([agentId, engine]) => {
+ const mine = questions.outcomes.filter(outcome => outcome.agentId === agentId)
+ const sessionId = String(rows.find(row => row.id === agentId)?.sessionId ?? '')
+ return { agentId, engine, asked: mine.length, answered: mine.filter(outcome => outcome.ok).length,
+ ...compareAnswers(mine.filter(outcome => outcome.ok).map(outcome => outcome.expected!), sessionId ? engineAnswers(d.root, engine, sessionId) : []) }
+ })
+ const outcomes = questions.outcomes
+ return {
+ asked: outcomes.length, answered: outcomes.filter(outcome => outcome.ok).length,
+ refusedThenAnswered: outcomes.filter(outcome => outcome.ok && outcome.errors.length).length,
+ neverAnswered: outcomes.filter(outcome => !outcome.ok).length,
+ refusals: outcomes.filter(outcome => outcome.errors.length).map(({ at, agentId, kind, token, attempts, errors, ok }) => ({ at, agentId, kind, token, attempts, errors, ok })),
+ lost: ledger.reduce((sum, row) => sum + row.lost, 0), duplicated: ledger.reduce((sum, row) => sum + row.duplicated, 0),
+ ledger, latency: summarizeAnswers(outcomes),
+ }
+}
/** An agent's pane as it is now, kept beside the report (`SOAK_OUT`) once per agent and token. */
async function keepPane(d: IsolatedDaemon, agentId: string, name: string): Promise<void> {
@@ -125,26 +154,38 @@ async function keepPane(d: IsolatedDaemon, agentId: string, name: string): Promi
/** One agent's turns, one after another until `until`: plain, a tool call, a question answered, an
* interrupt, a flood of output; each carries a token the ledger checks. */
-async function agentLoop(d: IsolatedDaemon, agentId: string, tag: string, ledger: TurnLedger, deadline: () => boolean, rand: () => number, findings: Findings): Promise<number> {
+async function agentLoop(d: IsolatedDaemon, agentId: string, engine: QuestionEngine, tag: string, ledger: TurnLedger, deadline: () => boolean, rand: () => number, findings: Findings, questions: Questions): Promise<number> {
const client = await LocalClient.connect(d)
let n = 0
+ let asked = 0
try {
while (!deadline()) {
const token = `soak-${tag}-${n++}`
const pick = rand()
const kind = pick < 0.5 ? 'plain' : pick < 0.65 ? 'tool' : pick < 0.78 ? 'ask' : pick < 0.93 ? 'interrupt' : 'flood'
- const content = kind === 'plain' ? `${token} hello` : kind === 'tool' ? `!tool echo ${token}` : kind === 'ask' ? `!ask ${token}`
+ if (kind === 'ask') {
+ // Asked, answered through question_response, its result awaited and a refusal retried as a new intent.
+ const kinds = QUESTION_KINDS[engine]
+ ledger.send(agentId, token)
+ const outcome = await askAndAnswer(client, { id: agentId, engine }, kinds[asked % kinds.length], asked, { token, askMs: 60_000, endMs: 120_000, retries: 20 })
+ asked++
+ questions.outcomes.push({ ...outcome, agentId, at: new Date().toISOString() })
+ if (!outcome.ok || (outcome.errors.length && questions.refusalsAreFindings)) {
+ findings.lines.push(`${new Date().toISOString()} ${tag} ask ${outcome.kind} ${token}: ${outcome.errors.join('; ')}`)
+ await keepPane(d, agentId, `${tag}-${token}`)
+ }
+ // Never answered, its dialog is still up: this agent asks nothing more.
+ if (!outcome.ok) return n
+ forget(client)
+ await sleep(rand() * 1_500)
+ continue
+ }
+ const content = kind === 'plain' ? `${token} hello` : kind === 'tool' ? `!tool echo ${token}`
: kind === 'interrupt' ? `!holdtool sleep-${token}` : `!flood ${token}`
const ended = kind === 'interrupt' ? null : client.next(isTurn('turn_ended', agentId), 120_000, `turn_ended (${token})`)
- const asked = kind === 'ask' ? client.next((frame) => frame.type === 'commander_question' && frame.agentId === agentId, 60_000, `question (${token})`) : null
ledger.send(agentId, token)
client.send('message', { agentId, content })
try {
- if (asked) {
- const question = (await asked).payload ?? {}
- const shaped = (question.questions as Array<{ q: string }> | undefined)?.[0]
- client.send('question_response', { requestId: question.requestId, agentId, answers: shaped ? { [shaped.q]: 'Coffee' } : {} })
- }
if (kind === 'interrupt') {
await client.next((frame) => frame.type === 'turn_started' && frame.agentId === agentId, 60_000, `turn_started (${token})`)
await sleep(800 + rand() * 1_500)
@@ -230,6 +271,8 @@ async function dialLoop(desk: Desk, deadline: () => boolean, rand: () => number)
return plugs
}
+const engineOf = (index: number): QuestionEngine => index % 2 ? 'codex' : 'claude'
+
async function createAgents(d: IsolatedDaemon, count: number): Promise<string[]> {
const client = await LocalClient.connect(d)
const ids: string[] = []
@@ -237,7 +280,7 @@ async function createAgents(d: IsolatedDaemon, count: number): Promise<string[]>
for (let i = 0; i < count; i++) {
const cwd = join(d.projectsDir, `soak-${i}`)
mkdirSync(cwd, { recursive: true })
- const created = await client.request('agent_create', { engine: i % 2 ? 'codex' : 'claude', cwd, bypassPermission: true }, 90_000)
+ const created = await client.request('agent_create', { engine: engineOf(i), cwd, bypassPermission: true }, 90_000)
expect(created.error, JSON.stringify(created)).toBeUndefined()
ids.push(created.agent.id)
}
@@ -291,12 +334,13 @@ describe.skipIf(!ON)('the daemon over time, every service in its own process', (
const stopSampling = startSampler(d, SAMPLE_MS, join(OUT, 'soak-samples.csv'), samples)
cleanup.push(stopSampling)
const findings: Findings = { lines: [] }
+ const questions: Questions = { outcomes: [], refusalsAreFindings: true }
const ends = Date.now() + SOAK_MINUTES * 60_000
let stopping = false
cleanup.push(() => { stopping = true })
const deadline = () => stopping || Date.now() >= ends
const [turns, windows, plugs] = await Promise.all([
- Promise.all(agentIds.map((id, i) => agentLoop(d, id, `a${i}`, ledger, deadline, random(SEED + i + 1), findings))),
+ Promise.all(agentIds.map((id, i) => agentLoop(d, id, engineOf(i), `a${i}`, ledger, deadline, random(SEED + i + 1), findings, questions))),
deskLoop(d, agentIds, deadline, random(SEED + 100), findings),
dialLoop(desk, deadline, random(SEED + 200)),
])
@@ -304,15 +348,18 @@ describe.skipIf(!ON)('the daemon over time, every service in its own process', (
clearInterval(reading)
await sleep(3_000)
const differences = ledger.differences()
+ const asked = await questionReport(d, observer, questions, new Map(agentIds.map((id, i) => [id, engineOf(i)])))
observer.close()
const warmup = Math.min(10 * 60_000, (SOAK_MINUTES * 60_000) / 4)
const growth = slopes(samples, warmup, Math.max(SAMPLE_MS * 4, 2 * 60_000))
- const report = { minutes: SOAK_MINUTES, agents: AGENTS, turns: turns.reduce((sum, n) => sum + n, 0), windows, plugs, ledger: ledger.totals(), differences, findings: findings.lines, slopes: growth, coresStarted: d.coresStarted() }
+ const report = { minutes: SOAK_MINUTES, agents: AGENTS, turns: turns.reduce((sum, n) => sum + n, 0), windows, plugs, ledger: ledger.totals(), differences, questions: asked, findings: findings.lines, slopes: growth, coresStarted: d.coresStarted() }
writeFileSync(join(OUT, 'soak-report.json'), JSON.stringify(report, null, 2))
console.log(`soak report: ${join(OUT, 'soak-report.json')}\n${growth.map((s) => `${s.name}: ${s.first.toFixed(0)} → ${s.last.toFixed(0)} MiB, ${s.perHour?.toFixed(1) ?? 'unmeasured'} MiB/h; fds ${s.fdsFirst} → ${s.fdsLast}, ${s.fdsPerHour?.toFixed(1)}/h; restarts ${s.restarts}`).join('\n')}`)
expect(d.coresStarted()).toBe(1)
expect(differences).toEqual([])
expect(findings.lines).toEqual([])
+ expect(asked.answered, 'no question answered').toBeGreaterThan(0)
+ expect(asked.ledger.filter(row => !row.equal)).toEqual([])
expect(growth.map(p => p.name).sort()).toEqual(['master', 'core', ...Object.keys(PROBES)].sort())
for (const process of growth) {
expect(process.samples, `${process.name} sample count`).toBeGreaterThanOrEqual(2)
@@ -346,6 +393,9 @@ describe.skipIf(!ON)('the daemon over time, every service in its own process', (
const reading = setInterval(() => ledger.drain(), 1_000)
cleanup.push(() => clearInterval(reading))
const findings: Findings = { lines: [] }
+ // A killed engine worker fails the answer it was entering (it never resumes in a replacement), so a
+ // refusal here is expected; an answer that never goes in, or goes in twice, is not.
+ const questions: Questions = { outcomes: [], refusalsAreFindings: false }
// The experiments and the devices, woken as the apps wake them, so their processes are in the run too.
const waker = await LocalClient.connect(d)
await desk.plug('CHAOS-DIAL', 'e2:e0:00:00:00:5b')
@@ -426,7 +476,7 @@ describe.skipIf(!ON)('the daemon over time, every service in its own process', (
}
})()
const [turns] = await Promise.all([
- Promise.all(agentIds.map((id, i) => agentLoop(d, id, `c${i}`, ledger, deadline, random(SEED + 2_000 + i), findings))),
+ Promise.all(agentIds.map((id, i) => agentLoop(d, id, engineOf(i), `c${i}`, ledger, deadline, random(SEED + 2_000 + i), findings, questions))),
deskLoop(d, agentIds, deadline, random(SEED + 3_000), findings),
chaos,
])
@@ -434,6 +484,7 @@ describe.skipIf(!ON)('the daemon over time, every service in its own process', (
clearInterval(reading)
await sleep(3_000)
const differences = ledger.differences()
+ const asked = await questionReport(d, observer, questions, new Map(agentIds.map((id, i) => [id, engineOf(i)])))
observer.close()
waker.close()
await desk.unplug('CHAOS-DIAL')
@@ -441,13 +492,15 @@ describe.skipIf(!ON)('the daemon over time, every service in its own process', (
const clients = await until('every tmux client to be let go', async () => ((await tmuxClients(d)) === 0 ? true : null), 30_000, 500).catch(async () => `still ${await tmuxClients(d)}`)
const pids = everyPid(d)
const growth = slopes(samples, 0, Math.max(SAMPLE_MS * 4, 2 * 60_000))
- const report = { minutes: CHAOS_MINUTES, agents: AGENTS, turns: turns.reduce((sum, n) => sum + n, 0), events, ledger: ledger.totals(), differences, findings: findings.lines, slopes: growth, coresStarted: d.coresStarted(), tmuxClients: clients }
+ const report = { minutes: CHAOS_MINUTES, agents: AGENTS, turns: turns.reduce((sum, n) => sum + n, 0), events, ledger: ledger.totals(), differences, questions: asked, findings: findings.lines, slopes: growth, coresStarted: d.coresStarted(), tmuxClients: clients }
writeFileSync(join(OUT, 'chaos-report.json'), JSON.stringify(report, null, 2))
console.log(`chaos report: ${join(OUT, 'chaos-report.json')}: ${events.length} events, ${report.turns} turns`)
expect(d.coresStarted()).toBe(1)
expect(differences).toEqual([])
expect(findings.lines).toEqual([])
expect(events.length, 'no chaos event exercised').toBeGreaterThan(0)
+ expect(asked.answered, 'no question answered').toBeGreaterThan(0)
+ expect(asked.ledger.filter(row => !row.equal)).toEqual([])
if (CHAOS_MINUTES >= 15) {
expect(new Set(events.map(event => event.action))).toEqual(new Set(actions))
expect(new Set(events.flatMap(event => event.targets as string[]))).toEqual(new Set(Object.keys(PROBES)))
diff --git a/cli/e2e/engineQuestionControl.e2e.ts b/cli/e2e/engineQuestionControl.e2e.ts
new file mode 100644
index 000000000..ee3f3ceaa
--- /dev/null
+++ b/cli/e2e/engineQuestionControl.e2e.ts
@@ -0,0 +1,263 @@
+/**
+ * Question answers whose keystrokes an engine worker chooses (`Engine.questionControl`), on a real private
+ * daemon, tmux, supervised engine workers and RPC; deterministic CLIs, no model accounts.
+ *
+ * The worker is stopped between two keystrokes of one answer by the fake engine itself, the moment the
+ * named keystroke reaches it (fakeEngine.mjs `question-keys-<engine>.signal`), so the stop lands inside
+ * the step on every run rather than whenever a poll happens to notice. What reached the engine is read
+ * back from its own key log, not from the screen.
+ */
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient, type Frame } from './harness/client.js'
+import { IsolatedDaemon, until } from './harness/daemon.js'
+import { alive, harnessdProcesses } from './harness/endurance.js'
+
+type Engine = 'claude' | 'codex'
+type Agent = Record<string, any>
+type Shaped = { key: string; q: string; options: string[]; multi: boolean }
+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
+const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type === type && frame.agentId === agentId
+
+/**
+ * One engine's question: the prompt that asks it, the answer the worker is stopped in (and the keys of it
+ * that reach the engine first), and a different answer: the keys it takes on a fresh dialog, and after
+ * the interrupted one.
+ */
+const QUESTIONS = {
+ // Five toggles and a Tab in one step: stopped after the second toggle.
+ claude: { prompt: '!askmany', first: ['Cheese', 'Ham', 'Basil', 'Olives', 'Onion'], stopAfter: 2, typed: ['1', '2'],
+ second: ['Basil', 'Peppers'], freshKeys: ['3', '6', 'Tab', '1'],
+ // The approved set is exact: the two rows the interrupted step left checked are unchecked again.
+ secondKeys: ['1', '2', '3', '6', 'Tab', '1'], chose: 'you chose Basil, Peppers' },
+ // The digit and its Enter in one step: stopped after the digit.
+ codex: { prompt: '!ask', first: ['Coffee'], stopAfter: 1, typed: ['2'],
+ second: ['Tea'], freshKeys: ['1', 'Enter'], secondKeys: ['1', 'Enter'], chose: 'you chose Tea' },
+} as const
+
+describe('engine question-control workers', () => {
+ let daemon: IsolatedDaemon | undefined, client: LocalClient | undefined
+ const frozen = new Set<number>()
+ afterEach(async () => {
+ for (const pid of frozen) { try { process.kill(pid, 'SIGCONT') } catch { /* gone */ } }
+ frozen.clear()
+ client?.close(); await daemon?.close(); client = undefined; daemon = undefined
+ })
+ async function fresh(env: Record<string, string> = {}) {
+ const d = daemon = await IsolatedDaemon.create({ env })
+ onTestFailed(() => console.log(`---- daemon log\n${d.log().split('\n').slice(-250).join('\n')}\n---- keys\n${JSON.stringify({ claude: keys(d, 'claude'), codex: keys(d, 'codex') })}`))
+ await d.start()
+ const c = client = await LocalClient.connect(d)
+ return { d, c }
+ }
+ const rows = async (c: LocalClient) => (await c.request<{ agents: Agent[] }>('agents_list', {}, 30_000)).agents
+ async function create(d: IsolatedDaemon, c: LocalClient, engine: Engine, folder: string): Promise<Agent> {
+ const cwd = join(d.projectsDir, folder); mkdirSync(cwd, { recursive: true })
+ const created = await c.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ return until(`${folder} to bind its conversation`, async () => {
+ const row = (await rows(c)).find((agent) => agent.id === created.agent.id)
+ return row?.sessionId && row.status === 'active' ? row : null
+ }, 60_000, 200)
+ }
+ async function turn(c: LocalClient, agent: Agent, content: string) {
+ const ended = c.next(isTurn('turn_ended', agent.id), 45_000, `turn_ended: ${content}`)
+ c.send('message', { agentId: agent.id, content })
+ await ended
+ }
+ async function ask(c: LocalClient, agent: Agent, prompt: string): Promise<{ requestId: string; shaped: Shaped }> {
+ const asked = c.next((frame) => frame.type === 'commander_question' && frame.agentId === agent.id, 30_000, `${prompt} question`)
+ c.send('message', { agentId: agent.id, content: prompt })
+ const payload = (await asked).payload!
+ return { requestId: payload.requestId, shaped: payload.questions[0] }
+ }
+ /** The answer as a window sends one it reviewed: the exact question, and for a multi-select the exact set. */
+ function answer(c: LocalClient, agent: Agent, requestId: string, shaped: Shaped, labels: readonly string[]): Promise<Record<string, any>> {
+ const result = c.next((frame) => frame.type === 'question_response_result' && frame.payload?.requestId === requestId, 60_000, 'question_response_result')
+ c.send('question_response', { requestId, agentId: agent.id, answers: { [shaped.key]: labels.join(', ') },
+ expectedQuestions: [shaped], ...(shaped.multi ? { selectedLabels: { [shaped.key]: [...labels] } } : {}) })
+ return result.then((frame) => frame.payload as Record<string, any>)
+ }
+ const keyLog = (d: IsolatedDaemon, engine: Engine) => join(d.engineConfig.root, `question-keys-${engine}`)
+ const keys = (d: IsolatedDaemon, engine: Engine): string[] => existsSync(keyLog(d, engine)) ? readFileSync(keyLog(d, engine), 'utf8').split('\n').filter(Boolean) : []
+ /** The fake engine signals `pid` once its key log holds `after` keys, before it acts on the last one. */
+ const arm = (d: IsolatedDaemon, engine: Engine, pid: number, signal: NodeJS.Signals, after: number, delayMs = 0) =>
+ writeFileSync(`${keyLog(d, engine)}.signal`, JSON.stringify({ pid, signal, after, delayMs }))
+ /** What the engine noted once it sent the signal, or null before. */
+ const fired = (d: IsolatedDaemon, engine: Engine) => {
+ const note = existsSync(`${keyLog(d, engine)}.fired`) ? readFileSync(`${keyLog(d, engine)}.fired`, 'utf8') : ''
+ return note.includes('"outcome"') ? note : null
+ }
+ const workerPid = (d: IsolatedDaemon, engine: Engine) => harnessdProcesses(d).get(`engine-${engine}`)
+ const replaced = (d: IsolatedDaemon, engine: Engine, old: number) => until(`a replacement engine-${engine} worker`, () => {
+ const pid = workerPid(d, engine)
+ return pid && pid !== old && alive(pid) ? pid : null
+ }, 30_000, 100)
+ const panePid = async (d: IsolatedDaemon, agent: Agent) => (await d.tmux.run('display-message', '-p', '-t', agent.tmuxPane, '#{pane_pid}')).trim()
+
+ it.each([
+ ['claude', 'SIGKILL'], ['claude', 'SIGSTOP'], ['codex', 'SIGKILL'], ['codex', 'SIGSTOP'],
+ ] as const)('%s: a worker stopped by %s inside one answer\'s step fails that answer, types nothing more, and a new answer succeeds once it is back', async (engine, signal) => {
+ const spec = QUESTIONS[engine]
+ const other: Engine = engine === 'claude' ? 'codex' : 'claude'
+ // A frozen worker is declared hung after 4 s (and a third more grace) and killed; a replacement waits
+ // 8 s more, so the other engine's turn below runs while this engine's worker is dead or frozen.
+ const { d, c } = await fresh({ HARNESSD_SERVICE_HEARTBEAT_TIMEOUT_MS: '4000', HARNESSD_SERVICE_STOP_GRACE_MS: '100',
+ HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '8000', HARNESSD_SERVICE_MAX_BACKOFF_MS: '8000' })
+ const agent = await create(d, c, engine, `q-${engine}`)
+ const bystander = await create(d, c, other, `q-${other}`)
+ await turn(c, bystander, `${other} before the question`)
+ const { requestId, shaped } = await ask(c, agent, spec.prompt)
+ expect(shaped.multi).toBe(engine === 'claude')
+ const core = d.corePid(), worker = workerPid(d, engine)!, otherWorker = workerPid(d, other)!
+ expect(worker && otherWorker).toBeTruthy()
+ const pane = await panePid(d, agent)
+ const before = keys(d, engine).length
+ arm(d, engine, worker, signal, before + spec.stopAfter)
+ if (signal === 'SIGSTOP') frozen.add(worker)
+ const started = Date.now()
+ const interrupted = answer(c, agent, requestId, shaped, spec.first).then((result) => ({ result, ms: Date.now() - started }))
+ await until('the worker stopped inside the step', () => fired(d, engine), 20_000, 20)
+ expect(fired(d, engine)).toContain('"outcome":"sent"')
+
+ // Meanwhile the other engine's agent takes a whole turn, and the core answers a request.
+ await turn(c, bystander, `${other} while ${engine} has no worker`)
+ expect((await rows(c)).map((row) => row.id).sort()).toEqual([agent.id, bystander.id].sort())
+ expect(workerPid(d, engine)).toBe(worker) // no replacement yet: this all ran during the outage
+ if (signal === 'SIGKILL') expect(alive(worker)).toBe(false)
+
+ // Failed, visibly: at once for a dead worker, once the master kills a frozen one.
+ const failed = await interrupted
+ expect(failed.result.error, JSON.stringify(failed)).toBe('ANSWER_FAILED')
+ expect(failed.ms).toBeLessThan(signal === 'SIGKILL' ? 5_000 : 15_000)
+ // An answer while there is no worker fails at once (its screen is read in that worker too, so the question
+ // cannot be read), and nothing is typed inline in its place.
+ const outage = await answer(c, agent, requestId, shaped, spec.second)
+ expect(outage.error, JSON.stringify(outage)).toBe('ANSWER_FAILED')
+ expect(workerPid(d, engine)).toBe(worker)
+ expect(keys(d, engine).slice(before)).toEqual(spec.typed)
+ await until('the stopped worker gone', () => !alive(worker), 15_000, 100)
+ frozen.delete(worker)
+ await replaced(d, engine, worker)
+ // Back, and given time: the interrupted step is not resumed, by the new worker or anyone.
+ await sleep(2_500)
+ expect(keys(d, engine).slice(before)).toEqual(spec.typed)
+ const screen = await d.capture(agent.tmuxPane)
+ expect(screen).toContain(shaped.q)
+ expect(screen).not.toContain('Review your answers')
+ expect(screen).not.toContain('you chose')
+ if (engine === 'claude') expect(screen).toMatch(/\[✔\] Cheese[\s\S]*\[✔\] Ham[\s\S]*\[ \] Basil/)
+
+ // A new answer is a new intent, and a different one: it succeeds, and nothing of the old one follows it.
+ const ended = c.next(isTurn('turn_ended', agent.id), 45_000, 'the answered turn')
+ const retried = await answer(c, agent, requestId, shaped, spec.second)
+ expect(retried.error, JSON.stringify(retried)).toBeUndefined()
+ await ended
+ expect(await d.capture(agent.tmuxPane)).toContain(spec.chose)
+ expect(keys(d, engine).slice(before)).toEqual([...spec.typed, ...spec.secondKeys])
+ await turn(c, agent, `${engine} after recovery`)
+ await turn(c, bystander, `${other} after recovery`)
+ expect(await panePid(d, agent)).toBe(pane)
+ expect(workerPid(d, other)).toBe(otherWorker)
+ expect(d.corePid()).toBe(core)
+ expect(d.coresStarted()).toBe(1)
+ })
+
+ it('claude: a worker frozen inside a step and woken after core revoked it types nothing more', async () => {
+ // Longer than the step's 30 s deadline: the default service heartbeat (30 s and its grace) is too.
+ const { d, c } = await fresh({ HARNESSD_SERVICE_HEARTBEAT_TIMEOUT_MS: '60000', HARNESSD_SERVICE_STOP_GRACE_MS: '100', HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200' })
+ const spec = QUESTIONS.claude
+ const agent = await create(d, c, 'claude', 'q-woken')
+ const bystander = await create(d, c, 'codex', 'q-woken-codex')
+ const { requestId, shaped } = await ask(c, agent, spec.prompt)
+ const core = d.corePid(), worker = workerPid(d, 'claude')!
+ const before = keys(d, 'claude').length
+ // Frozen a moment after the second toggle, once the worker has heard it went in and is waiting out
+ // the repaint before the third: the third is the first thing it does when woken.
+ arm(d, 'claude', worker, 'SIGSTOP', before + spec.stopAfter, 120)
+ frozen.add(worker)
+ const started = Date.now()
+ const interrupted = answer(c, agent, requestId, shaped, spec.first).then((result) => ({ result, ms: Date.now() - started }))
+ await until('the worker frozen inside the step', () => fired(d, 'claude'), 20_000, 20)
+ expect(fired(d, 'claude')).toContain('"outcome":"sent"')
+ expect(keys(d, 'claude').slice(before)).toEqual(spec.typed)
+ await turn(c, bystander, 'codex while claude is frozen')
+ // Failed at the step's own deadline (30 s), not before: core held the step for its whole life.
+ const failed = await interrupted
+ expect(failed.result.error, JSON.stringify(failed)).toBe('ANSWER_FAILED')
+ expect(failed.ms).toBeGreaterThan(25_000)
+ expect(alive(worker)).toBe(true) // still frozen: core gave up on the step, not on the process
+ // Woken now, its next toggle is already due. Core has revoked the step: nothing reaches the pane.
+ process.kill(worker, 'SIGCONT')
+ frozen.delete(worker)
+ await sleep(3_000)
+ expect(keys(d, 'claude').slice(before)).toEqual(spec.typed)
+ expect(await d.capture(agent.tmuxPane)).not.toContain('Review your answers')
+ // Whether the woken worker recycled itself at its own deadline or carries on, a new answer works.
+ await until('a live claude worker', () => { const pid = workerPid(d, 'claude'); return pid && alive(pid) ? pid : null }, 30_000, 100)
+ const ended = c.next(isTurn('turn_ended', agent.id), 45_000, 'the answered turn')
+ const retried = await answer(c, agent, requestId, shaped, spec.second)
+ expect(retried.error, JSON.stringify(retried)).toBeUndefined()
+ await ended
+ expect(await d.capture(agent.tmuxPane)).toContain(spec.chose)
+ expect(keys(d, 'claude').slice(before)).toEqual([...spec.typed, ...spec.secondKeys])
+ expect(d.corePid()).toBe(core)
+ expect(d.coresStarted()).toBe(1)
+ })
+
+ it.each(['claude', 'codex'] as const)('%s: explicit inline mode answers a question end to end', async (engine) => {
+ const { d, c } = await fresh({ HARNESSD_SERVICES: 'none' })
+ const spec = QUESTIONS[engine]
+ const agent = await create(d, c, engine, `q-inline-${engine}`)
+ const { requestId, shaped } = await ask(c, agent, spec.prompt)
+ const ended = c.next(isTurn('turn_ended', agent.id), 45_000, 'the answered turn')
+ const result = await answer(c, agent, requestId, shaped, spec.second)
+ expect(result.error, JSON.stringify(result)).toBeUndefined()
+ await ended
+ expect(await d.capture(agent.tmuxPane)).toContain(spec.chose)
+ // A fresh dialog: only the rows the answer checks, then on (Claude Code's review submits it).
+ expect(keys(d, engine)).toEqual(spec.freshKeys)
+ expect(workerPid(d, engine)).toBeUndefined()
+ expect(d.coresStarted()).toBe(1)
+ })
+
+ it.each(['claude', 'codex'] as const)('%s: a window cannot drive question control, even while a worker holds a live grant mid-step', async (engine) => {
+ // The worker is paused inside a real answer's step, so core holds a live grant for it, and woken well
+ // within the step's deadline: a pause, not an interruption, so the step then finishes.
+ const { d, c } = await fresh({ HARNESSD_SERVICE_HEARTBEAT_TIMEOUT_MS: '60000' })
+ const spec = QUESTIONS[engine]
+ const agent = await create(d, c, engine, `q-private-${engine}`)
+ const { requestId, shaped } = await ask(c, agent, spec.prompt)
+ const worker = workerPid(d, engine)!
+ arm(d, engine, worker, 'SIGSTOP', 1)
+ frozen.add(worker)
+ const ended = c.next(isTurn('turn_ended', agent.id), 60_000, 'the answered turn')
+ const answered = answer(c, agent, requestId, shaped, spec.second)
+ await until('the worker paused inside the step', () => fired(d, engine), 20_000, 20)
+ const step = { kind: 'select', row: { number: '1', label: shaped.options[0], checked: false } }
+ const token = 'a'.repeat(64)
+ for (const [type, payload] of [
+ ['engine_question_control_capabilities', { version: 1 }],
+ ['engine_question_control_apply', { version: 1, step, token }],
+ ['engine_question_control_apply', { version: 1, step, token, agentId: agent.id, sessionId: agent.sessionId }],
+ ['engine.questionControl', { version: 1, query: 'engine.questionControl', token, action: { kind: 'key', key: 'Enter' } }],
+ ['engine.questionControl', { version: 1, query: 'engine.questionControl', token, action: { kind: 'text', text: 'typed by a window' } }],
+ ] as const) {
+ const reply = await c.request(type, payload as Record<string, unknown>, 5_000)
+ expect(reply.error, `${type}: ${JSON.stringify(reply)}`).toBe('UNSUPPORTED')
+ }
+ await sleep(500)
+ expect(keys(d, engine)).toEqual(spec.freshKeys.slice(0, 1))
+ expect(await d.capture(agent.tmuxPane)).not.toContain('typed by a window')
+ process.kill(worker, 'SIGCONT')
+ frozen.delete(worker)
+ const result = await answered
+ expect(result.error, JSON.stringify(result)).toBeUndefined()
+ await ended
+ expect(await d.capture(agent.tmuxPane)).toContain(spec.chose)
+ expect(keys(d, engine)).toEqual(spec.freshKeys)
+ expect(workerPid(d, engine)).toBe(worker)
+ expect(d.coresStarted()).toBe(1)
+ })
+})
diff --git a/cli/e2e/engineReaders.e2e.ts b/cli/e2e/engineReaders.e2e.ts
index ed593352b..f0cc82398 100644
--- a/cli/e2e/engineReaders.e2e.ts
+++ b/cli/e2e/engineReaders.e2e.ts
@@ -59,7 +59,7 @@ describe('Claude Code and Codex readers in their own processes', () => {
expect(readerPid(d, 'claude')).toBeUndefined()
expect(readerPid(d, 'codex')).toBeUndefined()
for (const type of ['engine_history_page', 'engine_last_turn', 'engine_live_capabilities', 'engine_live_prepare',
- 'engine_live_read', 'engine_live_part', 'engine_live_close', 'engine_live_forget', 'engine_runtime_capabilities', 'engine_runtime_read', 'engine_screen_capabilities', 'engine_screen_read', 'engine_model_control_capabilities', 'engine_model_control_validate', 'engine_model_control_apply']) {
+ 'engine_live_read', 'engine_live_part', 'engine_live_close', 'engine_live_forget', 'engine_runtime_capabilities', 'engine_runtime_read', 'engine_screen_capabilities', 'engine_screen_read', 'engine_model_control_capabilities', 'engine_model_control_validate', 'engine_model_control_apply', 'engine_question_control_capabilities', 'engine_question_control_apply']) {
const answer = await c.request(type, { version: 1, session: { transcriptPath: '/etc/passwd' } })
expect(answer.error).toBe('UNSUPPORTED')
}
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjs
index 5d82d3b73..41effd7db 100644
--- a/cli/e2e/harness/fakeEngine.mjs
+++ b/cli/e2e/harness/fakeEngine.mjs
@@ -16,7 +16,8 @@
// before answering (the transcripts that crashed the daemon on 2026-10-03), `!hold` leaves the turn
// open until the next prompt, `!holdtool <command>` leaves it open with that tool still running (an
// interrupt then writes the tool's aborted output before the turn's end, as the CLIs do), `!ask` asks the person which drink they would like in the engine's own
-// dialog and answers with their choice, `!permit <command>` asks permission to run a command the way
+// dialog and answers with their choice (Claude Code's "Type something." row takes a typed answer too;
+// `!askmany`, Claude Code: which toppings, a multiSelect question of six), `!permit <command>` asks permission to run a command the way
// the engine does and runs it only if allowed, `!flood <KiB>` prints that much to the terminal, in
// numbered lines, the way a build log or a long diff does, `!clear` starts a new conversation in the
// same pane as Claude Code's `/clear` and Codex's `/new` do, `!compact` compacts the conversation as
@@ -56,7 +57,7 @@
// child in the same process group and terminal (`codexWrapper`).
import { execFileSync, spawn } from 'node:child_process'
import { randomUUID } from 'node:crypto'
-import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
import { homedir } from 'node:os'
import { dirname, isAbsolute, join, relative, resolve } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
@@ -650,9 +651,55 @@ export async function run(engine, config = {}, { native = false } = {}) {
let notes = ''
const QUESTION = 'Which drink would you like?'
const CHOICES = [['Tea', 'Lighter, steeped leaves.'], ['Coffee', 'Stronger, roasted beans.']]
+ // `!askmany` (Claude Code): one multiSelect question, drawn as Claude Code draws one
+ // (__fixtures__/question-multi.txt and question-review.txt). A digit toggles its row, Tab moves on
+ // to the Submit tab's review, whose 1 submits the checked rows and 2 goes back; Esc cancels.
+ const MANY = 'Which toppings do you want?'
+ const TOPPINGS = [['Cheese', 'Melted and savory.'], ['Ham', 'Salty cured meat.'], ['Basil', 'Fresh herb, aromatic.'],
+ ['Olives', 'Briny and dark.'], ['Onion', 'Sweet once cooked.'], ['Peppers', 'Crisp and bright.']]
+ // Every key a dialog takes, one per line (`question-keys-<engine>` in the test's root): what reached the
+ // engine, whoever typed it. A test can arm `question-keys-<engine>.signal`, `{ pid, signal, after, delayMs? }`:
+ // once `after` keys in all have reached a dialog, the engine signals that process before it acts on the
+ // key, and leaves `.fired` beside it. That is how a test stops an engine worker between two keystrokes of
+ // one answer, exactly, rather than whenever its own poll happens to notice the first.
+ const questionKeys = join(config.root, `question-keys-${engine}`)
+ const keyName = (key) => key.startsWith('\x1b[200~') ? `paste:${key.slice(6).replace(/\x1b\[201~$/, '')}`
+ : ({ '\r': 'Enter', '\n': 'Enter', '\t': 'Tab', '\x1b': 'Escape', '\x1b[A': 'Up', '\x1b[B': 'Down' })[key] ?? key
+ const noteDialogKey = (key) => {
+ appendFileSync(questionKeys, `${keyName(key)}\n`)
+ const armed = `${questionKeys}.signal`
+ if (!existsSync(armed)) return
+ let trigger
+ try { trigger = JSON.parse(readFileSync(armed, 'utf8')) } catch { return }
+ const count = readFileSync(questionKeys, 'utf8').split('\n').filter(Boolean).length
+ if (count < trigger.after) return
+ renameSync(armed, `${questionKeys}.fired`)
+ const fire = () => {
+ let outcome = 'sent'
+ try { process.kill(trigger.pid, trigger.signal) } catch (error) { outcome = String(error?.code ?? error) }
+ appendFileSync(`${questionKeys}.fired`, `\n${JSON.stringify({ count, outcome })}\n`)
+ }
+ // `delayMs`: a moment later instead, once the worker has heard that the key went in.
+ if (trigger.delayMs) setTimeout(fire, trigger.delayMs)
+ else fire()
+ }
const drawDialog = () => {
const rule = '─'.repeat(60)
const mark = (i, on) => (dialog.cursor === i ? on : ' ')
+ if (dialog.kind === 'many') {
+ const lines = dialog.review
+ ? [rule, '← ☒ Toppings ✔ Submit →', '', 'Review your answers', '', ` ● ${MANY}`,
+ ` → ${TOPPINGS.filter((_, i) => dialog.checked.has(i)).map(([label]) => label).join(', ')}`, '',
+ 'Ready to submit your answers?', '', `${mark(0, '❯')} 1. Submit answers`, `${mark(1, '❯')} 2. Cancel`]
+ : [rule, '← ☐ Toppings ✔ Submit →', '', MANY, '',
+ ...TOPPINGS.flatMap(([label, description], i) => [`${mark(i, '❯')} ${i + 1}. [${dialog.checked.has(i) ? '✔' : ' '}] ${label}`, ` ${description}`]),
+ `${mark(TOPPINGS.length, '❯')} ${TOPPINGS.length + 1}. [ ] Type something`, ' Submit', rule,
+ ` ${TOPPINGS.length + 2}. Chat about this`, '', 'Enter to select · ↑/↓ to navigate · Esc to cancel']
+ eraseDialog()
+ process.stdout.write(`\r\n${lines.join('\r\n')}\r\n`)
+ dialog.drawn = lines.length + 1
+ return
+ }
// A permission prompt, as the CLIs draw one (__fixtures__/permission-claude.txt, permission-codex.txt).
const command = dialog.command
const lines = dialog.kind === 'permit' ? (engine === 'claude'
@@ -665,7 +712,9 @@ export async function run(engine, config = {}, { native = false } = {}) {
: engine === 'claude'
? [rule, ' ☐ Drink', '', QUESTION, '',
...CHOICES.flatMap(([label, description], i) => [`${mark(i, '❯')} ${i + 1}. ${label}`, ` ${description}`]),
- ' 3. Type something.', rule, ' 4. Chat about this', '', 'Enter to select · ↑/↓ to navigate · Esc to cancel']
+ // Its free-text row: chosen, what is typed or pasted goes in under it, and Enter sends that.
+ `${mark(2, '❯')} 3. Type something.`, ...(dialog.typed === undefined ? [] : [` ${dialog.typed}`]),
+ rule, ' 4. Chat about this', '', 'Enter to select · ↑/↓ to navigate · Esc to cancel']
: [' Question 1/1 (1 unanswered)', ` ${QUESTION}`,
...CHOICES.map(([label, description], i) => ` ${mark(i, '›')} ${i + 1}. ${label.padEnd(7)} ${description}`),
` ${mark(2, '›')} 3. None of the above Optionally, add details in notes (tab).`,
@@ -687,9 +736,16 @@ export async function run(engine, config = {}, { native = false } = {}) {
// Accept). In a question, Claude Code drops the paste the same way and Enter picks the focused option;
// Codex takes a paste as notes on the focused option (request_user_input `handle_paste`) and Enter
// submits it. Digits pick a row; Codex's `y` approves; arrows move; Esc declines or cancels.
- const dialogKeys = (chunk) => {
- for (const key of chunk.match(/\x1b\[200~[\s\S]*?(?:\x1b\[201~|$)|\x1b\[[AB]|\x1b|\r|\n|./gs) ?? []) {
+ // A paste split across reads is one paste: its start is held until its end arrives.
+ let dialogPaste = ''
+ const dialogKeys = (input) => {
+ let chunk = dialogPaste + input
+ dialogPaste = ''
+ const opened = chunk.lastIndexOf('\x1b[200~')
+ if (opened >= 0 && chunk.indexOf('\x1b[201~', opened) < 0) { dialogPaste = chunk.slice(opened); chunk = chunk.slice(0, opened) }
+ for (const key of chunk.match(/\x1b\[200~[\s\S]*?(?:\x1b\[201~|$)|\x1b\[[ABCD]|\x1b|\r|\n|\x7f|./gs) ?? []) {
if (!dialog) return
+ noteDialogKey(key)
const settle = (choice) => {
// An old dialog can survive in tmux scrollback after a redraw/resize, as in the chaos run.
// Keep the whole frame for that acceptance case; the composer below it is the live screen.
@@ -697,6 +753,37 @@ export async function run(engine, config = {}, { native = false } = {}) {
else eraseDialog()
const asked = dialog; dialog = null; notes = asked.notes ?? ''; drawComposer(); asked.resolve(choice)
}
+ if (dialog.kind === 'many') {
+ // A paste is dropped, as in Claude Code's other dialogs; Enter on a row toggles it.
+ if (key.startsWith('\x1b[200~')) continue
+ const rows = dialog.review ? 2 : TOPPINGS.length
+ if (key === '\x1b[B') { dialog.cursor = Math.min(dialog.cursor + 1, rows - 1); drawDialog(); continue }
+ if (key === '\x1b[A') { dialog.cursor = Math.max(dialog.cursor - 1, 0); drawDialog(); continue }
+ if (key === '\x1b') { settle(null); continue }
+ if (dialog.review) {
+ const row = key === '\r' || key === '\n' ? dialog.cursor : /^[12]$/.test(key) ? Number(key) - 1 : -1
+ if (row === 0) settle(TOPPINGS.filter((_, i) => dialog.checked.has(i)).map(([label]) => label).join(', '))
+ else if (row === 1) { dialog.review = false; dialog.cursor = 0; drawDialog() }
+ continue
+ }
+ const toggle = key === '\r' || key === '\n' ? dialog.cursor : /^[1-9]$/.test(key) ? Number(key) - 1 : -1
+ if (toggle >= 0 && toggle < rows) {
+ dialog.cursor = toggle
+ if (dialog.checked.has(toggle)) dialog.checked.delete(toggle)
+ else dialog.checked.add(toggle)
+ drawDialog()
+ } else if (key === '\t') { dialog.review = true; dialog.cursor = 0; drawDialog() }
+ continue
+ }
+ if (dialog.typed !== undefined) {
+ // Claude Code's free-text row, chosen: a paste or typing goes in, Enter sends it, Esc cancels.
+ if (key.startsWith('\x1b[200~')) { dialog.typed += key.slice(6).replace(/\x1b\[201~$/, ''); drawDialog() }
+ else if (key === '\x1b') settle(null)
+ else if (key === '\r' || key === '\n') { if (dialog.typed.trim()) settle(dialog.typed) }
+ else if (key === '\x7f') { dialog.typed = dialog.typed.slice(0, -1); drawDialog() }
+ else if (!key.startsWith('\x1b') && key >= ' ') { dialog.typed += key; drawDialog() }
+ continue
+ }
const rows = dialog.kind === 'permit' ? 3 : engine === 'claude' ? CHOICES.length : CHOICES.length + 1
if (key.startsWith('\x1b[200~')) {
if (dialog.kind !== 'permit' && engine === 'codex') dialog.notes = key.slice(6).replace(/\x1b\[201~$/, '')
@@ -704,6 +791,12 @@ export async function run(engine, config = {}, { native = false } = {}) {
}
if (key === '\x1b[B') { dialog.cursor = Math.min(dialog.cursor + 1, rows - 1); drawDialog(); continue }
if (key === '\x1b[A') { dialog.cursor = Math.max(dialog.cursor - 1, 0); drawDialog(); continue }
+ if (dialog.kind !== 'permit' && engine === 'claude' && key === String(CHOICES.length + 1)) {
+ dialog.cursor = CHOICES.length
+ dialog.typed = ''
+ drawDialog()
+ continue
+ }
if (dialog.kind === 'permit') {
if (key === '\x1b') settle(null)
else if (key === 'y' && engine === 'codex') settle(0)
@@ -1255,6 +1348,22 @@ export async function run(engine, config = {}, { native = false } = {}) {
await finish(`you chose ${choice}${notes ? ` (notes: ${notes})` : ''}`)
return
}
+ if (engine === 'claude' && directive?.[1] === 'askmany') {
+ await new Promise((resolve) => setTimeout(resolve, 2_000))
+ const choice = await new Promise((resolve) => { eraseComposer(); dialog = { kind: 'many', cursor: 0, checked: new Set(), review: false, drawn: 0, resolve }; drawDialog() })
+ if (choice === null) {
+ say('(question cancelled)\r\n')
+ await finish('(question cancelled)')
+ return
+ }
+ const questions = [{ question: MANY, header: 'Toppings', multiSelect: true, options: TOPPINGS.map(([label, description]) => ({ label, description })) }]
+ const id = `toolu_${turn}`
+ claude({ type: 'assistant', message: { id: `msg_${turn}_q`, role: 'assistant', model: claudeModel, content: [{ type: 'tool_use', id, name: 'AskUserQuestion', input: { questions } }], stop_reason: 'tool_use' } })
+ claude({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: id, content: `User has answered your questions: "${MANY}"="${choice}"` }] } })
+ say(`⏺ User answered Claude's questions:\r\n ⎿ · ${MANY} → ${choice}\r\n`)
+ await finish(`you chose ${choice || 'nothing'}`)
+ return
+ }
if (engine === 'codex' && directive?.[1] === 'askasync') {
// Codex 0.160's question that does not stop the turn (shape measured on real rollouts): the call, its
// `{"accepted":true}` at once, and later the person's answer as a user message wrapped in
diff --git a/cli/e2e/harness/questionWork.ts b/cli/e2e/harness/questionWork.ts
new file mode 100644
index 000000000..66edcb926
--- /dev/null
+++ b/cli/e2e/harness/questionWork.ts
@@ -0,0 +1,196 @@
+/**
+ * Questions as a workload: an agent asks, a window answers through `question_response`, and the answer
+ * the engine took is read back from its own transcript. Shared by the opt-in performance run
+ * (perf.e2e.ts, `PERF_QUESTIONS`) and the soak (endurance.e2e.ts).
+ *
+ * The fake engines draw what the real CLIs draw (fakeEngine.mjs): a single choice (`!ask`), Claude Code's
+ * "Type something." row (a typed answer to `!ask`), Claude Code's multiSelect with its review (`!askmany`)
+ * and a permission prompt (`!permit`). Codex's recorded request_user_input has no free-text row and no
+ * checkboxes, so Codex answers choices and permissions only.
+ */
+import { existsSync, readdirSync, readFileSync } from 'node:fs'
+import { join } from 'node:path'
+import type { Frame, LocalClient } from './client.js'
+
+export type QuestionEngine = 'claude' | 'codex'
+export type QuestionKind = 'select' | 'multi' | 'text' | 'permit'
+export const QUESTION_KINDS: Record<QuestionEngine, QuestionKind[]> = {
+ claude: ['select', 'multi', 'text', 'permit'],
+ codex: ['select', 'permit'],
+}
+
+export interface QuestionOutcome {
+ engine: QuestionEngine
+ kind: QuestionKind
+ token: string
+ requestId: string | null
+ answer: string | null
+ /** What the engine says once it has the answer: the transcript's last word on that turn. */
+ expected: string | null
+ /** performance.now() when the first answer was sent. */
+ sentAt: number | null
+ /** Answer sent → its `question_response_result` (core answers once the dialog is gone or submitted). */
+ resultMs: number | null
+ /** Answer sent → `commander_question_close` for it, when one came by the time the turn ended. */
+ closeMs: number | null
+ /** Answer sent → the turn's `turn_ended` (the engine took the answer and finished). */
+ endedMs: number | null
+ attempts: number
+ errors: string[]
+ ok: boolean
+}
+
+const sleep = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))
+const isTurnEnd = (agentId: string) => (frame: Frame) => frame.type === 'turn_ended' && frame.agentId === agentId
+
+function prompt(kind: QuestionKind, token: string): { content: string; command: string } {
+ const command = `printf ${token || 'hi'}`
+ if (kind === 'multi') return { content: `!askmany ${token}`.trim(), command }
+ if (kind === 'permit') return { content: `!permit ${command}`, command }
+ return { content: `!ask ${token}`.trim(), command }
+}
+
+function answerFor(engine: QuestionEngine, kind: QuestionKind, n: number, options: string[], command: string): { answer: string; expected: string } {
+ if (kind === 'permit') {
+ const yes = n % 2 === 0
+ return { answer: options[yes ? 0 : 2] ?? options[0], expected: yes ? `ran ${command}` : `did not run ${command}` }
+ }
+ if (kind === 'multi') {
+ const answer = n % 2 === 0 ? 'Cheese, Basil' : 'Ham'
+ return { answer, expected: `you chose ${answer}` }
+ }
+ if (kind === 'text') {
+ const answer = `hot chocolate ${n}`
+ return { answer, expected: `you chose ${answer}` }
+ }
+ const choices = engine === 'codex' ? ['Coffee', 'Tea', 'None of the above'] : ['Coffee', 'Tea']
+ const answer = choices[n % choices.length]
+ return { answer, expected: `you chose ${answer}` }
+}
+
+/**
+ * One question: the prompt that asks it, the question as the window hears it, and the answer sent back
+ * under its request id. A refused answer is retried (`retries`) as a new intent, a second later: what a
+ * person does when the app says the answer did not go in. Never throws; what went wrong is in `errors`.
+ */
+export async function askAndAnswer(client: LocalClient, agent: { id: string; engine: QuestionEngine }, kind: QuestionKind, n: number,
+ options: { token?: string; askMs?: number; resultMs?: number; endMs?: number; retries?: number } = {}): Promise<QuestionOutcome> {
+ const token = options.token ?? ''
+ const { content, command } = prompt(kind, token)
+ const outcome: QuestionOutcome = { engine: agent.engine, kind, token, requestId: null, answer: null, expected: null,
+ sentAt: null, resultMs: null, closeMs: null, endedMs: null, attempts: 0, errors: [], ok: false }
+ const asked = client.next(frame => frame.type === 'commander_question' && frame.agentId === agent.id, options.askMs ?? 60_000, `question (${kind} ${token})`)
+ const ended = client.next(isTurnEnd(agent.id), options.endMs ?? 120_000, `turn_ended (${kind} ${token})`).then(() => performance.now())
+ ended.catch(() => {})
+ client.send('message', { agentId: agent.id, content })
+ let question: Record<string, any>
+ try { question = (await asked).payload ?? {} } catch (error) {
+ outcome.errors.push(`asked: ${error instanceof Error ? error.message : String(error)}`)
+ return outcome
+ }
+ const shaped = (question.questions as Array<{ q: string; options: string[] }> | undefined)?.[0]
+ if (!shaped || typeof question.requestId !== 'string') {
+ outcome.errors.push(`asked: unreadable question ${JSON.stringify(question).slice(0, 200)}`)
+ ended.catch(() => {})
+ return outcome
+ }
+ const { answer, expected } = answerFor(agent.engine, kind, n, shaped.options ?? [], command)
+ Object.assign(outcome, { requestId: question.requestId, answer, expected })
+ const closed = client.next(frame => frame.type === 'commander_question_close' && frame.agentId === agent.id
+ && frame.payload?.requestId === question.requestId, (options.endMs ?? 120_000) + 5_000, 'commander_question_close')
+ .then(() => performance.now(), () => null)
+ let closeAt: number | null | undefined
+ void closed.then(at => { closeAt = at })
+ for (let attempt = 0; attempt <= (options.retries ?? 0); attempt++) {
+ if (attempt) await sleep(1_000)
+ outcome.attempts++
+ const result = client.next(frame => frame.type === 'question_response_result' && frame.payload?.requestId === question.requestId,
+ options.resultMs ?? 45_000, `question_response_result (${kind} ${token})`)
+ const at = performance.now()
+ outcome.sentAt ??= at
+ client.send('question_response', { requestId: question.requestId, agentId: agent.id, answers: { [shaped.q]: answer } })
+ try {
+ const reply = (await result).payload ?? {}
+ if (reply.error === undefined) { outcome.resultMs = performance.now() - outcome.sentAt; outcome.ok = true; break }
+ outcome.errors.push(`answer ${attempt + 1}: ${String(reply.error)} ${String(reply.detail ?? reply.message ?? '').slice(0, 160)}`.trim())
+ } catch (error) {
+ outcome.errors.push(`answer ${attempt + 1}: ${error instanceof Error ? error.message : String(error)}`)
+ }
+ }
+ // Never answered: the dialog is still up and the turn cannot end. The caller stops asking this agent.
+ if (!outcome.ok) return outcome
+ try { outcome.endedMs = (await ended) - outcome.sentAt! } catch (error) {
+ outcome.ok = false
+ outcome.errors.push(`ended: ${error instanceof Error ? error.message : String(error)}`)
+ }
+ await sleep(0)
+ outcome.closeMs = typeof closeAt === 'number' ? closeAt - outcome.sentAt! : null
+ return outcome
+}
+
+/** The answers a question turn can end on, as the fake engines write them (fakeEngine.mjs `finish`). */
+const QUESTION_OUTCOME = /^(?:you chose .+|ran printf .+|did not run printf .+|\(question cancelled\))$/s
+
+function transcripts(directory: string, sessionId: string): string[] {
+ if (!existsSync(directory)) return []
+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
+ const path = join(directory, entry.name)
+ if (entry.isDirectory()) return transcripts(path, sessionId)
+ return entry.isFile() && entry.name.endsWith(`${sessionId}.jsonl`) ? [path] : []
+ })
+}
+
+/** What an agent's engine recorded as the end of each question turn, in order, from its transcript. */
+export function engineAnswers(root: string, engine: QuestionEngine, sessionId: string): string[] {
+ const files = transcripts(engine === 'claude' ? join(root, 'claude', 'projects') : join(root, 'codex', 'sessions'), sessionId)
+ const found: string[] = []
+ for (const file of files) {
+ for (const line of readFileSync(file, 'utf8').split('\n')) {
+ if (!line.trim()) continue
+ let record: Record<string, any>
+ try { record = JSON.parse(line) } catch { continue }
+ const text = engine === 'claude'
+ ? record.type === 'assistant' && record.message?.stop_reason === 'end_turn' ? record.message?.content?.[0]?.text : undefined
+ : record.type === 'event_msg' && record.payload?.type === 'task_complete' ? record.payload?.last_agent_message : undefined
+ if (typeof text === 'string' && QUESTION_OUTCOME.test(text)) found.push(text)
+ }
+ }
+ return found
+}
+
+/** The answers that went in against what the engine took: none lost, none taken twice, none out of order. */
+export function compareAnswers(expected: string[], seen: string[]): { expected: number; seen: number; equal: boolean; lost: number; duplicated: number; firstDifference: number | null } {
+ const count = (list: string[]) => list.reduce((map, value) => map.set(value, (map.get(value) ?? 0) + 1), new Map<string, number>())
+ const want = count(expected), got = count(seen)
+ let lost = 0, duplicated = 0
+ for (const [value, n] of want) lost += Math.max(0, n - (got.get(value) ?? 0))
+ for (const [value, n] of got) duplicated += Math.max(0, n - (want.get(value) ?? 0))
+ const length = Math.max(expected.length, seen.length)
+ let firstDifference: number | null = null
+ for (let i = 0; i < length; i++) if (expected[i] !== seen[i]) { firstDifference = i; break }
+ return { expected: expected.length, seen: seen.length, equal: firstDifference === null, lost, duplicated, firstDifference }
+}
+
+export function percentile(values: number[], p: number): number | null {
+ if (!values.length) return null
+ const sorted = [...values].sort((a, b) => a - b)
+ return sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * p))]
+}
+
+/** Count, p50 and p95 of each latency, overall and by engine and kind. */
+export function summarizeAnswers(outcomes: QuestionOutcome[]) {
+ const stats = (list: QuestionOutcome[]) => {
+ const pick = (key: 'resultMs' | 'endedMs' | 'closeMs') => list.map(o => o[key]).filter((v): v is number => typeof v === 'number')
+ const result = pick('resultMs'), ended = pick('endedMs'), close = pick('closeMs')
+ return {
+ count: list.length, ok: list.filter(o => o.ok).length, errors: list.reduce((sum, o) => sum + o.errors.length, 0),
+ retried: list.filter(o => o.attempts > 1).length,
+ resultMs: { n: result.length, p50: percentile(result, 0.5), p95: percentile(result, 0.95), max: result.length ? Math.max(...result) : null },
+ endedMs: { n: ended.length, p50: percentile(ended, 0.5), p95: percentile(ended, 0.95) },
+ closeMs: { n: close.length, p50: percentile(close, 0.5), p95: percentile(close, 0.95) },
+ }
+ }
+ const groups = (key: (o: QuestionOutcome) => string) => Object.fromEntries([...new Set(outcomes.map(key))].sort()
+ .map(name => [name, stats(outcomes.filter(o => key(o) === name))]))
+ return { all: stats(outcomes), byEngine: groups(o => o.engine), byKind: groups(o => `${o.engine}:${o.kind}`) }
+}
diff --git a/cli/e2e/perf.e2e.ts b/cli/e2e/perf.e2e.ts
index 29f92afb9..5a5b925cf 100644
--- a/cli/e2e/perf.e2e.ts
+++ b/cli/e2e/perf.e2e.ts
@@ -6,13 +6,19 @@
* Run alone. CPU is the core's process CPU (100% = one logical CPU), never the master's/children's.
* PERF_READERS=1 additionally measures reader PIDs and history pages every 2 s; totals include them.
* PERF_MODEL_CONTROLS=1 adds a window of alternating model changes in the two engine types.
+ * PERF_QUESTIONS=1 adds a window of questions asked and answered through `question_response`
+ * (e2e/harness/questionWork.ts): PERF_QUESTION_AGENTS (default all) agents ask again and again, Claude Code
+ * a choice, a multiSelect, a typed answer and a permission, Codex a choice and a permission. It measures the
+ * core and both engine workers (the workers without PERF_READERS' history pages), the master by `ps`, answer
+ * latency and errors, and compares every answer sent with the one the engine's transcript recorded.
+ * PERF_QUESTION_SECONDS (default PERF_SECONDS) is that window's length.
* PERF_BUNDLE_SOURCE identifies an externally built baseline bundle; its bytes are hashed either way.
* On macOS set HARNESS_PROCESS_IMAGES_ARTIFACT to a verified local build for release-like discovery.
*/
-import { execFileSync } from 'node:child_process'
+import { execFile, execFileSync } from 'node:child_process'
import { randomBytes, randomUUID, createHash } from 'node:crypto'
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
-import { cpus, platform, release, tmpdir, totalmem } from 'node:os'
+import { cpus, loadavg, platform, release, tmpdir, totalmem } from 'node:os'
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
@@ -21,6 +27,7 @@ import { LocalClient } from './harness/client.js'
import { CLI_ROOT, until } from './harness/daemon.js'
import { harnessdProcesses } from './harness/endurance.js'
import { startPhoneMachine, type PhoneMachine } from './harness/fleet.js'
+import { askAndAnswer, compareAnswers, engineAnswers, QUESTION_KINDS, summarizeAnswers, type QuestionEngine, type QuestionOutcome } from './harness/questionWork.js'
const sleep = (ms: number) => new Promise<void>(done => setTimeout(done, ms))
const sha = (file: string) => createHash('sha256').update(readFileSync(file)).digest('hex')
@@ -31,6 +38,29 @@ function transcriptBytes(directory: string): number {
return bytes + (entry.isDirectory() ? transcriptBytes(file) : entry.isFile() && entry.name.endsWith('.jsonl') ? statSync(file).size : 0)
}, 0)
}
+/** The master's CPU and resident memory from `ps`: the probe runs in the core and the engine workers only. */
+const ps = (pid: number) => new Promise<{ cpuSeconds: number; rssBytes: number } | null>((done) => {
+ execFile('ps', ['-o', 'time=,rss=', '-p', String(pid)], { timeout: 3_000 }, (error, stdout) => {
+ const [time, rss] = String(stdout).trim().split(/\s+/)
+ if (error || !time || !rss) { done(null); return }
+ done({ cpuSeconds: time.split(':').reverse().reduce((sum, part, i) => sum + Number(part) * 60 ** i, 0), rssBytes: Number(rss) * 1024 })
+ })
+})
+function sampleProcess(pid: number) {
+ const startedAt = performance.now()
+ const rss: number[] = []
+ const first = ps(pid)
+ const timer = setInterval(() => { void ps(pid).then(sample => { if (sample) rss.push(sample.rssBytes) }) }, 1_000)
+ return async () => {
+ clearInterval(timer)
+ const [begin, end] = [await first, await ps(pid)]
+ const seconds = (performance.now() - startedAt) / 1000
+ if (end) rss.push(end.rssBytes)
+ return { pid, durationSeconds: seconds, source: 'ps (10 ms CPU resolution)',
+ cpu: { percent: begin && end ? 100 * (end.cpuSeconds - begin.cpuSeconds) / seconds : null },
+ memory: { rssMean: rss.length ? rss.reduce((a, b) => a + b, 0) / rss.length : null, rssMax: rss.length ? Math.max(...rss) : null, samples: rss.length } }
+ }
+}
function knob(name: string, fallback: number, min: number, max: number): number {
const n = Number(process.env[name] ?? fallback)
if (!Number.isInteger(n) || n < min || n > max) throw new Error(`${name} must be an integer from ${min} to ${max}`)
@@ -100,6 +130,11 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
const historyMiB = knob('PERF_HISTORY_MIB', 1, 0, 8)
const measureReaders = process.env.PERF_READERS === '1'
const measureControls = process.env.PERF_MODEL_CONTROLS === '1'
+ const measureQuestions = process.env.PERF_QUESTIONS === '1'
+ const questionSeconds = knob('PERF_QUESTION_SECONDS', seconds, 10, 900)
+ const questionAgents = knob('PERF_QUESTION_AGENTS', agents, 2, agents)
+ // The engine workers' probes: with history pages (PERF_READERS), or for the question window, without.
+ const measureWorkers = measureReaders || measureQuestions
const profile = process.env.PERF_PROFILE === '1'
const heaps = process.env.PERF_HEAP === '1'
const bundle = process.env.E2E_BUNDLE_PATH
@@ -118,10 +153,13 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
dirty: Boolean(git('status', '--porcelain')), bundleSource: process.env.PERF_BUNDLE_SOURCE ?? git('rev-parse', 'HEAD'), bundleSha256: sha(bundle), preloadSha256: sha(preload) },
machine: { platform: platform(), release: release(), node: process.version, logicalCpus: cpus().length,
cpu: cpus()[0]?.model, ramBytes: totalmem(), tmux: execFileSync('tmux', ['-V'], { encoding: 'utf8', timeout: 5_000 }).trim() },
- workload: { modelControls: measureControls, readerPageEveryMs: measureReaders ? 2000 : null, agents, active, windows: 2, terminalStreams: 4, seconds, warmup, historyMiB,
+ workload: { modelControls: measureControls,
+ questions: measureQuestions ? { agents: questionAgents, seconds: questionSeconds, kinds: QUESTION_KINDS, answeredThrough: 'question_response from a local window, as the desktop app answers', retries: 0 } : null,
+ readerPageEveryMs: measureReaders ? 2000 : null, agents, active, windows: 2, terminalStreams: 4, seconds, warmup, historyMiB,
turnDelayMs: '5000 + a unique round offset', inventoryEveryMs: 60_000, heartbeatEveryMs: 5_000, ackEveryMs: 16 },
instrumentation: { profile, heaps, delayResolutionMs: 10, rssSampleEveryMs: 1_000, cpuPercentBasis: 'one logical CPU',
- scope: measureReaders ? 'core PID and both reader PIDs; excludes master, other services, engines and tmux' : 'core PID only; excludes master, services, engines and tmux', heapPausesOutsideWindows: true },
+ scope: measureWorkers ? 'core PID and both engine worker PIDs (engine-claude, engine-codex) by in-process probe; the master by ps, reported separately; excludes other services, engines and tmux' : 'core PID only; the master by ps, reported separately; excludes services, engines and tmux', heapPausesOutsideWindows: true },
+ loadAverage: { start: loadavg() },
nativeProcessImages: process.env.HARNESS_PROCESS_IMAGES_ARTIFACT
? { mode: 'embedded', artifactSha256: sha(process.env.HARNESS_PROCESS_IMAGES_ARTIFACT) } : { mode: 'fallback' },
limitations: ['Fake engines and a loopback fake backend; no real model latency or token streaming.',
@@ -134,7 +172,7 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
let corePid: number | null = null
try {
machine = await startPhoneMachine({ env: { NODE_OPTIONS: nodeOptions.join(' '),
- HARNESS_E2E_PERF_READERS: measureReaders ? '1' : '0', HARNESS_E2E_PERF_DIR: artifactDir, HARNESS_E2E_PERF_TOKEN: token } })
+ HARNESS_E2E_PERF_READERS: measureWorkers ? '1' : '0', HARNESS_E2E_PERF_DIR: artifactDir, HARNESS_E2E_PERF_TOKEN: token } })
const d = machine.machine.daemon
if (measureControls) writeFileSync(join(d.engineConfig.codexHome, 'models_cache.json'),
readFileSync(join(CLI_ROOT, 'src/lib/__fixtures__/codex-home-0.160/models_cache.json')))
@@ -142,6 +180,10 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
if (!corePid) throw new Error('no owned core PID')
report.corePid = corePid
report.masterPid = d.pid
+ // Which engine controls the master gave this core to its workers (harnessd/services.ts
+ // `serviceProcessesEnv`): a build without isolated question control has no QUESTION_CONTROL entry.
+ const coreEnvironment = await new Promise<string>(done => execFile('ps', ['-E', '-ww', '-o', 'command=', '-p', String(corePid)], { timeout: 3_000 }, (error, stdout) => done(error ? '' : String(stdout))))
+ report.coreEngineCapabilities = Object.fromEntries([...coreEnvironment.matchAll(/\b(HARNESSD_ENGINE_[A-Z_]+)=(\d+:\d+)/g)].map(match => [match[1], match[2] === `${d.pid}:1`]))
const readyFile = join(artifactDir, `core-${corePid}.json`)
await until('the owned core performance probe', () => existsSync(readyFile), 10_000)
const endpoint = JSON.parse(readFileSync(readyFile, 'utf8')) as { pid: number; port: number }
@@ -178,7 +220,7 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
client.send('message', { agentId: id, content })
await ended
}
- const phase = async (label: string, turning: boolean, controlling = false) => {
+ const phase = async (label: string, turning: boolean, controlling = false, asking = false) => {
await checkDesk()
const before = windows.map(w => w.stats())
const turns = Array.from({ length: turning ? active : 0 }, () => 0)
@@ -186,9 +228,13 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
const controlLatencies: Record<string, number[]> = { claude: [], codex: [] }
let running = true
let problem: unknown
- const readers = measureReaders ? [...harnessdProcesses(d)].filter(([name]) => name.startsWith('engine-')) : []
+ const readers = measureWorkers ? [...harnessdProcesses(d)].filter(([name]) => name.startsWith('engine-')) : []
+ // On demand: with no agent yet (the empty desk) neither worker has started.
+ if (measureWorkers && saved.length) expect(readers.map(([name]) => name).sort()).toEqual(['engine-claude', 'engine-codex'])
for (const [, pid] of readers) await until('reader performance probe', () => existsSync(join(artifactDir, `core-${pid}.json`)), 10_000)
+ const loadStart = loadavg()
await Promise.all([probe('start', label), ...readers.map(([, pid]) => probe('start', label, pid))])
+ const masterEnd = sampleProcess(d.pid!)
const readLatencies: number[] = []
const reads = (async () => {
while (measureReaders && saved.length && running) {
@@ -209,6 +255,18 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
if (running) { turns[i]++; latencies.push(performance.now() - began) }
}
})
+ // Questions: each asking agent asks, the window answers it, and the turn ends, again and again. An agent
+ // whose answer did not go in still has its dialog up, so it stops asking; its errors are reported.
+ const answers: Array<QuestionOutcome & { agentId: string; completedAt: number }> = []
+ let windowEndedAt = Infinity
+ const askers = (asking ? saved.slice(0, questionAgents) : []).map(async (agent, index) => {
+ const kinds = QUESTION_KINDS[agent.engine as QuestionEngine]
+ for (let n = 0; running; n++) {
+ const outcome = await askAndAnswer(client, { id: agent.id, engine: agent.engine as QuestionEngine }, kinds[n % kinds.length], n, { token: `q${index}-${n}` })
+ answers.push({ ...outcome, agentId: agent.id, completedAt: performance.now() })
+ if (!outcome.ok) return
+ }
+ })
const controls = (controlling ? saved.slice(0, active) : []).map(async agent => {
let changes = 0
while (running) {
@@ -226,14 +284,18 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
})
let readerMetrics: Record<string, any>[] = []
let metrics: Record<string, any>
- try { await sleep(seconds * 1000) }
+ let master: Record<string, any> | null = null
+ try { await sleep((asking ? questionSeconds : seconds) * 1000) }
finally {
running = false
+ windowEndedAt = performance.now()
const measured = await Promise.all([probe('end', label), ...readers.map(async ([name, pid]) => ({ name, ...await probe('end', label, pid) }))])
metrics = measured[0]; readerMetrics = measured.slice(1)
+ master = await masterEnd()
}
+ const loadEnd = loadavg()
const after = windows.map(w => w.stats())
- await Promise.all([...workers, ...controls, reads])
+ await Promise.all([...workers, ...controls, ...askers, reads])
if (problem) throw problem
expect(metrics!.cpu.percent).toBeGreaterThanOrEqual(0)
expect(Number.isFinite(metrics!.cpu.percent)).toBe(true)
@@ -243,7 +305,21 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
if (controlling) for (const agent of saved.slice(0, active)) expect(controlLatencies[agent.engine].length).toBeGreaterThan(0)
latencies.sort((a, b) => a - b)
readLatencies.sort((a, b) => a - b)
- report.phases.push({ ...metrics!, readers: readerMetrics,
+ let questions: Record<string, unknown> | null = null
+ if (asking) {
+ // What each engine took, from its transcript, against what was answered: none lost, none twice.
+ const ledger = saved.slice(0, questionAgents).map(agent => {
+ const mine = answers.filter(answer => answer.agentId === agent.id)
+ const seen = engineAnswers(d.root, agent.engine as QuestionEngine, agent.sessionId)
+ return { agentId: agent.id, engine: agent.engine, asked: mine.length, answered: mine.filter(answer => answer.ok).length,
+ ...compareAnswers(mine.filter(answer => answer.ok).map(answer => answer.expected!), seen) }
+ })
+ const inWindow = answers.filter(answer => answer.completedAt <= windowEndedAt)
+ questions = { summary: summarizeAnswers(answers), inWindow: { count: inWindow.length, summary: summarizeAnswers(inWindow) }, ledger,
+ errors: answers.flatMap(answer => answer.errors.map(error => `${answer.engine} ${answer.kind} ${answer.token}: ${error}`)),
+ samples: answers.map(({ sentAt, completedAt, ...answer }) => ({ ...answer, inWindow: completedAt <= windowEndedAt })) }
+ }
+ report.phases.push({ ...metrics!, readers: readerMetrics, master, loadAverage: { start: loadStart, end: loadEnd }, questions,
modelControls: Object.fromEntries(Object.entries(controlLatencies).map(([engine, values]) => {
values.sort((a, b) => a - b)
return [engine, { count: values.length, p50Ms: values[Math.floor(values.length * .5)] ?? null, p95Ms: values[Math.floor(values.length * .95)] ?? null }]
@@ -294,6 +370,7 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
await phase('populated-idle', false)
await phase('active', true)
if (measureControls) await phase('model-control', false, true)
+ if (measureQuestions) await phase('questions', false, false, true)
report.agents = saved
report.state = 'passed'
} catch (error) {
@@ -307,6 +384,7 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
await machine.close()
}
report.endedAt = new Date().toISOString()
+ report.loadAverage.end = loadavg()
report.cpuProfiles = readdirSync(artifactDir).filter(name => name.endsWith('.cpuprofile') && name.includes(`.${corePid}.`))
.map(name => ({ name, sha256: sha(join(artifactDir, name)), bytes: statSync(join(artifactDir, name)).size }))
const missingProfile = profile && report.state === 'passed' && report.cpuProfiles.length === 0
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index 3084bf8e3..04012863a 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -143,9 +143,9 @@ const SERVICE_MAY_IMPORT: Record<string, string> = {
/** What is not the core's, by path: each goes to a service or its own process, in the plan's order. */
const EDGE: RegExp[] = [
- /^engines\/(claude|codex)\/(screen|composer|activity|stoppedGoal|modelControl|modelPicker)\.ts$/,
+ /^engines\/(claude|codex)\/(screen|composer|activity|stoppedGoal|modelControl|modelPicker|questionControl)\.ts$/,
/^lib\/(askQuestion|runtimeProfileController|composerScreen|teamWriteHold|messageHold|terminalActivity|codexTurnRecovery)\.ts$/,
- /^engines\/(screens|modelControls)\.ts$/,
+ /^engines\/(screens|modelControls|questionControls)\.ts$/,
// The pilot reader implementations and their host are never loaded by supervised core.
/^engines\/(worker\/process|transcripts|(claude|codex)\/(transcript|\w+ReaderProcess))\.ts$/,
/^engines\/(runtime|(claude|codex)\/runtimeProfile)\.ts$/, /^lib\/runtimeProfile\.ts$/,
diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.md
index b6f4e1380..a0b12e99b 100644
--- a/cli/src/core/AGENTS.md
+++ b/cli/src/core/AGENTS.md
@@ -37,8 +37,10 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE
validates bounded replies, retains acknowledged cursors and owns binding/turn state. The explicit
inline/older-master compatibility path is the only live parser or runtime profile implementation
composition in core. Screen reads are bounded and fenced to the worker connection and session binding
- ([screen boundary](../../../docs/design/2026-10-08-engine-screen.md)). Core keeps accepted profiles and control authority; native model drivers run in workers through [revocable control grants](../../../docs/design/2026-10-08-engine-model-control.md). See [runtime profiles](../../../docs/design/2026-10-08-engine-runtime.md).
-- `input.ts`, `questions.ts`: messages into a pane; an agent's question and its answer.
+ ([screen boundary](../../../docs/design/2026-10-08-engine-screen.md)). Core keeps accepted profiles and control authority; native model drivers run in workers through [revocable control grants](../../../docs/design/2026-10-08-engine-model-control.md), and so does question navigation ([question control](../../../docs/design/2026-10-08-engine-question-control.md)). See [runtime profiles](../../../docs/design/2026-10-08-engine-runtime.md).
+- `input.ts`, `questions.ts`: messages into a pane; an agent's question and its answer. Core matches an answer to the
+ question on screen and holds the lease; Claude Code's and Codex's keys for each approved step come from their engine
+ worker through a revocable grant (`engines/questionControls.ts`).
`deviceInput.ts`: the pane writer lock every write takes, and a device's queued turns behind it.
`cardText.ts`: an engine's error, rewritten for a device's card.
- `deliveries.ts`: delivered turns, the Wi-Fi device's, a team's and the orchestrator's: text written into an
diff --git a/cli/src/core/engines/controlTransport.ts b/cli/src/core/engines/controlTransport.ts
new file mode 100644
index 000000000..bbcfd2f7e
--- /dev/null
+++ b/cli/src/core/engines/controlTransport.ts
@@ -0,0 +1,74 @@
+import { readerEngine, READER_SERVICES, type ReaderEngine } from '../../engines/worker/protocol.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import { sessionBinding } from './sessionBinding.js'
+
+export async function boundedControl<T>(work: Promise<T>, ms: number, unavailable: () => Error): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ try { return await Promise.race([work, new Promise<never>((_, reject) => { timer = setTimeout(() => reject(unavailable()), ms) })]) }
+ finally { clearTimeout(timer) }
+}
+
+export interface ControlTransportDeps {
+ handles(engine: string): boolean
+ resolve(id: string): RegisteredSession | undefined
+ call(service: string, method: string, payload: Record<string, unknown>, waitMs: number): Promise<Record<string, unknown>>
+}
+interface Contract {
+ version: number
+ capabilities: string
+ inFlight: number
+ capable(reply: Record<string, unknown>, engine: ReaderEngine): boolean
+ result(reply: Record<string, unknown>): void
+ unavailable(): Error
+ error(error: unknown): Error
+ connectionChanged(service: string): void
+}
+
+/** Shared control lifetime, not engine behavior. Binding and connection never follow a replacement. */
+export function createControlTransport(deps: ControlTransportDeps, contract: Contract) {
+ const states = new Map(Object.values(READER_SERVICES).map(service => [service as string, { generation: 0, connected: false, capable: false, pending: 0 }]))
+ const bind = (registered: RegisteredSession) => {
+ const engine = registered.engine
+ if (!readerEngine(engine)) return undefined
+ const session = structuredClone(registered), binding = sessionBinding(registered), service = READER_SERVICES[engine]
+ const isolated = deps.handles(engine), state = states.get(service)!
+ const generation = state.generation + (state.connected ? 0 : 1)
+ const sameSession = () => sessionBinding(deps.resolve(session.agentId)) === binding
+ const current = () => sameSession() && (!isolated || (state.connected && state.generation === generation))
+ const run = async <T>(ms: number, work: (allowed: () => boolean, call: (method: string, payload: Record<string, unknown>) => Promise<void>) => Promise<T>): Promise<T> => {
+ if (!sameSession() || state.pending >= contract.inFlight) throw contract.unavailable()
+ state.pending++
+ let active = true
+ const deadline = performance.now() + ms
+ const allowed = () => active && performance.now() < deadline && current()
+ const call = async (method: string, payload: Record<string, unknown>) => {
+ const reply = await deps.call(service, method, { version: contract.version, ...payload }, Math.max(1, Math.ceil(deadline - performance.now())))
+ if (!allowed()) throw contract.unavailable()
+ contract.result(reply)
+ }
+ try {
+ return await boundedControl((async () => {
+ if (isolated && !state.capable) {
+ // A first startup can finish this intent; a reconnect cannot resume it.
+ if (state.generation !== generation && (state.connected || state.generation !== generation - 1)) throw contract.unavailable()
+ const reply = await deps.call(service, contract.capabilities, { version: contract.version }, ms)
+ if (!allowed() || !contract.capable(reply, engine)) throw contract.unavailable()
+ state.capable = true
+ }
+ if (!allowed()) throw contract.unavailable()
+ const value = await work(allowed, call)
+ if (!allowed()) throw contract.unavailable()
+ return value
+ })(), ms, contract.unavailable)
+ } catch (error) { throw contract.error(error) }
+ finally { active = false; state.pending-- }
+ }
+ return { engine, service, session, isolated, run }
+ }
+ const connection = (service: string, connected: boolean) => {
+ const state = states.get(service)
+ if (state) { state.generation++; state.connected = connected; state.capable = false }
+ contract.connectionChanged(service)
+ }
+ return { bind, connected: (service: string) => connection(service, true), disconnected: (service: string) => connection(service, false) }
+}
diff --git a/cli/src/core/engines/modelControls.ts b/cli/src/core/engines/modelControls.ts
index 50ba0407a..612173c3c 100644
--- a/cli/src/core/engines/modelControls.ts
+++ b/cli/src/core/engines/modelControls.ts
@@ -2,7 +2,6 @@ import { randomBytes } from 'node:crypto'
import type { EngineModelControl } from '../../engines/facets/modelControl.js'
import { RuntimeProfileControlError, type RuntimeProfileErrorCode } from '../../engines/facets/modelControl.js'
import type { RuntimeCatalogModel, RuntimeProfile } from '../../engines/facets/runtime.js'
-import { readerEngine, READER_SERVICES } from '../../engines/worker/protocol.js'
import { createModelControlHost } from '../../engines/worker/modelControlHost.js'
import { modelControlAction, modelControlAnswer, modelControlCheck, modelControlEnvelope, modelControlInput, modelControlSize,
MODEL_CONTROL_APPLY, MODEL_CONTROL_CAPABILITIES, MODEL_CONTROL_CHECK_MS, MODEL_CONTROL_ERRORS, MODEL_CONTROL_HOST,
@@ -10,7 +9,7 @@ import { modelControlAction, modelControlAnswer, modelControlCheck, modelControl
MODEL_CONTROL_VERSION, MODEL_CONTROL_WAIT_MS, MODEL_CONTROL_WRITES } from '../../engines/worker/modelControlProtocol.js'
import type { RegisteredSession } from '../../lib/registry.js'
import type { ModelControlFor } from '../../lib/modelControl.js'
-import { sessionBinding } from './sessionBinding.js'
+import { boundedControl, createControlTransport } from './controlTransport.js'
export interface ModelControlsDeps {
handles(engine: string): boolean
@@ -26,11 +25,8 @@ export interface ModelControlsDeps {
confirmEffort(sessionId: string, effort: string): void
}
function fail(): never { throw new RuntimeProfileControlError('BUSY') }
-async function bounded<T>(work: Promise<T>, ms: number): Promise<T> {
- let timer: ReturnType<typeof setTimeout> | undefined
- try { return await Promise.race([work, new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new RuntimeProfileControlError('BUSY')), ms) })]) }
- finally { clearTimeout(timer) }
-}
+const unavailable = () => new RuntimeProfileControlError('BUSY')
+const bounded = <T>(work: Promise<T>, ms: number) => boundedControl(work, ms, unavailable)
interface Grant {
service: string
session: RegisteredSession
@@ -43,8 +39,18 @@ interface Grant {
/** Core holds identity, input authority and confirmation state. Workers receive none of those handles. */
export function createModelControls(deps: ModelControlsDeps) {
- const states = new Map(Object.values(READER_SERVICES).map(service => [service as string, { generation: 0, connected: false, capable: false, pending: 0 }]))
const grants = new Map<string, Grant>()
+ const transport = createControlTransport(deps, {
+ version: MODEL_CONTROL_VERSION, capabilities: MODEL_CONTROL_CAPABILITIES, inFlight: MODEL_CONTROL_IN_FLIGHT,
+ capable: (reply, engine) => modelControlEnvelope(reply, ['modelControl', 'engine']) && reply.modelControl === MODEL_CONTROL_VERSION && reply.engine === engine,
+ result: reply => {
+ if (!modelControlEnvelope(reply, ['ok', 'error'])) fail()
+ if (reply.error !== undefined) throw new RuntimeProfileControlError(MODEL_CONTROL_ERRORS.includes(reply.error as RuntimeProfileErrorCode) ? reply.error as RuntimeProfileErrorCode : 'BUSY')
+ if (reply.ok !== true) fail()
+ },
+ unavailable, error: error => error instanceof RuntimeProfileControlError ? error : unavailable(),
+ connectionChanged: service => { for (const [token, grant] of grants) if (grant.service === service) grants.delete(token) },
+ })
const answer = (service: string, query: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> | null => {
if (query !== MODEL_CONTROL_HOST) return null
return (async () => {
@@ -77,43 +83,10 @@ export function createModelControls(deps: ModelControlsDeps) {
})()
}
const forSession: ModelControlFor = registered => {
- const engine = registered.engine
- if (!readerEngine(engine)) return undefined
- // Snapshot before the controller's first await: in-place registry edits cannot retarget this request.
- const session = structuredClone(registered), binding = sessionBinding(registered), service = READER_SERVICES[engine]
- const isolated = deps.handles(engine), state = states.get(service)!
- const generation = state.generation + (state.connected ? 0 : 1)
- const sameSession = () => sessionBinding(deps.resolve(session.agentId)) === binding
- const current = () => sameSession() && (!isolated || (state.connected && state.generation === generation))
+ const bound = transport.bind(registered)
+ if (!bound) return undefined
+ const { engine, session, service, isolated, run } = bound
let catalog: RuntimeCatalogModel[] = []
- const run = async (ms: number, work: (allowed: () => boolean, call: (method: string, payload: Record<string, unknown>) => Promise<void>) => Promise<void>) => {
- if (!sameSession() || state.pending >= MODEL_CONTROL_IN_FLIGHT) fail()
- state.pending++
- let active = true
- const deadline = performance.now() + ms
- const allowed = () => active && performance.now() < deadline && current()
- const call = async (method: string, payload: Record<string, unknown>) => {
- const reply = await deps.call(service, method, { version: MODEL_CONTROL_VERSION, ...payload }, Math.max(1, Math.ceil(deadline - performance.now())))
- if (!allowed() || !modelControlEnvelope(reply, ['ok', 'error'])) fail()
- if (reply.error !== undefined) throw new RuntimeProfileControlError(MODEL_CONTROL_ERRORS.includes(reply.error as RuntimeProfileErrorCode) ? reply.error as RuntimeProfileErrorCode : 'BUSY')
- if (reply.ok !== true) fail()
- }
- try {
- await bounded((async () => {
- if (isolated && !state.capable) {
- // Allow only the first startup connection. A replacement cannot resume an old UI intent.
- if (state.generation !== generation && (state.connected || state.generation !== generation - 1)) fail()
- const reply = await deps.call(service, MODEL_CONTROL_CAPABILITIES, { version: MODEL_CONTROL_VERSION }, ms)
- if (!allowed() || !modelControlEnvelope(reply, ['modelControl', 'engine']) || reply.modelControl !== MODEL_CONTROL_VERSION || reply.engine !== engine) fail()
- state.capable = true
- }
- if (!allowed()) fail()
- await work(allowed, call)
- if (!allowed()) fail()
- })(), ms)
- } catch (error) { throw error instanceof RuntimeProfileControlError ? error : new RuntimeProfileControlError('BUSY') }
- finally { active = false; state.pending-- }
- }
return {
validate: check => run(MODEL_CONTROL_CHECK_MS, async (allowed, call) => {
if (check.stage === 'target') catalog = await deps.catalog(session)
@@ -139,10 +112,5 @@ export function createModelControls(deps: ModelControlsDeps) {
},
}
}
- const connection = (service: string, connected: boolean) => {
- const state = states.get(service)
- if (state) { state.generation++; state.connected = connected; state.capable = false }
- for (const [token, grant] of grants) if (grant.service === service) grants.delete(token)
- }
- return { forSession, answer, connected: (service: string) => connection(service, true), disconnected: (service: string) => connection(service, false) }
+ return { forSession, answer, connected: transport.connected, disconnected: transport.disconnected }
}
diff --git a/cli/src/core/engines/questionControls.spec.ts b/cli/src/core/engines/questionControls.spec.ts
new file mode 100644
index 000000000..5c010f40f
--- /dev/null
+++ b/cli/src/core/engines/questionControls.spec.ts
@@ -0,0 +1,233 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { RegisteredSession } from '../../lib/registry.js'
+import type { EngineQuestionControl, QuestionControlHost, QuestionStep } from '../../engines/facets/questionControl.js'
+import { engineQuestionControlRequests } from '../../engines/worker/questionControlRequests.js'
+import { QUESTION_CONTROL_CAPABILITIES, QUESTION_CONTROL_HOST, QUESTION_CONTROL_IN_FLIGHT, QUESTION_CONTROL_WAIT_MS } from '../../engines/worker/questionControlProtocol.js'
+import { createQuestionControls } from './questionControls.js'
+
+const denied = { version: 1, error: 'ANSWER_FAILED' }
+const row = { number: '2', label: 'Coffee', checked: false }
+const step: QuestionStep = { kind: 'select', row, enterSubmits: true }
+const deferred = <T>() => { let resolve!: (value: T) => void; const promise = new Promise<T>(r => { resolve = r }); return { promise, resolve } }
+function setup(engine: 'claude' | 'codex' = 'claude', isolated = true, connected = true) {
+ let session = { agentId: 'agent', sessionId: 'session', engine, active: true, boundAt: 1, tmuxPane: '%1' } as RegisteredSession
+ const service = `engine-${engine}`
+ let token = ''
+ const native: EngineQuestionControl = { apply: vi.fn(async () => true) }
+ const deps = {
+ handles: () => isolated, resolve: () => session, inline: vi.fn(() => native as EngineQuestionControl | undefined),
+ call: vi.fn(async (_service: string, method: string, payload: Record<string, unknown>, _ms: number): Promise<Record<string, unknown>> => {
+ if (payload.token) token = payload.token as string
+ if (!connected) { controls.connected(service); connected = true }
+ return { ...await requests[method]({ ...payload, requestId: 'core-request' }, { owner: true, local: true }), requestId: 'worker-reply' }
+ }),
+ key: vi.fn(async (_target: string, _key: string, allowed: () => boolean) => allowed()),
+ text: vi.fn(async (_target: string, _text: string, allowed: () => boolean) => allowed()),
+ }
+ const controls = createQuestionControls(deps)
+ const request = (action: unknown, extra: Record<string, unknown> = {}, source = service) => controls.answer(source, QUESTION_CONTROL_HOST,
+ { version: 1, query: QUESTION_CONTROL_HOST, requestId: 'worker-request', token, action, ...extra })!
+ const requests = engineQuestionControlRequests(engine, { load: async () => native, recycle: vi.fn(),
+ query: async (query, payload) => ({ ...await controls.answer(service, query, { ...payload, query, requestId: 'worker-request' })!, requestId: 'core-reply' }) })
+ if (connected) controls.connected(service)
+ return { controls, deps, native, service, request, session: () => session, replace: (value: RegisteredSession) => { session = value }, port: () => controls.forSession(session)! }
+}
+
+describe('question-control authority', () => {
+ beforeEach(() => vi.useFakeTimers())
+ afterEach(() => vi.useRealTimers())
+
+ it.each(['claude', 'codex'] as const)('routes an approved %s step without giving the worker terminal identity', async engine => {
+ const s = setup(engine, true, false), port = s.port()
+ let host!: QuestionControlHost
+ s.native.apply = vi.fn(async (value, ports) => {
+ host = ports
+ expect(value).toEqual({ kind: 'text', row, text: 'My answer' })
+ expect(value).not.toHaveProperty('session')
+ expect(await host.key('2')).toBe(true)
+ expect(await host.text('My answer')).toBe(true)
+ expect(await host.key('Enter')).toBe(true)
+ return true
+ })
+ expect(await port.apply({ kind: 'text', row, text: 'My answer' })).toBe(true)
+ expect(await port.apply({ kind: 'text', row, text: 'My answer' })).toBe(true)
+ expect(s.deps.key).toHaveBeenCalledWith('agent', 'Enter', expect.any(Function))
+ expect(s.deps.call.mock.calls.filter(c => c[1] === QUESTION_CONTROL_CAPABILITIES)).toHaveLength(1)
+ expect(s.deps.inline).not.toHaveBeenCalled()
+ await expect(host.key('Enter')).rejects.toThrow()
+ expect(await s.request({ kind: 'key', key: 'Enter' })).toEqual(denied)
+ })
+
+ it('uses the grant in explicit inline mode, refuses a missing driver, and leaves other engines alone', async () => {
+ const s = setup('claude', false)
+ let host!: QuestionControlHost
+ s.native.apply = vi.fn(async (_step, value) => { host = value; return value.key('2') })
+ expect(await s.port().apply(step)).toBe(true)
+ expect(s.deps.call).not.toHaveBeenCalled()
+ await expect(host.key('Enter')).rejects.toThrow()
+ s.native.apply = vi.fn(async () => false)
+ expect(await s.port().apply(step)).toBe(false)
+ s.deps.inline.mockReturnValue(undefined)
+ expect(await s.port().apply(step)).toBe(false)
+ expect(s.controls.forSession({ ...s.session(), engine: 'cursor' })).toBeUndefined()
+ expect(s.controls.answer(s.service, 'live', {})).toBeNull()
+ })
+
+ it.each(['version', 'engine', 'questionControl', 'extra'])('rejects an incompatible %s capability before any write', async field => {
+ const s = setup()
+ s.deps.call.mockResolvedValueOnce({ version: 1, engine: 'claude', questionControl: 1, [field]: 'wrong' })
+ expect(await s.port().apply(step)).toBe(false)
+ expect(s.native.apply).not.toHaveBeenCalled()
+ expect(s.deps.inline).not.toHaveBeenCalled()
+ })
+
+ it('rejects failed, malformed and unexpected-field completion replies', async () => {
+ const s = setup(), port = s.port()
+ expect(await port.apply(step)).toBe(true)
+ for (const reply of [{ version: 2, ok: true }, { version: 1, ok: true, extra: true }, { version: 1, error: 'ANSWER_FAILED' }, { version: 1, ok: false }]) {
+ s.deps.call.mockResolvedValueOnce(reply)
+ expect(await port.apply(step)).toBe(false)
+ }
+ expect(await port.apply({ ...step, terminal: '%9' } as any)).toBe(false)
+ })
+
+ it('binds before the first await and never resumes a pre-reconnect answer', async () => {
+ const s = setup(), port = s.port()
+ expect(await port.apply(step)).toBe(true)
+ s.controls.disconnected(s.service); s.controls.connected(s.service)
+ expect(await port.apply(step)).toBe(false)
+ const fresh = s.port()
+ expect(await fresh.apply(step)).toBe(true)
+ s.session().sessionId = 'replacement'
+ expect(await fresh.apply(step)).toBe(false)
+ })
+
+ it('refuses other services and extra authority, and permits only the reviewed text', async () => {
+ const s = setup()
+ s.native.apply = vi.fn(async () => {
+ expect(await s.request({ kind: 'key', key: '2' }, {}, 'engine-codex')).toEqual(denied)
+ expect(await s.request({ kind: 'key', key: '2' }, { token: 'guess' })).toEqual(denied)
+ expect(await s.request({ kind: 'key', key: '2', target: '%9' })).toEqual(denied)
+ expect(await s.request({ kind: 'key', key: '2' }, { extra: true })).toEqual(denied)
+ s.controls.disconnected('engine-codex') // another engine cannot revoke this answer
+ expect(await s.request({ kind: 'key', key: '2' })).toEqual({ version: 1, value: true })
+ expect(await s.request({ kind: 'text', text: 'unreviewed answer' })).toEqual(denied)
+ expect(await s.request({ kind: 'key', key: 'Enter' })).toEqual(denied)
+ return true
+ })
+ expect(await s.port().apply(step)).toBe(false)
+ expect(s.deps.text).not.toHaveBeenCalled()
+ })
+
+ it('enters the approved text once: the same text again is refused and revokes the step', async () => {
+ const s = setup()
+ s.native.apply = vi.fn(async () => {
+ expect(await s.request({ kind: 'key', key: '2' })).toEqual({ version: 1, value: true })
+ expect(await s.request({ kind: 'text', text: 'My answer' })).toEqual({ version: 1, value: true })
+ expect(await s.request({ kind: 'text', text: 'My answer' })).toEqual(denied)
+ expect(await s.request({ kind: 'key', key: 'Enter' })).toEqual(denied)
+ return true
+ })
+ expect(await s.port().apply({ kind: 'text', row, text: 'My answer' })).toBe(false)
+ expect(s.deps.text).toHaveBeenCalledOnce()
+ })
+
+ it('says why a step failed: refused when it typed nothing, uncertain once a write had gone out', async () => {
+ const s = setup(), port = s.port()
+ expect(await port.apply(step)).toBe(true)
+ expect(port.failure!()).toBeUndefined()
+ s.native.apply = vi.fn(async () => false)
+ expect(await port.apply(step)).toBe(false)
+ expect(port.failure!()).toBe('refused')
+ s.native.apply = vi.fn(async () => {
+ expect(await s.request({ kind: 'key', key: '2' })).toEqual({ version: 1, value: true })
+ throw new Error('worker killed after the key')
+ })
+ expect(await port.apply(step)).toBe(false)
+ expect(port.failure!()).toBe('uncertain')
+ // A write the terminal refused was still handed to it.
+ s.deps.key.mockResolvedValueOnce(false)
+ s.native.apply = vi.fn(async () => { await s.request({ kind: 'key', key: '2' }); return true })
+ expect(await port.apply(step)).toBe(false)
+ expect(port.failure!()).toBe('uncertain')
+ // A step refused by the broker before it was admitted typed nothing.
+ expect(await port.apply({ kind: 'select', row: { ...row, number: 'C-c' } } as never)).toBe(false)
+ expect(port.failure!()).toBe('refused')
+ })
+
+ it('refuses a step past its engine\'s capacity as typing nothing', async () => {
+ const s = setup(), gate = deferred<boolean>()
+ s.native.apply = vi.fn(() => gate.promise)
+ const ports = Array.from({ length: QUESTION_CONTROL_IN_FLIGHT }, () => s.port())
+ const held = ports.map(port => port.apply(step))
+ await vi.waitFor(() => expect(s.native.apply).toHaveBeenCalledTimes(QUESTION_CONTROL_IN_FLIGHT))
+ const extra = s.port()
+ expect(await extra.apply(step)).toBe(false)
+ expect(extra.failure!()).toBe('refused')
+ gate.resolve(true)
+ expect(await Promise.all(held)).toEqual(Array(QUESTION_CONTROL_IN_FLIGHT).fill(true))
+ })
+
+ it('limits a granted step and revokes it after excess keys', async () => {
+ const s = setup()
+ s.native.apply = vi.fn(async () => {
+ for (let i = 0; i < 128; i++) expect(await s.request({ kind: 'key', key: 'Down' })).toHaveProperty('value', true)
+ expect(await s.request({ kind: 'key', key: 'Enter' })).toEqual(denied)
+ return true
+ })
+ expect(await s.port().apply(step)).toBe(false)
+ })
+
+ it('refuses the first effect if the registered conversation changed after admission', async () => {
+ const s = setup()
+ s.native.apply = vi.fn(async () => {
+ s.session().sessionId = 'replacement'
+ expect(await s.request({ kind: 'key', key: '2' })).toEqual(denied)
+ return true
+ })
+ expect(await s.port().apply(step)).toBe(false)
+ expect(s.deps.key).not.toHaveBeenCalled()
+ })
+
+ it.each(['failed', 'throw', 'malformed'] as const)('revokes all later keys after a %s terminal write', async failure => {
+ const s = setup()
+ if (failure === 'failed') s.deps.key.mockResolvedValueOnce(false)
+ else if (failure === 'throw') s.deps.key.mockRejectedValueOnce(new Error('gone'))
+ else s.deps.key.mockResolvedValueOnce('yes' as any)
+ s.native.apply = vi.fn(async () => {
+ expect(await s.request({ kind: 'key', key: '2' })).toEqual(failure === 'failed' ? { version: 1, value: false } : denied)
+ expect(await s.request({ kind: 'key', key: 'Enter' })).toEqual(denied)
+ return true
+ })
+ expect(await s.port().apply(step)).toBe(false)
+ expect(s.deps.key).toHaveBeenCalledOnce()
+ })
+
+ it.each(['disconnect', 'rebind', 'overlap', 'completed', 'timeout'] as const)('revokes queued effects on %s', async reason => {
+ const s = setup(), gate = deferred<void>(), entered = deferred<void>(), effects: string[] = []
+ let permitted!: () => boolean
+ s.deps.key.mockImplementation(async (_target, key, allowed) => {
+ permitted = allowed; entered.resolve(); await gate.promise
+ if (allowed()) effects.push(key)
+ return allowed()
+ })
+ s.deps.call.mockImplementation(async (_service, method, payload) => {
+ if (method === QUESTION_CONTROL_CAPABILITIES) return { version: 1, questionControl: 1, engine: 'claude' }
+ const effect = s.controls.answer(s.service, QUESTION_CONTROL_HOST, { version: 1, token: payload.token, action: { kind: 'key', key: 'Enter' } })!
+ if (reason === 'completed') { void effect; return { version: 1, ok: true } }
+ if (reason === 'overlap') expect(await s.controls.answer(s.service, QUESTION_CONTROL_HOST, { version: 1, token: payload.token, action: { kind: 'key', key: '2' } })).toEqual(denied)
+ await effect
+ return { version: 1, ok: true }
+ })
+ const outcome = s.port().apply(step)
+ await entered.promise
+ if (reason === 'disconnect') s.controls.disconnected(s.service)
+ if (reason === 'rebind') s.session().boundAt = 2
+ if (reason === 'timeout') await vi.advanceTimersByTimeAsync(QUESTION_CONTROL_WAIT_MS + 1)
+ if (reason === 'completed') await outcome
+ expect(permitted()).toBe(false)
+ gate.resolve()
+ expect(await outcome).toBe(false)
+ expect(effects).toEqual([])
+ })
+})
diff --git a/cli/src/core/engines/questionControls.ts b/cli/src/core/engines/questionControls.ts
new file mode 100644
index 000000000..867c575f8
--- /dev/null
+++ b/cli/src/core/engines/questionControls.ts
@@ -0,0 +1,95 @@
+import { randomBytes } from 'node:crypto'
+import type { EngineQuestionControl } from '../../engines/facets/questionControl.js'
+import { createQuestionControlHost } from '../../engines/worker/questionControlHost.js'
+import { questionControlAction, questionControlEnvelope, questionControlStep, questionStepText,
+ QUESTION_CONTROL_APPLY, QUESTION_CONTROL_CAPABILITIES, QUESTION_CONTROL_HOST, QUESTION_CONTROL_IN_FLIGHT,
+ QUESTION_CONTROL_QUERY_MS, QUESTION_CONTROL_VERSION, QUESTION_CONTROL_WAIT_MS, QUESTION_CONTROL_WRITES } from '../../engines/worker/questionControlProtocol.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import type { QuestionControlFor, QuestionStepFailure } from '../../lib/questionControl.js'
+import { boundedControl, createControlTransport, type ControlTransportDeps } from './controlTransport.js'
+
+export interface QuestionControlsDeps extends ControlTransportDeps {
+ inline(engine: string): EngineQuestionControl | undefined
+ text(target: string, text: string, allowed: () => boolean): Promise<boolean>
+ key(target: string, key: string, allowed: () => boolean): Promise<boolean>
+}
+const unavailable = () => new Error('question control unavailable')
+interface Grant {
+ service: string
+ session: RegisteredSession
+ text: string | undefined
+ allowed(): boolean
+ pending: boolean
+ writes: number
+ /** Writes handed to the terminal: any one of them may have gone in, whatever the step's outcome. */
+ dispatched: number
+}
+
+/** The worker navigates one approved step; it never receives the pending answer map or a pane locator. */
+export function createQuestionControls(deps: QuestionControlsDeps) {
+ const grants = new Map<string, Grant>()
+ const transport = createControlTransport(deps, {
+ version: QUESTION_CONTROL_VERSION, capabilities: QUESTION_CONTROL_CAPABILITIES, inFlight: QUESTION_CONTROL_IN_FLIGHT,
+ capable: (reply, engine) => questionControlEnvelope(reply, ['questionControl', 'engine']) && reply.questionControl === QUESTION_CONTROL_VERSION && reply.engine === engine,
+ result: reply => { if (!questionControlEnvelope(reply, ['ok', 'error']) || reply.error !== undefined || reply.ok !== true) throw unavailable() },
+ unavailable, error: unavailable,
+ connectionChanged: service => { for (const [token, grant] of grants) if (grant.service === service) grants.delete(token) },
+ })
+ const answer = (service: string, query: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> | null => {
+ if (query !== QUESTION_CONTROL_HOST) return null
+ return (async () => {
+ const denied = { version: QUESTION_CONTROL_VERSION, error: 'ANSWER_FAILED' }
+ if (!questionControlEnvelope(payload, ['query', 'token', 'action']) || typeof payload.token !== 'string' || !questionControlAction(payload.action)) return denied
+ const grant = grants.get(payload.token), action = payload.action
+ if (!grant || grant.service !== service) return denied
+ if (!grant.allowed() || grant.pending || ++grant.writes > QUESTION_CONTROL_WRITES
+ || (action.kind === 'text' && action.text !== grant.text)) { grants.delete(payload.token); return denied }
+ // The approved text goes in once: typed a second time it would be a different answer from the one approved.
+ if (action.kind === 'text') grant.text = undefined
+ grant.pending = true
+ grant.dispatched++
+ try {
+ const value = await boundedControl(action.kind === 'text'
+ ? deps.text(grant.session.agentId, action.text, grant.allowed)
+ : deps.key(grant.session.agentId, action.key, grant.allowed), QUESTION_CONTROL_QUERY_MS, unavailable)
+ if (!grant.allowed() || typeof value !== 'boolean') { grants.delete(payload.token); return denied }
+ if (!value) grants.delete(payload.token) // A failed or uncertain write never authorizes another key.
+ return { version: QUESTION_CONTROL_VERSION, value }
+ } catch { grants.delete(payload.token); return denied }
+ finally { grant.pending = false }
+ })()
+ }
+ const forSession: QuestionControlFor = registered => {
+ const bound = transport.bind(registered)
+ if (!bound) return undefined
+ const { session, engine, service, isolated, run } = bound
+ let failure: QuestionStepFailure | undefined
+ return { failure: () => failure, apply: async step => {
+ const token = randomBytes(32).toString('hex')
+ let admitted: Grant | undefined
+ failure = undefined
+ try {
+ return await run(QUESTION_CONTROL_WAIT_MS, async (allowed, call) => {
+ if (!questionControlStep(step)) throw unavailable()
+ const value = structuredClone(step)
+ admitted = { service, session, text: questionStepText(value), allowed: () => allowed() && grants.has(token), pending: false, writes: 0, dispatched: 0 }
+ grants.set(token, admitted)
+ if (isolated) await call(QUESTION_CONTROL_APPLY, { step: value, token })
+ else {
+ const control = deps.inline(engine)
+ if (!control || !await control.apply(value, createQuestionControlHost(action => answer(service, QUESTION_CONTROL_HOST, { version: QUESTION_CONTROL_VERSION, token, action })!))) throw unavailable()
+ }
+ const grant = grants.get(token)
+ if (!grant || grant.pending) throw unavailable()
+ return true
+ })
+ } catch {
+ // A step that dispatched nothing typed nothing; one that dispatched a write may have answered (found by
+ // the chaos run: the worker killed after the last key, the dialog closed, and the answer was reported failed).
+ failure = admitted && admitted.dispatched > 0 ? 'uncertain' : 'refused'
+ return false
+ } finally { grants.delete(token) }
+ } }
+ }
+ return { forSession, answer, connected: transport.connected, disconnected: transport.disconnected }
+}
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index fddd6261f..89642a7e0 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -1,3 +1,5 @@
+import { createQuestionControls } from './engines/questionControls.js'
+import { masterRunsEngineQuestionControl } from '../harnessd/services.js'
import { createModelControls } from './engines/modelControls.js'
import { masterRunsEngineModelControl } from '../harnessd/services.js'
import { createScreens } from './engines/screens.js'
@@ -547,12 +549,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// An older master's explicit capability report selects compatibility. A failed worker never does.
const isolatedLive = (engine: string): boolean => liveHosted
&& readerEngine(engine) && outOfProcess.has(READER_SERVICES[engine])
+ const questionControlHosted = masterRunsEngineQuestionControl(process.env, process.ppid)
+ const isolatedQuestionControl = (engine: string): boolean => questionControlHosted && isolatedLive(engine)
const modelControlHosted = masterRunsEngineModelControl(process.env, process.ppid)
const isolatedModelControl = (engine: string): boolean => modelControlHosted && isolatedLive(engine)
const screenHosted = masterRunsEngineScreen(process.env, process.ppid)
const isolatedScreen = (engine: string): boolean => screenHosted && isolatedLive(engine)
const isolatedRuntime = (engine: string): boolean => runtimeHosted && isolatedLive(engine)
- const inline = KNOWN_SERVICES.some((name) => !outOfProcess.has(name)) || !runtimeHosted || !screenHosted || !modelControlHosted
+ const inline = KNOWN_SERVICES.some((name) => !outOfProcess.has(name)) || !runtimeHosted || !screenHosted || !modelControlHosted || !questionControlHosted
? await import('../services/inline.js') : null
let serviceLinksRef: ServiceLinks | null = null
const runtimeTransport = createRuntimeTransport({
@@ -567,6 +571,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {
legacy: new LegacyRuntimeProfileManager(engine => isolatedRuntime(engine) ? undefined : inline?.runtimeFor(engine)),
handles: isolatedRuntime,
resolve: id => registry.resolve(id), transport: runtimeTransport })
+ const questionControls = createQuestionControls({
+ handles: isolatedQuestionControl, inline: engine => inline?.questionControlFor(engine), resolve: id => registry.resolve(id),
+ call: (service, method, payload, waitMs) => serviceLinksRef?.call(service, method, payload, waitMs) ?? Promise.resolve({ error: 'SERVICE_UNAVAILABLE' }),
+ text: (target, text, allowed) => submitTerminal(target, text, { allowed }), key: keyTerminal,
+ })
const modelControls = createModelControls({
handles: isolatedModelControl, inline: engine => inline?.modelControlFor(engine), resolve: id => registry.resolve(id),
call: (service, method, payload, waitMs) => serviceLinksRef?.call(service, method, payload, waitMs) ?? Promise.resolve({ error: 'SERVICE_UNAVAILABLE' }),
@@ -1078,6 +1087,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Questions an agent asks the person: shown on the dial and the window, answered from anywhere
// (core/questions.ts).
const asking = createQuestions({
+ questionControlFor: questionControls.forSession,
readQuestion: screens.question,
resolve: (id) => registry.resolve(id),
terminal: terminalControl,
@@ -1202,7 +1212,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
onDemand: new Set([...experiments, ...DEVICES_ON_DEMAND, ...Object.values(READER_SERVICES), 'models', 'gateway', 'shell']),
want: (service) => experimentHooks.want(service),
// The gateway's first: its `backend` reads (the device key log) were refused below as NOT_AN_EXPERIMENT.
- answer: async (service, query, payload) => await modelControls.answer(service, query, payload) ?? engineReaders.answer(service) ?? (service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : null) ?? deliveries.answer(service, query, payload)
+ answer: async (service, query, payload) => await questionControls.answer(service, query, payload) ?? await modelControls.answer(service, query, payload) ?? engineReaders.answer(service) ?? (service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : null) ?? deliveries.answer(service, query, payload)
?? await answerExperimentQuery(coreApi, experiments, service, query, payload)
?? await terminalWatch.answer(service, query, payload)
?? (service === 'orchestrator' ? orchestratorLink.answer(query, payload) : null)
@@ -1226,6 +1236,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
runtimeTransport.connected(service)
screenTransport.connected(service)
modelControls.connected(service)
+ questionControls.connected(service)
if (service === 'gateway') gatewayLink?.connected()
if (service === 'teams') teamsLink.on()
if (service === 'devices') devicesLink.connected()
@@ -1238,6 +1249,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
runtimeTransport.disconnected(service)
screenTransport.disconnected(service)
modelControls.disconnected(service)
+ questionControls.disconnected(service)
if (service === 'gateway') gatewayLink?.disconnected()
if (service === 'devices') devicesLink.disconnected()
if (service === 'wifi') wifiCore.stopped()
diff --git a/cli/src/core/questions.spec.ts b/cli/src/core/questions.spec.ts
index 82c146d5e..b4dd750ff 100644
--- a/cli/src/core/questions.spec.ts
+++ b/cli/src/core/questions.spec.ts
@@ -10,6 +10,7 @@ const agents = new Map<string, RegisteredSession>([
function setup(over: Partial<QuestionDeps> = {}) {
const deps: QuestionDeps = {
+ questionControlFor: () => undefined,
readQuestion: (session, capture) => parseEngineQuestionPane(session.engine, capture),
resolve: (id) => agents.get(id),
terminal: {
diff --git a/cli/src/core/questions.ts b/cli/src/core/questions.ts
index fed6cc7eb..6e6af89ef 100644
--- a/cli/src/core/questions.ts
+++ b/cli/src/core/questions.ts
@@ -16,6 +16,7 @@ import type { TerminalControl } from './terminals/control.js'
type Frame = { type: string; agentId?: string; dbSessionId?: string; payload: Record<string, unknown> }
export interface QuestionDeps {
+ questionControlFor: import('../lib/questionControl.js').QuestionControlFor
readQuestion: import('../lib/questionController.js').QuestionWatcherDeps['readQuestion']
resolve: (id: string) => RegisteredSession | undefined
terminal: Pick<TerminalControl, 'captureTerminal' | 'submitTerminal' | 'keyTerminal'>
@@ -31,12 +32,13 @@ export interface QuestionDeps {
}
export function createQuestions({
- readQuestion, resolve, terminal, acquireTerminalControl, clients, agentIdFor, sessionTurnOpen, someoneCanAnswer, deviceInput,
+ questionControlFor, readQuestion, resolve, terminal, acquireTerminalControl, clients, agentIdFor, sessionTurnOpen, someoneCanAnswer, deviceInput,
}: QuestionDeps) {
const { captureTerminal, submitTerminal, keyTerminal } = terminal
// AskUserQuestion bridge: mirrors the question to the device's question screen, and keys the device's
// answer back into the CLI's own terminal dialog.
const questions = new AskQuestionController({
+ questionControlFor,
getSession: (id) => resolve(id),
capture: captureTerminal,
readQuestion,
diff --git a/cli/src/engines/README.md b/cli/src/engines/README.md
index 8166bf78a..a4ad35899 100644
--- a/cli/src/engines/README.md
+++ b/cli/src/engines/README.md
@@ -18,8 +18,9 @@ that stream.
launch contracts, history/last-turn readers and hook behavior behind `Engine` (`engine.ts`). `registry.ts`
selects those engines; `launches.ts` and `hooks.ts` expose their respective facets without loading history
readers. Hook transport, process binding and event delivery stay with core. Claude Code and Codex history/last-turn reads,
-live transcript parsing, runtime profiles/catalogs, screen interpretation and model-control drivers run on demand in supervised workers;
+live transcript parsing, runtime profiles/catalogs, screen interpretation, model-control drivers and question navigation run on demand in supervised workers;
the other facets still run in core. Explicit inline mode and older masters retain inline implementations. See
+[question control](../../../docs/design/2026-10-08-engine-question-control.md),
[model control](../../../docs/design/2026-10-08-engine-model-control.md),
[screen interpretation](../../../docs/design/2026-10-08-engine-screen.md),
[runtime profiles](../../../docs/design/2026-10-08-engine-runtime.md) and the
diff --git a/cli/src/engines/claude/questionControl.ts b/cli/src/engines/claude/questionControl.ts
new file mode 100644
index 000000000..1d3722484
--- /dev/null
+++ b/cli/src/engines/claude/questionControl.ts
@@ -0,0 +1,8 @@
+import { numberedQuestionControl } from '../kit/questionControl.js'
+
+export const createQuestionControl = (wait?: (ms: number) => Promise<void>) => numberedQuestionControl(({ row }) => {
+ // Numbered questions normally submit on the digit. Preserve the shared dialog's explicit walk hint.
+ if (row.walk) return [...Array(Number(row.number)).fill(row.walk === 'right' ? 'Right' : 'Down'), 'Enter']
+ return [row.number]
+}, wait)
+export const questionControl = createQuestionControl()
diff --git a/cli/src/engines/codex/questionControl.ts b/cli/src/engines/codex/questionControl.ts
new file mode 100644
index 000000000..2b6d30b8c
--- /dev/null
+++ b/cli/src/engines/codex/questionControl.ts
@@ -0,0 +1,10 @@
+import type { QuestionRow, QuestionView } from '../facets/screen.js'
+import { numberedQuestionControl } from '../kit/questionControl.js'
+
+/** Measured on 0.149: request_user_input highlights on a digit and submits on Enter;
+ * approval prompts select and commit on the digit alone. */
+export function codexRowKeys(row: QuestionRow, view?: QuestionView | Pick<QuestionView, 'enterSubmits'>): string[] {
+ return view?.enterSubmits ? [row.number, 'Enter'] : [row.number]
+}
+export const createQuestionControl = (wait?: (ms: number) => Promise<void>) => numberedQuestionControl(step => codexRowKeys(step.row, step), wait)
+export const questionControl = createQuestionControl()
diff --git a/cli/src/engines/engine.ts b/cli/src/engines/engine.ts
index afa854220..1446dbf18 100644
--- a/cli/src/engines/engine.ts
+++ b/cli/src/engines/engine.ts
@@ -1,3 +1,4 @@
+import type { EngineQuestionControl } from './facets/questionControl.js'
import type { EngineScreen } from './facets/screen.js'
import type { EngineModelControl } from './facets/modelControl.js'
import type { ProcessEngine } from './types.js'
@@ -17,4 +18,5 @@ export interface Engine {
readonly runtime: EngineRuntime
readonly screen: EngineScreen
readonly modelControl: EngineModelControl
+ readonly questionControl: EngineQuestionControl
}
diff --git a/cli/src/engines/facets/questionControl.ts b/cli/src/engines/facets/questionControl.ts
new file mode 100644
index 000000000..3eebf0387
--- /dev/null
+++ b/cli/src/engines/facets/questionControl.ts
@@ -0,0 +1,16 @@
+import type { QuestionRow } from './screen.js'
+
+/** One step already matched to the user's answer by core. No pending answers or terminal identity. */
+export type QuestionStep =
+ | { kind: 'select'; row: QuestionRow; enterSubmits?: boolean }
+ | { kind: 'multiple'; rows: QuestionRow[]; freeText?: { row: QuestionRow; text: string } }
+ | { kind: 'text'; row: QuestionRow; text: string }
+ | { kind: 'review'; key: string }
+
+export interface QuestionControlHost {
+ key(key: string): Promise<boolean>
+ text(text: string): Promise<boolean>
+}
+export interface EngineQuestionControl {
+ apply(step: QuestionStep, host: QuestionControlHost): Promise<boolean>
+}
diff --git a/cli/src/engines/kit/questionControl.ts b/cli/src/engines/kit/questionControl.ts
new file mode 100644
index 000000000..fd06727db
--- /dev/null
+++ b/cli/src/engines/kit/questionControl.ts
@@ -0,0 +1,38 @@
+import type { EngineQuestionControl, QuestionControlHost, QuestionStep } from '../facets/questionControl.js'
+
+const sleep = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms))
+/** Numbered TUI navigation shared by Claude Code and Codex. Core supplies only an approved step. */
+export function numberedQuestionControl(
+ selection: (step: Extract<QuestionStep, { kind: 'select' }>) => string[],
+ wait: (ms: number) => Promise<void> = sleep,
+): EngineQuestionControl {
+ const text = async (row: string, value: string, host: QuestionControlHost) => {
+ if (!await host.key(row)) return false
+ await wait(250)
+ if (!await host.text(value)) return false
+ await wait(250)
+ return host.key('Enter')
+ }
+ return {
+ async apply(step, host) {
+ if (step.kind === 'review') return host.key(step.key)
+ if (step.kind === 'select') {
+ for (const key of selection(step)) {
+ if (!await host.key(key)) return false
+ await wait(250)
+ }
+ } else if (step.kind === 'text') {
+ if (!await text(step.row.number, step.text, host)) return false
+ } else {
+ for (const row of step.rows) {
+ if (!await host.key(row.number)) return false
+ await wait(250)
+ }
+ if (step.freeText && !await text(step.freeText.row.number, step.freeText.text, host)) return false
+ if (!await host.key('Tab')) return false
+ }
+ await wait(350) // The next capture must see the repaint after the last key.
+ return true
+ },
+ }
+}
diff --git a/cli/src/engines/questionControls.ts b/cli/src/engines/questionControls.ts
new file mode 100644
index 000000000..272f1f3dc
--- /dev/null
+++ b/cli/src/engines/questionControls.ts
@@ -0,0 +1,5 @@
+/** Explicit inline composition; supervised core does not import native navigation. */
+import { createQuestionControl as claude } from './claude/questionControl.js'
+import { createQuestionControl as codex } from './codex/questionControl.js'
+export const questionControlFor = (engine: string, wait?: (ms: number) => Promise<void>) =>
+ engine === 'claude' ? claude(wait) : engine === 'codex' ? codex(wait) : undefined
diff --git a/cli/src/engines/registry.ts b/cli/src/engines/registry.ts
index 07ae04c33..73eda56a0 100644
--- a/cli/src/engines/registry.ts
+++ b/cli/src/engines/registry.ts
@@ -1,3 +1,5 @@
+import { questionControl as claudeQuestionControl } from './claude/questionControl.js'
+import { questionControl as codexQuestionControl } from './codex/questionControl.js'
import { screen as claudeScreen } from './claude/screen.js'
import { modelControl as claudeModelControl } from './claude/modelControl.js'
import { modelControl as codexModelControl } from './codex/modelControl.js'
@@ -14,8 +16,8 @@ import { runtime as codexRuntime } from './codex/runtimeProfile.js'
/** Only the migrated engines. Others keep their existing handlers until their own small batch. */
const engines = {
- claude: { name: 'claude', launch: engineLaunches.claude, transcript: claudeTranscript, hooks: engineHooks.claude, live: claudeLive, runtime: claudeRuntime, screen: claudeScreen, modelControl: claudeModelControl },
- codex: { name: 'codex', launch: engineLaunches.codex, transcript: codexTranscript, hooks: engineHooks.codex, live: codexLive, runtime: codexRuntime, screen: codexScreen, modelControl: codexModelControl },
+ claude: { name: 'claude', launch: engineLaunches.claude, transcript: claudeTranscript, hooks: engineHooks.claude, live: claudeLive, runtime: claudeRuntime, screen: claudeScreen, modelControl: claudeModelControl, questionControl: claudeQuestionControl },
+ codex: { name: 'codex', launch: engineLaunches.codex, transcript: codexTranscript, hooks: engineHooks.codex, live: codexLive, runtime: codexRuntime, screen: codexScreen, modelControl: codexModelControl, questionControl: codexQuestionControl },
} satisfies Record<string, Engine>
type MigratedEngine = keyof typeof engines
export function engineFor(name: string | null | undefined): Engine | undefined {
diff --git a/cli/src/engines/worker/controlWire.ts b/cli/src/engines/worker/controlWire.ts
new file mode 100644
index 000000000..0b81c6bcd
--- /dev/null
+++ b/cli/src/engines/worker/controlWire.ts
@@ -0,0 +1,9 @@
+/** Common bounds for private control messages. Each facet separately validates its payload. */
+export const CONTROL_BYTES = 1024 * 1024
+export const controlFields = (value: Record<string, unknown>, names: string[]) => Object.keys(value).every(key => names.includes(key))
+export const controlToken = (value: unknown): value is string => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value)
+export const controlSize = (value: unknown) => Buffer.byteLength(JSON.stringify(value)) <= CONTROL_BYTES
+export function controlEnvelope(payload: Record<string, unknown>, version: number, names: string[]): boolean {
+ return payload.version === version && controlFields(payload, ['version', 'requestId', ...names])
+ && (payload.requestId === undefined || (typeof payload.requestId === 'string' && payload.requestId.length <= 200)) && controlSize(payload)
+}
diff --git a/cli/src/engines/worker/modelControlProtocol.ts b/cli/src/engines/worker/modelControlProtocol.ts
index c0687fcea..d8a34ac4d 100644
--- a/cli/src/engines/worker/modelControlProtocol.ts
+++ b/cli/src/engines/worker/modelControlProtocol.ts
@@ -3,6 +3,7 @@ import type { ModelControlCheck, ModelControlInput, RuntimeProfileErrorCode } fr
import type { RuntimeCatalogModel, RuntimeProfile, RuntimeSession } from '../facets/runtime.js'
import { record, type ReaderEngine } from './protocol.js'
import { runtimeContext } from './runtimeProtocol.js'
+import { CONTROL_BYTES, controlEnvelope, controlSize, controlToken } from './controlWire.js'
import { screenCapture } from './screenProtocol.js'
export const MODEL_CONTROL_VERSION = 1
@@ -16,15 +17,15 @@ export const MODEL_CONTROL_QUERY_MS = 10_000
export const MODEL_CONTROL_IN_FLIGHT = 4
export const MODEL_CONTROL_QUERIES = 128
export const MODEL_CONTROL_WRITES = 32
-export const MODEL_CONTROL_BYTES = 1024 * 1024
+export const MODEL_CONTROL_BYTES = CONTROL_BYTES
export const MODEL_CONTROL_ERRORS: readonly RuntimeProfileErrorCode[] = ['AGENT_NOT_FOUND', 'INVALID_RUNTIME_PROFILE', 'BUSY',
'UNSUPPORTED_CLI_VERSION', 'MODEL_UNAVAILABLE', 'EFFORT_UNSUPPORTED', 'PLAN_SCOPE_AMBIGUOUS', 'CONFIRM_TIMEOUT', 'TMUX_FAILED']
const EMPTY_STATE = { model: null, effort: null, mode: 'unknown' as const, cliVersion: null, observedAt: null }
const fields = (value: Record<string, unknown>, names: string[]) => Object.keys(value).every(key => names.includes(key))
const text = (v: unknown, max: number): v is string => typeof v === 'string' && v.length <= max
const label = (v: unknown): v is string => text(v, 2000) && !!v && !/[\x00-\x1f\x7f]/.test(v)
-export const modelControlToken = (value: unknown): value is string => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value)
-export const modelControlSize = (value: unknown) => Buffer.byteLength(JSON.stringify(value)) <= MODEL_CONTROL_BYTES
+export const modelControlToken = controlToken
+export const modelControlSize = controlSize
export function modelControlCatalog(value: unknown): value is RuntimeCatalogModel[] {
return Array.isArray(value) && value.length <= 512 && value.every(m => record(m)
@@ -90,6 +91,5 @@ export function modelControlAnswer(action: ModelControlAction, value: unknown):
}
export function modelControlEnvelope(payload: Record<string, unknown>, names: string[]): boolean {
- return payload.version === MODEL_CONTROL_VERSION && fields(payload, ['version', 'requestId', ...names])
- && (payload.requestId === undefined || text(payload.requestId, 200)) && modelControlSize(payload)
+ return controlEnvelope(payload, MODEL_CONTROL_VERSION, names)
}
diff --git a/cli/src/engines/worker/process.ts b/cli/src/engines/worker/process.ts
index e1b70d9f2..8e6a887aa 100644
--- a/cli/src/engines/worker/process.ts
+++ b/cli/src/engines/worker/process.ts
@@ -1,3 +1,4 @@
+import { engineQuestionControlRequests } from './questionControlRequests.js'
import type { CoreConnection } from '../../services/process.js'
import { engineModelControlRequests } from './modelControlRequests.js'
/** One engine's facets, hosted by the master's existing service supervisor. */
@@ -92,6 +93,8 @@ export function runEngineReader(engine: ReaderEngine, options: EngineProcessOpti
name: READER_SERVICES[engine], socketPath: options.socketPath, machineId: options.machineId,
token: options.token, requests: options.requests ?? { ...engineReaderRequests(engine), ...engineLiveRequests(engine), ...engineRuntimeRequests(engine), ...engineScreenRequests(engine), ...engineModelControlRequests(engine, {
query: (query, payload) => core ? core.query(query, payload) : Promise.reject(new Error('core disconnected')),
+ }), ...engineQuestionControlRequests(engine, {
+ query: (query, payload) => core ? core.query(query, payload) : Promise.reject(new Error('core disconnected')),
}) },
onConnected: connected => { core = connected }, onDisconnected: () => { core = null },
})
diff --git a/cli/src/engines/worker/questionControlHost.ts b/cli/src/engines/worker/questionControlHost.ts
new file mode 100644
index 000000000..de3cfd016
--- /dev/null
+++ b/cli/src/engines/worker/questionControlHost.ts
@@ -0,0 +1,11 @@
+import type { QuestionControlHost } from '../facets/questionControl.js'
+import { questionControlEnvelope, type QuestionControlAction } from './questionControlProtocol.js'
+
+export function createQuestionControlHost(ask: (action: QuestionControlAction) => Promise<Record<string, unknown>>): QuestionControlHost {
+ const call = async (action: QuestionControlAction) => {
+ const reply = await ask(action)
+ if (!questionControlEnvelope(reply, ['value', 'error']) || reply.error !== undefined || typeof reply.value !== 'boolean') throw new Error('question control unavailable')
+ return reply.value
+ }
+ return { key: key => call({ kind: 'key', key }), text: text => call({ kind: 'text', text }) }
+}
diff --git a/cli/src/engines/worker/questionControlProtocol.ts b/cli/src/engines/worker/questionControlProtocol.ts
new file mode 100644
index 000000000..caf3494ef
--- /dev/null
+++ b/cli/src/engines/worker/questionControlProtocol.ts
@@ -0,0 +1,41 @@
+import type { QuestionStep } from '../facets/questionControl.js'
+import type { QuestionRow } from '../facets/screen.js'
+import { record } from './protocol.js'
+import { controlEnvelope, controlFields as fields, controlSize } from './controlWire.js'
+
+export const QUESTION_CONTROL_VERSION = 1
+export const QUESTION_CONTROL_CAPABILITIES = 'engine_question_control_capabilities'
+export const QUESTION_CONTROL_APPLY = 'engine_question_control_apply'
+export const QUESTION_CONTROL_HOST = 'engine.questionControl'
+export const QUESTION_CONTROL_WAIT_MS = 30_000
+export const QUESTION_CONTROL_QUERY_MS = 5_000
+// One step per agent's dialog at a time (the controller drives one answer per terminal). Four refused two of
+// six Claude Code agents answered at once in the question workload (e2e/perf.e2e.ts, PERF_QUESTIONS=1), which
+// the inline path never did; sixteen covers a machine's agents and still bounds the worker.
+export const QUESTION_CONTROL_IN_FLIGHT = 16
+export const QUESTION_CONTROL_WRITES = 128
+export const questionControlEnvelope = (payload: Record<string, unknown>, names: string[]) => controlEnvelope(payload, QUESTION_CONTROL_VERSION, names)
+const digit = (value: unknown): value is string => typeof value === 'string' && /^[1-9]\d?$/.test(value)
+const text = (value: unknown): value is string => typeof value === 'string' && Buffer.byteLength(value) <= 32768 && !/[\x00-\x09\x0b-\x1f\x7f]/.test(value)
+const row = (value: unknown): value is QuestionRow => record(value) && fields(value, ['number', 'label', 'checked', 'walk'])
+ && digit(value.number) && typeof value.label === 'string' && value.label.length <= 262144 && typeof value.checked === 'boolean'
+ && (value.walk === undefined || value.walk === 'right' || value.walk === 'down')
+export function questionControlStep(value: unknown): value is QuestionStep {
+ if (!record(value) || !controlSize(value)) return false
+ if (value.kind === 'select') return fields(value, ['kind', 'row', 'enterSubmits']) && row(value.row)
+ && (value.enterSubmits === undefined || typeof value.enterSubmits === 'boolean')
+ if (value.kind === 'text') return fields(value, ['kind', 'row', 'text']) && row(value.row) && text(value.text)
+ if (value.kind === 'review') return fields(value, ['kind', 'key']) && (digit(value.key) || value.key === 'Enter')
+ if (value.kind !== 'multiple' || !fields(value, ['kind', 'rows', 'freeText']) || !Array.isArray(value.rows)
+ || value.rows.length > 99 || !value.rows.every(row)) return false
+ return value.freeText === undefined || (record(value.freeText) && fields(value.freeText, ['row', 'text']) && row(value.freeText.row) && text(value.freeText.text))
+}
+export type QuestionControlAction = { kind: 'text'; text: string } | { kind: 'key'; key: string }
+export function questionControlAction(value: unknown): value is QuestionControlAction {
+ if (!record(value)) return false
+ if (value.kind === 'text') return fields(value, ['kind', 'text']) && text(value.text)
+ return value.kind === 'key' && fields(value, ['kind', 'key']) && (digit(value.key) || ['Enter', 'Tab', 'Right', 'Down'].includes(value.key as string))
+}
+export function questionStepText(step: QuestionStep): string | undefined {
+ return step.kind === 'text' ? step.text : step.kind === 'multiple' ? step.freeText?.text : undefined
+}
diff --git a/cli/src/engines/worker/questionControlRequests.spec.ts b/cli/src/engines/worker/questionControlRequests.spec.ts
new file mode 100644
index 000000000..0bb9b3b86
--- /dev/null
+++ b/cli/src/engines/worker/questionControlRequests.spec.ts
@@ -0,0 +1,109 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { EngineQuestionControl, QuestionControlHost, QuestionStep } from '../facets/questionControl.js'
+import { createQuestionControl as claude } from '../claude/questionControl.js'
+import { createQuestionControl as codex } from '../codex/questionControl.js'
+import { engineQuestionControlRequests } from './questionControlRequests.js'
+import { createQuestionControlHost } from './questionControlHost.js'
+import { questionControlStep, questionControlAction, QUESTION_CONTROL_APPLY as APPLY, QUESTION_CONTROL_CAPABILITIES as CAP,
+ QUESTION_CONTROL_IN_FLIGHT, QUESTION_CONTROL_QUERY_MS, QUESTION_CONTROL_WAIT_MS } from './questionControlProtocol.js'
+
+const row = { number: '2', label: 'Coffee', checked: false }
+const step: QuestionStep = { kind: 'select', row, enterSubmits: true }
+const request = { version: 1, token: 'a'.repeat(64), step, requestId: 'core-request' }
+const asker = { owner: true, local: true }
+const denied = { version: 1, error: 'ANSWER_FAILED' }
+function setup(engine: 'claude' | 'codex' = 'claude') {
+ const control: EngineQuestionControl = { apply: vi.fn(async () => true) }
+ const deps = { load: vi.fn(async () => control), recycle: vi.fn(), query: vi.fn(async () => ({ version: 1, value: true, requestId: 'core-reply' } as Record<string, unknown>)) }
+ const requests = engineQuestionControlRequests(engine, deps)
+ return { requests, control, deps }
+}
+
+describe('private question-control worker', () => {
+ beforeEach(() => vi.useFakeTimers())
+ afterEach(() => vi.useRealTimers())
+
+ it('loads only for a private, bounded core request and retries a failed import', async () => {
+ const s = setup()
+ expect(await s.requests[CAP]({ version: 1 }, asker)).toEqual({ version: 1, questionControl: 1, engine: 'claude' })
+ expect(s.deps.load).not.toHaveBeenCalled()
+ for (const who of [{ owner: false, local: true }, { owner: true, local: false }, { ...asker, connection: 'client' }]) {
+ expect(await s.requests[APPLY](request, who)).toEqual(denied)
+ }
+ for (const payload of [{ ...request, version: 2 }, { ...request, token: 'guess' }, { ...request, terminal: '%9' }, { ...request, requestId: 3 }, { ...request, step: {} }]) {
+ expect(await s.requests[APPLY](payload, asker)).toEqual(denied)
+ }
+ s.deps.load.mockRejectedValueOnce(new Error('load failed'))
+ expect(await s.requests[APPLY](request, asker)).toEqual(denied)
+ expect(await s.requests[APPLY](request, asker)).toEqual({ version: 1, ok: true })
+ expect(await s.requests[APPLY](request, asker)).toEqual({ version: 1, ok: true })
+ expect(s.deps.load).toHaveBeenCalledTimes(2)
+ s.control.apply = vi.fn(async () => false)
+ expect(await s.requests[APPLY](request, asker)).toEqual(denied)
+ })
+
+ it.each(['claude', 'codex'] as const)('runs %s native navigation and free-text sequencing through the host', async engine => {
+ const s = setup(engine), keys: string[] = []
+ s.control.apply = (engine === 'claude' ? claude : codex)(async () => {}).apply
+ s.deps.query.mockImplementation(async () => ({ version: 1, value: true, requestId: 'core-reply' }))
+ const actions: QuestionStep[] = [step, { kind: 'select', row }, { kind: 'text', row, text: 'My answer' },
+ { kind: 'multiple', rows: [row] }, { kind: 'multiple', rows: [], freeText: { row, text: 'Custom choice' } }, { kind: 'review', key: 'Enter' }]
+ for (const step of actions) expect(await s.requests[APPLY]({ ...request, step }, asker)).toEqual({ version: 1, ok: true })
+ for (const call of s.deps.query.mock.calls) {
+ const [query, payload] = call as unknown as [string, { token: string; action: { kind: string; key?: string; text?: string } }]
+ expect(query).toBe('engine.questionControl'); expect(payload.token).toBe(request.token)
+ keys.push(payload.action.key ?? `text:${payload.action.text}`)
+ }
+ expect(keys).toEqual([...(engine === 'codex' ? ['2', 'Enter'] : ['2']), '2', '2', 'text:My answer', 'Enter', '2', 'Tab', '2', 'text:Custom choice', 'Enter', 'Tab', 'Enter'])
+ })
+
+ it('bounds the step and effect vocabulary, including total payload bytes', () => {
+ for (const value of [null, [], {}, { ...step, terminal: '%9' }, { ...step, enterSubmits: 1 }, { ...step, row: { ...row, number: 'C-c' } },
+ { ...step, row: { ...row, walk: 'up' } }, { kind: 'text', row, text: 'a\u0000b' }, { kind: 'text', row, text: 'x'.repeat(32769) },
+ { kind: 'review', key: 'C-c' }, { kind: 'multiple', rows: Array(100).fill(row) }, { kind: 'multiple', rows: [], freeText: { row, text: 2 } },
+ { kind: 'multiple', rows: Array(5).fill({ ...row, label: 'x'.repeat(262144) }) }]) expect(questionControlStep(value)).toBe(false)
+ for (const value of [null, {}, { kind: 'key', key: 'C-c' }, { kind: 'text', text: '\t' }, { kind: 'key', key: '2', target: '%9' }]) expect(questionControlAction(value)).toBe(false)
+ for (const value of [{ kind: 'key', key: '99' }, { kind: 'key', key: 'Tab' }, { kind: 'text', text: 'two\nlines' }]) expect(questionControlAction(value)).toBe(true)
+ })
+
+ it('refuses malformed host replies and makes no late request after completion or abort', async () => {
+ for (const reply of [{ version: 2, value: true }, { version: 1, value: 1 }, { version: 1, value: true, terminal: '%9' },
+ { version: 1, value: true, error: 'ANSWER_FAILED' }, { version: 1, value: 'x'.repeat(1024 * 1024) }]) {
+ await expect(createQuestionControlHost(async () => reply).key('2')).rejects.toThrow()
+ }
+ const s = setup(), already = new AbortController()
+ already.abort()
+ expect(await s.requests[APPLY](request, asker, already.signal)).toEqual(denied)
+ let host!: QuestionControlHost
+ s.control.apply = vi.fn(async (_step, value) => { host = value; return value.key('2') })
+ expect(await s.requests[APPLY](request, asker)).toHaveProperty('ok', true)
+ await expect(host.key('Enter')).rejects.toThrow()
+ const closed = new AbortController()
+ s.control.apply = vi.fn(async (_step, value) => { closed.abort(); return value.key('Enter') })
+ expect(await s.requests[APPLY](request, asker, closed.signal)).toEqual(denied)
+ expect(s.deps.query).toHaveBeenCalledOnce()
+ })
+
+ it.each(['load', 'apply', 'query'] as const)('bounds and recycles a hung %s', async kind => {
+ const s = setup()
+ let host!: QuestionControlHost
+ if (kind === 'load') s.deps.load.mockImplementation(() => new Promise(() => {}))
+ else s.control.apply = vi.fn(async (_step, value) => { host = value; return kind === 'query' ? value.key('2') : new Promise(() => {}) })
+ if (kind === 'query') s.deps.query.mockImplementation(() => new Promise(() => {}))
+ const result = s.requests[APPLY](request, asker)
+ await vi.advanceTimersByTimeAsync((kind === 'query' ? QUESTION_CONTROL_QUERY_MS : QUESTION_CONTROL_WAIT_MS) + 1)
+ expect(await result).toEqual(denied)
+ expect(s.deps.recycle).toHaveBeenCalledOnce()
+ if (host) await expect(host.text('late')).rejects.toThrow()
+ })
+
+ it('refuses overflow without queueing and aborts pending work when core disconnects', async () => {
+ const s = setup(), closed = new AbortController()
+ s.control.apply = vi.fn(() => new Promise<boolean>(() => {}))
+ const pending = Array.from({ length: QUESTION_CONTROL_IN_FLIGHT }, () => s.requests[APPLY](request, asker, closed.signal))
+ expect(await s.requests[APPLY](request, asker)).toEqual(denied)
+ closed.abort()
+ expect(await Promise.all(pending)).toEqual(Array(QUESTION_CONTROL_IN_FLIGHT).fill(denied))
+ expect(s.deps.recycle).not.toHaveBeenCalled()
+ })
+})
diff --git a/cli/src/engines/worker/questionControlRequests.ts b/cli/src/engines/worker/questionControlRequests.ts
new file mode 100644
index 000000000..cdbf3d4b5
--- /dev/null
+++ b/cli/src/engines/worker/questionControlRequests.ts
@@ -0,0 +1,66 @@
+import type { ServiceRequests } from '../../core/api.js'
+import type { EngineQuestionControl } from '../facets/questionControl.js'
+import { controlToken } from './controlWire.js'
+import { createQuestionControlHost } from './questionControlHost.js'
+import { questionControlEnvelope, questionControlStep, QUESTION_CONTROL_APPLY, QUESTION_CONTROL_CAPABILITIES,
+ QUESTION_CONTROL_HOST, QUESTION_CONTROL_IN_FLIGHT, QUESTION_CONTROL_QUERY_MS, QUESTION_CONTROL_VERSION, QUESTION_CONTROL_WAIT_MS } from './questionControlProtocol.js'
+import type { ReaderEngine } from './protocol.js'
+
+const loadControl = {
+ claude: async () => (await import('../claude/questionControl.js')).questionControl,
+ codex: async () => (await import('../codex/questionControl.js')).questionControl,
+}
+export interface QuestionControlRequestDeps {
+ query(query: string, payload: Record<string, unknown>): Promise<Record<string, unknown>>
+ load?: () => Promise<EngineQuestionControl>
+ recycle?: () => void
+}
+
+export function engineQuestionControlRequests(engine: ReaderEngine, deps: QuestionControlRequestDeps): ServiceRequests {
+ let loaded: Promise<EngineQuestionControl> | null = null
+ let pending = 0
+ const failure = () => ({ version: QUESTION_CONTROL_VERSION, error: 'ANSWER_FAILED' })
+ const recycle = deps.recycle ?? (() => process.exit(1))
+ const handler = (capability: boolean): ServiceRequests[string] => async (payload, asker, closed) => {
+ if (!asker.owner || !asker.local || asker.connection !== undefined || closed?.aborted) return failure()
+ if (!questionControlEnvelope(payload, capability ? [] : ['step', 'token'])) return failure()
+ if (capability) return { version: QUESTION_CONTROL_VERSION, questionControl: QUESTION_CONTROL_VERSION, engine }
+ if (!questionControlStep(payload.step) || !controlToken(payload.token) || pending >= QUESTION_CONTROL_IN_FLIGHT) return failure()
+ const step = payload.step
+ pending++
+ let active = true
+ let timer: ReturnType<typeof setTimeout> | undefined
+ let abort: (() => void) | undefined
+ const stopped = new Promise<Record<string, unknown>>(resolve => {
+ abort = () => { active = false; resolve(failure()) }
+ closed?.addEventListener('abort', abort, { once: true })
+ timer = setTimeout(() => { abort!(); recycle() }, QUESTION_CONTROL_WAIT_MS)
+ })
+ const valid = () => { if (!active) throw new Error('question control revoked') }
+ const host = createQuestionControlHost(async action => {
+ valid()
+ let timeout: ReturnType<typeof setTimeout> | undefined
+ try {
+ const reply = await Promise.race([
+ deps.query(QUESTION_CONTROL_HOST, { version: QUESTION_CONTROL_VERSION, token: payload.token, action }),
+ new Promise<never>((_, reject) => { timeout = setTimeout(() => {
+ active = false; reject(new Error('question host timeout')); recycle()
+ }, QUESTION_CONTROL_QUERY_MS) }),
+ ])
+ valid()
+ return reply
+ } finally { clearTimeout(timeout) }
+ })
+ try {
+ return await Promise.race([stopped, (async () => {
+ const control = await (loaded ??= (deps.load ?? loadControl[engine])().catch(error => { loaded = null; throw error }))
+ valid()
+ const ok = await control.apply(step, host)
+ valid()
+ return ok ? { version: QUESTION_CONTROL_VERSION, ok: true } : failure()
+ })()])
+ } catch { return failure() }
+ finally { active = false; clearTimeout(timer); closed?.removeEventListener('abort', abort!); pending-- }
+ }
+ return { [QUESTION_CONTROL_CAPABILITIES]: handler(true), [QUESTION_CONTROL_APPLY]: handler(false) }
+}
diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.ts
index 81feeee96..2ebf9216f 100644
--- a/cli/src/harnessd/services.spec.ts
+++ b/cli/src/harnessd/services.spec.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
- DEFAULT_SERVICE_OPTIONS, ENGINE_LIVE_ENV, ENGINE_RUNTIME_ENV, ENGINE_SCREEN_ENV, ENGINE_MODEL_CONTROL_ENV, masterRunsEngineModelControl, KNOWN_SERVICES, SERVICE_HOSTS, SERVICE_PROCESSES_ENV, ServiceSupervisor, UPDATER_HOST, masterRunsLiveEngines, masterRunsEngineRuntime, masterRunsEngineScreen, serviceOptions, serviceProcessesEnv, serviceSpecs, servicesTheMasterRuns,
+ DEFAULT_SERVICE_OPTIONS, ENGINE_LIVE_ENV, ENGINE_RUNTIME_ENV, ENGINE_SCREEN_ENV, ENGINE_MODEL_CONTROL_ENV, masterRunsEngineModelControl, ENGINE_QUESTION_CONTROL_ENV, masterRunsEngineQuestionControl, KNOWN_SERVICES, SERVICE_HOSTS, SERVICE_PROCESSES_ENV, ServiceSupervisor, UPDATER_HOST, masterRunsLiveEngines, masterRunsEngineRuntime, masterRunsEngineScreen, serviceOptions, serviceProcessesEnv, serviceSpecs, servicesTheMasterRuns,
type ServiceSpec, type ServiceSupervisorOptions,
} from './services.js'
import type { CoreHandle } from './supervisor.js'
@@ -472,15 +472,15 @@ describe('which services the core leaves to its master', () => {
it('is what the master says it runs, told in a form a core from before the list reads too', () => {
const specs = serviceSpecs({ HARNESSD_SERVICES: 'search,workspaces' }, SERVICE_HOSTS)
- expect(serviceProcessesEnv(specs, 42)).toEqual({ [SERVICE_PROCESSES_ENV]: 'search,workspaces', HARNESSD_SERVICES: 'search,workspaces', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_ENV]: '42:1' })
+ expect(serviceProcessesEnv(specs, 42)).toEqual({ [SERVICE_PROCESSES_ENV]: 'search,workspaces', HARNESSD_SERVICES: 'search,workspaces', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_ENV]: '42:1', [ENGINE_QUESTION_CONTROL_ENV]: '42:1' })
// A process named as one of its services is named whole: the viewers' process runs the Store beside them.
expect(serviceProcessesEnv(serviceSpecs({ HARNESSD_SERVICES: 'viewers' }, SERVICE_HOSTS), 42)).toMatchObject({ [SERVICE_PROCESSES_ENV]: 'viewers,store' })
expect(serviceProcessesEnv(serviceSpecs({ HARNESSD_SERVICES: 'store' }, SERVICE_HOSTS), 42)).toMatchObject({ [SERVICE_PROCESSES_ENV]: 'store' })
// By service, not by process: a core from before the edge host routes the services it knows of it.
const hosted = serviceSpecs({ HARNESSD_SERVICES: 'edge' }, SERVICE_HOSTS)
- expect(serviceProcessesEnv(hosted, 42)).toEqual({ [SERVICE_PROCESSES_ENV]: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_ENV]: '42:1' })
+ expect(serviceProcessesEnv(hosted, 42)).toEqual({ [SERVICE_PROCESSES_ENV]: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames,shell', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_ENV]: '42:1', [ENGINE_QUESTION_CONTROL_ENV]: '42:1' })
expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(hosted, 42) }, known)]).toEqual(['workspaces'])
- expect(serviceProcessesEnv([], 42)).toEqual({ [SERVICE_PROCESSES_ENV]: '', HARNESSD_SERVICES: 'none', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_ENV]: '42:1' })
+ expect(serviceProcessesEnv([], 42)).toEqual({ [SERVICE_PROCESSES_ENV]: '', HARNESSD_SERVICES: 'none', [ENGINE_LIVE_ENV]: '42:1', [ENGINE_RUNTIME_ENV]: '42:1', [ENGINE_SCREEN_ENV]: '42:1', [ENGINE_MODEL_CONTROL_ENV]: '42:1', [ENGINE_QUESTION_CONTROL_ENV]: '42:1' })
expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(specs, 42) }, known)]).toEqual(['search', 'workspaces'])
expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv([], 42) }, known)]).toEqual([])
// What the master says wins over whatever HARNESSD_SERVICES the core inherited; names it does not know are its own.
@@ -519,6 +519,10 @@ describe('which services the core leaves to its master', () => {
it('negotiates model controls only from a capable supervising parent', () => {
const env = { ...supervised, ...serviceProcessesEnv([], 42) }
+ expect(masterRunsEngineQuestionControl(env, 42)).toBe(true)
+ expect(masterRunsEngineQuestionControl(env, 43)).toBe(false)
+ expect(masterRunsEngineQuestionControl({ ...env, [ENGINE_QUESTION_CONTROL_ENV]: undefined }, 42)).toBe(false)
+ expect(masterRunsEngineQuestionControl({ ...env, HARNESSD_SERVICE_TOKEN: undefined }, 42)).toBe(false)
expect(masterRunsEngineModelControl(env, 42)).toBe(true)
expect(masterRunsEngineModelControl(env, 43)).toBe(false)
expect(masterRunsEngineModelControl({ ...env, [ENGINE_MODEL_CONTROL_ENV]: undefined }, 42)).toBe(false)
diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.ts
index 93a1d1ec4..a0e7f2635 100644
--- a/cli/src/harnessd/services.ts
+++ b/cli/src/harnessd/services.ts
@@ -461,6 +461,7 @@ export const ENGINE_LIVE_ENV = 'HARNESSD_ENGINE_LIVE'
export const ENGINE_RUNTIME_ENV = 'HARNESSD_ENGINE_RUNTIME'
export const ENGINE_SCREEN_ENV = 'HARNESSD_ENGINE_SCREEN'
export const ENGINE_MODEL_CONTROL_ENV = 'HARNESSD_ENGINE_MODEL_CONTROL'
+export const ENGINE_QUESTION_CONTROL_ENV = 'HARNESSD_ENGINE_QUESTION_CONTROL'
/**
* What a master puts in its core's environment about the services it runs in their own processes: the
@@ -472,7 +473,7 @@ export function serviceProcessesEnv(specs: readonly ServiceSpec[], masterPid: nu
// The services, not the processes: a core knows what it routes by service, and one from before the
// edge host still finds the services it knows here (workspaces) and runs the rest itself.
const names = specs.flatMap((spec) => spec.services).join(',')
- return { [SERVICE_PROCESSES_ENV]: names, HARNESSD_SERVICES: names || 'none', [ENGINE_LIVE_ENV]: `${masterPid}:1`, [ENGINE_RUNTIME_ENV]: `${masterPid}:1`, [ENGINE_SCREEN_ENV]: `${masterPid}:1`, [ENGINE_MODEL_CONTROL_ENV]: `${masterPid}:1` }
+ return { [SERVICE_PROCESSES_ENV]: names, HARNESSD_SERVICES: names || 'none', [ENGINE_LIVE_ENV]: `${masterPid}:1`, [ENGINE_RUNTIME_ENV]: `${masterPid}:1`, [ENGINE_SCREEN_ENV]: `${masterPid}:1`, [ENGINE_MODEL_CONTROL_ENV]: `${masterPid}:1`, [ENGINE_QUESTION_CONTROL_ENV]: `${masterPid}:1` }
}
/** An older master may inherit a newer master's environment after rollback. Trust only this parent. */
@@ -532,3 +533,7 @@ export function masterRunsEngineScreen(env: NodeJS.ProcessEnv, parentPid: number
export function masterRunsEngineModelControl(env: NodeJS.ProcessEnv, parentPid: number): boolean {
return masterRunsLiveEngines(env, parentPid) && env[ENGINE_MODEL_CONTROL_ENV] === `${parentPid}:1`
}
+
+export function masterRunsEngineQuestionControl(env: NodeJS.ProcessEnv, parentPid: number): boolean {
+ return masterRunsLiveEngines(env, parentPid) && env[ENGINE_QUESTION_CONTROL_ENV] === `${parentPid}:1`
+}
diff --git a/cli/src/lib/askQuestion.ts b/cli/src/lib/askQuestion.ts
index 877ed9625..6bf9cad3b 100644
--- a/cli/src/lib/askQuestion.ts
+++ b/cli/src/lib/askQuestion.ts
@@ -1,3 +1,5 @@
+export { codexRowKeys } from '../engines/codex/questionControl.js'
+import { questionControlFor } from '../engines/questionControls.js'
export { isApprovalDialog, parsePermissionPane, parseQuestionPane } from '../engines/kit/questionPane.js'
/** Explicit inline compatibility for direct users and recorded-screen fixtures. */
export * from './questionController.js'
@@ -7,7 +9,13 @@ import { AskQuestionController as Controller, QuestionWatcher as Watcher } from
import type { AskQuestionDeps, QuestionWatcherDeps, PaneView } from './questionController.js'
const readQuestion: AskQuestionDeps['readQuestion'] = (session, capture) => parseEngineQuestionPane(session.engine ?? 'claude', capture)
export class AskQuestionController extends Controller {
- constructor(deps: Omit<AskQuestionDeps, 'readQuestion'> & Partial<Pick<AskQuestionDeps, 'readQuestion'>>) { super({ readQuestion, ...deps }) }
+ constructor(deps: Omit<AskQuestionDeps, 'readQuestion' | 'questionControlFor'> & Partial<Pick<AskQuestionDeps, 'readQuestion' | 'questionControlFor'>>) {
+ super({ readQuestion, questionControlFor: session => {
+ const control = questionControlFor(session.engine ?? 'claude', deps.wait)
+ const target = session.agentId || session.sessionId
+ return control ? { apply: step => control.apply(step, { text: text => deps.sendText(target, text), key: key => deps.sendKey(target, key) }) } : undefined
+ }, ...deps })
+ }
}
export class QuestionWatcher extends Watcher {
constructor(private readonly inlineDeps: Omit<QuestionWatcherDeps, 'readQuestion'> & Partial<Pick<QuestionWatcherDeps, 'readQuestion'>>) { super({ readQuestion, ...inlineDeps }) }
diff --git a/cli/src/lib/questionControl.ts b/cli/src/lib/questionControl.ts
new file mode 100644
index 000000000..89046fafa
--- /dev/null
+++ b/cli/src/lib/questionControl.ts
@@ -0,0 +1,16 @@
+import type { QuestionStep } from '../engines/facets/questionControl.js'
+import type { RegisteredSession } from './registry.js'
+
+/**
+ * Why the last step failed: `refused`, nothing was typed (no capacity, no worker, a refused grant); `uncertain`,
+ * at least one key or text had gone to the terminal before it failed (a worker killed mid-step), so only the
+ * pane can tell whether the answer went in.
+ */
+export type QuestionStepFailure = 'refused' | 'uncertain'
+/** Bound once for the complete answer, before any screen read or terminal write. */
+export interface QuestionControlSession {
+ apply(step: QuestionStep): Promise<boolean>
+ /** After `apply` resolved false; undefined when it is not known. */
+ failure?(): QuestionStepFailure | undefined
+}
+export type QuestionControlFor = (session: RegisteredSession) => QuestionControlSession | undefined
diff --git a/cli/src/lib/questionController.spec.ts b/cli/src/lib/questionController.spec.ts
index fbdf365de..db3320364 100644
--- a/cli/src/lib/questionController.spec.ts
+++ b/cli/src/lib/questionController.spec.ts
@@ -12,6 +12,102 @@ const deferred = <T>() => { let resolve!: (value: T) => void; const promise = ne
afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() })
describe('asynchronous question evidence', () => {
+ it('binds native control before capture and snapshots the reviewed answer', async () => {
+ const current = row(), release = vi.fn(), apply = vi.fn(async () => true), questionControlFor = vi.fn(() => ({ apply }))
+ const sendKey = vi.fn(async () => true), sendText = vi.fn(async () => true)
+ const question = { kind: 'question' as const, question: 'Drink?', multi: false, typeRow: null,
+ rows: [{ number: '1', label: 'Tea', checked: false }, { number: '2', label: 'Coffee', checked: false }] }
+ const payload = { agentId: 'agent', answers: { 'Drink?': 'Coffee' }, expectedQuestions: [{ key: 'Drink?', q: 'Drink?', options: ['Tea', 'Coffee'], multi: false }] }
+ const readQuestion = vi.fn(async (): Promise<PaneView> => question).mockResolvedValueOnce(question).mockResolvedValueOnce(null)
+ const controller = new AskQuestionController({ getSession: () => current, questionControlFor, readQuestion, sendKey, sendText,
+ acquireControl: () => release, capture: async () => {
+ expect(questionControlFor).toHaveBeenCalledOnce()
+ payload.answers['Drink?'] = 'Tea'; payload.expectedQuestions[0].options = ['changed']
+ return capture
+ } })
+ expect(await controller.answer(payload)).toEqual({ ok: true })
+ expect(apply).toHaveBeenCalledWith({ kind: 'select', row: question.rows[1], enterSubmits: undefined })
+ expect(sendKey).not.toHaveBeenCalled(); expect(sendText).not.toHaveBeenCalled()
+ expect(release).toHaveBeenCalledOnce()
+ })
+
+ it('does not use the local writer after the bound native driver fails', async () => {
+ const current = row(), sendKey = vi.fn(async () => true), sendText = vi.fn(async () => true), release = vi.fn()
+ const controller = new AskQuestionController({ getSession: () => current, capture: async () => capture,
+ readQuestion: async () => view, sendKey, sendText, acquireControl: () => release,
+ questionControlFor: () => ({ apply: async () => { throw new Error('worker went away') } }) })
+ if (!view || view.kind !== 'question') throw new Error('missing recorded fixture')
+ expect(await controller.answer({ agentId: 'agent', answers: { [view.question]: view.rows[0].label } })).toMatchObject({ ok: false, error: 'ANSWER_FAILED' })
+ expect(sendKey).not.toHaveBeenCalled(); expect(sendText).not.toHaveBeenCalled()
+ expect(release).toHaveBeenCalledOnce()
+ })
+
+ it('releases its lease and types nothing when the control port cannot be bound', async () => {
+ const current = row(), sendKey = vi.fn(async () => true), sendText = vi.fn(async () => true), release = vi.fn()
+ let bind: () => undefined = () => { throw new Error('no control port') }
+ const controller = new AskQuestionController({ getSession: () => current, capture: async () => capture,
+ readQuestion: async () => view, sendKey, sendText, acquireControl: () => release, questionControlFor: () => bind() })
+ if (!view || view.kind !== 'question') throw new Error('missing recorded fixture')
+ const answer = { agentId: 'agent', answers: { [view.question]: view.rows[0].label } }
+ expect(await controller.answer(answer)).toMatchObject({ ok: false, error: 'ANSWER_FAILED' })
+ expect(sendKey).not.toHaveBeenCalled(); expect(sendText).not.toHaveBeenCalled()
+ expect(release).toHaveBeenCalledOnce()
+ // Nothing is left marked as driving this terminal: the next answer is entered, not refused as busy.
+ bind = () => undefined
+ expect(await controller.answer(answer)).not.toMatchObject({ error: 'ANSWER_BUSY' })
+ expect(release).toHaveBeenCalledTimes(2)
+ })
+
+ describe('a native step that failed', () => {
+ const question = { kind: 'question' as const, question: 'Drink?', multi: false, typeRow: null,
+ rows: [{ number: '1', label: 'Tea', checked: false }, { number: '2', label: 'Coffee', checked: false }] }
+ const answer = { agentId: 'agent', answers: { 'Drink?': 'Coffee' } }
+ const run = async (failure: 'refused' | 'uncertain' | undefined, views: PaneView[], applies = [false]) => {
+ const current = row(), release = vi.fn(), sendKey = vi.fn(async () => true), sendText = vi.fn(async () => true)
+ const apply = vi.fn(async () => false)
+ for (const value of applies) apply.mockResolvedValueOnce(value)
+ const readQuestion = vi.fn(async (): Promise<PaneView> => views.at(-1)!)
+ for (const view of views) readQuestion.mockResolvedValueOnce(view)
+ const controller = new AskQuestionController({ getSession: () => current, capture: async () => capture, readQuestion, sendKey, sendText,
+ acquireControl: () => release, wait: async () => {}, questionControlFor: () => ({ apply, failure: () => failure }) })
+ const result = await controller.answer(answer)
+ expect(sendKey).not.toHaveBeenCalled(); expect(sendText).not.toHaveBeenCalled()
+ expect(release).toHaveBeenCalledOnce()
+ return { result, apply }
+ }
+
+ it('says busy, with nothing typed, when the step was refused before any write', async () => {
+ expect((await run('refused', [question])).result).toEqual({ ok: false, error: 'ANSWER_BUSY', detail: expect.stringContaining('Nothing was typed') })
+ })
+
+ it('reports the answer taken when a step that wrote failed and the dialog then closed', async () => {
+ // Found by the chaos run: the worker was killed after the last key, and the answer was reported failed.
+ const { result, apply } = await run('uncertain', [question, null])
+ expect(result).toEqual({ ok: true })
+ expect(apply).toHaveBeenCalledOnce()
+ })
+
+ it('types nothing more, and reports it stuck, when a step that wrote failed and the dialog stayed', async () => {
+ const { result, apply } = await run('uncertain', [question])
+ expect(result).toMatchObject({ ok: false, error: 'ANSWER_FAILED', detail: 'The question did not take the answer.' })
+ expect(apply).toHaveBeenCalledOnce()
+ })
+
+ it('keeps the old failure when the port does not say why', async () => {
+ expect((await run(undefined, [question])).result).toMatchObject({ ok: false, error: 'ANSWER_FAILED', detail: expect.stringContaining('could not be typed') })
+ })
+
+ it('checks the pane once after an uncertain submit of the review: gone is submitted, still there is not', async () => {
+ const review: PaneView = { kind: 'review', submitRow: '1' }
+ expect((await run('uncertain', [question, review, null], [true, false])).result).toEqual({ ok: true })
+ const stayed = await run('uncertain', [question, review, review], [true, false])
+ expect(stayed.result).toMatchObject({ ok: false, error: 'ANSWER_FAILED', detail: 'The answers could not be submitted.' })
+ expect(stayed.apply).toHaveBeenCalledTimes(2)
+ expect((await run('refused', [question, review], [true, false])).result).toMatchObject({ error: 'ANSWER_BUSY' })
+ expect((await run(undefined, [question, review], [true, false])).result).toMatchObject({ detail: 'The answers could not be submitted.' })
+ })
+ })
+
it('keeps a previously announced question while the screen reader is unavailable', async () => {
vi.useFakeTimers()
const current = row(), onQuestion = vi.fn(), onQuestionGone = vi.fn()
@@ -47,7 +143,7 @@ describe('asynchronous question evidence', () => {
})
it.each(['unavailable', 'rebound', 'capture-rebound'] as const)('types no answer after %s and releases its input lease', async change => {
const current = row(), release = vi.fn(), sendKey = vi.fn(async () => true), sendText = vi.fn(async () => true)
- const controller = new AskQuestionController({ getSession: () => current,
+ const controller = new AskQuestionController({ questionControlFor: () => undefined, getSession: () => current,
capture: async () => { if (change === 'capture-rebound') current.sessionId = 'replacement'; return capture },
sendKey, sendText, acquireControl: () => release,
readQuestion: async () => {
diff --git a/cli/src/lib/questionController.ts b/cli/src/lib/questionController.ts
index a2cc09772..9e586dda4 100644
--- a/cli/src/lib/questionController.ts
+++ b/cli/src/lib/questionController.ts
@@ -1,3 +1,5 @@
+import type { QuestionStep } from '../engines/facets/questionControl.js'
+import type { QuestionControlFor, QuestionControlSession, QuestionStepFailure } from './questionControl.js'
import type { RegisteredSession } from './registry.js'
import type { AgentEngine } from '../engines/types.js'
import type { ShapedQuestion, QuestionRow, QuestionView, ReviewView, PaneView } from '../engines/facets/screen.js'
@@ -41,9 +43,8 @@ export function shapeQuestions(questions: unknown): ShapedQuestion[] {
})
}
-function rowKeys(engine: AgentEngine, row: QuestionRow, view?: QuestionView): string[] {
+function rowKeys(engine: AgentEngine, row: QuestionRow): string[] {
if (engine === 'amp') return ampSelectionKeys(row)
- if (engine === 'codex') return codexRowKeys(row, view)
// Kilo's rows sit side by side, so its walk is horizontal — see engines/kilo/askQuestion.ts.
if (engine === 'kilo') return kiloSelectionKeys(row)
// Same dialog, different engine: opencode numbers its ask dialog but not its permission prompt, so the
@@ -53,16 +54,6 @@ function rowKeys(engine: AgentEngine, row: QuestionRow, view?: QuestionView): st
return [row.number]
}
-/**
- * Codex, measured 2026-09-15 on 0.149: in its request_user_input dialog a digit only MOVES the highlight
- * and Enter submits (`enter to submit answer`) — a digit alone left the dialog up and the device's answer
- * reported as stuck. Its approval prompt is the other way round and was verified earlier: one digit
- * selects and commits, so that one keeps the single key.
- */
-export function codexRowKeys(row: QuestionRow, view?: QuestionView): string[] {
- return view?.enterSubmits ? [row.number, 'Enter'] : [row.number]
-}
-
export function matchRow(rows: QuestionRow[], answer: string): QuestionRow | null {
const a = norm(answer)
if (!a) return null
@@ -119,8 +110,11 @@ const STALE_GONE: QuestionAnswerResult = { ok: false, error: 'STALE_QUESTION', d
const failed = (detail: string): QuestionAnswerResult => ({ ok: false, error: 'ANSWER_FAILED', detail })
const KEYS_FAILED = failed('The answer could not be typed into the agent\'s terminal.')
const STUCK = failed('The question did not take the answer.')
+// Nothing was typed: the engine's worker had no room for the step, or was not there to take it.
+const BUSY: QuestionAnswerResult = { ok: false, error: 'ANSWER_BUSY', detail: 'The agent could not take the answer just now. Nothing was typed. Try again.' }
export interface AskQuestionDeps {
+ questionControlFor: QuestionControlFor
readQuestion(session: RegisteredSession, capture: string): PaneView | Promise<PaneView>
getSession: (sessionId: string) => RegisteredSession | undefined
capture: (terminalTarget: string, historyLines?: number) => Promise<string | null>
@@ -178,7 +172,7 @@ export class AskQuestionController {
}
const remembered = this.pending.get(requestId)
const sessionId = payload.sessionId || payload.agentId || remembered || ''
- const answers = payload.answers && typeof payload.answers === 'object' ? payload.answers : null
+ const answers = payload.answers && typeof payload.answers === 'object' ? structuredClone(payload.answers) : null
if (!sessionId || !answers || Object.keys(answers).length === 0) {
console.warn(`[question] ignoring answer with no session/answers (req=${requestId})`)
return failed('The answer named no agent or carried no choice.')
@@ -210,7 +204,17 @@ export class AskQuestionController {
const owners = [...new Set([remembered, session?.sessionId].filter((id): id is string => !!id))]
this.driving.add(terminalTarget)
try {
- const result = await this.drive(terminalTarget, answers, this.deps.getSession(sessionId)?.engine ?? 'claude', payload.allowPermissions !== false, { requestId, owners }, payload.expectedQuestions ? payload : undefined)
+ // Inside the protected region: the lease is held from here, and a control port or a reviewed snapshot
+ // that throws must still release it rather than leave the terminal busy with nothing typed.
+ let native: QuestionControlSession | undefined, reviewed: QuestionAnswerPayload | undefined
+ try {
+ native = session ? this.deps.questionControlFor(session) : undefined
+ reviewed = payload.expectedQuestions ? structuredClone(payload) : undefined
+ } catch (error) {
+ console.warn(`[question] ${sessionId.slice(0, 8)} answer dropped · ${(error as Error).message}`)
+ return failed('The answer could not be prepared. Nothing was typed.')
+ }
+ const result = await this.drive(terminalTarget, answers, this.deps.getSession(sessionId)?.engine ?? 'claude', payload.allowPermissions !== false, { requestId, owners }, reviewed, native)
this.pending.delete(requestId)
const outcome = result.ok ? 'submitted' : result.error === 'STALE_QUESTION' ? 'refused · STALE_QUESTION, nothing typed' : 'FAILED'
console.log(`[question] ${sessionId.slice(0, 8)} answered from device · ${outcome} (req=${requestId || 'none'})`)
@@ -236,8 +240,19 @@ export class AskQuestionController {
allowPermissions: boolean,
asked: { requestId: string; owners: string[] },
reviewed?: QuestionAnswerPayload,
+ native?: QuestionControlSession,
): Promise<QuestionAnswerResult> {
const wait = this.deps.wait ?? sleep
+ // 'uncertain': a key had gone to the terminal before the engine's worker failed. The pane decides on the next
+ // read (the dialog gone: the answer went in); nothing is typed again, since the port stays bound to that worker.
+ const apply = async (step: QuestionStep): Promise<'done' | 'failed' | QuestionStepFailure> => {
+ if (!native) return await this.applyLegacyStep(terminalTarget, engine, step, wait) ? 'done' : 'failed'
+ if (await native.apply(step).catch(() => false)) return 'done'
+ return native.failure?.() ?? 'failed'
+ }
+ const notEntered = (outcome: Awaited<ReturnType<typeof apply>>): QuestionAnswerResult | null =>
+ outcome === 'refused' ? BUSY : outcome === 'failed' ? KEYS_FAILED : null
+ let submitUncertain = false
const used = new Set<string>()
const reviewedComplete = () => !reviewed || used.size === reviewed.expectedQuestions!.length
let lastQuestion = ''
@@ -274,7 +289,15 @@ export class AskQuestionController {
// answered somewhere else — submitting would send answers this person never gave.
if (answered === 0) return STALE_GONE
if (!reviewedComplete()) return STALE_CHANGED
- return await this.deps.sendKey(terminalTarget, view.submitRow) ? { ok: true } : failed('The answers could not be submitted.')
+ if (submitUncertain) return failed('The answers could not be submitted.')
+ const outcome = await apply({ kind: 'review', key: view.submitRow })
+ if (outcome === 'done') return { ok: true }
+ if (outcome === 'refused') return BUSY
+ if (outcome === 'failed') return failed('The answers could not be submitted.')
+ // Read the pane once more: the review gone is the form submitted.
+ submitUncertain = true
+ await wait(STEP_MS)
+ continue
}
// Mid-repaint the question line can read blank for a capture (see parseQuestionPane). Neither its id
// nor its text can be checked against a blank, so look again rather than judge the dialog by it.
@@ -332,8 +355,8 @@ export class AskQuestionController {
if (!expected?.canText || view.permission || view.multi || !view.typeRow ||
!picked.value.trim() || Buffer.byteLength(picked.value, 'utf8') > 1200 ||
/[\x00-\x09\x0b-\x1f\x7f]/.test(picked.value)) return failed('The text answer cannot be entered into this question.')
- if (!await this.typeFreeText(terminalTarget, view.typeRow, picked.value, wait)) return KEYS_FAILED
- await wait(STEP_MS)
+ const typed = notEntered(await apply({ kind: 'text', row: view.typeRow, text: picked.value }))
+ if (typed) return typed
continue
}
@@ -342,50 +365,51 @@ export class AskQuestionController {
const labels = reviewed ? reviewed.selectedLabels?.[picked.key] ?? []
: picked.value.split(',').map((s) => s.trim()).filter(Boolean)
if (reviewed && (!labels.length || labels.some(label => !view.rows.some(row => row.label === label)))) return failed('That answer matches no option.')
- if (reviewed) {
- // Set the exact reviewed set, including clearing choices selected in another client.
- for (const row of view.rows) if (row.checked !== labels.includes(row.label)) {
- if (!await this.deps.sendKey(terminalTarget, row.number)) return KEYS_FAILED
- await wait(TEXT_MS)
- }
- if (!await this.deps.sendKey(terminalTarget, multiSubmitKey(engine))) return KEYS_FAILED
- await wait(STEP_MS)
- continue
- }
- let toggled = 0
- for (const label of labels) {
- const row = matchRow(view.rows, label)
- if (!row || row.checked) continue
- if (!await this.deps.sendKey(terminalTarget, row.number)) return KEYS_FAILED
- await wait(TEXT_MS)
- toggled++
- }
- if (!toggled && view.typeRow
- && !await this.typeFreeText(terminalTarget, view.typeRow, picked.value, wait)) return KEYS_FAILED
- if (!await this.deps.sendKey(terminalTarget, multiSubmitKey(engine))) return KEYS_FAILED // advance to the next question / review
- await wait(STEP_MS)
+ // Core chooses the exact approved set; the engine owns toggling and advancing its UI.
+ const rows = reviewed ? view.rows.filter(row => row.checked !== labels.includes(row.label))
+ : labels.map(label => matchRow(view.rows, label)).filter((row): row is QuestionRow => !!row && !row.checked)
+ const freeText = !reviewed && !rows.length && view.typeRow ? { row: view.typeRow, text: picked.value } : undefined
+ const toggled = notEntered(await apply({ kind: 'multiple', rows, ...(freeText ? { freeText } : {}) }))
+ if (toggled) return toggled
continue
}
const row = reviewed ? view.rows.find(row => row.label === picked.value) ?? null : matchRow(view.rows, picked.value)
if (row) {
- // One digit selects AND submits — except on Amp, whose rows are unnumbered and reached by
- // walking the list, so this is a short sequence rather than a single key.
- for (const key of rowKeys(engine, row, view)) {
- if (!await this.deps.sendKey(terminalTarget, key)) return KEYS_FAILED
- await wait(TEXT_MS)
- }
- await wait(STEP_MS)
+ const selected = notEntered(await apply({ kind: 'select', row, enterSubmits: view.enterSubmits }))
+ if (selected) return selected
continue
}
if (reviewed) return failed('That answer matches no option.')
if (!view.typeRow) { console.warn(`[question] no option matched "${picked.value.slice(0, 40)}" and no free-text row`); return failed('That answer matches no option.') }
- if (!await this.typeFreeText(terminalTarget, view.typeRow, picked.value, wait)) return KEYS_FAILED
- await wait(STEP_MS)
+ const typed = notEntered(await apply({ kind: 'text', row: view.typeRow, text: picked.value }))
+ if (typed) return typed
}
return STUCK
}
+ /** Other engines keep their existing navigation until their migration batch. */
+ private async applyLegacyStep(target: string, engine: AgentEngine, step: QuestionStep, wait: (ms: number) => Promise<void>): Promise<boolean> {
+ if (step.kind === 'review') return this.deps.sendKey(target, step.key)
+ if (step.kind === 'select') {
+ for (const key of rowKeys(engine, step.row)) {
+ if (!await this.deps.sendKey(target, key)) return false
+ await wait(TEXT_MS)
+ }
+ } else if (step.kind === 'text') {
+ if (!await this.typeFreeText(target, step.row, step.text, wait)) return false
+ } else {
+ for (const row of step.rows) {
+ if (!await this.deps.sendKey(target, row.number)) return false
+ await wait(TEXT_MS)
+ }
+ if (step.freeText && !await this.typeFreeText(target, step.freeText.row, step.freeText.text, wait)) return false
+ if (!await this.deps.sendKey(target, multiSubmitKey(engine))) return false
+ }
+ await wait(STEP_MS)
+ return true
+ }
+
/** True while a dialog is being keyed — the watcher pauses so a half-driven dialog isn't re-announced. */
isDriving(sessionId: string): boolean {
const session = this.deps.getSession(sessionId)
diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.md
index 29067036e..700bfeed4 100644
--- a/cli/src/services/AGENTS.md
+++ b/cli/src/services/AGENTS.md
@@ -51,7 +51,7 @@ that process. A process per risk, not per feature (`SERVICE_HOSTS` in `src/harne
| Process | Services | Why its own | Started |
|---|---|---|---|
-| `engine-claude`, `engine-codex` | history, live parsers, runtime profiles, screens and model control (`src/engines/worker/`) | engine behavior outside core; snapshots and revocable model-control grants | on demand |
+| `engine-claude`, `engine-codex` | history, live parsers, runtime profiles, screens, model control and question navigation (`src/engines/worker/`) | engine behavior outside core; snapshots and revocable model- and question-control grants | on demand |
| `search` | search | native `node:sqlite`, the index's memory | always |
| `viewers` | viewers, store | the viewer servers, the remote viewer streams and rendered surfaces, minutes-long installs | always |
| `edge` | workspaces, usage, monitor, projects, handoff, recaps, windowNames, shell | light pure-JS services: isolated from the core, not from each other | always |
diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.ts
index ef8db7f68..72ed84a35 100644
--- a/cli/src/services/inline.spec.ts
+++ b/cli/src/services/inline.spec.ts
@@ -1,3 +1,4 @@
+import { questionControlFor } from '../engines/questionControls.js'
import { modelControlFor } from '../engines/modelControls.js'
import { screenFor } from '../engines/screens.js'
import { describe, expect, it } from 'vitest'
@@ -27,6 +28,6 @@ import { startWorkspaces } from './workspaces.js'
describe('the services the core runs in its own process only when they do not run in theirs', () => {
it('are their own starts, unchanged: the same services either way', () => {
- expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, modelControlFor, startCommandBar, startDevices, startHandoff, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startSearch, startSharing, startShell, startStore, startTeamsInCore, startUsage, startViewers, startWifi, startWindowNames, startWorkspaces })
+ expect({ ...inline }).toEqual({ engineTranscriptFor, liveFor, runtimeFor, screenFor, modelControlFor, questionControlFor, startCommandBar, startDevices, startHandoff, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startSearch, startSharing, startShell, startStore, startTeamsInCore, startUsage, startViewers, startWifi, startWindowNames, startWorkspaces })
})
})
diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.ts
index 532f1b7e4..cd46afc88 100644
--- a/cli/src/services/inline.ts
+++ b/cli/src/services/inline.ts
@@ -1,3 +1,4 @@
+export { questionControlFor } from '../engines/questionControls.js'
/**
* The services that run in a process of their own by default (harnessd/services.ts `SERVICE_HOSTS`), for
* when they run in the core's instead: with `HARNESSD_SERVICES=none` (debugging, or a quick way back), a
diff --git a/docs/design/2026-10-05-engine-interface.md b/docs/design/2026-10-05-engine-interface.md
index caa40c3a6..14aaa470f 100644
--- a/docs/design/2026-10-05-engine-interface.md
+++ b/docs/design/2026-10-05-engine-interface.md
@@ -12,6 +12,10 @@
> facet. Launch metadata and hooks load separately from history readers. Core retains authenticated
> transport, process binding, prompt timestamps and event delivery. Discovery/resume, live ingestion,
> screen/input, models and one-shot handling remain to migrate.
+> Since then, Claude Code's and Codex's transcript readers (#1015), live parsing (#1017, #1019), runtime
+> profiles (#1022), screen interpretation (#1027), model controls (#1038) and question navigation run in
+> their supervised engine workers. Still in core for them: submission verification, hook admission and
+> installers, engine-specific launch, discovery and resume, and native control connections.
> The older all-engine branches (`engine-interface-1..5`, `engine-lane-*`, draft PR #842) are retained as
> reference work; they are not the implementation currently landing. The phased plan below is the
> target architecture, not a claim that all facets or engine isolation are already complete.
diff --git a/docs/design/2026-10-08-engine-question-control.md b/docs/design/2026-10-08-engine-question-control.md
new file mode 100644
index 000000000..4f4637150
--- /dev/null
+++ b/docs/design/2026-10-08-engine-question-control.md
@@ -0,0 +1,74 @@
+# Engine question control
+
+Claude Code and Codex navigate question dialogs through `Engine.questionControl` in their
+supervised engine workers. Core still owns question identity, remembered requests, the user's
+answers, permission policy, reviewed labels, stale-question checks and the input lease.
+
+## One approved step
+
+`lib/questionController.ts` matches a captured question against the request and the answer the
+person supplied. It snapshots the answer map and reviewed metadata before awaiting a screen read.
+It passes one approved `QuestionStep` to a control port bound before that first read:
+
+- Select one row, retaining the observed submit behavior.
+- Toggle the rows needed for a multiple-choice answer, then advance.
+- Open the observed text row and enter the approved text.
+- Submit a review reached by this answer, after checking completeness.
+
+The native facets own key selection, text entry and repaint timing. The worker receives neither
+the pending answer map nor a terminal locator. Codex's digit-then-Enter question behavior and
+digit-only approval behavior remain distinct, as recorded in the existing fixtures. Other engines
+keep their legacy navigation until their own migration batches.
+
+## Revocable effects
+
+Core grants each step a random token tied to the original agent, conversation, terminal binding
+and worker connection. `core/engines/controlTransport.ts` shares the previously tested model-control
+binding, deadline, capacity and reconnect rules. It does not contain native navigation.
+
+Question grants allow only finite key operations and the exact text approved for that step.
+No capture, registry or general core-query capability is granted. Requests and replies have strict
+private v1 envelopes and a 1 MiB ceiling; text is limited to 32 KiB and excludes terminal control
+characters other than newline. Existing reviewed voice answers retain their stricter 1,200-byte rule.
+Each engine admits sixteen concurrent steps (one per agent's dialog), each with a 30-second deadline, at most 128 writes and
+one outstanding host request. A host query has a five-second deadline. Worker deadlines recycle
+that worker, never core.
+
+Disconnect, replacement, completion, timeout, rebinding, overlapping host calls or a failed terminal
+write revokes the grant. Terminal writes use the existing guard after lease validation and in the
+tmux queue/buffer/Enter path. Failure does not resume navigation through a replacement worker or
+fall back inline. A command already dispatched to the OS can have an uncertain effect and is not
+automatically retried; a new user answer is a new intent.
+
+The parent-bound `HARNESSD_ENGINE_QUESTION_CONTROL=<master-pid>:1` capability selects the isolated
+path. Explicit inline mode and older masters use the same core broker with inline native facets.
+The compatibility wrapper `lib/askQuestion.ts` retains direct-fixture APIs outside normal core's
+import closure.
+
+## Validation and continuation
+
+Existing recorded-question/controller fixtures cover matching, permission policy, exact reviewed
+sets, free text, review screens and refusal behavior. New broker and worker tests exercise malformed
+messages, wrong service/token, exact-text enforcement, limits, aborts, timeouts, worker replacement,
+late writes and immutable reviewed answers. Model-control tests exercise the extracted shared
+transport without changing its contract.
+
+`cli/e2e/engineQuestionControl.e2e.ts` runs the routed path on a real private daemon. The fake engine
+signals the worker the moment a chosen keystroke of one step reaches it, so each stop lands inside the
+step: Claude Code's worker killed or frozen between two toggles of a multi-select, and Codex's between
+the digit and its Enter. The answer fails as ANSWER_FAILED, as does one sent while no worker runs
+(nothing is typed inline instead), no later key of the step reaches the pane after the worker is gone
+or replaced, the other engine's agent finishes a turn and core answers requests during the outage, core
+never restarts, and a different new answer then succeeds. A worker frozen past the step's deadline is
+woken with its next key due, and core refuses that key. Explicit inline mode answers end to end, and a
+window's `engine_question_control_*` or `engine.questionControl` request is refused even while a worker
+holds a live grant.
+
+The handoff checkpoint must retain actual receipts and distinguish passing checks from missing
+evidence. Before merge, finish a paired question-workload CPU/RSS/latency comparison, review the final
+source, and complete automatic CLI CI. Question E2E uses private homes, tmux and deterministic CLI
+fixtures, not real model accounts.
+
+The full extraction remains incomplete: submission verification, hooks and their installers/admission,
+launch/discovery/resume, and native control connections still need migration and a final import/runtime
+audit. This question-control batch does not claim to complete that objective.