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 submission readings (#1041)

Deefe496d5cc3d0
diff --git a/cli/AGENTS.md b/cli/AGENTS.md
index ebcd450c4..47a150a2a 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, model control and question navigation | 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, submission verification readings, 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/e2e/engineSubmission.e2e.ts b/cli/e2e/engineSubmission.e2e.ts
new file mode 100644
index 000000000..29f387883
--- /dev/null
+++ b/cli/e2e/engineSubmission.e2e.ts
@@ -0,0 +1,110 @@
+/**
+ * Submission verification read by the engine workers: a real private daemon, tmux, supervised workers and
+ * the fake CLIs, which take a `!latestart` prompt off the composer and hold its turn's start until released.
+ * The core's checks then find the composer clear and no turn, and ask the worker again each window.
+ */
+import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it, onTestFailed } from 'vitest'
+import { LocalClient } from './harness/client.js'
+import { IsolatedDaemon, until, type DaemonOptions } from './harness/daemon.js'
+import { harnessdProcesses } from './harness/endurance.js'
+
+type Engine = 'claude' | 'codex'
+
+describe('submission verification in the engine workers', () => {
+ let daemon: IsolatedDaemon | undefined, client: LocalClient | undefined
+ afterEach(async () => { client?.close(); await daemon?.close(); client = undefined; daemon = undefined })
+
+ async function fresh(engine: Engine, env: DaemonOptions['env'] = {}) {
+ const d = daemon = await IsolatedDaemon.create({ submissionGate: true, env: { HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200',
+ HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000', HARNESSD_SERVICE_HEARTBEAT_TIMEOUT_MS: '4000', HARNESSD_SERVICE_STOP_GRACE_MS: '100', ...env } })
+ onTestFailed(() => console.log(d.log()))
+ await d.start()
+ const c = client = await LocalClient.connect(d)
+ const cwd = join(d.projectsDir, engine); mkdirSync(cwd, { recursive: true })
+ const created = await c.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ const agent = await until('bound engine', async () => (await c.request('agents_list', {})).agents.find((row: any) => row.id === created.agent.id && row.sessionId), 60_000, 100)
+ const log = join(d.engineConfig.root, 'submitted-prompts')
+ // Every Enter that sent the composer's text, as the fake CLI took it: an Enter pressed twice is a second line.
+ const submitted = (): string[] => existsSync(log) ? readFileSync(log, 'utf8').trim().split('\n').map(line => JSON.parse(line)) : []
+ const turn = async (content: string) => {
+ const ended = c.next(frame => frame.type === 'turn_ended' && frame.agentId === agent.id, 30_000, content)
+ c.send('message', { agentId: agent.id, content }); await ended
+ }
+ const started = (since: number, content: string) => c.frames.slice(since)
+ .filter(frame => frame.type === 'turn_started' && frame.agentId === agent.id && JSON.stringify(frame.payload).includes(content))
+ // The core's first reading of the composer, which only the engine's worker (or, inline, its reader) gives.
+ const observed = (n: number) => until(`reading ${n} of the composer`, () => new RegExp(`accepted \\(queued/submitted\\) · engine=${engine} · observe=${n}/`).test(d.log()) || null, 20_000, 20)
+ return { d, c, agent, submitted, turn, started, observed, release: () => writeFileSync(`${log}.release`, 'go') }
+ }
+
+ it.each([['claude', 'SIGSTOP'], ['codex', 'SIGKILL']] as const)('%s: a worker lost (%s) in the middle of verifying a prompt costs no second Enter, and the core, the CLI and the next prompt go on', async (engine, signal) => {
+ const { d, c, agent, submitted, turn, started, observed, release } = await fresh(engine)
+ await turn('before the check')
+ const core = d.corePid(), worker = harnessdProcesses(d).get(`engine-${engine}`)!
+ const panePid = (await d.tmux.run('display-message', '-p', '-t', agent.tmuxPane, '#{pane_pid}')).trim()
+ const first = c.frames.length
+ c.send('message', { agentId: agent.id, content: '!latestart held' })
+ await observed(1)
+ process.kill(worker, signal)
+ // Frozen, the next check gets no reading and says the message could not be confirmed; killed, a new
+ // worker may answer it instead. Either way no Enter is pressed: the composer was clear when read.
+ await until('a replacement worker', () => {
+ const pid = harnessdProcesses(d).get(`engine-${engine}`)
+ return pid && pid !== worker ? pid : null
+ }, 30_000, 100)
+ if (signal === 'SIGSTOP') {
+ await until('the message reported unconfirmed', () => c.frames.slice(first).some(frame => frame.type === 'error' && frame.agentId === agent.id
+ && /could not be confirmed/.test(String(frame.payload?.message))) || null, 20_000, 50)
+ expect(d.log()).toContain(`service engine-${engine} sent no heartbeat`)
+ }
+ const ended = c.next(frame => frame.type === 'turn_ended' && frame.agentId === agent.id, 30_000, 'the held turn')
+ release()
+ await ended
+ expect(started(first, '!latestart held')).toHaveLength(1)
+ expect(submitted()).toEqual(['before the check', '!latestart held'])
+ await turn('after the worker came back')
+ expect(submitted()).toEqual(['before the check', '!latestart held', 'after the worker came back'])
+ expect((await d.tmux.run('display-message', '-p', '-t', agent.tmuxPane, '#{pane_pid}')).trim()).toBe(panePid)
+ expect(d.corePid()).toBe(core)
+ expect(d.coresStarted()).toBe(1)
+ })
+
+ it('codex: a worker whose reading itself fails, its screen read fine, leaves the message unconfirmed and presses no Enter', async () => {
+ const { d, c, agent, submitted, turn, started, release } = await fresh('codex', { HARNESSD_TEST_FAULTS: 'engine-codex.engine_submission_read' })
+ await turn('before the check')
+ const core = d.corePid(), worker = harnessdProcesses(d).get('engine-codex')
+ const first = c.frames.length
+ c.send('message', { agentId: agent.id, content: '!latestart held' })
+ await until('the message reported unconfirmed', () => c.frames.slice(first).some(frame => frame.type === 'error' && frame.agentId === agent.id
+ && /could not be confirmed/.test(String(frame.payload?.message))) || null, 20_000, 50)
+ expect(d.log()).toContain('engine_submission_read failed · injected fault')
+ expect(d.log()).not.toMatch(/accepted \(queued\/submitted\) · engine=codex/)
+ const ended = c.next(frame => frame.type === 'turn_ended' && frame.agentId === agent.id, 30_000, 'the held turn')
+ release()
+ await ended
+ expect(started(first, '!latestart held')).toHaveLength(1)
+ expect(submitted()).toEqual(['before the check', '!latestart held'])
+ await turn('the next prompt')
+ expect(harnessdProcesses(d).get('engine-codex')).toBe(worker)
+ expect(d.corePid()).toBe(core)
+ })
+
+ it('reads the composer with the engine\'s own reader in explicit inline mode, and presses no second Enter', async () => {
+ const { d, c, agent, submitted, turn, started, observed, release } = await fresh('claude', { HARNESSD_SERVICES: 'none' })
+ await turn('before the check')
+ const first = c.frames.length
+ c.send('message', { agentId: agent.id, content: '!latestart held' })
+ await observed(2)
+ const ended = c.next(frame => frame.type === 'turn_ended' && frame.agentId === agent.id, 30_000, 'the held turn')
+ release()
+ await ended
+ expect(started(first, '!latestart held')).toHaveLength(1)
+ expect(submitted()).toEqual(['before the check', '!latestart held'])
+ expect(c.frames.slice(first).filter(frame => frame.type === 'error' && frame.agentId === agent.id)).toEqual([])
+ expect(harnessdProcesses(d).get('engine-claude')).toBeUndefined()
+ expect(d.coresStarted()).toBe(1)
+ })
+})
diff --git a/cli/e2e/harness/daemon.ts b/cli/e2e/harness/daemon.ts
index 9230ccb42..3bc9a332d 100644
--- a/cli/e2e/harness/daemon.ts
+++ b/cli/e2e/harness/daemon.ts
@@ -34,6 +34,8 @@ export interface EngineConfig {
claudeModel?: string
/** Pause model commands at a disposable file gate for worker failure tests. */
modelControlGate?: boolean
+ /** Note every submitted prompt and hold a `!latestart` turn's start at a file gate (submission tests). */
+ submissionGate?: boolean
codexModel?: string
/** The test's throwaway root: the engine runs no hooks from settings outside it. */
root: string
@@ -59,6 +61,8 @@ export interface DaemonOptions {
claudeModel?: string
/** Pause model commands at a disposable file gate for worker failure tests. */
modelControlGate?: boolean
+ /** Note every submitted prompt and hold a `!latestart` turn's start at a file gate (submission tests). */
+ submissionGate?: boolean
codexModel?: string
/** Boot the core on its own (`__run`) instead of under harnessd's master (`__harnessd`). */
noMaster?: boolean
@@ -215,6 +219,7 @@ export class IsolatedDaemon {
const config: EngineConfig = {
port, dataDir: dirs.data, claudeProjectsDir: dirs.claudeProjects, codexHome: dirs.codexHome,
claudeModel: options.claudeModel, codexModel: options.codexModel, modelControlGate: options.modelControlGate,
+ ...(options.submissionGate ? { submissionGate: true } : {}),
root, hookLog: join(own, 'fake-engine-hooks.log'),
...(options.trustPrompt ? { trustPrompt: true } : {}),
}
diff --git a/cli/e2e/harness/fakeEngine.mjs b/cli/e2e/harness/fakeEngine.mjs
index 41effd7db..1f7319245 100644
--- a/cli/e2e/harness/fakeEngine.mjs
+++ b/cli/e2e/harness/fakeEngine.mjs
@@ -32,7 +32,10 @@
// scrollback mode, `!search` searching its prompt history, as ctrl+r does, `!config` (Claude Code) in its
// settings and `!center` (Codex) in its agent command center, screens the daemon has no name for,
// `!permitnext <command>` keeps its turn open and asks permission to run the command the moment a
-// message is pasted, before its Enter (a request arriving mid-turn), `!exit` ends the process.
+// message is pasted, before its Enter (a request arriving mid-turn), `!latestart` (with `submissionGate` in
+// the config) takes the prompt off the composer and holds its turn's start, the prompt hook and the record,
+// until the test's release file exists, as a CLI does whose hooks or first record are slow, `!exit` ends the
+// process.
// Everything else is echoed as the answer. Codex's `/model` is not a prompt: it opens 0.160's model
// picker over the `models_cache.json` in its CODEX_HOME, and a choice in it is applied to the turns
// that follow (see `openModelPicker`).
@@ -1193,6 +1196,12 @@ export async function run(engine, config = {}, { native = false } = {}) {
await runHooks('SessionStart', { source: 'clear' })
return
}
+ if (config.submissionGate && /^!latestart\b/.test(prompt)) {
+ // Taken off the composer (above), its turn not started: the daemon's check of the submission finds
+ // the composer clear and no turn yet, and keeps looking, until the test releases it.
+ const release = join(config.root, 'submitted-prompts.release')
+ while (!existsSync(release)) await new Promise((resolve) => setTimeout(resolve, 20))
+ }
runningTool = null
if (open) await finish('(interrupted by a new prompt)')
// Both CLIs run their UserPromptSubmit hooks on every prompt, before the prompt is taken: notify.mjs
@@ -1668,6 +1677,8 @@ export async function run(engine, config = {}, { native = false } = {}) {
})
return
}
+ // What the test counts: every Enter that sent the composer's text, an empty one included.
+ if (config.submissionGate) appendFileSync(join(config.root, 'submitted-prompts'), `${JSON.stringify(line)}\n`)
queue = queue.then(() => handle(line))
} else if (part) {
buffer += part
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index 04012863a..26f6e4e72 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -143,9 +143,13 @@ 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|questionControl)\.ts$/,
+ /^engines\/(claude|codex)\/(screen|composer|activity|stoppedGoal|modelControl|modelPicker|questionControl|submission)\.ts$/,
/^lib\/(askQuestion|runtimeProfileController|composerScreen|teamWriteHold|messageHold|terminalActivity|codexTurnRecovery)\.ts$/,
- /^engines\/(screens|modelControls|questionControls)\.ts$/,
+ /^engines\/(screens|modelControls|questionControls|submissions)\.ts$/,
+ // Claude Code's and Codex's reading of their composer: shared by the two, loaded only by their workers.
+ /^engines\/kit\/nativeSubmission\.ts$/,
+ // A worker's request handlers, the submission readers' among them, run in the engine's own process.
+ /^engines\/worker\/\w+Requests\.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$/,
@@ -219,8 +223,9 @@ describe('the daemon\'s shape', () => {
}
})
- it('screen transport and input authority do not load native screen implementations', () => {
- for (const entry of ['core/input.ts', 'core/questions.ts', 'core/engines/screens.ts', 'core/engines/screenTransport.ts']) {
+ it('screen and submission transports and input authority do not load native screen or submission readers', () => {
+ for (const entry of ['core/input.ts', 'core/questions.ts', 'core/engines/screens.ts', 'core/engines/screenTransport.ts',
+ 'core/deviceInput.ts', 'lib/sessionInput.ts', 'core/engines/submissions.ts', 'core/engines/submissionTransport.ts']) {
expect([...closureOf(entry).keys()].filter(file => /^engines\/(claude|codex)\//.test(file)), entry).toEqual([])
}
})
diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.md
index a0b12e99b..c508e86a7 100644
--- a/cli/src/core/AGENTS.md
+++ b/cli/src/core/AGENTS.md
@@ -37,7 +37,7 @@ 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), 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).
+ ([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)). Whether a typed prompt was taken is read there too: core keeps the writer, every Enter and the verdict ([submission](../../../docs/design/2026-10-08-engine-submission.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`).
diff --git a/cli/src/core/deviceInput.edges.spec.ts b/cli/src/core/deviceInput.edges.spec.ts
index 14af24f3e..72ed87536 100644
--- a/cli/src/core/deviceInput.edges.spec.ts
+++ b/cli/src/core/deviceInput.edges.spec.ts
@@ -5,6 +5,7 @@
*/
import { afterEach, describe, expect, it, vi } from 'vitest'
import { AutonomousDeviceInput, type DeviceInputDeps } from './deviceInput.js'
+import { inlineSubmission } from '../testing/inlineSubmission.js'
import type { RegisteredSession } from '../lib/registry.js'
import type { TerminalActionResult } from '../lib/terminalTypes.js'
@@ -20,7 +21,7 @@ function lock(overrides: Partial<DeviceInputDeps> = {}) {
const device = new AutonomousDeviceInput({
getSession: () => claude,
validateRuntime: async () => true, inject: async () => executed, sendKey: async () => true,
- capture: async () => '› ', acquireControl: () => () => {}, legacySubmit: vi.fn(), legacyCancel: () => false,
+ capture: async () => '› ', submission: inlineSubmission, acquireControl: () => () => {}, legacySubmit: vi.fn(), legacyCancel: () => false,
onDelivery, onInputStatus, ...overrides,
})
const states = (deliveryId: string) => onDelivery.mock.calls.map(([event]) => event).filter((event) => event.deliveryId === deliveryId)
@@ -124,6 +125,60 @@ describe('the pane writer lock, at its edges', () => {
}
})
+ it('writes a busy Claude Code turn into its own queue, and never claims steering for an engine retargeted after it was queued', async () => {
+ for (const [engine, mode] of [['claude', 'native_queue'], ['commandcode', 'native_input'], ['codex', 'steering']] as const) {
+ // Queued for a native engine; the registry row changes in place before it is typed.
+ const session = codex('0.200.0')
+ const f = lock({ getSession: () => session, validateRuntime: async () => { session.engine = engine; return true } })
+ f.device.onTurnStarted('agent', 'already working')
+ f.device.submit('agent', 'and this', 'd1')
+ await vi.waitFor(() => expect(f.onInputStatus).toHaveBeenCalledWith(expect.objectContaining({ deliveryId: 'd1', mode, phase: 'submitted' })))
+ f.device.forget('agent')
+ }
+ })
+
+ it('reads the composer through the engine\'s worker, and takes no reading as an unreadable pane', async () => {
+ vi.useFakeTimers()
+ const sendKey = vi.fn(async () => true)
+ // The draft is still there as the worker reads it: the one evidence-backed Enter.
+ const pending = lock({ sendKey, submission: { ...inlineSubmission, read: async () => ({ draft: true, composer: true, nativeDraft: 'pending' }) } })
+ pending.device.submit('agent', 'hello', 'd1')
+ await vi.advanceTimersByTimeAsync(1_600)
+ expect(sendKey).toHaveBeenCalledWith('agent', 'Enter')
+ pending.device.forget('agent')
+ for (const read of [async () => null, async () => { throw new Error('worker gone') }]) {
+ sendKey.mockClear()
+ const f = lock({ sendKey, submission: { ...inlineSubmission, read } })
+ f.device.submit('agent', 'hello', 'd2')
+ await vi.advanceTimersByTimeAsync(20_000)
+ expect(sendKey).not.toHaveBeenCalled()
+ expect(f.onInputStatus).toHaveBeenLastCalledWith(expect.objectContaining({ deliveryId: 'd2', phase: 'unconfirmed' }))
+ f.device.forget('agent')
+ }
+ // The agent gone by the time the pane was read: nothing to read it for.
+ let present = true
+ const read = vi.fn(async () => ({ draft: false, composer: true, nativeDraft: 'clear' as const }))
+ const gone = lock({ sendKey, getSession: () => present ? claude : undefined, submission: { ...inlineSubmission, read }, capture: async () => { present = false; return '› ' } })
+ gone.device.submit('agent', 'hello', 'd3')
+ await vi.advanceTimersByTimeAsync(1_600)
+ expect(read).not.toHaveBeenCalled()
+ gone.device.forget('agent')
+ })
+
+ it('drops a reading that comes back after the write was settled', async () => {
+ const reading = held<{ draft: boolean; composer: boolean; nativeDraft: 'pending' } | null>()
+ const sendKey = vi.fn(async () => true)
+ const f = lock({ sendKey, submission: { ...inlineSubmission, read: () => reading.promise } })
+ f.device.submit('agent', 'hello', 'd1')
+ await vi.waitFor(() => expect(f.states('d1')).toEqual(['queued', 'delivered']))
+ f.device.onTurnStarted('agent', 'hello')
+ reading.resolve({ draft: true, composer: true, nativeDraft: 'pending' })
+ await vi.waitFor(() => expect(f.states('d1')).toEqual(['queued', 'delivered', 'started']))
+ await new Promise(resolve => setTimeout(resolve, 0))
+ expect(sendKey).not.toHaveBeenCalled()
+ f.device.forget('agent')
+ })
+
it('finishes a write whose turn began while it was being typed', async () => {
const typing = held<TerminalActionResult>()
const f = lock({ inject: () => typing.promise })
diff --git a/cli/src/core/deviceInput.spec.ts b/cli/src/core/deviceInput.spec.ts
index e568187a9..44a12be58 100644
--- a/cli/src/core/deviceInput.spec.ts
+++ b/cli/src/core/deviceInput.spec.ts
@@ -1,4 +1,5 @@
import { readInlineScreen } from '../testing/inlineScreen.js'
+import { inlineSubmission } from '../testing/inlineSubmission.js'
import { CodexNormalizer } from '../engines/codex/normalizer.js'
import { lineToEvents, newTurnState, type LiveEvent } from '../lib/normalize.js'
import { randomUUID } from 'node:crypto'
@@ -13,7 +14,7 @@ function makeDevice(overrides: Partial<DeviceInputDeps>): AutonomousDeviceInput
return new AutonomousDeviceInput({
getSession: () => ({ agentId: 'agent', engine: 'claude' }) as RegisteredSession,
validateRuntime: async () => true, inject: async () => true, sendKey: async () => true,
- capture: async () => '› ', acquireControl: () => () => {}, legacySubmit: vi.fn(), legacyCancel: () => false,
+ capture: async () => '› ', submission: inlineSubmission, acquireControl: () => () => {}, legacySubmit: vi.fn(), legacyCancel: () => false,
onDelivery: vi.fn(), onInputStatus: vi.fn(), ...overrides,
})
}
@@ -30,7 +31,7 @@ function fixture(engine: 'claude' | 'codex' | 'commandcode' = 'codex') {
submit: (id, text, delivery) => controller.submit(id, text, delivery), cancelDelivery: id => controller.cancelDelivery(id),
stop: async () => true, answer: async () => true, recent: () => [], emit: frame => events.push(frame),
})
- const legacy: SessionInputController = new SessionInputController({ readScreen: readInlineScreen,
+ const legacy: SessionInputController = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => available ? session : undefined, validateRuntime: async () => available,
inject: (id, text) => controller.legacyWrite(id, () => inject(id, text)),
sendKey: (id, key) => controller.legacyWrite(id, () => sendKey(id, key)), capture, onError: vi.fn(),
@@ -42,7 +43,7 @@ function fixture(engine: 'claude' | 'codex' | 'commandcode' = 'codex') {
legacyCancel: id => legacy.cancelDelivery(id),
onForget: id => service.agentGone(id),
getSession: () => available ? session : undefined, validateRuntime: async () => available,
- inject, capture, sendKey, onDelivery: event => service.delivery(event),
+ inject, capture, sendKey, submission: inlineSubmission, onDelivery: event => service.delivery(event),
onInputStatus: event => service.inputStatus(event),
})
const send = (key: string, text = key, focusRevision?: string) => service.request('device', {
@@ -346,7 +347,7 @@ it.each(['codex', 'claude'] as const)('%s Device filter rejects an inferred comp
: lineToEvents(JSON.stringify({ type: 'user', message: { role: 'user', content: [{ type: 'text', text }] } }), claude)
const observe = (events: LiveEvent[]) => {
for (const [index, event] of events.entries()) {
- if (isDeviceInputBoundary(engine, events, index)) continue
+ if (isDeviceInputBoundary(inlineSubmission.policy(engine), events, index)) continue
if (event.type === 'turn_started') f.start(event.payload.userMessage)
if (event.type === 'turn_ended') f.end()
}
diff --git a/cli/src/core/deviceInput.ts b/cli/src/core/deviceInput.ts
index dcbf0be17..ad4de7cc2 100644
--- a/cli/src/core/deviceInput.ts
+++ b/cli/src/core/deviceInput.ts
@@ -14,8 +14,8 @@ import type { SessionInputDelivery } from '../lib/sessionInput.js'
import type { LiveEvent } from '../lib/normalize.js'
import { isMessageHold } from '../lib/messageHolds.js'
import { enterWithheldReason, type TerminalActionResult } from '../lib/terminalTypes.js'
-
-const NATIVE = new Set(['claude', 'codex'])
+import type { SubmissionReader } from '../lib/submissionReader.js'
+import type { SubmissionPolicy } from '../engines/facets/submission.js'
const VERIFY_MS = 1500
const TTL_MS = 5 * 60_000
export interface DeviceInputStatus {
@@ -58,6 +58,8 @@ export interface DeviceInputDeps {
inject: (id: string, text: string) => Promise<boolean | TerminalActionResult>
sendKey: (id: string, key: string) => Promise<boolean | TerminalActionResult>
capture: (id: string) => Promise<string | null>
+ /** The engine's reading of its composer after a paste, from its worker; core decides on it. */
+ submission: Pick<SubmissionReader, 'read' | 'policy'>
isAwaitingUser?: (session: RegisteredSession) => Promise<boolean>
acquireControl: (id: string) => (() => void) | null
legacySubmit: (id: string, text: string, deliveryId: string) => void
@@ -68,13 +70,16 @@ export interface DeviceInputDeps {
onForget?: (id: string) => void
}
const fingerprint = (text: string) => createHash('sha256').update(text.replace(/\r\n/g, '\n').trim()).digest('hex')
-const visible = (text: string) => text.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
-const normalize = (text: string) => text.replace(/\s+/g, ' ').trim()
-function draft(capture: string, content: string): 'pending' | 'clear' | 'unreadable' {
- const lines = visible(capture).split('\n')
- const index = lines.findLastIndex(line => /[›❯]/u.test(line) && !/[›❯]\s*\d+\.\s/u.test(line))
- if (index < 0) return 'unreadable'
- return normalize(lines.slice(index).join('\n')).includes(normalize(content)) ? 'pending' : 'clear'
+/**
+ * How a message typed mid-turn is taken, as the engine declares it: steering from the release it names on,
+ * its own mode before that or with no release known. An engine without a policy (one retargeted after its
+ * message was queued) is native input: never claimed as steering.
+ */
+function busyMode(policy: SubmissionPolicy | undefined, session: RegisteredSession): DeviceInputStatus['mode'] {
+ const busy = policy?.busyInput ?? { mode: 'native_input' }
+ const version = session.cliVersion?.match(/(\d+)\.(\d+)\.(\d+)/)
+ const [major, minor] = busy.steeringSince ?? [Infinity, 0]
+ return version && (Number(version[1]) > major || (Number(version[1]) === major && Number(version[2]) >= minor)) ? 'steering' : busy.mode
}
const executed = (result: boolean | TerminalActionResult) => result === true || (typeof result !== 'boolean' && result.dispatch === 'executed')
const rejected = (result: boolean | TerminalActionResult) => result === false || (typeof result !== 'boolean' && (result.dispatch === 'not_started' || result.dispatch === 'rejected'))
@@ -84,6 +89,11 @@ export class AutonomousDeviceInput {
private states = new Map<string, State>()
private writers = new Map<string, Writer>()
constructor(private readonly deps: DeviceInputDeps) {}
+ /** The engines whose TUI takes a message typed mid-turn, which this route queues and verifies itself
+ * (Claude Code and Codex, as their submission policies declare); every other engine's goes the legacy way. */
+ private native(engine: string): boolean {
+ return this.deps.submission.policy(engine)?.typesWhileBusy === true
+ }
private state(id: string): State {
let state = this.states.get(id)
if (!state) { state = { busy: false, userAction: false, queue: [], pending: [], writing: false }; this.states.set(id, state) }
@@ -117,7 +127,7 @@ export class AutonomousDeviceInput {
const session = this.deps.getSession(id)
if (!session) { this.deps.onDelivery({ sessionId: id, deliveryId, state: 'rejected', reason: 'agent_gone' }); return }
const state = this.state(id)
- if (!NATIVE.has(session.engine)) {
+ if (!this.native(session.engine)) {
this.deps.legacySubmit(id, content, deliveryId)
this.deps.onInputStatus({ sessionId: id, deliveryId, mode: state.busy ? 'daemon_queue' : 'direct', phase: state.busy ? 'waiting_for_turn' : 'waiting_for_writer' })
return
@@ -194,9 +204,7 @@ export class AutonomousDeviceInput {
this.later(id, state)
return
}
- const version = session.cliVersion?.match(/(\d+)\.(\d+)\.(\d+)/)
- item.mode = !state.busy ? 'direct' : session.engine === 'claude' ? 'native_queue'
- : version && (Number(version[1]) > 0 || Number(version[2]) >= 106) ? 'steering' : 'native_input'
+ item.mode = !state.busy ? 'direct' : busyMode(this.deps.submission.policy(session.engine), session)
this.deps.onDispatch?.(id, item.deliveryId, item.content)
item.dispatched = true
state.pending.push(item)
@@ -234,7 +242,8 @@ export class AutonomousDeviceInput {
try {
const pane = await this.deps.capture(id)
if (this.states.get(id) !== state || state.active !== item) return
- const evidence = pane ? draft(pane, item.content) : 'unreadable'
+ const evidence = pane ? await this.draft(id, pane, item.content) : 'unreadable'
+ if (this.states.get(id) !== state || state.active !== item) return
if (item.started || evidence === 'clear') {
this.status(id, item, 'accepted'); this.finishWrite(id, state, item); return
}
@@ -269,6 +278,12 @@ export class AutonomousDeviceInput {
if (item.started) this.finishWrite(id, state, item)
}
}
+ /** Whether the prompt is still in the engine's composer, as its worker reads it; no reading is unreadable. */
+ private async draft(id: string, pane: string, content: string): Promise<'pending' | 'clear' | 'unreadable'> {
+ const session = this.deps.getSession(id)
+ const reading = session ? await this.deps.submission.read(session, pane, content).catch(() => null) : null
+ return reading?.nativeDraft ?? 'unreadable'
+ }
onTurnStarted(id: string, content: string): void {
const state = this.state(id)
state.busy = true
@@ -323,6 +338,6 @@ export class AutonomousDeviceInput {
/** Filter only the Autonomous Device view. Shared normalizers and other consumers stay unchanged.
* A same-batch end immediately preceding new input is not sufficient completion evidence.
*/
-export function isDeviceInputBoundary(engine: string, events: readonly LiveEvent[], index: number): boolean {
- return NATIVE.has(engine) && events[index]?.type === 'turn_ended' && events[index + 1]?.type === 'turn_started'
+export function isDeviceInputBoundary(policy: SubmissionPolicy | undefined, events: readonly LiveEvent[], index: number): boolean {
+ return policy?.typesWhileBusy === true && events[index]?.type === 'turn_ended' && events[index + 1]?.type === 'turn_started'
}
diff --git a/cli/src/core/engines/screenTransport.ts b/cli/src/core/engines/screenTransport.ts
index d47357e7a..2d6abfe3e 100644
--- a/cli/src/core/engines/screenTransport.ts
+++ b/cli/src/core/engines/screenTransport.ts
@@ -1,73 +1,21 @@
/** Core's screen port: plain snapshots, a single deadline, and connection-generation fencing. */
import type { ScreenReading } from '../../engines/facets/screen.js'
-import { EngineReadError, readerEngine, READER_ERRORS, READER_SERVICES, type ReaderEngine } from '../../engines/worker/protocol.js'
+import { EngineReadError } from '../../engines/worker/protocol.js'
import { screenReading, screenCapture, SCREEN_CAPABILITIES, SCREEN_IN_FLIGHT, SCREEN_QUEUED, SCREEN_READ, SCREEN_REPLY_BYTES,
SCREEN_VERSION, SCREEN_WAIT_MS } from '../../engines/worker/screenProtocol.js'
+import { createSnapshotTransport, type SnapshotTransportDeps } from './snapshotTransport.js'
-export interface ScreenTransportDeps {
- call(service: string, method: string, payload: Record<string, unknown>, waitMs: number): Promise<Record<string, unknown>>
-}
+export type ScreenTransportDeps = SnapshotTransportDeps
export function createScreenTransport(deps: ScreenTransportDeps) {
- const states = new Map(Object.values(READER_SERVICES).map(service => [service as string,
- { generation: 0, connected: false, capable: false, pending: 0, waiting: [] as Array<() => void> }]))
- const fail = (code: EngineReadError['code']): never => { throw new EngineReadError(code) }
+ const transport = createSnapshotTransport(deps, { version: SCREEN_VERSION, capabilities: SCREEN_CAPABILITIES, capability: 'screen',
+ inFlight: SCREEN_IN_FLIGHT, queued: SCREEN_QUEUED, waitMs: SCREEN_WAIT_MS, replyBytes: SCREEN_REPLY_BYTES })
return {
- connected(service: string): void {
- const state = states.get(service)
- if (state) { state.generation++; state.connected = true; state.capable = false }
- },
- disconnected(service: string): void {
- const state = states.get(service)
- if (state) { state.generation++; state.connected = false; state.capable = false }
- },
+ connected: transport.connected,
+ disconnected: transport.disconnected,
async read(engine: string, capture: string): Promise<ScreenReading> {
- if (!readerEngine(engine) || !screenCapture(capture)) fail('ENGINE_INVALID_REQUEST')
- const service = READER_SERVICES[engine as ReaderEngine], state = states.get(service)!
- const generation = state.generation + (state.connected ? 0 : 1)
- const deadline = performance.now() + SCREEN_WAIT_MS
- // A poll tick can capture dozens of panes together. Refusing every read
- // after the first eight starves the same later sessions on every tick.
- // FIFO admission is bounded, and spends the caller's original deadline.
- // Earlier active reads have the same hard budget and release their slots
- // even on a hung link; expired queued reads send nothing and release next.
- if (state.pending >= SCREEN_IN_FLIGHT) {
- if (state.waiting.length >= SCREEN_QUEUED) fail('ENGINE_BUSY')
- await new Promise<void>(resolve => { state.waiting.push(resolve) })
- } else state.pending++
- const call = async (method: string, payload: Record<string, unknown>): Promise<Record<string, unknown>> => {
- const remaining = Math.ceil(deadline - performance.now())
- if (remaining <= 0) fail('ENGINE_UNAVAILABLE')
- // Service startup has its own wait. Enforce one wall-clock budget here,
- // including a worker that never answers or a link that loses its timer.
- let timer: ReturnType<typeof setTimeout> | undefined
- let reply: Record<string, unknown>
- try {
- reply = await Promise.race([deps.call(service, method, { version: SCREEN_VERSION, ...payload }, remaining),
- new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new EngineReadError('ENGINE_UNAVAILABLE')), remaining) })])
- } finally { clearTimeout(timer) }
- if (performance.now() > deadline) fail('ENGINE_UNAVAILABLE')
- if (reply.error === 'SERVICE_FAILED' || reply.error === 'SERVICE_UNAVAILABLE') fail('ENGINE_UNAVAILABLE')
- if (state.generation !== generation) fail('ENGINE_STALE_REPLY')
- if (reply.version !== SCREEN_VERSION) fail('ENGINE_INVALID_REPLY')
- if (reply.error !== undefined) fail(READER_ERRORS.includes(reply.error as EngineReadError['code']) ? reply.error as EngineReadError['code'] : 'ENGINE_INVALID_REPLY')
- return reply
- }
- try {
- if (!state.capable) {
- const capability = await call(SCREEN_CAPABILITIES, {})
- if (capability.screen !== SCREEN_VERSION || capability.engine !== engine) fail('ENGINE_INVALID_REPLY')
- state.capable = true
- }
- const reply = await call(SCREEN_READ, { capture })
- if (Buffer.byteLength(JSON.stringify(reply)) > SCREEN_REPLY_BYTES || !screenReading(reply.answer)) fail('ENGINE_INVALID_REPLY')
- return reply.answer as ScreenReading
- } catch (error) { throw error instanceof EngineReadError ? error : new EngineReadError('ENGINE_UNAVAILABLE') }
- finally {
- const next = state.waiting.shift()
- if (next) next()
- else state.pending--
- }
+ if (!screenCapture(capture)) throw new EngineReadError('ENGINE_INVALID_REQUEST')
+ return await transport.read(engine, SCREEN_READ, { capture }, screenReading) as ScreenReading
},
}
}
diff --git a/cli/src/core/engines/sessionBinding.ts b/cli/src/core/engines/sessionBinding.ts
index 5fa0c0e89..041aefb47 100644
--- a/cli/src/core/engines/sessionBinding.ts
+++ b/cli/src/core/engines/sessionBinding.ts
@@ -5,3 +5,19 @@ export function sessionBinding(session: RegisteredSession | undefined): string {
session.registeredAt, session.boundAt, session.transcriptPath, session.tmuxPane,
session.primaryRuntimeKey, session.runtimes, session.processIdentity]) : ''
}
+
+/**
+ * The record a write begun under `typed` finishes under: `now` when it is `typed`'s launch, bound since,
+ * otherwise `typed` itself, whose binding a fenced reading then refuses. An engine draws its composer
+ * before its first hook binds the conversation, so a message typed in that gap sees its record rebuilt
+ * before the Enter, the same agent in the same pane and process. A first startup can finish this
+ * intent; a rebind, a rotation, another pane or another process cannot resume it.
+ */
+export function launchBound(typed: RegisteredSession, now: RegisteredSession | undefined): RegisteredSession {
+ const starting = typed.launch !== undefined && typed.boundAt === null
+ return starting && now !== undefined && now.agentId === typed.agentId && now.engine === typed.engine
+ && now.registeredAt === typed.registeredAt && now.tmuxPane === typed.tmuxPane && now.primaryRuntimeKey === typed.primaryRuntimeKey
+ // Unknown while starting, a process found since is the one the pane started; one known when typed must stay.
+ && (!typed.processIdentity || JSON.stringify(now.processIdentity) === JSON.stringify(typed.processIdentity))
+ ? now : typed
+}
diff --git a/cli/src/core/engines/snapshotTransport.ts b/cli/src/core/engines/snapshotTransport.ts
new file mode 100644
index 000000000..ac65aaec3
--- /dev/null
+++ b/cli/src/core/engines/snapshotTransport.ts
@@ -0,0 +1,88 @@
+/**
+ * Core's side of an engine worker's stateless readings (screens, submissions): plain snapshots out, a single
+ * deadline, FIFO admission and connection-generation fencing. Nothing is cached across calls; a timeout, a
+ * malformed reply or a replaced connection supplies no evidence.
+ */
+import { EngineReadError, readerEngine, READER_ERRORS, READER_SERVICES, type ReaderEngine } from '../../engines/worker/protocol.js'
+
+export interface SnapshotTransportDeps {
+ call(service: string, method: string, payload: Record<string, unknown>, waitMs: number): Promise<Record<string, unknown>>
+}
+
+export interface SnapshotKind {
+ version: number
+ capabilities: string
+ /** The capability reply's field naming this reader's version. */
+ capability: string
+ inFlight: number
+ queued: number
+ waitMs: number
+ replyBytes: number
+}
+
+export function createSnapshotTransport(deps: SnapshotTransportDeps, kind: SnapshotKind) {
+ const states = new Map(Object.values(READER_SERVICES).map(service => [service as string,
+ { generation: 0, connected: false, capable: false, pending: 0, waiting: [] as Array<() => void> }]))
+ const fail = (code: EngineReadError['code']): never => { throw new EngineReadError(code) }
+ return {
+ connected(service: string): void {
+ const state = states.get(service)
+ if (state) { state.generation++; state.connected = true; state.capable = false }
+ },
+ disconnected(service: string): void {
+ const state = states.get(service)
+ if (state) { state.generation++; state.connected = false; state.capable = false }
+ },
+ /** The reply's `answer`, once `valid` and within the reply bound; otherwise an EngineReadError. */
+ async read(engine: string, method: string, payload: Record<string, unknown>, valid: (answer: unknown) => boolean): Promise<unknown> {
+ if (!readerEngine(engine)) fail('ENGINE_INVALID_REQUEST')
+ const service = READER_SERVICES[engine as ReaderEngine], state = states.get(service)!
+ const generation = state.generation + (state.connected ? 0 : 1)
+ const deadline = performance.now() + kind.waitMs
+ // A poll tick can capture dozens of panes together. Refusing every read
+ // after the first eight starves the same later sessions on every tick.
+ // FIFO admission is bounded, and spends the caller's original deadline.
+ // Earlier active reads have the same hard budget and release their slots
+ // even on a hung link; expired queued reads send nothing and release next.
+ if (state.pending >= kind.inFlight) {
+ if (state.waiting.length >= kind.queued) fail('ENGINE_BUSY')
+ await new Promise<void>(resolve => { state.waiting.push(resolve) })
+ } else state.pending++
+ const call = async (name: string, body: Record<string, unknown>): Promise<Record<string, unknown>> => {
+ const remaining = Math.ceil(deadline - performance.now())
+ if (remaining <= 0) fail('ENGINE_UNAVAILABLE')
+ // Service startup has its own wait. Enforce one wall-clock budget here,
+ // including a worker that never answers or a link that loses its timer.
+ let timer: ReturnType<typeof setTimeout> | undefined
+ let reply: Record<string, unknown>
+ try {
+ reply = await Promise.race([deps.call(service, name, { version: kind.version, ...body }, remaining),
+ new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new EngineReadError('ENGINE_UNAVAILABLE')), remaining) })])
+ } finally { clearTimeout(timer) }
+ if (performance.now() > deadline) fail('ENGINE_UNAVAILABLE')
+ if (reply.error === 'SERVICE_FAILED' || reply.error === 'SERVICE_UNAVAILABLE') fail('ENGINE_UNAVAILABLE')
+ if (state.generation !== generation) fail('ENGINE_STALE_REPLY')
+ if (reply.version !== kind.version) fail('ENGINE_INVALID_REPLY')
+ if (reply.error !== undefined) fail(READER_ERRORS.includes(reply.error as EngineReadError['code']) ? reply.error as EngineReadError['code'] : 'ENGINE_INVALID_REPLY')
+ return reply
+ }
+ try {
+ if (!state.capable) {
+ const capability = await call(kind.capabilities, {})
+ if (capability[kind.capability] !== kind.version || capability.engine !== engine) fail('ENGINE_INVALID_REPLY')
+ state.capable = true
+ }
+ const reply = await call(method, payload)
+ if (Buffer.byteLength(JSON.stringify(reply)) > kind.replyBytes || !valid(reply.answer)) fail('ENGINE_INVALID_REPLY')
+ return reply.answer
+ } catch (error) { throw error instanceof EngineReadError ? error : new EngineReadError('ENGINE_UNAVAILABLE') }
+ finally {
+ const next = state.waiting.shift()
+ if (next) next()
+ else state.pending--
+ }
+ },
+ }
+}
+
+export type SnapshotTransport = ReturnType<typeof createSnapshotTransport>
diff --git a/cli/src/core/engines/submissionTransport.spec.ts b/cli/src/core/engines/submissionTransport.spec.ts
new file mode 100644
index 000000000..a66edc46f
--- /dev/null
+++ b/cli/src/core/engines/submissionTransport.spec.ts
@@ -0,0 +1,53 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { engineSubmissionRequests } from '../../engines/worker/submissionRequests.js'
+import { SUBMISSION_CAPABILITIES, SUBMISSION_ECHO, SUBMISSION_READ, SUBMISSION_REPLY_BYTES, SUBMISSION_TEXT_BYTES } from '../../engines/worker/submissionProtocol.js'
+import { createSubmissionTransport, type SubmissionTransport } from './submissionTransport.js'
+
+const capture = '────────────\n❯ hello\n────────────\n? for shortcuts'
+const recorded = '<pasted_content id="ab">\nhello\n</pasted_content id="ab">'
+afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() })
+
+describe('submission transport', () => {
+ it('negotiates each connection, and decodes the real worker\'s readings', async () => {
+ const requests = engineSubmissionRequests('claude')
+ let transport: SubmissionTransport
+ const call = vi.fn(async (service: string, method: string, payload: Record<string, unknown>) => {
+ if (call.mock.calls.length === 1) transport.connected(service)
+ return await requests[method]({ ...payload, requestId: `core-route-${call.mock.calls.length}` }, { owner: true, local: true })
+ })
+ transport = createSubmissionTransport({ call })
+ expect(await transport.read('claude', capture, 'hello')).toEqual({ draft: true, composer: true, nativeDraft: 'pending' })
+ expect(await transport.echo('claude', recorded)).toEqual({ start: 25, end: 30 })
+ expect(call.mock.calls.map(c => c[1])).toEqual([SUBMISSION_CAPABILITIES, SUBMISSION_READ, SUBMISSION_ECHO])
+ transport.disconnected('engine-claude'); transport.connected('engine-claude')
+ await transport.echo('claude', 'hello')
+ expect(call.mock.calls.filter(c => c[1] === SUBMISSION_CAPABILITIES)).toHaveLength(2)
+ })
+
+ it('sends nothing past its bounds or for an engine with no worker', async () => {
+ const call = vi.fn()
+ const transport = createSubmissionTransport({ call }); transport.connected('engine-codex')
+ await expect(transport.read('codex', 'x'.repeat(300_000), 'hello')).rejects.toThrow('ENGINE_INVALID_REQUEST')
+ await expect(transport.read('codex', capture, 'x'.repeat(SUBMISSION_TEXT_BYTES + 1))).rejects.toThrow('ENGINE_INVALID_REQUEST')
+ await expect(transport.echo('codex', 'x'.repeat(SUBMISSION_TEXT_BYTES + 1))).rejects.toThrow('ENGINE_INVALID_REQUEST')
+ await expect(transport.echo('cursor', 'hello')).rejects.toThrow('ENGINE_INVALID_REQUEST')
+ expect(call).not.toHaveBeenCalled()
+ })
+
+ it('takes no reading a worker could not have made: a span outside the text, malformed facts, an oversized reply', async () => {
+ const capability = { version: 1, submission: 1, engine: 'codex' }
+ for (const [method, answer] of [
+ ['echo', { start: 0, end: 6 }], ['echo', { start: 3, end: 2 }], ['echo', { start: -1, end: 2 }], ['echo', { start: 0, end: 1.5 }],
+ ['echo', { start: 0, end: 1, more: true }], ['read', { draft: true, composer: true }], ['read', { draft: 'yes', composer: true, nativeDraft: 'clear' }],
+ ['read', { draft: true, composer: true, nativeDraft: 'gone' }], ['read', { draft: true, composer: true, nativeDraft: 'clear', note: 'x'.repeat(SUBMISSION_REPLY_BYTES) }],
+ ] as const) {
+ const transport = createSubmissionTransport({ call: async (_s, name) => name === SUBMISSION_CAPABILITIES ? capability : { version: 1, answer } })
+ transport.connected('engine-codex')
+ await expect(method === 'echo' ? transport.echo('codex', 'hello') : transport.read('codex', capture, 'hello')).rejects.toThrow('ENGINE_INVALID_REPLY')
+ }
+ // A screen worker is not a submission worker: its capability names no submission reader.
+ const screen = createSubmissionTransport({ call: async () => ({ version: 1, screen: 1, engine: 'codex' }) })
+ screen.connected('engine-codex')
+ await expect(screen.read('codex', capture, 'hello')).rejects.toThrow('ENGINE_INVALID_REPLY')
+ })
+})
diff --git a/cli/src/core/engines/submissionTransport.ts b/cli/src/core/engines/submissionTransport.ts
new file mode 100644
index 000000000..e6203d785
--- /dev/null
+++ b/cli/src/core/engines/submissionTransport.ts
@@ -0,0 +1,26 @@
+/** Core's submission port: the screen's transport with the submission reader's version, bounds and replies. */
+import type { PromptSpan, SubmissionReading } from '../../engines/facets/submission.js'
+import { EngineReadError } from '../../engines/worker/protocol.js'
+import { promptSpan, submissionCapture, submissionReading, submissionText, SUBMISSION_CAPABILITIES, SUBMISSION_ECHO, SUBMISSION_IN_FLIGHT,
+ SUBMISSION_QUEUED, SUBMISSION_READ, SUBMISSION_REPLY_BYTES, SUBMISSION_VERSION, SUBMISSION_WAIT_MS } from '../../engines/worker/submissionProtocol.js'
+import { createSnapshotTransport, type SnapshotTransportDeps } from './snapshotTransport.js'
+
+export function createSubmissionTransport(deps: SnapshotTransportDeps) {
+ const transport = createSnapshotTransport(deps, { version: SUBMISSION_VERSION, capabilities: SUBMISSION_CAPABILITIES, capability: 'submission',
+ inFlight: SUBMISSION_IN_FLIGHT, queued: SUBMISSION_QUEUED, waitMs: SUBMISSION_WAIT_MS, replyBytes: SUBMISSION_REPLY_BYTES })
+ const invalid = (): never => { throw new EngineReadError('ENGINE_INVALID_REQUEST') }
+ return {
+ connected: transport.connected,
+ disconnected: transport.disconnected,
+ async read(engine: string, capture: string, prompt: string): Promise<SubmissionReading> {
+ if (!submissionCapture(capture) || !submissionText(prompt)) invalid()
+ return await transport.read(engine, SUBMISSION_READ, { capture, prompt }, submissionReading) as SubmissionReading
+ },
+ async echo(engine: string, recorded: string): Promise<PromptSpan> {
+ if (!submissionText(recorded)) invalid()
+ return await transport.read(engine, SUBMISSION_ECHO, { recorded }, answer => promptSpan(answer, recorded)) as PromptSpan
+ },
+ }
+}
+
+export type SubmissionTransport = ReturnType<typeof createSubmissionTransport>
diff --git a/cli/src/core/engines/submissions.spec.ts b/cli/src/core/engines/submissions.spec.ts
new file mode 100644
index 000000000..faa806291
--- /dev/null
+++ b/cli/src/core/engines/submissions.spec.ts
@@ -0,0 +1,74 @@
+import { describe, expect, it, vi } from 'vitest'
+import { submissionFor } from '../../engines/submissions.js'
+import { submissionPolicy } from '../../engines/submissionPolicies.js'
+import type { PromptSpan, SubmissionReading } from '../../engines/facets/submission.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import { createSubmissions } from './submissions.js'
+
+const capture = '────────────\n❯ hello\n────────────\n? for shortcuts'
+const row = () => ({ agentId: 'agent', sessionId: 'session', engine: 'claude', active: true,
+ runtimes: [], processIdentity: { pid: 10, startMarker: 'one' } }) as unknown as RegisteredSession
+function setup() {
+ let current: RegisteredSession | undefined = row()
+ const claude = submissionFor('claude')!
+ const reading = claude.read(capture, 'hello'), span = { start: 0, end: 5 }
+ const transport = { read: vi.fn(async (): Promise<SubmissionReading> => reading), echo: vi.fn(async (): Promise<PromptSpan> => span) }
+ const inline = vi.fn(() => claude), handles = vi.fn(() => true)
+ return { submissions: createSubmissions({ policy: submissionPolicy, resolve: () => current, transport, inline, handles }),
+ transport, inline, handles, reading, span, row: current, replace: (next?: RegisteredSession) => { current = next } }
+}
+
+describe('core submission evidence', () => {
+ it('asks the bound worker, or the inline reader only in explicit inline mode, and keeps nothing', async () => {
+ const t = setup()
+ expect(t.submissions.policy('claude')).toEqual(submissionFor('claude')!.policy)
+ expect(t.submissions.policy('cursor')).toBeUndefined()
+ expect(await t.submissions.read(t.row, capture, 'hello')).toEqual(t.reading)
+ expect(await t.submissions.echo(t.row, 'hello')).toEqual(t.span)
+ expect(t.transport.read).toHaveBeenCalledWith('claude', capture, 'hello')
+ expect(t.transport.echo).toHaveBeenCalledWith('claude', 'hello')
+ expect(t.inline).not.toHaveBeenCalled()
+ t.handles.mockReturnValue(false)
+ expect(await t.submissions.read(t.row, capture, 'hello')).toEqual({ draft: true, composer: true, nativeDraft: 'pending' })
+ const recorded = '<pasted_content id="ab">\nhello\n</pasted_content id="ab">'
+ expect(await t.submissions.echo(t.row, recorded)).toEqual({ start: 25, end: 30 })
+ expect(t.inline).toHaveBeenCalledWith('claude')
+ // An engine with no reader inline is no reading, never an empty one.
+ t.inline.mockReturnValue(undefined as never)
+ expect(await t.submissions.read(t.row, capture, 'hello')).toBeNull()
+ expect(await t.submissions.echo(t.row, 'hello')).toBeNull()
+ expect(t.transport.read).toHaveBeenCalledOnce()
+ })
+
+ it('refuses text past the bounds, and a session that is not the one bound, before asking anyone', async () => {
+ const t = setup()
+ expect(await t.submissions.read(t.row, 'é'.repeat(256 * 1024), 'hello')).toBeNull()
+ expect(await t.submissions.read(t.row, capture, 'x'.repeat(1024 * 1024 + 1))).toBeNull()
+ expect(await t.submissions.echo(t.row, 'é'.repeat(512 * 1024 + 1))).toBeNull()
+ expect(await t.submissions.read({ ...t.row, agentId: '' }, capture, 'hello')).toBeNull()
+ expect(await t.submissions.echo({ ...t.row, sessionId: 'old' }, 'hello')).toBeNull()
+ t.replace()
+ expect(await t.submissions.read(t.row, capture, 'hello')).toBeNull()
+ expect(t.transport.read).not.toHaveBeenCalled()
+ expect(t.transport.echo).not.toHaveBeenCalled()
+ })
+
+ it('takes a failed worker as no reading, and never reads inline instead', async () => {
+ const t = setup()
+ t.transport.read.mockRejectedValue(new Error('worker stopped'))
+ t.transport.echo.mockRejectedValue(new Error('worker stopped'))
+ expect(await t.submissions.read(t.row, capture, 'hello')).toBeNull()
+ expect(await t.submissions.echo(t.row, 'hello')).toBeNull()
+ expect(t.inline).not.toHaveBeenCalled()
+ })
+
+ it.each(['sessionId', 'engine', 'active', 'processIdentity', 'runtimes'] as const)('discards a reading after an in-place %s change', async field => {
+ const t = setup()
+ let finish!: (value: SubmissionReading) => void
+ t.transport.read.mockImplementation(() => new Promise(resolve => { finish = resolve }))
+ const read = t.submissions.read(t.row, capture, 'hello')
+ Object.assign(t.row, { [field]: field === 'active' ? false : field === 'processIdentity' ? { pid: 20 } : field === 'runtimes' ? [{ paneId: 'new' }] : 'changed' })
+ finish(t.reading)
+ expect(await read).toBeNull()
+ })
+})
diff --git a/cli/src/core/engines/submissions.ts b/cli/src/core/engines/submissions.ts
new file mode 100644
index 000000000..1eed95085
--- /dev/null
+++ b/cli/src/core/engines/submissions.ts
@@ -0,0 +1,41 @@
+/**
+ * Core's submission evidence: an engine's reading of its composer after a paste, and of a turn's prompt as
+ * it recorded it. Core passes plain text and keeps every verdict (lib/sessionInput.ts, core/deviceInput.ts);
+ * an answer is fenced to the session binding it was asked under and never cached.
+ */
+import { sessionBinding as identity } from './sessionBinding.js'
+import type { EngineSubmission, SubmissionPolicy } from '../../engines/facets/submission.js'
+import type { AgentEngine } from '../../engines/types.js'
+import { submissionCapture, submissionText } from '../../engines/worker/submissionProtocol.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import type { SubmissionReader } from '../../lib/submissionReader.js'
+import type { SubmissionTransport } from './submissionTransport.js'
+
+export interface SubmissionDeps {
+ /** The declared timing (engines/submissionPolicies.ts), passed in so the input path loads no engine. */
+ policy(engine: string): SubmissionPolicy | undefined
+ /** The engine's readings run in its supervised worker. */
+ handles(engine: AgentEngine): boolean
+ transport: Pick<SubmissionTransport, 'read' | 'echo'>
+ resolve(id: string): RegisteredSession | undefined
+ /** Explicit inline mode and older masters only; a failed worker never selects it. */
+ inline(engine: AgentEngine): EngineSubmission | undefined
+}
+
+export function createSubmissions(deps: SubmissionDeps): SubmissionReader {
+ const fenced = async <T>(session: RegisteredSession, ask: (engine: AgentEngine) => Promise<T> | T | undefined): Promise<T | null> => {
+ const key = identity(session), agentId = session.agentId
+ if (!agentId || identity(deps.resolve(agentId)) !== key) return null
+ try {
+ const answer = await ask(session.engine)
+ return answer !== undefined && identity(deps.resolve(agentId)) === key ? answer : null
+ } catch { return null }
+ }
+ return {
+ policy: engine => deps.policy(engine),
+ read: (session, capture, prompt) => !submissionCapture(capture) || !submissionText(prompt) ? Promise.resolve(null)
+ : fenced(session, engine => deps.handles(engine) ? deps.transport.read(engine, capture, prompt) : deps.inline(engine)?.read(capture, prompt)),
+ echo: (session, recorded) => !submissionText(recorded) ? Promise.resolve(null)
+ : fenced(session, engine => deps.handles(engine) ? deps.transport.echo(engine, recorded) : deps.inline(engine)?.echo(recorded)),
+ }
+}
diff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.ts
index 8d585ebb9..34c091e4d 100644
--- a/cli/src/core/input.spec.ts
+++ b/cli/src/core/input.spec.ts
@@ -1,4 +1,5 @@
import { readInlineScreen } from '../testing/inlineScreen.js'
+import { inlineSubmission } from '../testing/inlineSubmission.js'
import { readdirSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -7,9 +8,12 @@ import type { AutonomousDeviceInput } from './deviceInput.js'
import { deviceErrorText } from './cardText.js'
import type { RegisteredSession } from '../lib/registry.js'
import type { SessionInputDelivery } from '../lib/sessionInput.js'
-import { TERMINAL_LEASE_REFUSED, type TerminalActionResult } from '../lib/terminalTypes.js'
+import { TERMINAL_LEASE_REFUSED, type ProcessIdentity, type TerminalActionResult } from '../lib/terminalTypes.js'
import { CLAUDE_REWIND_LIST, CODEX_BROWSING_SCROLLBACK } from '../lib/__fixtures__/rewindPickers.js'
import { createInput, createMessageRequest, deviceInputDeps, messageWriter, sessionInputDeps, type InputDeps } from './input.js'
+import { createScreens } from './engines/screens.js'
+import { screenFor } from '../engines/screens.js'
+import { readerEngine } from '../engines/worker/protocol.js'
const ok: TerminalActionResult = { state: 'succeeded', dispatch: 'executed' }
const fixture = (name: string) => readFileSync(new URL(`../lib/__fixtures__/${name}`, import.meta.url), 'utf8')
@@ -40,6 +44,7 @@ function deps(over: Partial<InputDeps> = {}) {
let pane: string | null = READY_PANE
const base: InputDeps = {
readScreen: readInlineScreen,
+ submission: inlineSubmission,
resolve: (id) => agents.get(id),
byAgent: (agentId) => agents.get(agentId),
terminal: {
@@ -223,6 +228,57 @@ describe('the session input controller\'s dependencies', () => {
}
})
+ it('presses the Enter of a message typed while its engine started once it binds its first conversation, and under no other change', async () => {
+ // An engine draws its composer before its first hook binds the conversation: a message typed in that gap
+ // finds its record rebuilt by the Enter. The screen is read under the record as it now stands only when it
+ // is that launch, in the same pane and process; any other change is read as typed, and the fence holds it.
+ const engineProcess = (pid: number): ProcessIdentity => ({ pid, executable: 'claude', startMarker: `start ${pid}` })
+ const starting = { agentId: 'a9', sessionId: '', boundAt: null, engine: 'claude', active: true, launch: { state: 'ready' },
+ registeredAt: 1, tmuxPane: '%9', primaryRuntimeKey: 'tmux:%9', runtimes: [], transcriptPath: null, processIdentity: null } as unknown as RegisteredSession
+ const bound = { ...starting, launch: undefined, sessionId: 's9', boundAt: 2, transcriptPath: '/t/s9.jsonl', processIdentity: engineProcess(7) } as RegisteredSession
+ const known = { ...starting, processIdentity: engineProcess(7) } as RegisteredSession
+ const resumed = { ...bound, launch: { state: 'ready' }, resumeOnly: true } as RegisteredSession
+ const cases: Array<[string, RegisteredSession, RegisteredSession | undefined, string | null]> = [
+ ['its first bind', starting, bound, null],
+ ['its first bind, the process it knew', known, bound, null],
+ ['nothing changed', bound, bound, null],
+ ['another process', known, { ...bound, processIdentity: engineProcess(8) }, 'screen_unreadable'],
+ ['another pane', starting, { ...bound, tmuxPane: '%10' }, 'screen_unreadable'],
+ ['another route', starting, { ...bound, primaryRuntimeKey: 'tmux:%10' }, 'screen_unreadable'],
+ ['another registration', starting, { ...bound, registeredAt: 3 }, 'screen_unreadable'],
+ ['another engine', starting, { ...bound, engine: 'codex' }, 'screen_unreadable'],
+ ['another agent', starting, { ...bound, agentId: 'a10' }, 'screen_unreadable'],
+ ['the agent gone', starting, undefined, 'screen_unreadable'],
+ ['a rotation', bound, { ...bound, sessionId: 's10', boundAt: 3 }, 'screen_unreadable'],
+ ['a resumed conversation rebound', resumed, { ...resumed, sessionId: 's10', boundAt: 3 }, 'screen_unreadable'],
+ ]
+ for (const [name, typed, after, answer] of cases) {
+ let current: RegisteredSession | undefined = typed
+ const answers: Array<string | null> = []
+ const screens = createScreens({ handles: () => false, transport: { read: vi.fn() }, resolve: () => current,
+ inline: (engine, capture) => readerEngine(engine) && capture !== null ? screenFor(engine).inspect(capture) : undefined })
+ const write = messageWriter({ readScreen: screens.read,
+ resolve: () => current,
+ terminal: {
+ validateTerminal: vi.fn(async () => true),
+ captureTerminal: vi.fn(async () => READY_PANE),
+ submitTerminalAction: vi.fn(async (_id: string, _text: string, options?: { beforeEnter?: () => Promise<string | null> }) => {
+ current = after
+ answers.push(await options!.beforeEnter!())
+ return ok
+ }),
+ } as unknown as InputDeps['terminal'],
+ })
+ vi.useFakeTimers()
+ try {
+ const written = write('a9', 'sent while it was starting')
+ await vi.advanceTimersByTimeAsync(5_000)
+ await written
+ } finally { vi.useRealTimers() }
+ expect(answers, name).toEqual([answer])
+ }
+ })
+
it('writes a team turn only into a ready pane whose delivery still holds control', async () => {
const run = deps()
const wired = sessionInputDeps(run.deps, () => lock(run.calls))
diff --git a/cli/src/core/input.ts b/cli/src/core/input.ts
index 97beebc79..a9a7b343e 100644
--- a/cli/src/core/input.ts
+++ b/cli/src/core/input.ts
@@ -20,14 +20,18 @@ import type { RegisteredSession } from '../lib/registry.js'
import { SessionInputController, type SessionInputDelivery, type SessionInputDeps } from '../lib/sessionInput.js'
import { passingHold } from '../lib/messageHolds.js'
import type { ScreenReader } from '../lib/screenReader.js'
+import type { SubmissionReader } from '../lib/submissionReader.js'
import type { ScreenReading } from '../engines/facets/screen.js'
import { TERMINAL_LEASE_REFUSED, terminalActionNotStarted, type TerminalActionResult } from '../lib/terminalTypes.js'
import type { TerminalControl } from './terminals/control.js'
+import { launchBound } from './engines/sessionBinding.js'
type Frame = { type: string; agentId?: string; dbSessionId?: string; payload: Record<string, unknown> }
export interface InputDeps {
readScreen: ScreenReader
+ /** Claude Code's and Codex's reading of a prompt typed into their pane, from their worker (core/engines/submissions.ts). */
+ submission: SubmissionReader
resolve: (id: string) => RegisteredSession | undefined
byAgent: (agentId: string) => RegisteredSession | undefined
terminal: Pick<TerminalControl, 'captureTerminal' | 'validateTerminal' | 'submitTerminalAction' | 'keyTerminalAction' | 'pinTerminalControl'>
@@ -88,7 +92,10 @@ export function messageWriter({ readScreen, resolve, terminal: { captureTerminal
// (a re-attach can blank one capture): only what is on screen holds the Enter back, never a
// read that failed once. Still not read after that, it is held, as nothing says it is safe.
for (let tries = 1; ; tries++) {
- const next = await readScreen(session, await captureTerminal(id))
+ // Read under the record as it now stands when it is the launch typed into, bound to its first
+ // conversation since (sessionBinding.ts `launchBound`); under any other change, as typed, which
+ // the reading's fence refuses.
+ const next = await readScreen(launchBound(session, resolve(id)), await captureTerminal(id))
const before = next ? next.messageHold : 'screen_unreadable'
if (before === 'popup_open') return null
if (!before || !passingHold(before) || tries >= ENTER_CHECK_TRIES) return before
@@ -114,6 +121,7 @@ export function sessionInputDeps(
return {
beforeSubmit: (id, text, tabId, deliveryId) => teams.prepare(id, text, tabId, deliveryId),
readScreen: deps.readScreen,
+ submission: deps.submission,
getSession: (id) => resolve(id),
onDelivery: (event) => {
device()?.delivery(event)
@@ -170,6 +178,7 @@ export function deviceInputDeps(
inject: messageWriter(deps),
sendKey: keyTerminalAction,
capture: captureTerminal,
+ submission: deps.submission,
// Whatever a message is not typed into, the Device's waits for it to close, rather than be refused.
isAwaitingUser: async session => {
const pane = await captureTerminal(session.agentId)
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 89642a7e0..f9c82712f 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -6,6 +6,10 @@ import { createScreens } from './engines/screens.js'
import { createScreenTransport } from './engines/screenTransport.js'
import { legacyScreen } from '../lib/legacyScreen.js'
import { masterRunsEngineScreen } from '../harnessd/services.js'
+import { createSubmissions } from './engines/submissions.js'
+import { submissionPolicy } from '../engines/submissionPolicies.js'
+import { createSubmissionTransport } from './engines/submissionTransport.js'
+import { masterRunsEngineSubmission } from '../harnessd/services.js'
/**
* The core's entry: `harness __run`. `runForeground` is the composition root, which builds the core's
* modules, starts the services through `serviceHost` and wires them to the socket
@@ -555,8 +559,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const isolatedModelControl = (engine: string): boolean => modelControlHosted && isolatedLive(engine)
const screenHosted = masterRunsEngineScreen(process.env, process.ppid)
const isolatedScreen = (engine: string): boolean => screenHosted && isolatedLive(engine)
+ const submissionHosted = masterRunsEngineSubmission(process.env, process.ppid)
+ const isolatedSubmission = (engine: string): boolean => submissionHosted && isolatedLive(engine)
const isolatedRuntime = (engine: string): boolean => runtimeHosted && isolatedLive(engine)
- const inline = KNOWN_SERVICES.some((name) => !outOfProcess.has(name)) || !runtimeHosted || !screenHosted || !modelControlHosted || !questionControlHosted
+ const inline = KNOWN_SERVICES.some((name) => !outOfProcess.has(name)) || !runtimeHosted || !screenHosted || !modelControlHosted || !questionControlHosted || !submissionHosted
? await import('../services/inline.js') : null
let serviceLinksRef: ServiceLinks | null = null
const runtimeTransport = createRuntimeTransport({
@@ -567,6 +573,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {
})
const screens = createScreens({ handles: isolatedScreen, transport: screenTransport, resolve: id => registry.resolve(id),
inline: (engine, capture) => readerEngine(engine) ? capture === null ? undefined : inline?.screenFor(engine).inspect(capture) : legacyScreen(engine, capture) })
+ const submissionTransport = createSubmissionTransport({
+ call: (service, type, payload, waitMs) => serviceLinksRef?.call(service, type, payload, waitMs) ?? Promise.resolve({ error: 'SERVICE_UNAVAILABLE' }),
+ })
+ const submissions = createSubmissions({ policy: submissionPolicy, handles: isolatedSubmission, transport: submissionTransport, resolve: id => registry.resolve(id),
+ inline: engine => inline?.submissionFor(engine) })
const runtimeProfiles = createRuntimeProfiles({
legacy: new LegacyRuntimeProfileManager(engine => isolatedRuntime(engine) ? undefined : inline?.runtimeFor(engine)),
handles: isolatedRuntime,
@@ -1049,6 +1060,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// Everything the core writes into a pane, and the device's pane lock (core/input.ts).
const inputs = createInput({
readScreen: screens.read,
+ submission: submissions,
resolve: (id) => registry.resolve(id),
byAgent: (agentId) => registry.byAgent(agentId),
terminal: terminalControl,
@@ -1235,6 +1247,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
liveTransport.connected(service)
runtimeTransport.connected(service)
screenTransport.connected(service)
+ submissionTransport.connected(service)
modelControls.connected(service)
questionControls.connected(service)
if (service === 'gateway') gatewayLink?.connected()
@@ -1248,6 +1261,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
liveTransport.disconnected(service)
runtimeTransport.disconnected(service)
screenTransport.disconnected(service)
+ submissionTransport.disconnected(service)
modelControls.disconnected(service)
questionControls.disconnected(service)
if (service === 'gateway') gatewayLink?.disconnected()
@@ -1390,6 +1404,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
input,
teams,
deviceInput,
+ submission: submissions,
device: () => wifiCore.feed,
startHeartbeat,
questionWatcher,
diff --git a/cli/src/core/turns/funnel.spec.ts b/cli/src/core/turns/funnel.spec.ts
index ed1b72d15..1707ea51b 100644
--- a/cli/src/core/turns/funnel.spec.ts
+++ b/cli/src/core/turns/funnel.spec.ts
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { deviceErrorText } from '../cardText.js'
+import { inlineSubmission } from '../../testing/inlineSubmission.js'
import type { RegisteredSession } from '../../lib/registry.js'
import { createEventFunnel, funnelFor, outsideConsumers, type FunnelDeps } from './funnel.js'
@@ -28,6 +29,7 @@ function setup(engine = 'claude', over: Partial<FunnelDeps> = {}) {
input: { onTurnStarted: vi.fn(log('input started')), onTurnEnded: vi.fn(log('input ended')) },
teams: { started: vi.fn(log('teams started')) },
deviceInput: { onTurnStarted: vi.fn(log('deviceInput started')), onTurnEnded: vi.fn(log('deviceInput ended')) },
+ submission: inlineSubmission,
device: () => ({ turnStarted: vi.fn(log('device started')), turnEnded: vi.fn(log('device ended')), stream: vi.fn(log('device stream')) }),
startHeartbeat: vi.fn(log('heartbeat')),
questionWatcher: { start: vi.fn(log('questions start')), noteTurnStart: vi.fn(log('questions pre-turn')), stop: vi.fn(log('questions stop')) },
diff --git a/cli/src/core/turns/funnel.ts b/cli/src/core/turns/funnel.ts
index adb834793..c78e69b65 100644
--- a/cli/src/core/turns/funnel.ts
+++ b/cli/src/core/turns/funnel.ts
@@ -13,6 +13,7 @@
import { correlateAgentEvent } from '../../lib/agentEvent.js'
import type { AutonomousDeviceInput } from '../deviceInput.js'
import { isDeviceInputBoundary } from '../deviceInput.js'
+import type { SubmissionReader } from '../../lib/submissionReader.js'
import type { WifiFeed } from '../wifi.js'
import type { TurnRecaps } from './recaps.js'
import { deviceErrorText } from '../cardText.js'
@@ -48,6 +49,8 @@ export interface FunnelDeps {
input: Pick<SessionInputController, 'onTurnStarted' | 'onTurnEnded'>
teams: Pick<SwarmPromptScopes, 'started'>
deviceInput: Pick<AutonomousDeviceInput, 'onTurnStarted' | 'onTurnEnded'>
+ /** Which engines take a message typed mid-turn into their own queue (their declared submission policy). */
+ submission: Pick<SubmissionReader, 'policy'>
device: () => Pick<WifiFeed, 'turnStarted' | 'turnEnded' | 'stream'> | undefined
startHeartbeat: (sessionId: string) => void
questionWatcher: Pick<QuestionWatcher, 'start' | 'noteTurnStart' | 'stop'>
@@ -94,7 +97,7 @@ export function outsideConsumers(options: {
/** The funnel itself, over what it feeds. */
export function funnelFor({
bySession, tokenUsage, agentIdFor, turnActivity, isSubagentSession, clients, search, turnStartedAt, input, teams,
- deviceInput, device, startHeartbeat, questionWatcher, mirror, outside = outsideConsumers(),
+ deviceInput, submission, device, startHeartbeat, questionWatcher, mirror, outside = outsideConsumers(),
}: FunnelDeps) {
return (sessionId: string, events: Events, opts?: EmitOptions): void => {
if (!events.length || !bySession(sessionId)?.active) return
@@ -150,7 +153,7 @@ export function funnelFor({
`${startedAt ? ` · ${Date.now() - startedAt}ms` : ''}`,
)
// Filter only the Device receipt view; shared normalizers, mirror, and local input stay unchanged.
- if (!isDeviceInputBoundary(usageSession?.engine ?? '', events, eventIndex)) {
+ if (!isDeviceInputBoundary(submission.policy(usageSession?.engine ?? ''), events, eventIndex)) {
outside('devices', () => device()?.turnEnded(agentId, event.payload.aborted === true))
deviceInput.onTurnEnded(agentId)
}
diff --git a/cli/src/engines/README.md b/cli/src/engines/README.md
index a4ad35899..90c3f972b 100644
--- a/cli/src/engines/README.md
+++ b/cli/src/engines/README.md
@@ -18,9 +18,10 @@ 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, model-control drivers and question navigation run on demand in supervised workers;
+live transcript parsing, runtime profiles/catalogs, screen interpretation, submission readings, 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),
+[submission](../../../docs/design/2026-10-08-engine-submission.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
@@ -415,7 +416,7 @@ Only needed for the capabilities your agent actually has. Skip what does not app
| File | What to add |
|---|---|
-| `lib/sessionInput.ts` | How text is submitted, and how long to wait before deciding the submit failed. Muse writes its `started` record as soon as it accepts a prompt, so 6 seconds is enough; a slower agent needs a longer window |
+| `lib/sessionInput.ts` | How text is submitted, and how long to wait before deciding the submit failed. Muse writes its `started` record as soon as it accepts a prompt, so 6 seconds is enough; a slower agent needs a longer window. Claude Code and Codex declare theirs in `<engine>/submissionPolicy.ts` and read their composer in `<engine>/submission.ts`, in their worker |
| `lib/sessionRepair.ts` | Rebinding a pane to its session after a restart |
| `lib/oneshot.ts` | Running a single prompt outside an interactive session |
diff --git a/cli/src/engines/claude/submission.ts b/cli/src/engines/claude/submission.ts
new file mode 100644
index 000000000..cd4e2b2f2
--- /dev/null
+++ b/cli/src/engines/claude/submission.ts
@@ -0,0 +1,19 @@
+import type { EngineSubmission } from '../facets/submission.js'
+import { readNativeSubmission } from '../kit/nativeSubmission.js'
+import { policy } from './submissionPolicy.js'
+
+/**
+ * Claude Code 2.1.283 records a bracketed paste inside an envelope whose opening and closing ids match.
+ * Only its exact payload is the typed prompt: never a substring of a different prompt, or text outside
+ * the envelope (lib/sessionInput.spec.ts keeps the recorded cases). Moved from sessionInput.ts unchanged.
+ */
+const PASTED = /^\s*<pasted_content id="([a-f0-9]+)">\r?\n([\s\S]*)\r?\n<\/pasted_content id="\1">\s*$/d
+
+export const submission: EngineSubmission = {
+ policy,
+ read: readNativeSubmission,
+ echo(recorded) {
+ const payload = PASTED.exec(recorded)?.indices?.[2]
+ return payload ? { start: payload[0], end: payload[1] } : { start: 0, end: recorded.length }
+ },
+}
diff --git a/cli/src/engines/claude/submissionPolicy.ts b/cli/src/engines/claude/submissionPolicy.ts
new file mode 100644
index 000000000..bb49d00e2
--- /dev/null
+++ b/cli/src/engines/claude/submissionPolicy.ts
@@ -0,0 +1,14 @@
+import type { SubmissionPolicy } from '../facets/submission.js'
+
+/**
+ * Claude Code's submission timing, declared as data so the core times its decisions without loading the
+ * reader. It takes typing while a turn runs and queues the message itself (its own queue is the one the
+ * person sees), so the core types at once. Its window has been 3 s since the CLI's first release: a long
+ * paste is collapsed to `[Pasted text]` before Enter counts as submit (lib/tmux.ts), and the prompt reaches
+ * the transcript only after its UserPromptSubmit hooks have run.
+ */
+export const policy: SubmissionPolicy = {
+ typesWhileBusy: true,
+ verifyMs: 3_000,
+ busyInput: { mode: 'native_queue' },
+}
diff --git a/cli/src/engines/codex/submission.ts b/cli/src/engines/codex/submission.ts
new file mode 100644
index 000000000..178ef5755
--- /dev/null
+++ b/cli/src/engines/codex/submission.ts
@@ -0,0 +1,10 @@
+import type { EngineSubmission } from '../facets/submission.js'
+import { readNativeSubmission } from '../kit/nativeSubmission.js'
+import { policy } from './submissionPolicy.js'
+
+/** Codex records the typed prompt as it was typed: the whole of it is the prompt, matched exactly. */
+export const submission: EngineSubmission = {
+ policy,
+ read: readNativeSubmission,
+ echo: recorded => ({ start: 0, end: recorded.length }),
+}
diff --git a/cli/src/engines/codex/submissionPolicy.ts b/cli/src/engines/codex/submissionPolicy.ts
new file mode 100644
index 000000000..ebeda61f2
--- /dev/null
+++ b/cli/src/engines/codex/submissionPolicy.ts
@@ -0,0 +1,15 @@
+import type { SubmissionPolicy } from '../facets/submission.js'
+
+/**
+ * Codex's submission timing, declared as data so the core times its decisions without loading the reader.
+ * It takes typing while a turn runs: it joined Claude Code here on 2026-09-15 (owner: a voice command spoken
+ * while a Codex task ran sat invisible until the task ended); Codex has queued composer input since 0.36,
+ * and a prompt that left the composer without a turn start is "queued by the TUI as a follow-up", not lost.
+ * From 0.106 a message typed mid-turn steers the running turn (docs/in-flight-agent-input.md, #294); an
+ * older or unknown release is native input, never claimed as steering.
+ */
+export const policy: SubmissionPolicy = {
+ typesWhileBusy: true,
+ verifyMs: 1_500,
+ busyInput: { mode: 'native_input', steeringSince: [0, 106] },
+}
diff --git a/cli/src/engines/engine.ts b/cli/src/engines/engine.ts
index 1446dbf18..a30fba004 100644
--- a/cli/src/engines/engine.ts
+++ b/cli/src/engines/engine.ts
@@ -1,4 +1,5 @@
import type { EngineQuestionControl } from './facets/questionControl.js'
+import type { EngineSubmission } from './facets/submission.js'
import type { EngineScreen } from './facets/screen.js'
import type { EngineModelControl } from './facets/modelControl.js'
import type { ProcessEngine } from './types.js'
@@ -19,4 +20,5 @@ export interface Engine {
readonly screen: EngineScreen
readonly modelControl: EngineModelControl
readonly questionControl: EngineQuestionControl
+ readonly submission: EngineSubmission
}
diff --git a/cli/src/engines/facets/submission.ts b/cli/src/engines/facets/submission.ts
new file mode 100644
index 000000000..297437484
--- /dev/null
+++ b/cli/src/engines/facets/submission.ts
@@ -0,0 +1,44 @@
+/**
+ * Whether a prompt core typed into a pane was taken: the engine's reading of its own composer and of the
+ * prompt as it recorded it. Core keeps the writer, the lease, every Enter and every verdict; an engine
+ * only reads text core passes it and reports what it sees.
+ */
+
+/**
+ * The declared facts that time core's own decisions on the input path. Data, not code: core reads them
+ * synchronously as a message arrives, without loading an interpreter or waiting on a worker.
+ */
+export interface SubmissionPolicy {
+ /** The engine's own TUI takes a message typed while a turn runs and queues it itself. */
+ readonly typesWhileBusy: boolean
+ /** How long after Enter core waits for the turn to start before it reads the pane. */
+ readonly verifyMs: number
+ /**
+ * How a message typed mid-turn is taken, as the Device is told: `native_queue` or `native_input`, or
+ * `steering` from the release `steeringSince` ([major, minor]) on.
+ */
+ readonly busyInput: { readonly mode: 'native_queue' | 'native_input'; readonly steeringSince?: readonly [number, number] }
+}
+
+/** What a pane shows of a prompt core typed. Facts only: core decides whether Enter is pressed again. */
+export interface SubmissionReading {
+ /** The prompt's text is still in the composer: the rows from the last prompt marker down (the whole
+ * pane when none is drawn) hold it, unsent. */
+ draft: boolean
+ /** A row starts with a prompt marker: a composer is on screen. */
+ composer: boolean
+ /** The Device's stricter reading of the same: only the engine's own prompt rows count, and a pane
+ * with none drawn is unreadable rather than read whole. */
+ nativeDraft: 'pending' | 'clear' | 'unreadable'
+}
+
+/** Where, in a prompt as the engine recorded it, the text that was typed lies: its own wrapping left out. */
+export interface PromptSpan { start: number; end: number }
+
+export interface EngineSubmission {
+ readonly policy: SubmissionPolicy
+ /** The pane after a paste, against the prompt typed into it. */
+ read(capture: string, prompt: string): SubmissionReading
+ /** A turn's prompt as the engine recorded it. */
+ echo(recorded: string): PromptSpan
+}
diff --git a/cli/src/engines/kit/nativeSubmission.ts b/cli/src/engines/kit/nativeSubmission.ts
new file mode 100644
index 000000000..1967de4f2
--- /dev/null
+++ b/cli/src/engines/kit/nativeSubmission.ts
@@ -0,0 +1,22 @@
+/**
+ * Claude Code's and Codex's reading of a prompt typed into their composer, in their engine worker. The core's
+ * session input judged the composer from its last prompt marker down and the Device's route from Claude Code's
+ * `❯` or Codex's `›` alone; both readings moved here verbatim (sessionInput.ts, deviceInput.ts), so each route
+ * decides as it did before the move.
+ */
+import type { SubmissionReading } from '../facets/submission.js'
+import { composerHolds, composerShown, visibleTerminal } from './submission.js'
+
+/** The Device's reading: only `❯` and `›` start a composer, a pane with neither is unreadable rather than read
+ * whole, and the prompt is compared as typed. */
+function nativeDraft(capture: string, content: string): SubmissionReading['nativeDraft'] {
+ const lines = visibleTerminal(capture).split('\n')
+ const index = lines.findLastIndex(line => /[›❯]/u.test(line) && !/[›❯]\s*\d+\.\s/u.test(line))
+ if (index < 0) return 'unreadable'
+ const normalize = (text: string) => text.replace(/\s+/g, ' ').trim()
+ return normalize(lines.slice(index).join('\n')).includes(normalize(content)) ? 'pending' : 'clear'
+}
+
+export function readNativeSubmission(capture: string, prompt: string): SubmissionReading {
+ return { draft: composerHolds(capture, prompt), composer: composerShown(capture), nativeDraft: nativeDraft(capture, prompt) }
+}
diff --git a/cli/src/engines/kit/submission.ts b/cli/src/engines/kit/submission.ts
new file mode 100644
index 000000000..8c818f7a2
--- /dev/null
+++ b/cli/src/engines/kit/submission.ts
@@ -0,0 +1,35 @@
+/**
+ * Reading a typed prompt in a composer: the mechanics Claude Code's and Codex's submission readers
+ * (nativeSubmission.ts) share with the core's reading for the engines not yet behind a facet
+ * (lib/sessionInput.ts). Moved verbatim from sessionInput.ts, so a prompt is judged as it was before.
+ */
+
+export function visibleTerminal(value: string): string {
+ return value.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
+}
+
+export function normalizedTerminalText(value: string): string {
+ return visibleTerminal(value).replace(/\s+/g, ' ').trim()
+}
+
+// Composer region = from the last prompt-marker line to the end (mirrors runtimeProfile.currentPaneUi).
+// Marker set covers claude ❯, codex ›, cursor →. A numbered row after the marker is a dialog's, not a prompt.
+function composerRegion(capture: string): string {
+ const lines = visibleTerminal(capture).split('\n')
+ const idx = lines.findLastIndex((line) => {
+ const marker = line.search(/[›❯→]/u)
+ return marker >= 0 && !/^\s*\d+\.\s/.test(line.slice(marker + 1))
+ })
+ return (idx >= 0 ? lines.slice(idx) : lines).join('\n') // no marker → whole pane (safe fallback)
+}
+
+/** True while the injected prompt is still sitting un-submitted in the terminal composer. */
+export function composerHolds(capture: string, content: string): boolean {
+ const expected = normalizedTerminalText(content)
+ return !!expected && normalizedTerminalText(composerRegion(capture)).includes(expected)
+}
+
+/** A row begins with a prompt marker: some composer is drawn, whatever it holds. */
+export function composerShown(capture: string): boolean {
+ return /^\s*[›❯→]/mu.test(visibleTerminal(capture))
+}
diff --git a/cli/src/engines/registry.ts b/cli/src/engines/registry.ts
index 73eda56a0..0d0d3b4af 100644
--- a/cli/src/engines/registry.ts
+++ b/cli/src/engines/registry.ts
@@ -1,6 +1,8 @@
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 { submission as claudeSubmission } from './claude/submission.js'
+import { submission as codexSubmission } from './codex/submission.js'
import { modelControl as claudeModelControl } from './claude/modelControl.js'
import { modelControl as codexModelControl } from './codex/modelControl.js'
import { screen as codexScreen } from './codex/screen.js'
@@ -16,8 +18,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, questionControl: claudeQuestionControl },
- codex: { name: 'codex', launch: engineLaunches.codex, transcript: codexTranscript, hooks: engineHooks.codex, live: codexLive, runtime: codexRuntime, screen: codexScreen, modelControl: codexModelControl, questionControl: codexQuestionControl },
+ claude: { name: 'claude', launch: engineLaunches.claude, transcript: claudeTranscript, hooks: engineHooks.claude, live: claudeLive, runtime: claudeRuntime, screen: claudeScreen, modelControl: claudeModelControl, questionControl: claudeQuestionControl, submission: claudeSubmission },
+ codex: { name: 'codex', launch: engineLaunches.codex, transcript: codexTranscript, hooks: engineHooks.codex, live: codexLive, runtime: codexRuntime, screen: codexScreen, modelControl: codexModelControl, questionControl: codexQuestionControl, submission: codexSubmission },
} satisfies Record<string, Engine>
type MigratedEngine = keyof typeof engines
export function engineFor(name: string | null | undefined): Engine | undefined {
diff --git a/cli/src/engines/submissionPolicies.ts b/cli/src/engines/submissionPolicies.ts
new file mode 100644
index 000000000..b2aec0a44
--- /dev/null
+++ b/cli/src/engines/submissionPolicies.ts
@@ -0,0 +1,14 @@
+import type { SubmissionPolicy } from './facets/submission.js'
+import { policy as claude } from './claude/submissionPolicy.js'
+import { policy as codex } from './codex/submissionPolicy.js'
+
+/**
+ * The submission timing of the engines whose submissions their worker reads: data only, like the launch
+ * contract (launches.ts), so the core's input path reads it in line and loads no reader. An engine not
+ * here keeps the core's own reading (lib/sessionInput.ts) until its batch.
+ */
+const policies: Readonly<Record<string, SubmissionPolicy>> = { claude, codex }
+
+export function submissionPolicy(engine: string | null | undefined): SubmissionPolicy | undefined {
+ return engine && Object.hasOwn(policies, engine) ? policies[engine] : undefined
+}
diff --git a/cli/src/engines/submissions.ts b/cli/src/engines/submissions.ts
new file mode 100644
index 000000000..a0cb60b50
--- /dev/null
+++ b/cli/src/engines/submissions.ts
@@ -0,0 +1,4 @@
+/** Explicit inline composition; supervised core does not import the native submission readers. */
+import { submission as claude } from './claude/submission.js'
+import { submission as codex } from './codex/submission.js'
+export const submissionFor = (engine: string) => engine === 'claude' ? claude : engine === 'codex' ? codex : undefined
diff --git a/cli/src/engines/worker/process.ts b/cli/src/engines/worker/process.ts
index 8e6a887aa..3926a9f37 100644
--- a/cli/src/engines/worker/process.ts
+++ b/cli/src/engines/worker/process.ts
@@ -10,6 +10,7 @@ import type { ServiceProcessOptions } from '../../serviceProcess.js'
import type { EngineTranscript, HistoryAsk, TranscriptSession } from '../facets/transcript.js'
import { engineLiveRequests } from './liveRequests.js'
import { engineScreenRequests } from './screenRequests.js'
+import { engineSubmissionRequests } from './submissionRequests.js'
import { engineRuntimeRequests } from './runtimeRequests.js'
import {
EngineReadError, record, READER_HISTORY, READER_IN_FLIGHT, READER_LAST_TURN, READER_REPLY_BYTES,
@@ -91,7 +92,7 @@ export function runEngineReader(engine: ReaderEngine, options: EngineProcessOpti
let core: CoreConnection | null = null
return (options.run ?? runServiceProcess)({
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, {
+ token: options.token, requests: options.requests ?? { ...engineReaderRequests(engine), ...engineLiveRequests(engine), ...engineRuntimeRequests(engine), ...engineScreenRequests(engine), ...engineSubmissionRequests(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')),
diff --git a/cli/src/engines/worker/screenRequests.ts b/cli/src/engines/worker/screenRequests.ts
index b468b8a83..58c581155 100644
--- a/cli/src/engines/worker/screenRequests.ts
+++ b/cli/src/engines/worker/screenRequests.ts
@@ -3,6 +3,7 @@ import type { EngineScreen } from '../facets/screen.js'
import type { ReaderEngine } from './protocol.js'
import { screenCapture, screenReading, SCREEN_CAPABILITIES, SCREEN_IN_FLIGHT, SCREEN_READ,
SCREEN_REPLY_BYTES, SCREEN_VERSION, SCREEN_WAIT_MS } from './screenProtocol.js'
+import { snapshotRequests } from './snapshotRequests.js'
const loadScreen = {
claude: async () => (await import('../claude/screen.js')).screen,
@@ -11,35 +12,16 @@ const loadScreen = {
export interface ScreenRequestDeps { load?: () => Promise<EngineScreen>; recycle?: () => void }
export function engineScreenRequests(engine: ReaderEngine, deps: ScreenRequestDeps = {}): ServiceRequests {
- let loaded: Promise<EngineScreen> | null = null
- let pending = 0
- const failure = (error: string) => ({ version: SCREEN_VERSION, error })
- const handle = (method: string): ServiceRequests[string] => async (payload, asker, closed) => {
- if (!asker.owner || !asker.local || asker.connection !== undefined || payload.version !== SCREEN_VERSION) return failure('ENGINE_INVALID_REQUEST')
- if (closed?.aborted) return failure('ENGINE_UNAVAILABLE')
- if (method === SCREEN_CAPABILITIES) return { version: SCREEN_VERSION, screen: SCREEN_VERSION, engine }
- // ServiceLinks adds its routing id inside the payload. It is transport
- // metadata, not a terminal capability or engine input.
- if (!screenCapture(payload.capture) || Object.keys(payload).some(key => !['version', 'capture', 'requestId'].includes(key))
- || (payload.requestId !== undefined && (typeof payload.requestId !== 'string' || payload.requestId.length > 200))) return failure('ENGINE_INVALID_REQUEST')
- if (pending >= SCREEN_IN_FLIGHT) return failure('ENGINE_BUSY')
- pending++
- let timer: ReturnType<typeof setTimeout> | undefined
- const deadline = new Promise<Record<string, unknown>>(resolve => {
- timer = setTimeout(() => { resolve(failure('ENGINE_UNAVAILABLE')); (deps.recycle ?? (() => process.exit(1)))() }, SCREEN_WAIT_MS)
- })
- try {
- const capture = payload.capture
- return await Promise.race([deadline, (async () => {
- const adapter = await (loaded ??= (deps.load ?? loadScreen[engine])().catch(error => { loaded = null; throw error }))
- if (closed?.aborted) return failure('ENGINE_UNAVAILABLE')
- const answer = adapter.inspect(capture)
- const reply = { version: SCREEN_VERSION, answer }
- if (Buffer.byteLength(JSON.stringify(reply)) > SCREEN_REPLY_BYTES) return failure('ENGINE_REPLY_TOO_LARGE')
- return screenReading(answer) ? reply : failure('ENGINE_INVALID_REPLY')
- })()])
- } catch { return failure('ENGINE_UNAVAILABLE') }
- finally { clearTimeout(timer); pending-- }
- }
- return { [SCREEN_CAPABILITIES]: handle(SCREEN_CAPABILITIES), [SCREEN_READ]: handle(SCREEN_READ) }
+ return snapshotRequests<EngineScreen>({
+ engine, version: SCREEN_VERSION, capabilities: SCREEN_CAPABILITIES, capability: 'screen',
+ inFlight: SCREEN_IN_FLIGHT, waitMs: SCREEN_WAIT_MS, replyBytes: SCREEN_REPLY_BYTES,
+ load: deps.load ?? loadScreen[engine], recycle: () => (deps.recycle ?? (() => process.exit(1)))(),
+ methods: {
+ [SCREEN_READ]: {
+ fields: ['capture'], accepts: payload => screenCapture(payload.capture),
+ answer: (adapter, payload) => adapter.inspect(payload.capture as string),
+ valid: answer => screenReading(answer),
+ },
+ },
+ })
}
diff --git a/cli/src/engines/worker/snapshotRequests.ts b/cli/src/engines/worker/snapshotRequests.ts
new file mode 100644
index 000000000..0fde43e8c
--- /dev/null
+++ b/cli/src/engines/worker/snapshotRequests.ts
@@ -0,0 +1,63 @@
+/**
+ * Private, stateless readings in an engine worker: core sends text, the worker answers facts. Shared by the
+ * screen and submission readers, each with its own version, bounds and validators. A worker gets no terminal
+ * handle, no lease and no general core API: what it answers is all it can do.
+ */
+import type { ServiceRequests } from '../../core/api.js'
+
+export interface SnapshotMethod<A> {
+ /** The payload's own fields; `version` and the link's `requestId` are always allowed beside them. */
+ fields: readonly string[]
+ accepts(payload: Record<string, unknown>): boolean
+ answer(adapter: A, payload: Record<string, unknown>): unknown
+ valid(answer: unknown, payload: Record<string, unknown>): boolean
+}
+
+export interface SnapshotSpec<A> {
+ engine: string
+ version: number
+ capabilities: string
+ /** The capability reply's field naming this reader's version. */
+ capability: string
+ inFlight: number
+ waitMs: number
+ replyBytes: number
+ load(): Promise<A>
+ /** A timed-out reading may still hold the worker; recycle it rather than accumulate abandoned work. */
+ recycle(): void
+ methods: Readonly<Record<string, SnapshotMethod<A>>>
+}
+
+export function snapshotRequests<A>(spec: SnapshotSpec<A>): ServiceRequests {
+ let loaded: Promise<A> | null = null
+ let pending = 0
+ const failure = (error: string) => ({ version: spec.version, error })
+ const handle = (method?: SnapshotMethod<A>): ServiceRequests[string] => async (payload, asker, closed) => {
+ if (!asker.owner || !asker.local || asker.connection !== undefined || payload.version !== spec.version) return failure('ENGINE_INVALID_REQUEST')
+ if (closed?.aborted) return failure('ENGINE_UNAVAILABLE')
+ if (!method) return { version: spec.version, [spec.capability]: spec.version, engine: spec.engine }
+ // ServiceLinks adds its routing id inside the payload. It is transport
+ // metadata, not a terminal capability or engine input.
+ if (!method.accepts(payload) || Object.keys(payload).some(key => key !== 'version' && key !== 'requestId' && !method.fields.includes(key))
+ || (payload.requestId !== undefined && (typeof payload.requestId !== 'string' || payload.requestId.length > 200))) return failure('ENGINE_INVALID_REQUEST')
+ if (pending >= spec.inFlight) return failure('ENGINE_BUSY')
+ pending++
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const deadline = new Promise<Record<string, unknown>>(resolve => {
+ timer = setTimeout(() => { resolve(failure('ENGINE_UNAVAILABLE')); spec.recycle() }, spec.waitMs)
+ })
+ try {
+ return await Promise.race([deadline, (async () => {
+ const adapter = await (loaded ??= spec.load().catch(error => { loaded = null; throw error }))
+ if (closed?.aborted) return failure('ENGINE_UNAVAILABLE')
+ const answer = method.answer(adapter, payload)
+ const reply = { version: spec.version, answer }
+ if (Buffer.byteLength(JSON.stringify(reply)) > spec.replyBytes) return failure('ENGINE_REPLY_TOO_LARGE')
+ return method.valid(answer, payload) ? reply : failure('ENGINE_INVALID_REPLY')
+ })()])
+ } catch { return failure('ENGINE_UNAVAILABLE') }
+ finally { clearTimeout(timer); pending-- }
+ }
+ return Object.fromEntries([[spec.capabilities, handle()],
+ ...Object.entries(spec.methods).map(([name, method]) => [name, handle(method)])])
+}
diff --git a/cli/src/engines/worker/submissionProtocol.ts b/cli/src/engines/worker/submissionProtocol.ts
new file mode 100644
index 000000000..df4573656
--- /dev/null
+++ b/cli/src/engines/worker/submissionProtocol.ts
@@ -0,0 +1,38 @@
+/** Private, stateless submission readings. A worker receives text, never a terminal handle or a lease. */
+import type { PromptSpan, SubmissionReading } from '../facets/submission.js'
+import { record } from './protocol.js'
+import { screenCapture } from './screenProtocol.js'
+
+export const SUBMISSION_VERSION = 1
+export const SUBMISSION_CAPABILITIES = 'engine_submission_capabilities'
+/** The pane after a paste, against the prompt typed into it. */
+export const SUBMISSION_READ = 'engine_submission_read'
+/** A turn's prompt as the engine recorded it: where the typed text lies within it. */
+export const SUBMISSION_ECHO = 'engine_submission_echo'
+/** The same budget as a screen read: a verification waits on both, one after the other. */
+export const SUBMISSION_WAIT_MS = 1_000
+export const SUBMISSION_IN_FLIGHT = 8
+export const SUBMISSION_QUEUED = 64
+/** A prompt as typed or recorded. Larger than any message the apps send; beyond it nothing is read, and
+ * core decides as it does for any reading it could not get. The capture keeps the screen's bound. */
+export const SUBMISSION_TEXT_BYTES = 1024 * 1024
+/** An answer is three facts or two offsets. */
+export const SUBMISSION_REPLY_BYTES = 4 * 1024
+
+export const submissionCapture = screenCapture
+
+export function submissionText(value: unknown): value is string {
+ return typeof value === 'string' && value.length <= SUBMISSION_TEXT_BYTES && Buffer.byteLength(value) <= SUBMISSION_TEXT_BYTES
+}
+
+const DRAFTS = ['pending', 'clear', 'unreadable']
+export function submissionReading(value: unknown): value is SubmissionReading {
+ return record(value) && Object.keys(value).length === 3 && typeof value.draft === 'boolean'
+ && typeof value.composer === 'boolean' && DRAFTS.includes(value.nativeDraft as string)
+}
+
+/** A span of the very text core sent: offsets inside it, in order, and nothing else. */
+export function promptSpan(value: unknown, recorded: string): value is PromptSpan {
+ return record(value) && Object.keys(value).length === 2 && Number.isInteger(value.start) && Number.isInteger(value.end)
+ && (value.start as number) >= 0 && (value.start as number) <= (value.end as number) && (value.end as number) <= recorded.length
+}
diff --git a/cli/src/engines/worker/submissionRequests.spec.ts b/cli/src/engines/worker/submissionRequests.spec.ts
new file mode 100644
index 000000000..405aa74fd
--- /dev/null
+++ b/cli/src/engines/worker/submissionRequests.spec.ts
@@ -0,0 +1,75 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { submissionFor } from '../submissions.js'
+import type { EngineSubmission } from '../facets/submission.js'
+import { engineSubmissionRequests } from './submissionRequests.js'
+import { SUBMISSION_CAPABILITIES, SUBMISSION_ECHO, SUBMISSION_IN_FLIGHT, SUBMISSION_READ, SUBMISSION_TEXT_BYTES, SUBMISSION_WAIT_MS } from './submissionProtocol.js'
+
+const who = { owner: true, local: true }
+const capture = '\n\u001b[1m›\u001b[0m hello\n\n ? for shortcuts'
+const fail = (error: string) => ({ version: 1, error })
+afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() })
+
+describe('read-only engine submission workers', () => {
+ it.each(['claude', 'codex'] as const)('%s answers with its own reading, loaded once and only when first asked', async engine => {
+ const load = vi.fn(async () => submissionFor(engine)!)
+ const requests = engineSubmissionRequests(engine, { load })
+ expect(await requests[SUBMISSION_CAPABILITIES]({ version: 1 }, who)).toEqual({ version: 1, submission: 1, engine })
+ expect(load).not.toHaveBeenCalled()
+ expect(await requests[SUBMISSION_READ]({ version: 1, capture, prompt: 'hello' }, who)).toEqual({ version: 1, answer: { draft: true, composer: true, nativeDraft: 'pending' } })
+ expect(await requests[SUBMISSION_READ]({ version: 1, capture: '› \n', prompt: 'hello', requestId: 'core-route-2' }, who))
+ .toEqual({ version: 1, answer: { draft: false, composer: true, nativeDraft: 'clear' } })
+ const recorded = '<pasted_content id="ab">\nhello\n</pasted_content id="ab">'
+ expect(await requests[SUBMISSION_ECHO]({ version: 1, recorded }, who))
+ .toEqual({ version: 1, answer: engine === 'claude' ? { start: 25, end: 30 } : { start: 0, end: recorded.length } })
+ expect(load).toHaveBeenCalledOnce()
+ })
+
+ it('accepts only private local core requests with bounded text', async () => {
+ const load = vi.fn(async () => submissionFor('claude')!)
+ const requests = engineSubmissionRequests('claude', { load })
+ const read = { version: 1, capture, prompt: 'hello' }
+ for (const asker of [{ owner: false, local: true }, { owner: true, local: false }, { ...who, connection: 'client' }]) {
+ expect(await requests[SUBMISSION_READ](read, asker)).toEqual(fail('ENGINE_INVALID_REQUEST'))
+ }
+ for (const payload of [{ ...read, version: 2 }, { ...read, prompt: 42 }, { ...read, capture: 'é'.repeat(256 * 1024) },
+ { ...read, prompt: 'x'.repeat(SUBMISSION_TEXT_BYTES + 1) }, { ...read, pane: '%1' }, { ...read, requestId: 7 },
+ { ...read, requestId: 'x'.repeat(201) }]) {
+ expect(await requests[SUBMISSION_READ](payload, who)).toEqual(fail('ENGINE_INVALID_REQUEST'))
+ }
+ for (const payload of [{ version: 1, recorded: 7 }, { version: 1, recorded: 'hello', capture }]) {
+ expect(await requests[SUBMISSION_ECHO](payload, who)).toEqual(fail('ENGINE_INVALID_REQUEST'))
+ }
+ expect(await requests[SUBMISSION_ECHO]({ version: 1, recorded: 'hello' }, who, AbortSignal.abort())).toEqual(fail('ENGINE_UNAVAILABLE'))
+ expect(load).not.toHaveBeenCalled()
+ })
+
+ it('bounds concurrent readings, recycles a stalled worker, and retries an import that failed', async () => {
+ vi.useFakeTimers()
+ const recycle = vi.fn()
+ let finish!: (value: EngineSubmission) => void
+ const requests = engineSubmissionRequests('codex', { recycle, load: () => new Promise(resolve => { finish = resolve }) })
+ const send = () => requests[SUBMISSION_ECHO]({ version: 1, recorded: 'hello' }, who)
+ const pending = Array.from({ length: SUBMISSION_IN_FLIGHT }, send)
+ expect(await send()).toEqual(fail('ENGINE_BUSY'))
+ await vi.advanceTimersByTimeAsync(SUBMISSION_WAIT_MS)
+ for (const reading of pending) expect(await reading).toEqual(fail('ENGINE_UNAVAILABLE'))
+ expect(recycle).toHaveBeenCalled()
+ finish(submissionFor('codex')!)
+ vi.useRealTimers()
+ const load = vi.fn().mockRejectedValueOnce(new Error('import failed')).mockResolvedValue(submissionFor('codex'))
+ const retry = engineSubmissionRequests('codex', { load })
+ expect(await retry[SUBMISSION_ECHO]({ version: 1, recorded: 'hello' }, who)).toEqual(fail('ENGINE_UNAVAILABLE'))
+ expect(await retry[SUBMISSION_ECHO]({ version: 1, recorded: 'hello' }, who)).toEqual({ version: 1, answer: { start: 0, end: 5 } })
+ })
+
+ it('drops work for a closed connection and rejects a faulty reader\'s answers', async () => {
+ const closed = new AbortController()
+ const requests = engineSubmissionRequests('claude', { load: async () => { closed.abort(); return submissionFor('claude')! } })
+ expect(await requests[SUBMISSION_READ]({ version: 1, capture, prompt: 'hello' }, who, closed.signal)).toEqual(fail('ENGINE_UNAVAILABLE'))
+ const faulty = (reader: Partial<EngineSubmission>) => engineSubmissionRequests('claude', { load: async () => ({ ...submissionFor('claude')!, ...reader }) })
+ expect(await faulty({ echo: () => ({ start: 0, end: 99 }) })[SUBMISSION_ECHO]({ version: 1, recorded: 'hello' }, who)).toEqual(fail('ENGINE_INVALID_REPLY'))
+ expect(await faulty({ read: () => ({ draft: true }) as never })[SUBMISSION_READ]({ version: 1, capture, prompt: 'hello' }, who)).toEqual(fail('ENGINE_INVALID_REPLY'))
+ expect(await faulty({ read: () => ({ draft: true, composer: true, nativeDraft: 'clear', note: 'x'.repeat(8192) }) as never })[SUBMISSION_READ]({ version: 1, capture, prompt: 'hello' }, who)).toEqual(fail('ENGINE_REPLY_TOO_LARGE'))
+ expect(await faulty({ echo: () => { throw new Error('bad decoder') } })[SUBMISSION_ECHO]({ version: 1, recorded: 'hello' }, who)).toEqual(fail('ENGINE_UNAVAILABLE'))
+ })
+})
diff --git a/cli/src/engines/worker/submissionRequests.ts b/cli/src/engines/worker/submissionRequests.ts
new file mode 100644
index 000000000..401d0f320
--- /dev/null
+++ b/cli/src/engines/worker/submissionRequests.ts
@@ -0,0 +1,33 @@
+import type { ServiceRequests } from '../../core/api.js'
+import type { EngineSubmission } from '../facets/submission.js'
+import type { ReaderEngine } from './protocol.js'
+import { snapshotRequests } from './snapshotRequests.js'
+import { promptSpan, submissionCapture, submissionReading, submissionText, SUBMISSION_CAPABILITIES, SUBMISSION_ECHO,
+ SUBMISSION_IN_FLIGHT, SUBMISSION_READ, SUBMISSION_REPLY_BYTES, SUBMISSION_VERSION, SUBMISSION_WAIT_MS } from './submissionProtocol.js'
+
+const loadSubmission = {
+ claude: async () => (await import('../claude/submission.js')).submission,
+ codex: async () => (await import('../codex/submission.js')).submission,
+}
+export interface SubmissionRequestDeps { load?: () => Promise<EngineSubmission>; recycle?: () => void }
+
+/** The engine's reading of its own composer and recorded prompt; the verdict and every Enter are core's. */
+export function engineSubmissionRequests(engine: ReaderEngine, deps: SubmissionRequestDeps = {}): ServiceRequests {
+ return snapshotRequests<EngineSubmission>({
+ engine, version: SUBMISSION_VERSION, capabilities: SUBMISSION_CAPABILITIES, capability: 'submission',
+ inFlight: SUBMISSION_IN_FLIGHT, waitMs: SUBMISSION_WAIT_MS, replyBytes: SUBMISSION_REPLY_BYTES,
+ load: deps.load ?? loadSubmission[engine], recycle: () => (deps.recycle ?? (() => process.exit(1)))(),
+ methods: {
+ [SUBMISSION_READ]: {
+ fields: ['capture', 'prompt'], accepts: payload => submissionCapture(payload.capture) && submissionText(payload.prompt),
+ answer: (adapter, payload) => adapter.read(payload.capture as string, payload.prompt as string),
+ valid: answer => submissionReading(answer),
+ },
+ [SUBMISSION_ECHO]: {
+ fields: ['recorded'], accepts: payload => submissionText(payload.recorded),
+ answer: (adapter, payload) => adapter.echo(payload.recorded as string),
+ valid: (answer, payload) => promptSpan(answer, payload.recorded as string),
+ },
+ },
+ })
+}
diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.ts
index 2ebf9216f..ed28c3797 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, ENGINE_QUESTION_CONTROL_ENV, masterRunsEngineQuestionControl, 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, ENGINE_SUBMISSION_ENV, masterRunsEngineSubmission, 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', [ENGINE_QUESTION_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', [ENGINE_SUBMISSION_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', [ENGINE_QUESTION_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', [ENGINE_SUBMISSION_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', [ENGINE_QUESTION_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', [ENGINE_SUBMISSION_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.
@@ -539,6 +539,16 @@ describe('which services the core leaves to its master', () => {
expect(masterRunsEngineScreen({ ...env, HARNESSD_SERVICE_TOKEN: undefined }, 42)).toBe(false)
})
+ it('negotiates submission readers only from a capable supervising parent', () => {
+ const env = { ...supervised, ...serviceProcessesEnv([], 42) }
+ expect(masterRunsEngineSubmission(env, 42)).toBe(true)
+ expect(masterRunsEngineSubmission(env, 43)).toBe(false)
+ // An older master never set it: the core composes the inline readers, the way it does for the others.
+ expect(masterRunsEngineSubmission({ ...env, [ENGINE_SUBMISSION_ENV]: undefined }, 42)).toBe(false)
+ expect(masterRunsEngineSubmission({ ...env, [ENGINE_LIVE_ENV]: undefined }, 42)).toBe(false)
+ expect(masterRunsEngineSubmission({ ...env, HARNESSD_SERVICE_TOKEN: undefined }, 42)).toBe(false)
+ })
+
it('is none without a master, or without the token its services would connect with', () => {
expect([...servicesTheMasterRuns({ [SERVICE_PROCESSES_ENV]: 'search' }, known)]).toEqual([])
expect([...servicesTheMasterRuns({ HARNESSD_SUPERVISED: '1', [SERVICE_PROCESSES_ENV]: 'search' }, known)]).toEqual([])
diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.ts
index a0e7f2635..5ba66ff8d 100644
--- a/cli/src/harnessd/services.ts
+++ b/cli/src/harnessd/services.ts
@@ -462,6 +462,7 @@ 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'
+export const ENGINE_SUBMISSION_ENV = 'HARNESSD_ENGINE_SUBMISSION'
/**
* What a master puts in its core's environment about the services it runs in their own processes: the
@@ -473,7 +474,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`, [ENGINE_QUESTION_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`, [ENGINE_SUBMISSION_ENV]: `${masterPid}:1` }
}
/** An older master may inherit a newer master's environment after rollback. Trust only this parent. */
@@ -537,3 +538,8 @@ export function masterRunsEngineModelControl(env: NodeJS.ProcessEnv, parentPid:
export function masterRunsEngineQuestionControl(env: NodeJS.ProcessEnv, parentPid: number): boolean {
return masterRunsLiveEngines(env, parentPid) && env[ENGINE_QUESTION_CONTROL_ENV] === `${parentPid}:1`
}
+
+/** A new core must not ask an older worker host for submission readings it does not serve. */
+export function masterRunsEngineSubmission(env: NodeJS.ProcessEnv, parentPid: number): boolean {
+ return masterRunsLiveEngines(env, parentPid) && env[ENGINE_SUBMISSION_ENV] === `${parentPid}:1`
+}
diff --git a/cli/src/lib/sessionInput.spec.ts b/cli/src/lib/sessionInput.spec.ts
index 03623bc36..a6528eefb 100644
--- a/cli/src/lib/sessionInput.spec.ts
+++ b/cli/src/lib/sessionInput.spec.ts
@@ -1,11 +1,17 @@
import { readInlineScreen } from '../testing/inlineScreen.js'
+import { inlineSubmission } from '../testing/inlineSubmission.js'
import { readFileSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { SessionInputController } from './sessionInput.js'
import type { RegisteredSession } from './registry.js'
-import { TERMINAL_LEASE_REFUSED, type TerminalActionResult } from './terminalTypes.js'
+import { TERMINAL_LEASE_REFUSED, type ProcessIdentity, type TerminalActionResult } from './terminalTypes.js'
+import { createScreens } from '../core/engines/screens.js'
+import { createSubmissions } from '../core/engines/submissions.js'
+import { screenFor } from '../engines/screens.js'
+import { submissionFor } from '../engines/submissions.js'
+import { submissionPolicy } from '../engines/submissionPolicies.js'
function session(engine: 'claude' | 'codex' | 'cursor' | 'commandcode' = 'codex'): RegisteredSession {
return {
@@ -39,7 +45,7 @@ describe('SessionInputController', () => {
] as const)('%s, %s: tells the person why and what to do, asks no lease again, and awaits nothing', async (engine, reason, text) => {
const onError = vi.fn(), onSubmitted = vi.fn(), sleep = vi.fn(async () => {})
const inject = vi.fn(async () => held(reason))
- const controller = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session(engine), validateRuntime: async () => true,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session(engine), validateRuntime: async () => true,
inject, sendKey: async () => true, onError, onSubmitted, sleep })
controller.submit('s1', 'a message from the app')
await vi.waitFor(() => expect(onError).toHaveBeenCalledWith('s1', text))
@@ -55,7 +61,7 @@ describe('SessionInputController', () => {
const onError = vi.fn(), onSubmitted = vi.fn()
const inject = vi.fn<() => Promise<TerminalActionResult>>().mockResolvedValueOnce(held('prompt_hidden'))
.mockResolvedValueOnce(held('screen_unreadable')).mockResolvedValue({ state: 'succeeded', dispatch: 'executed' })
- const controller = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session('codex'), validateRuntime: async () => true,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session('codex'), validateRuntime: async () => true,
inject, sendKey: async () => true, onError, onSubmitted, now: time.now, sleep: time.sleep })
controller.submit('s1', 'sent while it starts')
await vi.waitFor(() => expect(onSubmitted).toHaveBeenCalledWith('s1', 'sent while it starts'))
@@ -68,7 +74,7 @@ describe('SessionInputController', () => {
const time = { at: 0, now: () => time.at, sleep: vi.fn(async (ms: number) => { time.at += ms }) }
const onError = vi.fn()
const inject = vi.fn(async () => held('prompt_hidden'))
- const controller = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session('claude'), validateRuntime: async () => true,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session('claude'), validateRuntime: async () => true,
inject, sendKey: async () => true, onError, now: time.now, sleep: time.sleep })
controller.submit('s1', 'into a screen never seen')
await vi.waitFor(() => expect(onError).toHaveBeenCalledWith('s1', 'Claude Code isn\'t showing its prompt; finish what\'s on its screen in its terminal, then send the message again.'))
@@ -80,7 +86,7 @@ describe('SessionInputController', () => {
const withheld: TerminalActionResult = { state: 'unknown', dispatch: 'possibly_executed', reason: 'enter_withheld:permission_open' }
const onError = vi.fn(), onSubmitted = vi.fn(), sendKey = vi.fn(async () => true), forget = vi.fn(), onDelivery = vi.fn()
vi.useFakeTimers()
- const controller = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session('claude'), validateRuntime: async () => true,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session('claude'), validateRuntime: async () => true,
inject: async () => withheld, sendKey, onError, onSubmitted, onDelivery, beforeSubmit: () => forget, beforeTeamWrite: async () => null })
controller.submit('s1', 'a message from the app')
await vi.advanceTimersByTimeAsync(30_000)
@@ -104,7 +110,7 @@ describe('SessionInputController', () => {
it('rejects a message that wants a receipt with the reason, and says why', async () => {
const onError = vi.fn(), onDelivery = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session('codex'), validateRuntime: async () => true,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session('codex'), validateRuntime: async () => true,
inject: async () => held('permission_open'), sendKey: async () => true, onError, onDelivery })
controller.submit('s1', 'a message from the device', 'd1')
await vi.waitFor(() => expect(onDelivery).toHaveBeenCalledWith({ sessionId: 's1', deliveryId: 'd1', state: 'rejected', reason: 'permission_open' }))
@@ -114,7 +120,7 @@ describe('SessionInputController', () => {
it('rejects a team\'s turn with the reason, and tells no person: its team hears of it', async () => {
const onError = vi.fn(), onDelivery = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session('claude'), validateRuntime: async () => true,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session('claude'), validateRuntime: async () => true,
beforeTeamWrite: async () => null, inject: vi.fn(), injectTeam: async () => held('menu_open'), sendKey: async () => true, onError, onDelivery })
controller.submit('s1', 'a team turn', 'team:1')
await vi.waitFor(() => expect(onDelivery).toHaveBeenCalledWith({ sessionId: 's1', deliveryId: 'team:1', state: 'rejected', reason: 'menu_open' }))
@@ -135,7 +141,7 @@ describe('SessionInputController', () => {
it('waits for the lease — a resume whose new process is not confirmed yet — and then delivers, once', async () => {
const time = clock(), onError = vi.fn(), onSubmitted = vi.fn()
const inject = vi.fn<() => Promise<TerminalActionResult>>().mockResolvedValueOnce(refused).mockResolvedValueOnce(refused).mockResolvedValue(done)
- const controller = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session('claude'), validateRuntime: async () => true,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session('claude'), validateRuntime: async () => true,
inject, sendKey: async () => true, onError, onSubmitted, ...time })
controller.submit('s1', 'right after the resume')
await vi.waitFor(() => expect(onSubmitted).toHaveBeenCalledWith('s1', 'right after the resume'))
@@ -148,7 +154,7 @@ describe('SessionInputController', () => {
it('gives up at fifteen seconds, says the message was not delivered, and wrote nothing', async () => {
const time = clock(), onError = vi.fn()
const inject = vi.fn(async () => refused)
- const controller = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session('claude'), validateRuntime: async () => true,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session('claude'), validateRuntime: async () => true,
inject, sendKey: async () => true, onError, ...time })
controller.submit('s1', 'never leased')
await vi.waitFor(() => expect(onError).toHaveBeenCalledWith('s1', 'The message could not be delivered to the agent.'))
@@ -161,14 +167,14 @@ describe('SessionInputController', () => {
const time = clock(), onError = vi.fn()
let present = true
const inject = vi.fn(async () => { present = false; return refused })
- const gone = new SessionInputController({ readScreen: readInlineScreen, getSession: () => (present ? session('claude') : undefined), validateRuntime: async () => true,
+ const gone = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => (present ? session('claude') : undefined), validateRuntime: async () => true,
inject, sendKey: async () => true, onError, ...time })
gone.submit('s1', 'to an agent that left')
await vi.waitFor(() => expect(onError).toHaveBeenCalled())
expect(inject).toHaveBeenCalledTimes(1)
const other = vi.fn(async (): Promise<TerminalActionResult> => ({ state: 'failed', dispatch: 'not_started', reason: 'terminal agent is unavailable' }))
- const elsewhere = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session('claude'), validateRuntime: async () => true,
+ const elsewhere = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session('claude'), validateRuntime: async () => true,
inject: other, sendKey: async () => true, onError: vi.fn(), ...time })
elsewhere.submit('s1', 'to an agent with no terminal')
await vi.waitFor(() => expect(other).toHaveBeenCalledTimes(1))
@@ -179,7 +185,7 @@ describe('SessionInputController', () => {
it('waits the same way for a message that wants a receipt, until it is cancelled', async () => {
const time = clock(), onDelivery = vi.fn()
const inject = vi.fn<() => Promise<TerminalActionResult>>().mockResolvedValueOnce(refused).mockResolvedValue(done)
- const controller = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session('codex'), validateRuntime: async () => true,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session('codex'), validateRuntime: async () => true,
inject, sendKey: async () => true, onError: vi.fn(), onDelivery, ...time })
controller.submit('s1', 'with a receipt', 'delivery-1')
await vi.waitFor(() => expect(inject).toHaveBeenCalledTimes(2))
@@ -187,7 +193,7 @@ describe('SessionInputController', () => {
const cancelled = vi.fn(async () => refused)
let cancel: () => void = () => {}
- const waiting = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session('codex'), validateRuntime: async () => true,
+ const waiting = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session('codex'), validateRuntime: async () => true,
inject: cancelled, sendKey: async () => true, onError: vi.fn(), onDelivery,
now: time.now, sleep: async (ms) => { time.sleep(ms); cancel() } })
cancel = () => waiting.forget('s1')
@@ -201,7 +207,7 @@ describe('SessionInputController', () => {
it('retains the submitted swarm through the input queue and records it only at dispatch', async () => {
const beforeSubmit = vi.fn(() => vi.fn())
- const controller = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session('cursor'), validateRuntime: async () => true,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session('cursor'), validateRuntime: async () => true,
inject: async () => true, sendKey: async () => true, beforeSubmit, onError: vi.fn() })
controller.setTurnOpen('s1', true)
controller.submit('s1', 'task from A', undefined, 'swarm-a')
@@ -213,7 +219,7 @@ describe('SessionInputController', () => {
it.each(['team_waiting_draft', 'team_waiting_user', 'team_waiting_idle'])('team input preserves the composer on %s', async reason => {
const inject = vi.fn(async () => true), sendKey = vi.fn(async () => true), onDelivery = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session('cursor'), validateRuntime: async () => true,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session('cursor'), validateRuntime: async () => true,
inject, sendKey, onError: vi.fn(), onDelivery, beforeTeamWrite: async () => reason })
controller.submit('s1', 'peer question', 'team:fixture')
await vi.waitFor(() => expect(onDelivery).toHaveBeenCalledWith(expect.objectContaining({ state: 'rejected', reason })))
@@ -224,7 +230,7 @@ describe('SessionInputController', () => {
it('rechecks a queued team message at the actual write boundary', async () => {
const beforeTeamWrite = vi.fn(async () => 'team_waiting_draft'), inject = vi.fn(async () => true), onDelivery = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session(), validateRuntime: async () => true,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session(), validateRuntime: async () => true,
inject, sendKey: async () => true, onError: vi.fn(), onDelivery, beforeTeamWrite })
controller.setTurnOpen('s1', true)
controller.submit('s1', 'peer question', 'team:fixture')
@@ -238,7 +244,7 @@ describe('SessionInputController', () => {
it('never retries Enter for an automatic team message with uncertain acceptance', async () => {
vi.useFakeTimers()
const sendKey = vi.fn(async () => true), onDelivery = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session(), validateRuntime: async () => true,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session(), validateRuntime: async () => true,
inject: async () => true, sendKey, onError: vi.fn(), onDelivery, beforeTeamWrite: async () => null })
controller.submit('s1', 'peer question', 'team:fixture')
await vi.advanceTimersByTimeAsync(12_000)
@@ -249,7 +255,7 @@ describe('SessionInputController', () => {
it('requeues a team notice when a draft appears while waiting for the terminal writer', async () => {
const inject = vi.fn(async () => true), onError = vi.fn(), onDelivery = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session(), validateRuntime: async () => true,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session(), validateRuntime: async () => true,
beforeTeamWrite: async () => null, inject,
injectTeam: async () => ({ state: 'failed', dispatch: 'not_started', reason: 'team_waiting_draft' }),
sendKey: async () => true, onError, onDelivery })
@@ -268,12 +274,13 @@ describe('SessionInputController', () => {
{ engine: 'codex', observed: '<pasted_content id="04e3">\npeer question\n</pasted_content id="04e3">', state: 'unknown' },
] as const)('attributes native paste evidence only to the exact $engine message: $state', async ({ engine, observed, state }) => {
const inject = vi.fn(async () => true), sendKey = vi.fn(async () => true), onDelivery = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session(engine), validateRuntime: async () => true,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session(engine), validateRuntime: async () => true,
inject, sendKey, onError: vi.fn(), onDelivery, beforeTeamWrite: async () => null })
controller.submit('s1', 'peer question', 'team:fixture')
await vi.waitFor(() => expect(onDelivery).toHaveBeenCalledWith(expect.objectContaining({ state: 'delivered' })))
controller.onTurnStarted('s1', observed)
- expect(onDelivery).toHaveBeenLastCalledWith(expect.objectContaining({ state }))
+ // The engine reads its own record in its worker: the receipt follows that reading.
+ await vi.waitFor(() => expect(onDelivery).toHaveBeenLastCalledWith(expect.objectContaining({ state })))
expect(inject).toHaveBeenCalledOnce()
expect(sendKey).not.toHaveBeenCalled()
controller.forget('s1')
@@ -283,7 +290,7 @@ describe('SessionInputController', () => {
// A voice command spoken while a Codex task ran used to sit in this controller's queue, invisible,
// until the task ended. Codex queues composer input itself, so the daemon types straight away.
const injected: string[] = []
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('codex'), validateRuntime: async () => true,
inject: async (_pane, content) => { injected.push(content); return true },
sendKey: async () => true, onError: vi.fn(),
@@ -304,7 +311,7 @@ describe('SessionInputController', () => {
it('queues Command Code prompts while busy and drains exactly one after turn end', async () => {
const injected: string[] = []
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('commandcode'), validateRuntime: async () => true,
inject: async (_pane, content) => { injected.push(content); return true },
sendKey: async () => true, onError: vi.fn(),
@@ -323,7 +330,7 @@ describe('SessionInputController', () => {
it('clears the echoed prompt from the Cursor composer once the turn starts', async () => {
const sendKey = vi.fn(async (_pane: string, _key: string) => true)
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('cursor'), validateRuntime: async () => true,
inject: async () => true, sendKey,
capture: async () => '⠰ Working\n\n→ hello\nAuto', // the submitted prompt is still on screen
@@ -337,7 +344,7 @@ describe('SessionInputController', () => {
it('leaves a fresh terminal draft alone when the Cursor composer no longer echoes our prompt', async () => {
const sendKey = vi.fn(async (_pane: string, _key: string) => true)
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('cursor'), validateRuntime: async () => true,
inject: async () => true, sendKey,
capture: async () => '⠰ Working\n\n→ something the user just typed\nAuto',
@@ -355,7 +362,7 @@ describe('SessionInputController', () => {
// message is typed onto the end of it and the two are submitted as one run-on prompt — observed as a
// turn starting with the PREVIOUS message's text.
const order: string[] = []
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('cursor'), validateRuntime: async () => true,
inject: async (_pane, content) => { order.push(`inject:${content}`); return true },
sendKey: async (_pane, key) => { order.push(`key:${key}`); return true },
@@ -372,7 +379,7 @@ describe('SessionInputController', () => {
vi.useFakeTimers()
const inject = vi.fn(async () => true)
const sendKey = vi.fn(async () => true)
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session(), validateRuntime: async () => true, inject, sendKey, onError: vi.fn(),
})
controller.submit('s1', 'hello')
@@ -386,7 +393,7 @@ describe('SessionInputController', () => {
vi.useFakeTimers()
const inject = vi.fn(async () => true)
const sendKey = vi.fn(async () => true)
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('claude'), validateRuntime: async () => true, inject, sendKey, onError: vi.fn(),
})
controller.submit('s1', 'hello')
@@ -402,7 +409,7 @@ describe('SessionInputController', () => {
const inject = vi.fn(async () => true)
const sendKey = vi.fn(async (_pane: string, _key: string) => true)
const onError = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('cursor'),
validateRuntime: async () => true,
inject,
@@ -425,7 +432,7 @@ describe('SessionInputController', () => {
it('retries Enter for Cursor only while the exact draft remains in an idle composer', async () => {
vi.useFakeTimers()
const sendKey = vi.fn(async (_pane: string, _key: string) => true)
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('cursor'),
validateRuntime: async () => true,
inject: async () => true,
@@ -445,7 +452,7 @@ describe('SessionInputController', () => {
it('waits for the Cursor composer to settle before draining the next prompt', async () => {
vi.useFakeTimers()
const injected: string[] = []
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('cursor'),
validateRuntime: async () => true,
inject: async (_pane, content) => { injected.push(content); return true },
@@ -467,7 +474,7 @@ describe('SessionInputController', () => {
vi.useFakeTimers()
const sendKey = vi.fn(async () => true)
const onError = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('claude'),
validateRuntime: async () => true,
inject: async () => true,
@@ -492,7 +499,7 @@ describe('SessionInputController', () => {
vi.useFakeTimers()
const sendKey = vi.fn(async () => true)
const onError = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('commandcode'),
validateRuntime: async () => true,
inject: async () => true,
@@ -515,7 +522,7 @@ describe('SessionInputController', () => {
const sendKey = vi.fn(async () => true)
const onError = vi.fn()
const capture = vi.fn(async () => '❯ What are you working on?\n✻ Waiting for 4 background agents to finish\n────\n❯ a different draft I am still writing\n────')
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('claude'), validateRuntime: async () => true,
inject: async () => true, sendKey, capture, onError,
})
@@ -542,7 +549,7 @@ describe('SessionInputController', () => {
vi.useFakeTimers()
const sendKey = vi.fn(async () => true), onError = vi.fn(), onDelivery = vi.fn()
let pasted = false
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('claude'), validateRuntime: async () => true, onDelivery,
inject: async () => { pasted = true; return true }, sendKey, capture: async () => pasted ? screen : '❯ ', onError,
})
@@ -557,7 +564,7 @@ describe('SessionInputController', () => {
vi.useFakeTimers()
const sendKey = vi.fn(async () => true), onError = vi.fn(), onDelivery = vi.fn()
let pasted = false
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('claude'), validateRuntime: async () => true, onDelivery,
inject: async () => { pasted = true; return true }, sendKey, capture: async () => pasted ? screen : '❯ ', onError,
})
@@ -573,7 +580,7 @@ describe('SessionInputController', () => {
const sendKey = vi.fn(async () => true), onError = vi.fn()
// Codex browsing its transcript (0.160): Enter would rewind the conversation to the prompt in view.
const browsing = `› ${message}\n\n Browsing transcript · ↑↓/jk scroll · ←→/hl prompts · ↵ rewind · esc back\n`
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('codex'), validateRuntime: async () => true,
inject: async () => true, sendKey, capture: async () => browsing, onError,
})
@@ -589,7 +596,7 @@ describe('SessionInputController', () => {
vi.useFakeTimers()
const sendKey = vi.fn(async () => true)
const onError = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('claude'), validateRuntime: async () => true,
inject: async () => true, sendKey, capture: async () => 'Sign in required', onError,
})
@@ -604,7 +611,7 @@ describe('SessionInputController', () => {
vi.useFakeTimers()
const sendKey = vi.fn(async () => true)
const onError = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('claude'),
validateRuntime: async () => true,
inject: async () => true,
@@ -621,11 +628,200 @@ describe('SessionInputController', () => {
controller.forget('s1')
})
+ describe('Claude Code and Codex readings from their engine worker', () => {
+ const held = <T,>() => {
+ let resolve!: (value: T) => void
+ return { promise: new Promise<T>(settle => { resolve = settle }), resolve }
+ }
+
+ it.each(['claude', 'codex'] as const)('%s: no reading of the composer is no evidence: no Enter, and the message unconfirmed', async engine => {
+ vi.useFakeTimers()
+ const sendKey = vi.fn(async () => true), onError = vi.fn(), onDelivery = vi.fn()
+ const read = vi.fn(async () => null)
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: { ...inlineSubmission, read },
+ getSession: () => session(engine), validateRuntime: async () => true, inject: async () => true, sendKey, onDelivery,
+ capture: async () => engine === 'claude' ? claudeBox('hello') : codexComposer('hello'), onError })
+ controller.submit('s1', 'hello', 'delivery-1')
+ await vi.advanceTimersByTimeAsync(30_000)
+ // The draft is on screen: the core's own reading would have pressed Enter. It is not the core's to read.
+ expect(read).toHaveBeenCalledWith(session(engine), engine === 'claude' ? claudeBox('hello') : codexComposer('hello'), 'hello')
+ expect(sendKey).not.toHaveBeenCalled()
+ expect(onDelivery).toHaveBeenLastCalledWith({ sessionId: 's1', deliveryId: 'delivery-1', state: 'unknown', reason: 'dispatch_ambiguous' })
+ expect(onError).toHaveBeenCalledWith('s1', expect.stringContaining('could not be confirmed'))
+ controller.forget('s1')
+ })
+
+ it('a reader that throws is no reading either', async () => {
+ vi.useFakeTimers()
+ const sendKey = vi.fn(async () => true), onError = vi.fn()
+ const controller = new SessionInputController({ readScreen: readInlineScreen,
+ submission: { ...inlineSubmission, read: async () => { throw new Error('worker gone') } },
+ getSession: () => session('claude'), validateRuntime: async () => true, inject: async () => true, sendKey,
+ capture: async () => claudeBox('hello'), onError })
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(30_000)
+ expect(sendKey).not.toHaveBeenCalled()
+ expect(onError).toHaveBeenCalledWith('s1', expect.stringContaining('could not be confirmed'))
+ controller.forget('s1')
+ })
+
+ it('a reading that comes back after the turn started decides nothing', async () => {
+ vi.useFakeTimers()
+ const sendKey = vi.fn(async () => true), onError = vi.fn()
+ const reading = held<{ draft: boolean; composer: boolean; nativeDraft: 'pending' } | null>()
+ const read = vi.fn(() => reading.promise)
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: { ...inlineSubmission, read },
+ getSession: () => session('claude'), validateRuntime: async () => true, inject: async () => true, sendKey,
+ capture: async () => claudeBox('hello'), onError })
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(3_100)
+ expect(read).toHaveBeenCalledOnce()
+ controller.onTurnStarted('s1', 'hello')
+ reading.resolve({ draft: true, composer: true, nativeDraft: 'pending' })
+ await vi.advanceTimersByTimeAsync(30_000)
+ expect(sendKey).not.toHaveBeenCalled()
+ expect(onError).not.toHaveBeenCalled()
+ controller.forget('s1')
+ })
+
+ describe('a message sent while its engine starts, its turn starting after the verify window', () => {
+ // The engine draws its composer before its first hook binds the conversation: the message is typed under
+ // the launch's record, which is rebuilt, bound, before the check after the paste. The readings here are
+ // the fenced ones core composes (core/engines/screens.ts, submissions.ts): each refuses a record that is
+ // no longer the agent's binding.
+ const engineProcess = (pid: number): ProcessIdentity => ({ pid, executable: 'engine', startMarker: `start ${pid}` })
+ const starting = (engine: 'claude' | 'codex'): RegisteredSession => ({ ...session(engine), launch: { state: 'ready' }, sessionId: '',
+ boundAt: null, transcriptPath: null })
+ const bound = (engine: 'claude' | 'codex'): RegisteredSession => ({ ...session(engine), boundAt: 5, processIdentity: engineProcess(7) })
+ const run = async (engine: 'claude' | 'codex', typed: RegisteredSession, after: RegisteredSession) => {
+ let current = typed
+ const sendKey = vi.fn(async () => true), onError = vi.fn()
+ const resolve = () => current
+ const screens = createScreens({ handles: () => false, transport: { read: vi.fn() }, resolve,
+ inline: (name, capture) => capture === null ? undefined : screenFor(name).inspect(capture) })
+ const submission = createSubmissions({ policy: submissionPolicy, handles: () => false, transport: { read: vi.fn(), echo: vi.fn() },
+ resolve, inline: name => submissionFor(name) })
+ const controller = new SessionInputController({ readScreen: screens.read, submission, getSession: () => current,
+ validateRuntime: async () => true, inject: async () => { current = after; return true }, sendKey,
+ // Taken off the composer, its turn not started yet.
+ capture: async () => engine === 'claude' ? claudeBox('') : codexComposer(''), onError })
+ vi.useFakeTimers()
+ controller.submit('s1', 'sent while it was starting')
+ await vi.advanceTimersByTimeAsync(5_000)
+ controller.onTurnStarted('s1', 'sent while it was starting')
+ await vi.advanceTimersByTimeAsync(30_000)
+ controller.forget('s1')
+ return { sendKey, onError }
+ }
+
+ it.each(['claude', 'codex'] as const)('%s: read under its first bind, the message is taken: no failure, no second Enter', async engine => {
+ const { sendKey, onError } = await run(engine, starting(engine), bound(engine))
+ expect(onError).not.toHaveBeenCalled()
+ expect(sendKey).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ['a rotation of a bound conversation', bound('claude'), { ...bound('claude'), sessionId: 's2', boundAt: 9 }],
+ ['another process than the one it knew', { ...starting('claude'), processIdentity: engineProcess(6) }, bound('claude')],
+ ['another pane', starting('claude'), { ...bound('claude'), tmuxPane: '%2' }],
+ ])('%s still fails closed: unconfirmed, and no second Enter', async (_name, typed, after) => {
+ const { sendKey, onError } = await run('claude', typed, after)
+ expect(onError).toHaveBeenCalledWith('s1', expect.stringContaining('could not be confirmed'))
+ expect(sendKey).not.toHaveBeenCalled()
+ })
+ })
+
+ it('a pending draft, as the worker reads it, is what lets the core press Enter again', async () => {
+ vi.useFakeTimers()
+ const sendKey = vi.fn(async () => true)
+ // The pane holds no draft as the core would read it; the engine says its composer still holds the prompt.
+ const read = vi.fn(async () => ({ draft: true, composer: true, nativeDraft: 'pending' as const }))
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: { ...inlineSubmission, read },
+ getSession: () => session('codex'), validateRuntime: async () => true, inject: async () => true, sendKey,
+ capture: async () => codexComposer(''), onError: vi.fn() })
+ controller.submit('s1', 'hello')
+ await vi.advanceTimersByTimeAsync(1_600)
+ expect(sendKey).toHaveBeenCalledWith('h1', 'Enter')
+ controller.forget('s1')
+ })
+
+ it('a turn\'s prompt the engine wrapped settles its receipt once read, and the pane at once', async () => {
+ const echo = held<{ start: number; end: number } | null>()
+ const onDelivery = vi.fn()
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: { ...inlineSubmission, echo: () => echo.promise },
+ getSession: () => session('claude'), validateRuntime: async () => true, inject: async () => true, sendKey: async () => true,
+ onError: vi.fn(), onDelivery })
+ controller.submit('s1', 'peer question', 'delivery-1')
+ await vi.waitFor(() => expect(onDelivery).toHaveBeenCalledWith(expect.objectContaining({ state: 'delivered' })))
+ const recorded = '<pasted_content id="04e3">\npeer question\n</pasted_content id="04e3">'
+ controller.onTurnStarted('s1', recorded)
+ // Nothing waits on the reading: the delivery is no longer the pane's to cancel, or to lose with the agent.
+ expect(controller.cancelDelivery('delivery-1')).toBe(false)
+ controller.forget('s1')
+ expect(onDelivery).not.toHaveBeenCalledWith(expect.objectContaining({ reason: 'agent_gone' }))
+ echo.resolve({ start: recorded.indexOf('peer'), end: recorded.indexOf('\n</') })
+ await vi.waitFor(() => expect(onDelivery).toHaveBeenLastCalledWith({ sessionId: 's1', deliveryId: 'delivery-1', state: 'started' }))
+ })
+
+ const noEcho: Array<[string, () => Promise<null>]> = [
+ ['no reading', async () => null],
+ ['a failed reading', async () => { throw new Error('worker gone') }],
+ ]
+ it.each(noEcho)('%s of a wrapped prompt is no match', async (_name, echo) => {
+ const onDelivery = vi.fn()
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: { ...inlineSubmission, echo },
+ getSession: () => session('claude'), validateRuntime: async () => true, inject: async () => true, sendKey: async () => true,
+ onError: vi.fn(), onDelivery })
+ controller.submit('s1', 'peer question', 'delivery-1')
+ await vi.waitFor(() => expect(onDelivery).toHaveBeenCalledWith(expect.objectContaining({ state: 'delivered' })))
+ controller.onTurnStarted('s1', '<pasted_content id="04e3">\npeer question\n</pasted_content id="04e3">')
+ await vi.waitFor(() => expect(onDelivery).toHaveBeenLastCalledWith({ sessionId: 's1', deliveryId: 'delivery-1', state: 'unknown', reason: 'prompt_mismatch' }))
+ controller.forget('s1')
+ })
+
+ it('an exact echo needs no reading, and a different prompt typed by hand is still noticed', async () => {
+ const echo = vi.fn(inlineSubmission.echo)
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const onSubmitted = vi.fn()
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: { ...inlineSubmission, echo },
+ getSession: () => session('claude'), validateRuntime: async () => true, inject: async () => true, sendKey: async () => true,
+ onError: vi.fn(), onSubmitted })
+ const turn = async (typed: string, recorded: string) => {
+ controller.submit('s1', typed)
+ await vi.waitFor(() => expect(onSubmitted).toHaveBeenCalledWith('s1', typed))
+ controller.onTurnStarted('s1', recorded)
+ await new Promise(resolve => setTimeout(resolve, 0))
+ controller.onTurnEnded('s1')
+ }
+ await turn('hello', 'hello')
+ expect(echo).not.toHaveBeenCalled()
+ await turn('second', '<pasted_content id="aa">\nsecond\n</pasted_content id="aa">')
+ expect(echo).toHaveBeenCalledOnce()
+ expect(warn).not.toHaveBeenCalledWith(expect.stringContaining('observed a different terminal prompt'))
+ await turn('third', 'typed by hand')
+ await vi.waitFor(() => expect(warn).toHaveBeenCalledWith(expect.stringContaining('observed a different terminal prompt')))
+ expect(echo).toHaveBeenCalledTimes(2)
+ // Another engine's record is compared whole, at once, as before.
+ const other = new SessionInputController({ readScreen: readInlineScreen, submission: { ...inlineSubmission, echo },
+ getSession: () => session('commandcode'), validateRuntime: async () => true, inject: async () => true, sendKey: async () => true,
+ onError: vi.fn(), onSubmitted })
+ other.submit('s1', 'fourth')
+ await vi.waitFor(() => expect(onSubmitted).toHaveBeenCalledWith('s1', 'fourth'))
+ warn.mockClear()
+ other.onTurnStarted('s1', 'not fourth')
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('observed a different terminal prompt'))
+ expect(echo).toHaveBeenCalledTimes(2)
+ warn.mockRestore()
+ controller.forget('s1')
+ other.forget('s1')
+ })
+ })
+
it('does not error or press Enter for Codex once the prompt has left the composer', async () => {
vi.useFakeTimers()
const sendKey = vi.fn(async () => true)
const onError = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('codex'),
validateRuntime: async () => true,
inject: async () => true,
@@ -646,7 +842,7 @@ describe('SessionInputController', () => {
vi.useFakeTimers()
const sendKey = vi.fn(async () => true)
const onError = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('codex'),
validateRuntime: async () => true,
inject: async () => true,
@@ -667,7 +863,7 @@ describe('SessionInputController', () => {
vi.useFakeTimers()
const sendKey = vi.fn(async () => true)
const onError = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('codex'),
validateRuntime: async () => true,
inject: async () => true,
@@ -690,7 +886,7 @@ describe('SessionInputController', () => {
const ambiguous: TerminalActionResult = {
state: 'unknown', dispatch: 'possibly_executed', reason: 'response was lost',
}
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('codex'),
validateRuntime: async () => true,
inject: async () => ambiguous,
@@ -712,7 +908,7 @@ describe('SessionInputController', () => {
const ambiguous: TerminalActionResult = {
state: 'unknown', dispatch: 'possibly_executed', reason: 'response was lost',
}
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('codex'),
validateRuntime: async () => true,
inject: async () => ambiguous,
@@ -735,7 +931,7 @@ describe('SessionInputController', () => {
const ambiguous: TerminalActionResult = {
state: 'unknown', dispatch: 'possibly_executed', reason: 'response was lost',
}
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('codex'),
validateRuntime: async () => true,
inject: async () => ambiguous,
@@ -759,7 +955,7 @@ describe('SessionInputController', () => {
state: 'unknown', dispatch: 'possibly_executed', reason: 'Enter response was lost',
}))
const onError = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('codex'),
validateRuntime: async () => true,
inject: async () => true,
@@ -783,7 +979,7 @@ describe('SessionInputController', () => {
const ambiguous: TerminalActionResult = {
state: 'unknown', dispatch: 'possibly_executed', reason: 'response was lost',
}
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('cursor'),
validateRuntime: async () => true,
inject: async () => ambiguous,
@@ -807,7 +1003,7 @@ describe('SessionInputController', () => {
state: 'unknown', dispatch: 'possibly_executed', reason: 'key response was lost',
}))
const onError = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('cursor'),
validateRuntime: async () => true,
inject: async () => true,
@@ -826,7 +1022,7 @@ describe('SessionInputController', () => {
it('serializes chat input behind a native runtime control lock', async () => {
const injected: string[] = []
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('claude'), validateRuntime: async () => true,
inject: async (_pane, content) => { injected.push(content); return true },
sendKey: async () => true, onError: vi.fn(),
@@ -850,7 +1046,7 @@ describe('delivery correlation', () => {
function setup(overrides: Partial<ConstructorParameters<typeof SessionInputController>[0]> = {}) {
const onDelivery = vi.fn()
const inject = vi.fn(async () => true)
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session(), validateRuntime: async () => true,
inject, sendKey: async () => true, onError: vi.fn(), onDelivery, ...overrides,
})
@@ -893,7 +1089,7 @@ describe('delivery correlation', () => {
controller.submit('s1', 'hello', 'delivery-1')
await vi.waitFor(() => expect(onDelivery).toHaveBeenCalledTimes(2))
controller.onTurnStarted('s1', 'different')
- expect(onDelivery).toHaveBeenLastCalledWith({ sessionId: 's1', deliveryId: 'delivery-1', state: 'unknown', reason: 'prompt_mismatch' })
+ await vi.waitFor(() => expect(onDelivery).toHaveBeenLastCalledWith({ sessionId: 's1', deliveryId: 'delivery-1', state: 'unknown', reason: 'prompt_mismatch' }))
controller.forget('s1')
})
@@ -983,7 +1179,7 @@ describe('optional lamp delivery preserves legacy behavior', () => {
// once: the second waits for the first's paste, not for the first's turn.
const validations: Array<(valid: boolean) => void> = []
const inject = vi.fn(async (_target: string, _text: string) => true)
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('claude'),
validateRuntime: () => new Promise<boolean>(resolve => validations.push(resolve)),
inject, sendKey: async () => true, onError: vi.fn(),
@@ -1004,7 +1200,7 @@ describe('optional lamp delivery preserves legacy behavior', () => {
it('writes messages that arrive together in the order they arrived, whichever check finishes first', async () => {
const checks: Array<(valid: boolean) => void> = []
const inject = vi.fn(async (_target: string, _text: string) => true)
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('codex'),
validateRuntime: () => new Promise<boolean>(resolve => checks.push(resolve)),
inject, sendKey: async () => true, onError: vi.fn(),
@@ -1018,7 +1214,7 @@ describe('optional lamp delivery preserves legacy behavior', () => {
expect(inject.mock.calls.map(([, text]) => text)).toEqual(['one', 'two', 'three'])
// A write that fails does not hold up the ones behind it.
const failing = vi.fn(async (_target: string, text: string) => { if (text === 'bad') throw new Error('pane gone'); return true })
- const next = new SessionInputController({ readScreen: readInlineScreen, getSession: () => session('codex'), validateRuntime: async () => true,
+ const next = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission, getSession: () => session('codex'), validateRuntime: async () => true,
inject: failing, sendKey: async () => true, onError: vi.fn() })
next.submit('s1', 'bad')
next.submit('s1', 'good')
@@ -1029,7 +1225,7 @@ describe('optional lamp delivery preserves legacy behavior', () => {
it('keeps native control available during untracked runtime validation', async () => {
let resolve!: (valid: boolean) => void
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('claude'),
validateRuntime: () => new Promise<boolean>(done => { resolve = done }),
inject: async () => true, sendKey: async () => true, onError: vi.fn(),
@@ -1046,7 +1242,7 @@ describe('optional lamp delivery preserves legacy behavior', () => {
it('reports the original legacy cancellation error for a vanished process', async () => {
const onError = vi.fn()
const sendKey = vi.fn(async () => true)
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session(), validateRuntime: async () => false,
inject: async () => true, sendKey, onError,
})
@@ -1060,7 +1256,7 @@ describe('optional lamp delivery preserves legacy behavior', () => {
vi.useFakeTimers()
const onDelivery = vi.fn()
const sendKey = vi.fn(async () => true)
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('commandcode'), validateRuntime: async () => true,
inject: async () => true, sendKey, capture: async () => 'Thinking… esc to interrupt',
onError: vi.fn(), onDelivery,
@@ -1077,7 +1273,7 @@ describe('optional lamp delivery preserves legacy behavior', () => {
it('does not invent rejection when a turn begins during pre-paste validation', async () => {
let resolve!: (valid: boolean) => void
const onDelivery = vi.fn()
- const controller = new SessionInputController({ readScreen: readInlineScreen,
+ const controller = new SessionInputController({ readScreen: readInlineScreen, submission: inlineSubmission,
getSession: () => session('claude'),
validateRuntime: () => new Promise<boolean>(done => { resolve = done }),
inject: async () => true, sendKey: async () => true, onError: vi.fn(), onDelivery,
diff --git a/cli/src/lib/sessionInput.ts b/cli/src/lib/sessionInput.ts
index d180e117b..7884efcd3 100644
--- a/cli/src/lib/sessionInput.ts
+++ b/cli/src/lib/sessionInput.ts
@@ -1,5 +1,8 @@
import type { ScreenReader } from './screenReader.js'
+import type { SubmissionReader } from './submissionReader.js'
import { createHash } from 'crypto'
+import { composerHolds, composerShown, normalizedTerminalText, visibleTerminal } from '../engines/kit/submission.js'
+import { launchBound } from '../core/engines/sessionBinding.js'
import type { RegisteredSession } from './registry.js'
import { sid } from './log.js'
import { isMessageHold, messageHoldText, messageWithheldText, passingHold, type MessageHold } from './messageHolds.js'
@@ -8,8 +11,9 @@ import { enterWithheldReason, TERMINAL_LEASE_REFUSED, type TerminalActionResult
const MAX_QUEUE_ITEMS = 8
const MAX_QUEUE_BYTES = 24 * 1024
const ITEM_TTL_MS = 5 * 60_000
+// The window for an engine that declares none of its own (engines/submissionPolicies.ts declares Claude
+// Code's and Codex's, with the reasons).
const SUBMIT_VERIFY_MS = 1_500
-const CLAUDE_SUBMIT_VERIFY_MS = 3_000
// OpenCode's accept signal is the reader's DB poll (~1s) surfacing a new user row → turn_started, so
// give it a slightly longer window than the file-based engines before a retry-Enter.
const OPENCODE_SUBMIT_VERIFY_MS = 2_500
@@ -59,14 +63,6 @@ const LEASE_RETRY_MS = 250
// Re-observe briefly while a submitted prompt awaits a transcript event. Reaching this limit is not
// evidence of rejection: Claude can hold an accepted follow-up while background agents finish.
const SUBMIT_MAX_OBSERVES = 5
-// Engines whose own TUI queues a message typed while a turn is running, and runs it when the turn ends.
-// For these the daemon types immediately — the follow-up appears in the pane the moment it is spoken,
-// and the TUI's queue is the one the user can see and edit. Every other engine gets this file's FIFO,
-// pasted only once the pane is idle. Codex joined claude here on 2026-09-15 (owner: a voice command
-// spoken while a Codex task ran sat invisible until the task ended); Codex has queued composer input
-// since 0.36, and the retry path below already knows a prompt that left the composer without a
-// turn_started is "queued by the TUI as a follow-up", not lost.
-const TYPES_WHILE_BUSY: ReadonlySet<string> = new Set(['claude', 'codex'])
export interface SessionInputDelivery {
deliveryId: string
@@ -107,6 +103,9 @@ interface InputState {
export interface SessionInputDeps {
readScreen: ScreenReader
+ /** The reading of a typed prompt by the engines whose worker reads it (Claude Code, Codex): the pane after
+ * the paste, and a turn's prompt as recorded. Every verdict and every Enter stays here. */
+ submission: SubmissionReader
/** A team-only preflight at the actual write boundary. A reason proves no paste occurred. */
beforeTeamWrite?: (session: RegisteredSession) => Promise<string | null>
onDelivery?: (event: SessionInputDelivery) => void
@@ -157,11 +156,32 @@ export class SessionInputController {
constructor(private readonly deps: SessionInputDeps) {}
+ /**
+ * An engine whose own TUI queues a message typed while a turn is running, and runs it when the turn ends,
+ * says so in its submission policy (`typesWhileBusy`: Claude Code and Codex). For those the daemon types
+ * immediately — the follow-up appears in the pane the moment it is spoken, and the TUI's queue is the one
+ * the user can see and edit. Every other engine gets this file's FIFO, pasted only once the pane is idle.
+ */
+ private typesWhileBusy(engine: string): boolean {
+ return this.deps.submission.policy(engine)?.typesWhileBusy === true
+ }
+
/** Controller dependencies take the stable agent id, never a backend route. */
private controlSession(id: string): RegisteredSession | undefined {
return this.deps.getSession(id)
}
+ /**
+ * The record the checks after a paste read the pane under. A message sent while its engine starts is
+ * typed before the engine's first hook binds the conversation, and its turn can start after the verify
+ * window: read as typed, the fenced readings refuse it and the message is reported unconfirmed. The
+ * record as it now stands is taken when it is that launch, bound since (core/engines/sessionBinding.ts
+ * `launchBound`); a rebind, a rotation, another pane or another process is read as typed, and fails closed.
+ */
+ private readingSession(session: RegisteredSession): RegisteredSession {
+ return launchBound(session, this.controlSession(session.agentId))
+ }
+
/**
* A paste the pane's control lease refused before a byte was written: the agent is there, but its
* process is not yet the one the registry holds — a resume or restart moments ago, before the new
@@ -251,7 +271,7 @@ export class SessionInputController {
this.dropExpired(sessionId, state)
if (state.controlLocked
|| (deliveryId && (state.deliveryId || state.dispatching || state.turnOpen || state.awaitingFingerprint || state.settling))
- || (!TYPES_WHILE_BUSY.has(session.engine) && (state.turnOpen || state.awaitingFingerprint || state.settling))) {
+ || (!this.typesWhileBusy(session.engine) && (state.turnOpen || state.awaitingFingerprint || state.settling))) {
console.log(`[inject] ${sid(sessionId)} queued · engine=${session.engine} · depth=${state.queue.length + 1}`)
this.enqueue(sessionId, state, content, deliveryId, tabId)
return
@@ -305,17 +325,28 @@ export class SessionInputController {
onTurnStarted(sessionId: string, userMessage: string): void {
const state = this.state(sessionId)
- // Claude 2.1.283 records bracketed pastes inside an envelope with matching
- // opening/closing IDs. Compare its exact payload, never a substring of a
- // different prompt or text outside the envelope. Other engines remain exact.
- const pasted = this.controlSession(sessionId)?.engine === 'claude'
- ? /^\s*<pasted_content id="([a-f0-9]+)">\r?\n([\s\S]*)\r?\n<\/pasted_content id="\1">\s*$/.exec(userMessage)
- : null
- const observedFingerprint = fingerprint(pasted?.[2] ?? userMessage)
+ const session = this.controlSession(sessionId)
+ // An exact echo of the typed prompt needs no reading. Anything else is, for an engine whose worker
+ // reads its submissions, that engine's to unwrap (Claude Code 2.1.283 records a bracketed paste inside
+ // an envelope of its own), and is settled once it has; every other engine's record is compared whole.
+ const observedFingerprint = fingerprint(userMessage)
+ const engineReads = !!session && !!this.deps.submission.policy(session.engine)
if (state.deliveryId && state.writing) state.observedStart = userMessage
- else if (state.deliveryId && state.deliveryFingerprint) this.finishDelivery(sessionId, state,
- state.deliveryFingerprint === observedFingerprint ? 'started' : 'unknown',
- state.deliveryFingerprint === observedFingerprint ? undefined : 'prompt_mismatch')
+ else if (state.deliveryId && state.deliveryFingerprint) {
+ const expected = state.deliveryFingerprint
+ if (expected === observedFingerprint || !engineReads) {
+ this.finishDelivery(sessionId, state, expected === observedFingerprint ? 'started' : 'unknown',
+ expected === observedFingerprint ? undefined : 'prompt_mismatch')
+ } else {
+ // Taken off the pane's state now, as a settled delivery is, so a write that follows never waits on
+ // the reading; only what is said of this delivery waits for it.
+ const deliveryId = state.deliveryId
+ state.deliveryId = undefined
+ state.deliveryFingerprint = undefined
+ void this.echoes(session, userMessage, expected).then(started => this.delivery(sessionId, deliveryId,
+ started ? 'started' : 'unknown', started ? undefined : 'prompt_mismatch'))
+ }
+ }
if (state.settleTimer) clearTimeout(state.settleTimer)
state.settleTimer = null
state.settling = false
@@ -327,8 +358,12 @@ export class SessionInputController {
// confirmed started.
void this.clearCursorEcho(sessionId, userMessage)
if (state.awaitingFingerprint) {
- const matched = state.awaitingFingerprint === observedFingerprint
- if (!matched) console.warn(`[inject] ${sessionId.slice(0, 8)} observed a different terminal prompt while awaiting submit`)
+ const warn = () => console.warn(`[inject] ${sessionId.slice(0, 8)} observed a different terminal prompt while awaiting submit`)
+ const expected = state.awaitingFingerprint
+ if (expected !== observedFingerprint) {
+ if (engineReads) void this.echoes(session, userMessage, expected).then(matched => { if (!matched) warn() })
+ else warn()
+ }
state.awaitingFingerprint = null
state.awaitingContent = null
state.retries = 0
@@ -339,6 +374,15 @@ export class SessionInputController {
}
}
+ /**
+ * Whether a turn's prompt, as the engine recorded it, is the prompt typed: the part of the record the
+ * engine says is the typed text, compared exactly. No reading is no match.
+ */
+ private async echoes(session: RegisteredSession, recorded: string, expected: string): Promise<boolean> {
+ const span = await this.deps.submission.echo(session, recorded).catch(() => null)
+ return !!span && fingerprint(recorded.slice(span.start, span.end)) === expected
+ }
+
/**
* Remove Cursor's leftover copy of a just-submitted prompt from its composer.
*
@@ -608,9 +652,7 @@ export class SessionInputController {
const retry = this.retrySubmit(sessionId, session, state)
if (state.deliveryId) void retry.catch(() => this.failAmbiguousSubmission(sessionId, state))
else void retry
- }, session.engine === 'claude'
- ? CLAUDE_SUBMIT_VERIFY_MS
- : session.engine === 'opencode'
+ }, this.deps.submission.policy(session.engine)?.verifyMs ?? (session.engine === 'opencode'
? OPENCODE_SUBMIT_VERIFY_MS
: session.engine === 'pi'
? PI_SUBMIT_VERIFY_MS
@@ -632,7 +674,7 @@ export class SessionInputController {
? AGY_SUBMIT_VERIFY_MS
: session.engine === 'copilot'
? COPILOT_SUBMIT_VERIFY_MS
- : SUBMIT_VERIFY_MS)
+ : SUBMIT_VERIFY_MS))
}
private async retrySubmit(sessionId: string, session: RegisteredSession, state: InputState): Promise<void> {
@@ -683,7 +725,8 @@ export class SessionInputController {
return
}
} else {
- // claude/codex/commandcode: verify against the terminal before pressing Enter again or declaring failure.
+ // Claude Code and Codex (their worker reads the pane) and Command Code: verify against the terminal
+ // before pressing Enter again or declaring failure.
const capture = await this.deps.capture?.(session.agentId)
if (!state.awaitingFingerprint || state.turnOpen) return
if (await this.dialogOverComposer(sessionId, session, state, capture)) return
@@ -702,35 +745,23 @@ export class SessionInputController {
state.ambiguousDispatch = false
return
}
- if (capture && !terminalComposerContains(capture, state.awaitingContent ?? '')) {
- // Submitted, or queued by the TUI as a follow-up while busy. A real turn_started will confirm
- // and clear this; keep observing (bounded) WITHOUT pressing Enter — a second Enter could
- // double-submit a queued follow-up — and WITHOUT a spurious error.
- if (state.observes < SUBMIT_MAX_OBSERVES) {
- state.observes++
- console.log(`[inject] ${sid(sessionId)} accepted (queued/submitted) · engine=${session.engine} · observe=${state.observes}/${SUBMIT_MAX_OBSERVES}`)
- this.armSubmitCheck(sessionId, session, state)
- return
- }
- // An ambiguous dispatch with no visible draft still may have run. It can never justify Enter.
- if (state.ambiguousDispatch) {
+ if (capture) {
+ // The engine's own reading for Claude Code and Codex, from their worker; the core's for the others.
+ const prompt = state.awaitingContent ?? ''
+ const reading = this.deps.submission.policy(session.engine)
+ ? await this.deps.submission.read(this.readingSession(session), capture, prompt).catch(() => null)
+ : { draft: composerHolds(capture, prompt), composer: composerShown(capture) }
+ if (this.states.get(sessionId) !== state || !state.awaitingFingerprint || state.turnOpen) return
+ // No reading is no evidence (the engine's worker down, or the agent rebound while it read): never
+ // an Enter on it, and never a claim the message was or was not taken, as for an unreadable screen.
+ if (!reading) {
this.failAmbiguousSubmission(sessionId, state)
return
}
- if (state.deliveryId || !/^\s*[›❯→]/mu.test(visibleTerminal(capture))) {
- // A receipt promises a correlated turn, which the pane alone cannot prove. Report unknown,
- // also when no composer is visible. Never retry Enter into a dialog or a new human draft.
- this.failAmbiguousSubmission(sessionId, state)
+ if (!reading.draft) {
+ this.leftComposer(sessionId, session, state, reading.composer)
return
}
- // The paste succeeded and our text left the composer. Stop polling without claiming that the
- // agent started or failed. Its real turn event can arrive much later; pressing Enter again can
- // submit somebody else's draft. This was the false "Claude didn't start" on a queued voice turn.
- console.log(`[inject] ${sid(sessionId)} submit left composer; awaiting agent turn · engine=${session.engine}`)
- state.awaitingFingerprint = null
- state.awaitingContent = null
- state.observes = 0
- return
}
// capture === null (dep missing / unreadable) → fall through to today's blind retry/error so a
// real delivery failure is never hidden.
@@ -770,6 +801,38 @@ export class SessionInputController {
this.armSubmitCheck(sessionId, session, state)
}
+ /**
+ * Our text left the composer: submitted, or queued by the TUI as a follow-up while busy. A real
+ * turn_started will confirm and clear this; keep observing (bounded) WITHOUT pressing Enter — a second
+ * Enter could double-submit a queued follow-up — and WITHOUT a spurious error.
+ */
+ private leftComposer(sessionId: string, session: RegisteredSession, state: InputState, composer: boolean): void {
+ if (state.observes < SUBMIT_MAX_OBSERVES) {
+ state.observes++
+ console.log(`[inject] ${sid(sessionId)} accepted (queued/submitted) · engine=${session.engine} · observe=${state.observes}/${SUBMIT_MAX_OBSERVES}`)
+ this.armSubmitCheck(sessionId, session, state)
+ return
+ }
+ // An ambiguous dispatch with no visible draft still may have run. It can never justify Enter.
+ if (state.ambiguousDispatch) {
+ this.failAmbiguousSubmission(sessionId, state)
+ return
+ }
+ if (state.deliveryId || !composer) {
+ // A receipt promises a correlated turn, which the pane alone cannot prove. Report unknown,
+ // also when no composer is visible. Never retry Enter into a dialog or a new human draft.
+ this.failAmbiguousSubmission(sessionId, state)
+ return
+ }
+ // The paste succeeded and our text left the composer. Stop polling without claiming that the
+ // agent started or failed. Its real turn event can arrive much later; pressing Enter again can
+ // submit somebody else's draft. This was the false "Claude didn't start" on a queued voice turn.
+ console.log(`[inject] ${sid(sessionId)} submit left composer; awaiting agent turn · engine=${session.engine}`)
+ state.awaitingFingerprint = null
+ state.awaitingContent = null
+ state.observes = 0
+ }
+
/**
* A dialog, a menu or a view over the composer, settled without an Enter. The prompt line the retry
* reads is then the transcript's echo of this very message, not a draft, and an Enter answers the
@@ -779,7 +842,7 @@ export class SessionInputController {
*/
private async dialogOverComposer(sessionId: string, session: RegisteredSession, state: InputState, capture: string | null | undefined): Promise<boolean> {
if (capture === undefined) return false
- const screen = await this.deps.readScreen(session, capture)
+ const screen = await this.deps.readScreen(this.readingSession(session), capture)
if (this.states.get(sessionId) !== state || state.turnOpen || !state.awaitingFingerprint) return true
const hold = screen ? screen.messageHold : 'screen_unreadable'
if (!hold) return false
@@ -839,31 +902,6 @@ export class SessionInputController {
}
}
-function visibleTerminal(value: string): string {
- return value.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '')
-}
-
-function normalizedTerminalText(value: string): string {
- return visibleTerminal(value).replace(/\s+/g, ' ').trim()
-}
-
-// Composer region = from the last prompt-marker line to the end (mirrors runtimeProfile.currentPaneUi,
-// kept local so sessionInput stays decoupled). Marker set covers claude ❯, codex ›, cursor →.
-function composerRegion(capture: string): string {
- const lines = visibleTerminal(capture).split('\n')
- const idx = lines.findLastIndex((line) => {
- const marker = line.search(/[›❯→]/u)
- return marker >= 0 && !/^\s*\d+\.\s/.test(line.slice(marker + 1))
- })
- return (idx >= 0 ? lines.slice(idx) : lines).join('\n') // no marker → whole pane (safe fallback)
-}
-
-/** True while the injected prompt is still sitting un-submitted in the terminal composer. */
-function terminalComposerContains(capture: string, content: string): boolean {
- const expected = normalizedTerminalText(content)
- return !!expected && normalizedTerminalText(composerRegion(capture)).includes(expected)
-}
-
function cursorComposerContains(capture: string, content: string): boolean {
const visible = visibleTerminal(capture)
const marker = visible.lastIndexOf('→')
diff --git a/cli/src/lib/submissionReader.ts b/cli/src/lib/submissionReader.ts
new file mode 100644
index 000000000..ca05b8935
--- /dev/null
+++ b/cli/src/lib/submissionReader.ts
@@ -0,0 +1,15 @@
+import type { PromptSpan, SubmissionPolicy, SubmissionReading } from '../engines/facets/submission.js'
+import type { RegisteredSession } from './registry.js'
+
+/**
+ * An engine's reading of a prompt core typed, for the engines whose submissions their worker reads
+ * (engines/submissionPolicies.ts). Null means no evidence: the worker unavailable, the session rebound
+ * while it answered, or text past the bounds. It never means the prompt was taken, or that it was not.
+ */
+export interface SubmissionReader {
+ /** The engine's declared timing, data read in line; undefined: the core reads this engine's submissions
+ * itself, as it did before (the engines not yet behind the facet). */
+ policy(engine: string): SubmissionPolicy | undefined
+ read(session: RegisteredSession, capture: string, prompt: string): Promise<SubmissionReading | null>
+ echo(session: RegisteredSession, recorded: string): Promise<PromptSpan | null>
+}
diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.md
index 700bfeed4..e67d0cb6e 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, model control and question navigation (`src/engines/worker/`) | engine behavior outside core; snapshots and revocable model- and question-control grants | on demand |
+| `engine-claude`, `engine-codex` | history, live parsers, runtime profiles, screens, submission readings, 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 72ed84a35..052a63fe2 100644
--- a/cli/src/services/inline.spec.ts
+++ b/cli/src/services/inline.spec.ts
@@ -1,6 +1,7 @@
import { questionControlFor } from '../engines/questionControls.js'
import { modelControlFor } from '../engines/modelControls.js'
import { screenFor } from '../engines/screens.js'
+import { submissionFor } from '../engines/submissions.js'
import { describe, expect, it } from 'vitest'
import { engineTranscriptFor } from '../engines/transcripts.js'
import { liveFor } from '../engines/live.js'
@@ -28,6 +29,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, questionControlFor, 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, submissionFor, 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 cd46afc88..241f815ba 100644
--- a/cli/src/services/inline.ts
+++ b/cli/src/services/inline.ts
@@ -16,6 +16,7 @@ export { questionControlFor } from '../engines/questionControls.js'
export { engineTranscriptFor } from '../engines/transcripts.js'
export { liveFor } from '../engines/live.js'
export { screenFor } from '../engines/screens.js'
+export { submissionFor } from '../engines/submissions.js'
export { modelControlFor } from '../engines/modelControls.js'
export { runtimeFor } from '../engines/runtime.js'
export { startGateway } from '../gateway/start.js'
diff --git a/cli/src/testing/inlineSubmission.ts b/cli/src/testing/inlineSubmission.ts
new file mode 100644
index 000000000..bf320750e
--- /dev/null
+++ b/cli/src/testing/inlineSubmission.ts
@@ -0,0 +1,9 @@
+/** Real native submission readers injected into unit hosts; production supervision never imports this. */
+import { submissionFor } from '../engines/submissions.js'
+import { submissionPolicy } from '../engines/submissionPolicies.js'
+import type { SubmissionReader } from '../lib/submissionReader.js'
+export const inlineSubmission: SubmissionReader = {
+ policy: submissionPolicy,
+ read: async (session, capture, prompt) => submissionFor(session.engine)?.read(capture, prompt) ?? null,
+ echo: async (session, recorded) => submissionFor(session.engine)?.echo(recorded) ?? null,
+}
diff --git a/docs/design/2026-10-05-engine-interface.md b/docs/design/2026-10-05-engine-interface.md
index 14aaa470f..8ca5b4e29 100644
--- a/docs/design/2026-10-05-engine-interface.md
+++ b/docs/design/2026-10-05-engine-interface.md
@@ -13,9 +13,10 @@
> 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.
+> profiles (#1022), screen interpretation (#1027), model controls (#1038), question navigation and the
+> readings behind submission verification run in their supervised engine workers. Still in core for them:
+> hook admission and installers, engine-specific launch, discovery and resume, and native control
+> connections; [the remaining facets](2026-10-08-engine-remaining-facets.md) maps them and their order.
> 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-remaining-facets.md b/docs/design/2026-10-08-engine-remaining-facets.md
new file mode 100644
index 000000000..1b487e722
--- /dev/null
+++ b/docs/design/2026-10-08-engine-remaining-facets.md
@@ -0,0 +1,94 @@
+# The remaining Claude Code and Codex facets
+
+What of Claude Code and Codex the core still runs, mapped from source on 2026-10-08. The core's static
+import closure comes from bundling `cli/src/core/main.ts` with esbuild, dynamic imports external.
+Before batch (a) it was 72,479 lines in 376 files. After it, 72,776 lines in 384 files: the shared
+transport, the broker and declared policy came in, and the native readings went out. Line counts are
+informational, never a gate.
+
+Every batch keeps the same split. Core keeps authority: the control lease, identity and binding, turn
+state, spawning tmux panes, and hook transport and authentication. The engine worker interprets
+snapshots or performs one bounded operation under a revocable grant. Inline mode and older masters
+compose the same code in process.
+
+## (a) Submission verification: done in this batch
+
+See [engine submission](2026-10-08-engine-submission.md).
+
+| File | Engine-specific behavior | Stays in core | Moved to the worker | Risk |
+| --- | --- | --- | --- | --- |
+| `lib/sessionInput.ts` | Claude's 3 s window and types-while-busy; the composer and composer-drawn checks; Claude's paste envelope on the recorded prompt | the queue, the lease wait, every Enter and verdict, receipts | the composer reading; `echo` (async) | An enveloped receipt now arrives one worker round trip later. The pane's state is released at once. |
+| `core/deviceInput.ts` | `NATIVE`, `draft()`, busy mode (Claude queue, Codex steering from 0.106) | the writer lock, retries, receipts | `nativeDraft` | A missing reading is unreadable, so the Device never presses an Enter on it. |
+| `core/turns/funnel.ts` | Native turn boundary for the Device | the funnel | nothing: it reads the declared policy | none |
+
+Still in core and engine-specific, as data or copy: `engines/{claude,codex}/submissionPolicy.ts`
+(declared timing), the per-engine wording in `lib/messageHolds.ts` and `core/cardText.ts`, and
+`lib/goalCommand.ts` (`/goal` and `/loop` adaptation, synchronous on the input path). The tmux paste
+settle in `lib/tmux.ts` is the writer's own and stays in core.
+
+## (b) Hook admission and installers
+
+| File | Engine-specific behavior | Stays in core | Can move | Risk |
+| --- | --- | --- | --- | --- |
+| `engines/claude/installHooks.ts` (68) | merges hooks into `~/.claude/settings.json` | when to install, and the hook command string (`engines/kit/notifyHooks.ts`) | the settings merge | synchronous write into an engine home at daemon start (`installEngineHooks`) |
+| `engines/codex/installHooks.ts` (60) | writes `<CODEX_HOME>/hooks.json` | the same | the file write | also per agent before spawn (`core/agents/create.ts`, restore). It must finish first, or no hook fires. |
+| `engines/claude/hooks.ts` (71) | `transcriptFor`, `onStop` (stale check, `/goal` continuation, grace) | `HookTurnContext`: `closeTurn`, `emit`, `drain` | the transcript correction and the Stop decision | `transcriptFor` is synchronous on the hook HTTP path (`hookServer.ts` `knownTranscriptFor`). `onStop` calls back into core. |
+| `engines/codex/hooks.ts` (13) | `admit` rejects subagent rollouts (a synchronous 128 KB read) | admission's fail-closed default | the rule | Synchronous in `hookServer.ts`. A worker that is down would reject every Codex hook. `registry.register` repeats the check. |
+| `core/engines/hooks.ts` (~20 of 234) | the moved-home install loop | `resolveHookAgent`, `onSessionEnd` | the loop | already best effort |
+
+About 230 lines would leave. Transport, credential, routes and `registry.register` stay.
+
+## (c) Launch, discovery and resume
+
+| File | Engine-specific behavior | Stays in core | Can move | Risk |
+| --- | --- | --- | --- | --- |
+| `engines/{claude,codex}/launch.ts`, `engines/launches.ts` | argv contracts | building argv | nothing: stays declared data | `buildEngineLaunchArgv` is synchronous, also at restore |
+| `lib/engineLaunch.ts` (~90 of 1,416), `lib/codexStartupRetry.ts` (41) | the Codex prelude and retry script | the shell wrapper | the script text | built synchronously into argv |
+| `lib/claudeTrust.ts` (129) | trust writes to `~/.claude.json` and Codex's `config.toml` | the trust decision (security policy) | the file reads and writes | writes into engine homes before spawn |
+| `engines/codex/portableHistory.ts` (220) | rewrites a rollout for resume | `setTail` before spawn | the rewrite | synchronous, at restore too. The order must be: await the worker, then set the tail, then spawn. |
+| `engines/codex/ownLoginProvider.ts` (105) | `-c model_provider=` from `config.toml` | none | all of it | a synchronous read inside an async launch |
+| `lib/sessionRepair.ts` (~190 of 716), `lib/captureResumeIdentity.ts`, `lib/handoffDiscovery.ts` | finding a live or resumed session from its pid or transcript | pid and start-marker evidence, the rebind | the readers | all async. Claude's pid record disappears when the process exits, so capture before the kill. |
+| `lib/registry.ts` (~45), `lib/claudeProject.ts`, `lib/cwdRepair.ts`, `lib/engineHomes.ts` | transcript roots, Codex child-rollout repair at load, Claude project cwd | `validTranscriptPath` containment, binding | the evidence | synchronous, at load before any worker exists, and on the hook path (`register`) |
+| `lib/tmux.ts` (~30) | process signatures, resume-argv table | process identification | nothing: stays static data | read for every process row in every discovery pass |
+| `lib/sessionSearch/externals/{claude,codex}.ts`, `lib/transcriptPages.ts` (~90), `lib/transcriptReader.ts` (~70), `lib/transcriptActivity.ts`, `lib/codexHomeProbe.ts` | listing, paging and probing sessions for adoption | `lineCount`, `forEachLine` | the providers and pagers | async |
+
+About 1,400 lines are pure Claude/Codex logic. Two normalizers stay in the closure through shared
+imports:
+
+- **`engines/claude/normalize.ts` (978).** It comes in through `lib/normalize.ts`, which
+ `core/transcripts/lastTurn.ts` and `history.ts` import. Command Code and Devin reuse its functions.
+- **`engines/codex/normalizer.ts` (771) and `subagent.ts` (271).** They come in through
+ `lib/transcriptPages.ts` and `lib/transcriptReader.ts`.
+
+Splitting the shared functions into `engines/kit` frees another 1,000 to 2,000 lines.
+
+## (d) Native control connections
+
+| File | Engine-specific behavior | Stays in core | Can move | Risk |
+| --- | --- | --- | --- | --- |
+| `lib/codexSessionLifecycle.ts` (176) | `connectCodexControl` spawns `codex app-server proxy` and speaks JSON-RPC over a WebSocket. `stopSharedCodexSession` pauses the goal, interrupts the turn and archives the thread. | the stop and close authority (`stopAgentService.ts`, `closeAgentService.ts`), the SIGTERM after it | the whole protocol, under a revocable grant | Async. The `guard()` checks between RPC steps need cancellation across the process boundary. An effect already sent is never retried. |
+| `lib/runtimeActivity.ts` (~45 of 88) | `CodexActivityReader`: one long-lived connection per `CODEX_HOME`, `thread/read` mapped to working or idle | the activity probe's decision | the reader | async. Today core keeps a child process and a socket open. |
+
+About 220 lines would leave, and with them core's only native child process and socket for an engine.
+`lib/apiConnections.ts` and `ownLoginProvider.ts` open no channel.
+
+## Proposed order
+
+1. **(a) Submission verification.** Done here.
+2. **(d) Native control connections.** The smallest and fully async. It removes a native child process
+ and a long-lived socket from core, the kind of work that crashes, hangs or leaks. It reuses the
+ control-grant pattern of model and question control.
+3. **(b) Hook admission and installers.** The installers become worker operations that core awaits
+ before it spawns or binds the hook port. Admission needs a bounded async path, or a declarative rule
+ core can evaluate in line, so a worker that is down does not reject every hook.
+4. **(c) Launch, discovery and resume.** The largest. It has the most synchronous call sites (registry
+ load, discovery tables, argv). Split it into sub-batches:
+ - resume preparation and trust writes (async callers, before spawn)
+ - session repair and adoption readers
+ - splitting the shared normalizers into `engines/kit`
+ - static tables and argv stay declared data
+
+This puts (d) before (b) and (c), unlike the order the owner listed. The reason: async work that is
+self-contained goes first; work with synchronous hot paths and dependencies at daemon start goes last.
+If the owner's order holds, (b) can go next with the same split. Each batch keeps behavior unchanged
+and adds an end-to-end case where the worker is lost mid-operation.
diff --git a/docs/design/2026-10-08-engine-screen.md b/docs/design/2026-10-08-engine-screen.md
index 08a6e0b86..0c4b363cf 100644
--- a/docs/design/2026-10-08-engine-screen.md
+++ b/docs/design/2026-10-08-engine-screen.md
@@ -46,6 +46,16 @@ malformed reply or changed identity supplies no evidence. Message and question
writes fail closed; close/activity checks remain unknown. The existing bounded
input queue may retry an unreadable screen, without typing anything first.
+One change of identity is not a reason: the check before a message's Enter, and
+the session input's checks after it (its screen and submission readings), read
+under the record as it then stands when that record is the launch the message was
+typed into, bound to its first conversation since (`core/engines/sessionBinding.ts`
+`launchBound`). An engine draws its composer before its first hook binds the
+conversation, so a message sent while it starts was otherwise left typed and
+unsent or, its turn starting after the verify window, reported unconfirmed. A
+rebind, a rotation, another pane or another process is read under the record as
+typed, and fails closed.
+
Worker startup and async loading have a deadline and recycle the worker on a
timeout. A synchronous parser stall is contained by core's deadline and the
master's existing heartbeat/restart policy. It can cost that engine's other
diff --git a/docs/design/2026-10-08-engine-submission.md b/docs/design/2026-10-08-engine-submission.md
new file mode 100644
index 000000000..f6f59babc
--- /dev/null
+++ b/docs/design/2026-10-08-engine-submission.md
@@ -0,0 +1,72 @@
+# Engine submission verification
+
+Claude Code and Codex read whether a prompt core typed was taken through `Engine.submission`, in
+their existing engine worker. Core keeps the writer, the lease, every Enter, the delivery receipts and
+every verdict. A worker gets text and answers facts. It has no terminal handle and cannot type.
+
+## What moved
+
+| Reading | Was in | Now |
+| --- | --- | --- |
+| Is the prompt still in the composer, and is a composer drawn (session input's retry check) | `lib/sessionInput.ts` | `engines/kit/nativeSubmission.ts`, called by `engines/{claude,codex}/submission.ts` |
+| The Device route's stricter reading (`❯` or `›` only, none drawn is unreadable) | `core/deviceInput.ts` | the same reader, field `nativeDraft` |
+| A turn's prompt as recorded, unwrapped (Claude Code 2.1.283's `<pasted_content>` envelope) | `lib/sessionInput.ts` | `engines/claude/submission.ts` `echo`. Codex answers the whole text |
+| Types while busy, the verify window, the Device's busy mode (Codex steering from 0.106) | constants in `sessionInput.ts`, `deviceInput.ts` | declared data, `engines/{claude,codex}/submissionPolicy.ts` |
+
+The readings moved verbatim, so each route decides as it did before. Other engines keep the core's
+reading (`engines/kit/submission.ts` holds the shared composer mechanics) until their own batches.
+
+## Policy is data
+
+Core reads the policy in line, as a message arrives. It needs it before typing (queue, or type at once)
+and to arm the check's timer. A worker round trip there would sit in front of every message, and would
+need a fallback for a missing worker. So, like the launch contract, the policy is declared data. Core
+gets it injected (`SubmissionReader.policy`). The input modules do not import it, and
+`architecture.spec.ts` keeps their closure free of Claude Code and Codex files.
+
+## Private transport
+
+`engine_submission_capabilities`, `engine_submission_read` (capture and prompt) and
+`engine_submission_echo` (recorded prompt) are private methods on the engine links. They are absent
+from the client router and require core's local owner identity. Core and the worker share the screen
+reader's transport (`core/engines/snapshotTransport.ts`, `engines/worker/snapshotRequests.ts`). Each
+result is fenced to the connection generation and to the session binding observed before the call.
+
+| Bound | Value |
+| --- | --- |
+| Capture | 256 KiB of UTF-8 (the screen's) |
+| Prompt or recorded text | 1 MiB of UTF-8 |
+| Reply | 4 KiB |
+| Concurrent readings | 8 per engine, at most 64 waiting in FIFO order |
+| Deadline | 1 second, including queueing, capability negotiation and worker start |
+
+A reply must be exactly three facts, or an in-range span of the text sent. Anything else is no reading.
+
+## No reading is no evidence
+
+- **Composer reading.** A missing, late or malformed reading is never an Enter and never a claim. The
+ session input reports the message unconfirmed, as it already did for an unreadable screen. The
+ Device route treats the pane as unreadable and keeps looking until its bound.
+- **Readings that land late.** If the turn started, or the agent was rebound, while a reading was in
+ flight, that reading decides nothing. A first bind is not a rebind: a message typed while its engine
+ started is read under the record as it now stands, that launch bound since (`launchBound`).
+- **Echoes.** An exact echo matches with no reading. A different record is the engine's to unwrap. Its
+ delivery leaves the pane's state at once, so later writes never wait on the reading. Only the receipt
+ waits: `started`, or `unknown`/`prompt_mismatch` when the reading says otherwise or there is none.
+
+The parent-bound `HARNESSD_ENGINE_SUBMISSION=<master-pid>:1` capability selects the workers. Explicit
+inline mode and older masters compose the inline readers. A failed worker never selects inline reading.
+
+## Validation
+
+- **Unit tests.** They cover the broker, both transports and the worker requests: bounds, wrong asker,
+ malformed and oversized replies, deadlines, recycling, stale generations and in-place rebinding.
+ Session-input and Device cases cover a missing reading, a throwing reader, a late reading and the
+ echo's release.
+- **`e2e/engineSubmission.e2e.ts`.** The fake CLIs take a `!latestart` prompt off the composer and hold
+ its turn. The test then stops (Claude Code) or kills (Codex) the worker after its first reading, or
+ fails the reading itself (Codex). Each time there is exactly one Enter, the turn starts once when
+ released, core and the CLI process stay up, and the next prompt works. A third case runs the inline
+ reader.
+- **Unchanged suites.** The existing composer, input-safety, turns, Device and teams suites run
+ unchanged.