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 transcript readers (#1015)

Dee2e2e1974e861
diff --git a/cli/AGENTS.md b/cli/AGENTS.md
index 266695f88..910f58a2f 100644
--- a/cli/AGENTS.md
+++ b/cli/AGENTS.md
@@ -25,6 +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 and last-turn readers only | on demand: a 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/endurance.e2e.ts b/cli/e2e/endurance.e2e.ts
index 985a74b82..037a14dfc 100644
--- a/cli/e2e/endurance.e2e.ts
+++ b/cli/e2e/endurance.e2e.ts
@@ -67,6 +67,8 @@ const isTurn = (type: string, agentId: string) => (frame: Frame) => frame.type =
/** A request each service's process answers, as the apps ask it: answered by the service when it is up. */
const PROBES: Record<string, { type: string; payload: Record<string, unknown> }> = {
+ 'engine-claude': { type: 'session_get', payload: { limit: 10 } },
+ 'engine-codex': { type: 'session_get', payload: { limit: 10 } },
gateway: { type: 'e2ee_pairings_list', payload: {} },
sharing: { type: 'harness_share_list', payload: {} },
search: { type: 'session_search', payload: { query: 'soak' } },
@@ -79,13 +81,19 @@ const PROBES: Record<string, { type: string; payload: Record<string, unknown> }>
commandBar: { type: 'command_bar', payload: { request: { prompt: '' } } },
}
/** The service names a process's comings and goings are logged under (`[services] <name> connected`). */
-const LINKS: Record<string, string> = { search: 'search', viewers: 'viewers', edge: 'monitor', gateway: 'gateway', models: 'models', devices: 'devices', orchestrator: 'orchestrator', teams: 'teams', commandBar: 'commandBar', sharing: 'sharing' }
-const down = (answer: Record<string, unknown>) => answer.error === 'SERVICE_UNAVAILABLE' || answer.error === 'SERVICE_FAILED' || answer.error === 'GATEWAY_UNAVAILABLE'
+const LINKS: Record<string, string> = { 'engine-claude': 'engine-claude', 'engine-codex': 'engine-codex', search: 'search', viewers: 'viewers', edge: 'monitor', gateway: 'gateway', models: 'models', devices: 'devices', orchestrator: 'orchestrator', teams: 'teams', commandBar: 'commandBar', sharing: 'sharing' }
+const down = (answer: Record<string, unknown>) => answer.error === 'SERVICE_UNAVAILABLE' || answer.error === 'SERVICE_FAILED' || answer.error === 'GATEWAY_UNAVAILABLE' || answer.error === 'ENGINE_UNAVAILABLE' || answer.error === 'ENGINE_STALE_REPLY' || answer.error === 'ENGINE_BUSY'
const acceptable = (name: string, answer: Record<string, unknown>): boolean => answer.error === undefined
|| (name === 'commandBar' && answer.error === 'INVALID_REQUEST')
|| (name === 'sharing' && answer.error === 'HARNESS_NOT_FOUND')
async function wakeServices(client: LocalClient): Promise<void> {
+ const agents = (await client.request('agents_list', {})).agents as Array<Record<string, unknown>>
+ for (const engine of ['claude', 'codex']) {
+ const agent = agents.find(agent => agent.engine === engine && agent.sessionId)
+ if (!agent) throw new Error(`no ${engine} conversation for the reader probe`)
+ PROBES[`engine-${engine}`].payload.sessionId = agent.id
+ }
for (const [name, probe] of Object.entries(PROBES)) {
await until(`${name} to answer its probe`, async () => {
const answer = await client.request(probe.type, probe.payload, 30_000)
diff --git a/cli/e2e/engineReaders.e2e.ts b/cli/e2e/engineReaders.e2e.ts
new file mode 100644
index 000000000..c73a3922d
--- /dev/null
+++ b/cli/e2e/engineReaders.e2e.ts
@@ -0,0 +1,129 @@
+/** Private daemon/home/tmux; real supervised reader processes and the engines' recorded wire format. */
+import { mkdirSync, readFileSync } 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 } from './harness/daemon.js'
+import { alive, harnessdProcesses } from './harness/endurance.js'
+
+type Engine = 'claude' | 'codex'
+type Agent = { id: string; sessionId: string; engine: Engine; processIdentity: unknown }
+const rows = async (client: LocalClient) => (await client.request('agents_list', {})).agents as Agent[]
+const history = (client: LocalClient, agent: Agent) => client.request('session_get', { sessionId: agent.id, limit: 10 }, 15_000)
+
+async function create(d: IsolatedDaemon, client: LocalClient, engine: Engine): Promise<Agent> {
+ const cwd = join(d.projectsDir, engine); mkdirSync(cwd, { recursive: true })
+ const created = await client.request('agent_create', { engine, cwd, bypassPermission: true }, 90_000)
+ expect(created.error, JSON.stringify(created)).toBeUndefined()
+ return until(`${engine} conversation`, async () => (await rows(client)).find(row => row.id === created.agent.id && row.sessionId) ?? null, 60_000, 200)
+}
+
+async function turn(client: LocalClient, agent: Agent, text: string, recap = false) {
+ const ended = client.next(frame => frame.type === 'turn_ended' && frame.agentId === agent.id, 30_000, text)
+ const summary = recap ? client.next(frame => frame.type === 'turn_summary' && frame.agentId === agent.id
+ && JSON.stringify(frame.payload).includes(text), 30_000, `recap ${text}`) : null
+ client.send('message', { agentId: agent.id, content: text })
+ await ended
+ if (summary) await summary
+}
+
+describe('Claude Code and Codex readers in their own processes', () => {
+ let daemon: IsolatedDaemon | undefined
+ let client: LocalClient | undefined
+ afterEach(async () => { client?.close(); await daemon?.close(); client = undefined; daemon = undefined })
+ async function fresh(env: Record<string, string> = {}) {
+ const d = daemon = await IsolatedDaemon.create({ env: { HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '200', HARNESSD_SERVICE_MAX_BACKOFF_MS: '1000', ...env } })
+ onTestFailed(() => console.log(d.log()))
+ await d.start()
+ client = await LocalClient.connect(d)
+ return { d, c: client }
+ }
+ const readerPid = (d: IsolatedDaemon, engine: Engine) => harnessdProcesses(d).get(`engine-${engine}`)
+ const linked = (d: IsolatedDaemon, engine: Engine) => d.log().split(`[services] engine-${engine} connected`).length - 1
+
+ it('starts no reader for an empty core, reads pages and recap text on demand, and keeps private requests off the client router', async () => {
+ const { d, c } = await fresh()
+ expect(readerPid(d, 'claude')).toBeUndefined()
+ expect(readerPid(d, 'codex')).toBeUndefined()
+ for (const type of ['engine_history_page', 'engine_last_turn']) {
+ const answer = await c.request(type, { version: 1, session: { transcriptPath: '/etc/passwd' } })
+ expect(answer.error).toBe('UNSUPPORTED')
+ }
+ for (const engine of ['claude', 'codex'] as const) {
+ const agent = await create(d, c, engine)
+ await turn(c, agent, `reader-cold-${engine}`, true)
+ const first = await history(c, agent)
+ expect(first.error, JSON.stringify(first)).toBeUndefined()
+ expect(JSON.stringify(first.events)).toContain(`reader-cold-${engine}`)
+ const pid = readerPid(d, engine)!
+ expect(alive(pid)).toBe(true)
+ const second = await history(c, agent)
+ expect(second).toMatchObject({ events: first.events, oldestCursor: first.oldestCursor })
+ expect(readerPid(d, engine)).toBe(pid)
+ }
+ expect(d.coresStarted()).toBe(1)
+ })
+
+ it('contains a killed or frozen reader, bounds failed reads, and recovers without restarting core or either CLI', async () => {
+ const { d, c } = await fresh({ HARNESSD_SERVICE_HEARTBEAT_TIMEOUT_MS: '4000', HARNESSD_SERVICE_STOP_GRACE_MS: '100' })
+ const agents = await Promise.all((['claude', 'codex'] as const).map(engine => create(d, c, engine)))
+ for (const agent of agents) { await turn(c, agent, `before-${agent.engine}`, true); await history(c, agent) }
+ const corePid = d.corePid()
+ const identities = () => {
+ const rows = JSON.parse(readFileSync(join(d.dataDir, 'registry.json'), 'utf8'))
+ return agents.map(agent => rows.find((row: any) => row.agentId === agent.id)?.processIdentity)
+ }
+ const identitiesBefore = identities()
+ for (const identity of identitiesBefore) expect(identity?.pid).toBeGreaterThan(0)
+ const panePids = await Promise.all(agents.map(async agent => {
+ const row = (await c.request('agents_list', {})).agents.find((row: any) => row.id === agent.id)
+ return { pane: row.tmuxPane, pid: (await d.tmux.run('display-message', '-p', '-t', row.tmuxPane, '#{pane_pid}')).trim() }
+ }))
+ for (const [index, signal] of (['SIGKILL', 'SIGSTOP'] as const).entries()) {
+ const agent = agents[index]
+ const other = agents[1 - index]
+ const before = readerPid(d, agent.engine)!
+ const connections = linked(d, agent.engine)
+ process.kill(before, signal)
+ const at = Date.now()
+ const pending = history(c, agent)
+ // Both the affected engine's live turn and the other engine's reader continue independently.
+ await Promise.all([turn(c, agent, `during-${signal}`), turn(c, other, `other-${signal}`, true)])
+ const answer = await pending
+ if (answer.error) expect(['ENGINE_UNAVAILABLE', 'ENGINE_STALE_REPLY']).toContain(answer.error)
+ expect(Date.now() - at).toBeLessThan(15_000)
+ expect((await history(c, other)).error).toBeUndefined()
+ await until(`${agent.engine} reader recovery`, () => linked(d, agent.engine) > connections && readerPid(d, agent.engine) !== before || null, 30_000, 100)
+ const recovered = await history(c, agent)
+ expect(recovered.error, JSON.stringify(recovered)).toBeUndefined()
+ expect(JSON.stringify(recovered.events)).toContain(`during-${signal}`)
+ await turn(c, agent, `recovered-${signal}`, true)
+ if (signal === 'SIGSTOP') expect(d.log()).toContain(`service engine-${agent.engine} sent no heartbeat`)
+ }
+ expect(identities()).toEqual(identitiesBefore)
+ for (const identity of identitiesBefore) expect(alive(identity.pid)).toBe(true)
+ expect(d.corePid()).toBe(corePid)
+ expect(d.coresStarted()).toBe(1)
+ for (const { pane, pid } of panePids) expect((await d.tmux.run('display-message', '-p', '-t', pane, '#{pane_pid}')).trim()).toBe(pid)
+ })
+
+ it('restarts a leaking reader at its memory budget while the agent continues', async () => {
+ const { d, c } = await fresh({ HARNESSD_TEST_FAULTS: 'engine-claude.leak', HARNESSD_SERVICE_HEAP_LIMIT_MIB: '128' })
+ const agent = await create(d, c, 'claude')
+ await history(c, agent)
+ await until('reader memory containment', () => /\[harnessd\] service engine-claude: (its heap is at|it is using)/.test(d.log()) || null, 60_000, 200)
+ await until('reader memory restart', () => linked(d, 'claude') >= 2 || null, 30_000, 200)
+ await turn(c, agent, 'reader-memory-contained')
+ expect(d.coresStarted()).toBe(1)
+ })
+
+ it('parks a crashing reader, returns an explicit failure, and leaves the agent working', async () => {
+ const { d, c } = await fresh({ HARNESSD_TEST_FAULTS: 'engine-codex.crash', HARNESSD_SERVICE_PARK_CRASHES: '3' })
+ const agent = await create(d, c, 'codex')
+ await history(c, agent)
+ await until('reader parked', () => d.log().includes('service engine-codex ended 3 times') || null, 60_000, 200)
+ expect(await history(c, agent)).toMatchObject({ error: 'ENGINE_UNAVAILABLE', retryable: true })
+ await turn(c, agent, 'reader-is-parked')
+ expect(d.coresStarted()).toBe(1)
+ })
+})
diff --git a/cli/e2e/harness/corePerf.cjs b/cli/e2e/harness/corePerf.cjs
index bfbe7f42b..3dff524ea 100644
--- a/cli/e2e/harness/corePerf.cjs
+++ b/cli/e2e/harness/corePerf.cjs
@@ -1,6 +1,7 @@
// Test-only preload. QA needed the core's CPU, not its master's or its children's.
// Nothing is loaded into production; only the opt-in E2E supplies these settings.
-if (process.argv.includes('__run') && process.env.HARNESS_E2E_PERF_DIR && process.env.HARNESS_E2E_PERF_TOKEN) {
+if ((process.argv.includes('__run') || (process.env.HARNESS_E2E_PERF_READERS === '1'
+ && process.argv.includes('__service') && /^engine-(claude|codex)$/.test(process.env.HARNESSD_SERVICE || ''))) && process.env.HARNESS_E2E_PERF_DIR && process.env.HARNESS_E2E_PERF_TOKEN) {
const { createServer } = require('node:http')
const { writeFileSync, renameSync } = require('node:fs')
const { join } = require('node:path')
diff --git a/cli/e2e/perf.e2e.ts b/cli/e2e/perf.e2e.ts
index 567532c6e..629692cf9 100644
--- a/cli/e2e/perf.e2e.ts
+++ b/cli/e2e/perf.e2e.ts
@@ -4,6 +4,8 @@
* PERF_PROFILE=1 adds node --cpu-prof; PERF_HEAP=1 writes snapshots AFTER measurement windows.
* PERF_REPORT=<file> writes JSON; raw artifacts stay in its recorded private temporary directory.
* Run alone. CPU is the core's process CPU (100% = one logical CPU), never the master's/children's.
+ * PERF_READERS=1 additionally measures reader PIDs and history pages every 2 s; totals include them.
+ * PERF_BUNDLE_SOURCE identifies an externally built baseline bundle; its bytes are hashed either way.
* On macOS set HARNESS_PROCESS_IMAGES_ARTIFACT to a verified local build for release-like discovery.
*/
import { execFileSync } from 'node:child_process'
@@ -16,6 +18,7 @@ import { describe, expect, it } from 'vitest'
import { TerminalBinaryKind } from '../src/lib/terminalBinary.js'
import { LocalClient } from './harness/client.js'
import { CLI_ROOT, until } from './harness/daemon.js'
+import { harnessdProcesses } from './harness/endurance.js'
import { startPhoneMachine, type PhoneMachine } from './harness/fleet.js'
const sleep = (ms: number) => new Promise<void>(done => setTimeout(done, ms))
@@ -94,6 +97,7 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
const seconds = knob('PERF_SECONDS', 60, 10, 600)
const warmup = knob('PERF_WARMUP_SECONDS', 20, 0, 120)
const historyMiB = knob('PERF_HISTORY_MIB', 1, 0, 8)
+ const measureReaders = process.env.PERF_READERS === '1'
const profile = process.env.PERF_PROFILE === '1'
const heaps = process.env.PERF_HEAP === '1'
const bundle = process.env.E2E_BUNDLE_PATH
@@ -109,13 +113,13 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
const report: Record<string, any> = {
schema: 1, state: 'running', startedAt: new Date().toISOString(), artifactDir,
source: { commit: git('rev-parse', 'HEAD'), tree: git('rev-parse', 'HEAD^{tree}'),
- dirty: Boolean(git('status', '--porcelain')), bundleSha256: sha(bundle), preloadSha256: sha(preload) },
+ dirty: Boolean(git('status', '--porcelain')), bundleSource: process.env.PERF_BUNDLE_SOURCE ?? git('rev-parse', 'HEAD'), bundleSha256: sha(bundle), preloadSha256: sha(preload) },
machine: { platform: platform(), release: release(), node: process.version, logicalCpus: cpus().length,
cpu: cpus()[0]?.model, ramBytes: totalmem(), tmux: execFileSync('tmux', ['-V'], { encoding: 'utf8', timeout: 5_000 }).trim() },
- workload: { agents, active, windows: 2, terminalStreams: 4, seconds, warmup, historyMiB,
+ workload: { readerPageEveryMs: measureReaders ? 2000 : null, agents, active, windows: 2, terminalStreams: 4, seconds, warmup, historyMiB,
turnDelayMs: '5000 + a unique round offset', inventoryEveryMs: 60_000, heartbeatEveryMs: 5_000, ackEveryMs: 16 },
instrumentation: { profile, heaps, delayResolutionMs: 10, rssSampleEveryMs: 1_000, cpuPercentBasis: 'one logical CPU',
- scope: 'core PID only; excludes master, services, engines and tmux', heapPausesOutsideWindows: true },
+ scope: measureReaders ? 'core PID and both reader PIDs; excludes master, other services, engines and tmux' : 'core PID only; excludes master, services, engines and tmux', heapPausesOutsideWindows: true },
nativeProcessImages: process.env.HARNESS_PROCESS_IMAGES_ARTIFACT
? { mode: 'embedded', artifactSha256: sha(process.env.HARNESS_PROCESS_IMAGES_ARTIFACT) } : { mode: 'fallback' },
limitations: ['Fake engines and a loopback fake backend; no real model latency or token streaming.',
@@ -128,7 +132,7 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
let corePid: number | null = null
try {
machine = await startPhoneMachine({ env: { NODE_OPTIONS: nodeOptions.join(' '),
- HARNESS_E2E_PERF_DIR: artifactDir, HARNESS_E2E_PERF_TOKEN: token } })
+ HARNESS_E2E_PERF_READERS: measureReaders ? '1' : '0', HARNESS_E2E_PERF_DIR: artifactDir, HARNESS_E2E_PERF_TOKEN: token } })
const d = machine.machine.daemon
corePid = d.corePid()
if (!corePid) throw new Error('no owned core PID')
@@ -138,14 +142,15 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
await until('the owned core performance probe', () => existsSync(readyFile), 10_000)
const endpoint = JSON.parse(readFileSync(readyFile, 'utf8')) as { pid: number; port: number }
expect(endpoint.pid).toBe(corePid)
- const probe = async (op: string, label: string) => {
- const response = await fetch(`http://127.0.0.1:${endpoint.port}/${op}`, {
+ const probe = async (op: string, label: string, pid = corePid!) => {
+ const target = pid === corePid ? endpoint : JSON.parse(readFileSync(join(artifactDir, `core-${pid}.json`), 'utf8'))
+ const response = await fetch(`http://127.0.0.1:${target.port}/${op}`, {
method: 'POST', headers: { 'x-harness-perf-token': token }, body: JSON.stringify({ label }),
signal: AbortSignal.timeout(op === 'heap' ? 120_000 : 10_000),
})
const result = await response.json() as Record<string, any>
if (!response.ok) throw new Error(`perf ${op}: ${JSON.stringify(result)}`)
- expect(result.pid).toBe(corePid)
+ expect(result.pid).toBe(pid)
return result
}
await until('signed in to the fake backend', () => machine!.backend.nodeUp(machine!.machine.machineId), 30_000)
@@ -176,7 +181,21 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
const latencies: number[] = []
let running = true
let problem: unknown
- await probe('start', label)
+ const readers = measureReaders ? [...harnessdProcesses(d)].filter(([name]) => name.startsWith('engine-')) : []
+ for (const [, pid] of readers) await until('reader performance probe', () => existsSync(join(artifactDir, `core-${pid}.json`)), 10_000)
+ await Promise.all([probe('start', label), ...readers.map(([, pid]) => probe('start', label, pid))])
+ const readLatencies: number[] = []
+ const reads = (async () => {
+ while (measureReaders && saved.length && running) {
+ await Promise.all(saved.map(async agent => {
+ const at = performance.now()
+ const answer = await client.request('session_get', { sessionId: agent.id, limit: 50 }, 15_000)
+ if (answer.error) throw new Error(`history read: ${JSON.stringify(answer)}`)
+ readLatencies.push(performance.now() - at)
+ }))
+ await sleep(2000)
+ }
+ })().catch(error => { problem ??= error })
const workers = turns.map(async (_, i) => {
while (running) {
const began = performance.now()
@@ -185,11 +204,16 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
if (running) { turns[i]++; latencies.push(performance.now() - began) }
}
})
+ let readerMetrics: Record<string, any>[] = []
let metrics: Record<string, any>
try { await sleep(seconds * 1000) }
- finally { running = false; metrics = await probe('end', label) }
+ finally {
+ running = false
+ const measured = await Promise.all([probe('end', label), ...readers.map(async ([name, pid]) => ({ name, ...await probe('end', label, pid) }))])
+ metrics = measured[0]; readerMetrics = measured.slice(1)
+ }
const after = windows.map(w => w.stats())
- await Promise.all(workers)
+ await Promise.all([...workers, reads])
if (problem) throw problem
expect(metrics!.cpu.percent).toBeGreaterThanOrEqual(0)
expect(Number.isFinite(metrics!.cpu.percent)).toBe(true)
@@ -197,7 +221,10 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
expect(metrics!.eventLoop.delaySamples).toBeGreaterThan(0)
if (turning) for (const count of turns) expect(count).toBeGreaterThan(0)
latencies.sort((a, b) => a - b)
- report.phases.push({ ...metrics!, turns, completedTurns: turns.reduce((a, b) => a + b, 0),
+ readLatencies.sort((a, b) => a - b)
+ report.phases.push({ ...metrics!, readers: readerMetrics,
+ historyReads: { count: readLatencies.length, p50Ms: readLatencies[Math.floor(readLatencies.length * .5)] ?? null, p95Ms: readLatencies[Math.floor(readLatencies.length * .95)] ?? null },
+ coreAndReaders: { cpuPercent: metrics!.cpu.percent + readerMetrics.reduce((sum, m) => sum + m.cpu.percent, 0), rssMean: metrics!.memory.rssMean + readerMetrics.reduce((sum, m) => sum + m.memory.rssMean, 0) }, turns, completedTurns: turns.reduce((a, b) => a + b, 0),
turnLatencyMs: { p50: latencies[Math.floor(latencies.length * .5)] ?? null, p95: latencies[Math.floor(latencies.length * .95)] ?? null },
windows: after.map((stats, i) => Object.fromEntries(Object.entries(stats).map(([key, value]) =>
[key, value - before[i][key as keyof ReturnType<PerfWindow['stats']>]]))) })
@@ -229,6 +256,15 @@ describe.runIf(process.env.PERF === '1')('core CPU and memory under a working de
await Promise.all(saved.slice(i, i + 4).map(agent => turn(agent.id, `!grow ${historyMiB}`)))
}
report.transcriptBytes = transcriptBytes(join(d.root, 'claude/projects')) + transcriptBytes(join(d.root, 'codex/sessions'))
+ if (measureReaders) {
+ report.firstHistoryReads = []
+ for (const agent of saved) {
+ const at = performance.now()
+ const answer = await client.request('session_get', { sessionId: agent.id, limit: 50 }, 15_000)
+ expect(answer.error, JSON.stringify(answer)).toBeUndefined()
+ report.firstHistoryReads.push({ engine: agent.engine, ms: performance.now() - at })
+ }
+ }
await sleep(warmup * 1000)
await phase('populated-idle', false)
await phase('active', true)
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.ts
index 2562e7d80..102013be4 100644
--- a/cli/src/architecture.spec.ts
+++ b/cli/src/architecture.spec.ts
@@ -143,6 +143,8 @@ 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[] = [
+ // The pilot reader implementations and their host are never loaded by supervised core.
+ /^engines\/(worker\/process|transcripts|(claude|codex)\/(transcript|\w+ReaderProcess))\.ts$/,
/^gateway\//, /^lib\/e2ee\//, /^cable\//, /^device\//, /^lib\/autonomous-device\//, /^sharing\//, /^teams\//, /^orchestrator\//, /^services\//,
/^lib\/grid(Attach|Credentials|Derive|Ensure|Envelope|Exec|FleetRpc|Handoff|Install|McpUrl|Models|ModelsPayload|Picture|Presence|Reader|Target|Wake)\.ts$/,
/^lib\/localModels\.ts$/,
diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.md
index b23fee873..3ebeeadc9 100644
--- a/cli/src/core/AGENTS.md
+++ b/cli/src/core/AGENTS.md
@@ -29,7 +29,8 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE
side of the recaps: the turn lifecycle it tells them, and what it reads back.
- `terminals/`: who controls a pane (the control lease), opening a terminal with a literal argv (`open.ts`),
and the requests about a terminal itself (`requests.ts`: `terminal_info`, `theme_set`).
-- `engines/`: the engines' hooks.
+- `engines/`: hook coordination and the reader port. Claude Code/Codex history and last-turn readers
+ run in supervised workers; core passes snapshots, validates replies and owns binding/turn state.
- `input.ts`, `questions.ts`: messages into a pane; an agent's question and its answer.
`deviceInput.ts`: the pane writer lock every write takes, and a device's queued turns behind it.
`cardText.ts`: an engine's error, rewritten for a device's card.
diff --git a/cli/src/core/engines/readers.spec.ts b/cli/src/core/engines/readers.spec.ts
new file mode 100644
index 000000000..53ccbfcdb
--- /dev/null
+++ b/cli/src/core/engines/readers.spec.ts
@@ -0,0 +1,119 @@
+import { describe, expect, it, vi } from 'vitest'
+import { createEngineReaders } from './readers.js'
+import type { EngineTranscript, TranscriptSession } from '../../engines/facets/transcript.js'
+import { EngineReadError, READER_ERRORS, READER_HISTORY, READER_IN_FLIGHT, READER_LAST_TURN, READER_SERVICES, READER_VERSION, READER_WAIT_MS } from '../../engines/worker/protocol.js'
+
+const session: TranscriptSession = { sessionId: 'conversation', transcriptPath: '/private/read.jsonl', touchedAt: 100, codexHome: '/private/codex' }
+const page = { events: [], timestamp: '2026-10-07T00:00:00.000Z' }
+const turn = { userMessage: 'hello', assistantText: 'world' }
+const pages = {} as Parameters<EngineTranscript['historyPage']>[2]
+const deferred = <T>() => { let resolve!: (value: T) => void; const promise = new Promise<T>((r) => { resolve = r }); return { promise, resolve } }
+
+function setup() {
+ const replies: ReturnType<typeof deferred<Record<string, unknown>>>[] = []
+ const call = vi.fn(() => { const reply = deferred<Record<string, unknown>>(); replies.push(reply); return reply.promise })
+ const inline = vi.fn(() => { throw new Error('isolated reads never fall back') })
+ const port = createEngineReaders({ isolated: new Set(Object.values(READER_SERVICES)), call, inline })
+ return { ...port, call, inline, replies, history: () => port.forEngine('claude')!.historyPage(session, { limit: 2, before: 'cursor' }, pages) }
+}
+
+describe('the core reader port', () => {
+ it('wakes on a cold call, passes only the immutable read snapshot, and accepts a versioned answer', async () => {
+ const p = setup()
+ const answer = p.history()
+ expect(p.call).toHaveBeenCalledWith('engine-claude', READER_HISTORY,
+ { version: READER_VERSION, session, ask: { limit: 2, before: 'cursor' } }, READER_WAIT_MS)
+ expect(p.call.mock.calls[0]).not.toContain(pages)
+ p.connected('engine-claude')
+ p.replies[0].resolve({ version: READER_VERSION, answer: page })
+ expect(await answer).toEqual(page)
+ const warm = p.forEngine('claude')!.historyPage(session, { limit: 0 }, pages)
+ p.replies[1].resolve({ version: READER_VERSION, answer: page })
+ expect(await warm).toEqual(page)
+ expect(p.call).toHaveBeenLastCalledWith('engine-claude', READER_HISTORY, expect.objectContaining({ ask: { limit: undefined, before: undefined } }), READER_WAIT_MS)
+ expect(p.inline).not.toHaveBeenCalled()
+ })
+
+ it('routes last-turn reads per engine and does not wake a worker for an unbound transcript', async () => {
+ const p = setup()
+ expect(await p.forEngine('codex')!.lastTurnText({ ...session, transcriptPath: null })).toBeNull()
+ expect(p.call).not.toHaveBeenCalled()
+ p.connected('engine-codex')
+ const answer = p.forEngine('codex')!.lastTurnText(session)
+ expect(p.call).toHaveBeenCalledWith('engine-codex', READER_LAST_TURN, { version: READER_VERSION, session }, READER_WAIT_MS)
+ p.replies[0].resolve({ version: READER_VERSION, answer: turn })
+ expect(await answer).toEqual(turn)
+ })
+
+ it('bounds concurrent reads per engine, rejects excess without queueing, and releases slots on failure', async () => {
+ const p = setup()
+ const requests = Array.from({ length: READER_IN_FLIGHT }, () => p.history())
+ const settled = Promise.allSettled(requests)
+ await expect(p.history()).rejects.toMatchObject({ code: 'ENGINE_BUSY' })
+ const codex = p.forEngine('codex')!.lastTurnText(session)
+ p.connected('engine-codex')
+ p.replies[READER_IN_FLIGHT].resolve({ version: READER_VERSION, answer: null })
+ expect(await codex).toBeNull()
+ for (const reply of p.replies.slice(0, READER_IN_FLIGHT)) reply.resolve({ error: 'SERVICE_UNAVAILABLE' })
+ expect((await settled).every(r => r.status === 'rejected')).toBe(true)
+ const next = p.history()
+ p.connected('engine-claude')
+ p.replies.at(-1)!.resolve({ version: READER_VERSION, answer: page })
+ expect(await next).toEqual(page)
+ })
+
+ it.each(['disconnect', 'replacement', 'reconnect'] as const)('rejects an old connection after %s without replaying the read', async (kind) => {
+ const p = setup()
+ p.connected('engine-claude')
+ const answer = p.history()
+ if (kind !== 'replacement') p.disconnected('engine-claude')
+ if (kind !== 'disconnect') p.connected('engine-claude')
+ p.replies[0].resolve({ version: READER_VERSION, answer: page })
+ await expect(answer).rejects.toMatchObject({ code: 'ENGINE_STALE_REPLY' })
+ expect(p.call).toHaveBeenCalledOnce()
+ })
+
+ it.each<[Record<string, unknown>, string]>([
+ [{ error: 'SERVICE_UNAVAILABLE' }, 'ENGINE_UNAVAILABLE'],
+ [{ error: 'SERVICE_FAILED' }, 'ENGINE_UNAVAILABLE'],
+ [{ version: 2, answer: page }, 'ENGINE_INVALID_REPLY'],
+ [{ version: 1, error: 'surprise' }, 'ENGINE_INVALID_REPLY'],
+ [{ version: 1, answer: { ...page, events: [{ type: 'turn_ended', payload: {} }] } }, 'ENGINE_INVALID_REPLY'],
+ ...READER_ERRORS.map((error): [Record<string, unknown>, string] => [{ version: 1, error }, error]),
+ ])('contains a failed or malformed reply %j', async (reply, code) => {
+ const p = setup(); p.connected('engine-claude')
+ const answer = p.history()
+ p.replies[0].resolve(reply as Record<string, unknown>)
+ await expect(answer).rejects.toMatchObject({ code })
+ expect(p.inline).not.toHaveBeenCalled()
+ })
+
+ it('contains unexpected transport exceptions and malformed last-turn replies', async () => {
+ const port = createEngineReaders({ isolated: new Set(['engine-claude']), call: async () => { throw new Error('socket') } })
+ await expect(port.forEngine('claude')!.lastTurnText(session)).rejects.toMatchObject({ code: 'ENGINE_UNAVAILABLE' })
+ const p = setup(); p.connected('engine-codex')
+ const answer = p.forEngine('codex')!.lastTurnText(session)
+ p.replies[0].resolve({ version: 1, answer: {} })
+ await expect(answer).rejects.toMatchObject({ code: 'ENGINE_INVALID_REPLY' })
+ })
+
+ it('uses explicit inline compatibility only when the master does not host this reader', () => {
+ const inlineReader = {} as EngineTranscript
+ const call = vi.fn(async () => ({}))
+ const inline = vi.fn(() => inlineReader)
+ const p = createEngineReaders({ isolated: new Set(['engine-codex']), call, inline })
+ expect(p.forEngine('claude')).toBe(inlineReader)
+ expect(p.forEngine('codex')).not.toBe(inlineReader)
+ expect(p.forEngine('constructor')).toBeUndefined()
+ expect(p.forEngine('pi')).toBeUndefined()
+ expect(inline).toHaveBeenCalledExactlyOnceWith('claude')
+ expect(createEngineReaders({ isolated: new Set(), call, inline: () => undefined }).forEngine('claude')).toBeDefined()
+ expect(createEngineReaders({ isolated: new Set(), call }).forEngine('claude')).toBeDefined()
+ p.connected('search'); p.disconnected('search')
+ expect(p.answer('search')).toBeNull()
+ for (const name of Object.values(READER_SERVICES)) expect(p.answer(name)).toEqual({ error: 'READER_HAS_NO_CORE_CAPABILITIES' })
+ expect(new EngineReadError('ENGINE_UNAVAILABLE').retryable).toBe(true)
+ expect(new EngineReadError('ENGINE_INVALID_REQUEST').retryable).toBe(false)
+ expect(new EngineReadError('ENGINE_REPLY_TOO_LARGE').retryable).toBe(false)
+ })
+})
diff --git a/cli/src/core/engines/readers.ts b/cli/src/core/engines/readers.ts
new file mode 100644
index 000000000..dafb508f7
--- /dev/null
+++ b/cli/src/core/engines/readers.ts
@@ -0,0 +1,72 @@
+/** The core's reader port: bounded calls, no reader implementation and no fallback after a failure. */
+import type { EngineTranscript, TranscriptSession } from '../../engines/facets/transcript.js'
+import type { HistoryAnswer, HistoryAsk } from '../../engines/facets/transcript.js'
+import type { LastTurnText } from '../../lib/normalize.js'
+import {
+ EngineReadError, historyAnswer, lastTurnAnswer, readerEngine, READER_ERRORS, READER_HISTORY,
+ READER_IN_FLIGHT, READER_LAST_TURN, READER_SERVICES, READER_VERSION, READER_WAIT_MS,
+ type ReaderEngine,
+} from '../../engines/worker/protocol.js'
+
+export interface EngineReaderDeps {
+ isolated: ReadonlySet<string>
+ call(service: string, type: string, payload: Record<string, unknown>, waitMs: number): Promise<Record<string, unknown>>
+ /** Only supplied by the explicit inline/older-master compatibility path. */
+ inline?: (engine: string) => EngineTranscript | undefined
+}
+
+export function createEngineReaders(deps: EngineReaderDeps) {
+ const states = new Map(Object.values(READER_SERVICES).map((service) => [service as string, { generation: 0, connected: false, pending: 0 }]))
+ const read = async (engine: ReaderEngine, type: string, session: TranscriptSession, ask?: HistoryAsk): Promise<unknown> => {
+ const service = READER_SERVICES[engine]
+ const state = states.get(service)!
+ if (state.pending >= READER_IN_FLIGHT) throw new EngineReadError('ENGINE_BUSY')
+ // A cold request expects the first connection; a reconnect must not validate an older answer.
+ const generation = state.generation + (state.connected ? 0 : 1)
+ state.pending++
+ try {
+ const reply = await deps.call(service, type, {
+ version: READER_VERSION,
+ session: { sessionId: session.sessionId, transcriptPath: session.transcriptPath,
+ touchedAt: session.touchedAt, codexHome: session.codexHome },
+ ...(ask ? { ask: { limit: ask.limit || undefined, before: ask.before } } : {}),
+ }, READER_WAIT_MS)
+ if (reply.error === 'SERVICE_UNAVAILABLE' || reply.error === 'SERVICE_FAILED') throw new EngineReadError('ENGINE_UNAVAILABLE')
+ if (state.generation !== generation) throw new EngineReadError('ENGINE_STALE_REPLY')
+ if (reply.version !== READER_VERSION) throw new EngineReadError('ENGINE_INVALID_REPLY')
+ if (reply.error !== undefined) {
+ throw new EngineReadError(READER_ERRORS.includes(reply.error as EngineReadError['code']) ? reply.error as EngineReadError['code'] : 'ENGINE_INVALID_REPLY')
+ }
+ if (!(type === READER_HISTORY ? historyAnswer(reply.answer) : lastTurnAnswer(reply.answer))) throw new EngineReadError('ENGINE_INVALID_REPLY')
+ return reply.answer
+ } catch (error) {
+ throw error instanceof EngineReadError ? error : new EngineReadError('ENGINE_UNAVAILABLE')
+ } finally { state.pending-- }
+ }
+ const makeReader = (engine: ReaderEngine): EngineTranscript => ({
+ historyPage: (session, ask) => read(engine, READER_HISTORY, session, ask) as Promise<HistoryAnswer>,
+ lastTurnText: async (session) => {
+ if (!session.transcriptPath) return null
+ return read(engine, READER_LAST_TURN, session) as Promise<LastTurnText | null>
+ },
+ })
+ const readers = { claude: makeReader('claude'), codex: makeReader('codex') }
+ return {
+ forEngine(engine: string): EngineTranscript | undefined {
+ if (!readerEngine(engine)) return undefined
+ return deps.isolated.has(READER_SERVICES[engine]) ? readers[engine] : deps.inline?.(engine) ?? readers[engine]
+ },
+ connected(service: string): void {
+ const state = states.get(service)
+ if (state) { state.generation++; state.connected = true }
+ },
+ disconnected(service: string): void {
+ const state = states.get(service)
+ if (state) { state.generation++; state.connected = false }
+ },
+ /** Readers receive a snapshot with each call and have no reason to query or act on the core. */
+ answer(service: string): Record<string, unknown> | null {
+ return states.has(service) ? { error: 'READER_HAS_NO_CORE_CAPABILITIES' } : null
+ },
+ }
+}
diff --git a/cli/src/core/main.ts b/cli/src/core/main.ts
index 21fc22e97..65b2d956e 100644
--- a/cli/src/core/main.ts
+++ b/cli/src/core/main.ts
@@ -87,6 +87,8 @@ import { createInput } from './input.js'
import { createQuestions } from './questions.js'
import { createTurnActivity } from './turns/activity.js'
import { createLastTurnReader } from './transcripts/lastTurn.js'
+import { createEngineReaders } from './engines/readers.js'
+import { READER_SERVICES } from '../engines/worker/protocol.js'
import { createRecaps } from './turns/recaps.js'
import { createUpdateHandoff, handOverOnceReleased, probeStagedMaster, type TeardownStep } from './updateHandoff.js'
import { needsUpdaterBeside, startUpdaterBeside } from './updaterBeside.js'
@@ -783,6 +785,8 @@ async function runForeground(session: AuthSession | null): Promise<void> {
Object.assign(coreApi.terminals, createTerminalSessions({ agents: coreApi.agents, paneState: tmuxPaneState, processState: checkPidRuntime }))
const account = (s = readAuthSession()): GatewayAccount => ({ machineId: s?.machineId ?? null, signIn: signInOf(s?.signInEpoch, s?.signInAcct), autonomousEnv: s?.autonomousEnv ?? env.AUTONOMOUS_ENV })
let serviceLinksRef: ServiceLinks | null = null
+ const engineReaders = createEngineReaders({ isolated: outOfProcess, inline: inline?.engineTranscriptFor,
+ call: (service, type, payload, waitMs) => serviceLinksRef?.call(service, type, payload, waitMs) ?? Promise.resolve({ error: 'SERVICE_UNAVAILABLE' }) })
const gatewayLink = outOfProcess.has('gateway') ? createGatewayLink({
events: backend.fromGateway,
notify: (frame) => serviceLinksRef?.notify('gateway', frame) ?? false,
@@ -976,7 +980,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const neverFoldedHistory = attach.neverFoldedHistory
const replayedFirstTurn = attach.replayedFirstTurn
// A conversation's history, a page at a time, and how long it is (core/transcripts/history.ts).
- const history = createHistory({ resolve: (id) => registry.resolve(id), stopped: () => stoppedAgents.list(),
+ const history = createHistory({ readerFor: engineReaders.forEngine, resolve: (id) => registry.resolve(id), stopped: () => stoppedAgents.list(),
pages: new TranscriptPager(), dbs: { opencode: OPENCODE_DB, kilo: KILO_DB, devin: DEVIN_DB },
hermesDb: (s) => hermesDbForSession(s) })
backend.historyProvider = history.sessionGet
@@ -1046,6 +1050,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// The turn's last text, for its recap, whatever the engine (core/transcripts/lastTurn.ts).
const readLastTurn = createLastTurnReader({
+ readerFor: engineReaders.forEngine,
bySession: (sessionId) => registry.bySession(sessionId),
dbs: { opencode: OPENCODE_DB, kilo: KILO_DB, devin: DEVIN_DB },
hermesDb: (s) => hermesDbForSession(s),
@@ -1140,10 +1145,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// An experiment's process runs once on, the devices' once there is one, models' and the gateway's once needed: a request asks.
// Shell is in the always-running edge host, but its first request can beat that host's connection.
// Hold it through the same bounded startup gate; after any disconnect, fail promptly as before.
- onDemand: new Set([...experiments, ...DEVICES_ON_DEMAND, 'models', 'gateway', 'shell']),
+ onDemand: new Set([...experiments, ...DEVICES_ON_DEMAND, ...Object.values(READER_SERVICES), 'models', 'gateway', 'shell']),
want: (service) => experimentHooks.want(service),
// The gateway's first: its `backend` reads (the device key log) were refused below as NOT_AN_EXPERIMENT.
- answer: async (service, query, payload) => (service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : null) ?? deliveries.answer(service, query, payload)
+ answer: async (service, query, payload) => engineReaders.answer(service) ?? (service === 'gateway' && gatewayLink ? gatewayLink.answer(query, payload) : null) ?? deliveries.answer(service, query, payload)
?? await answerExperimentQuery(coreApi, experiments, service, query, payload)
?? await terminalWatch.answer(service, query, payload)
?? (service === 'orchestrator' ? orchestratorLink.answer(query, payload) : null)
@@ -1162,6 +1167,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
notice: (service, payload) => { if (service === 'gateway') gatewayLink?.notice(payload); else if (service === 'devices') devicesLink.notice(payload); else if (service === 'wifi') wifiLink.notice(payload); else if (service === 'viewers') viewersLink.notice(payload); else if (service === 'recaps') recapsLink.notice(payload) },
binary: (service, bytes) => { if (service === 'gateway') gatewayLink?.binary(bytes) },
connected: (service) => {
+ engineReaders.connected(service)
if (service === 'gateway') gatewayLink?.connected()
if (service === 'teams') teamsLink.on()
if (service === 'devices') devicesLink.connected()
@@ -1169,6 +1175,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
devicesWake.connected(service)
},
disconnected: (service) => {
+ engineReaders.disconnected(service)
if (service === 'gateway') gatewayLink?.disconnected()
if (service === 'devices') devicesLink.disconnected()
if (service === 'wifi') wifiCore.stopped()
diff --git a/cli/src/core/transcripts/history.spec.ts b/cli/src/core/transcripts/history.spec.ts
index 0dd25c71b..09762a313 100644
--- a/cli/src/core/transcripts/history.spec.ts
+++ b/cli/src/core/transcripts/history.spec.ts
@@ -1,3 +1,5 @@
+import { EngineReadError } from '../../engines/worker/protocol.js'
+import { engineTranscriptFor } from '../../engines/transcripts.js'
import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -108,7 +110,7 @@ function transcript(lines: string[], name = 'session.jsonl'): string {
return file
}
-function setup(s?: RegisteredSession, kept: RegisteredSession[] = []) {
+function setup(s?: RegisteredSession, kept: RegisteredSession[] = [], readerFor = engineTranscriptFor) {
const pages = {
claude: vi.fn(async (_path: string, _opts: { limit?: number; before?: string }) => page([], false, null)),
codex: vi.fn(async (_path: string, _opts: { limit?: number; before?: string }) => page([], false, null)),
@@ -118,6 +120,7 @@ function setup(s?: RegisteredSession, kept: RegisteredSession[] = []) {
resolve: vi.fn((id: string) => (s && (id === s.sessionId || id === s.agentId) ? s : undefined)),
stopped: vi.fn(() => kept),
pages,
+ readerFor,
dbs: { opencode: '/stores/opencode.db', kilo: '/stores/kilo.db', devin: '/stores/sessions.db' },
hermesDb: vi.fn(async () => '/profiles/work/state.db'),
}
@@ -543,3 +546,32 @@ describe('asked by agent id', () => {
expect(readAmpThread).toHaveBeenNthCalledWith(2, 'T-0123456789abcdef')
})
})
+
+
+describe('history crossing a reader boundary', () => {
+ it('rejects results for a changed or removed binding, including an in-place mutation', async () => {
+ for (const change of ['mutate', 'remove']) {
+ const s = session('claude', { transcriptPath: '/read.jsonl' })
+ let finish!: () => void
+ const waiting = new Promise<void>((r) => { finish = r })
+ const adapter = { historyPage: async () => { await waiting; return { events: [], timestamp: MTIME.toISOString() } }, lastTurnText: async () => null }
+ const h = setup(s, [], () => adapter)
+ const result = h.sessionGet({ sessionId: s.sessionId })
+ if (change === 'mutate') s.transcriptPath = '/replacement.jsonl'
+ else h.deps.resolve.mockReturnValue(undefined)
+ finish()
+ expect(await result).toEqual({ error: 'ENGINE_STALE_REPLY', retryable: true })
+ }
+ })
+
+ it('returns explicit retry guidance and never invokes the inline pager on a failed worker read', async () => {
+ for (const error of [new EngineReadError('ENGINE_REPLY_TOO_LARGE'), new Error('socket failed')]) {
+ const h = setup(session('codex', { transcriptPath: '/read.jsonl' }), [], () => ({
+ historyPage: async () => { throw error }, lastTurnText: async () => null,
+ }))
+ expect(await h.sessionGet({ sessionId: 'codex-session' })).toEqual(error instanceof EngineReadError
+ ? { error: 'ENGINE_REPLY_TOO_LARGE', retryable: false } : { error: 'ENGINE_UNAVAILABLE', retryable: true })
+ expect(h.pages.codex).not.toHaveBeenCalled()
+ }
+ })
+})
diff --git a/cli/src/core/transcripts/history.ts b/cli/src/core/transcripts/history.ts
index beb94211a..3c94f80ea 100644
--- a/cli/src/core/transcripts/history.ts
+++ b/cli/src/core/transcripts/history.ts
@@ -14,7 +14,9 @@
* four database engines: each had its own copy of the same windowing, and they now share one.
*/
import { stat } from 'node:fs/promises'
-import { engineFor } from '../../engines/registry.js'
+import type { EngineTranscript } from '../../engines/facets/transcript.js'
+import { EngineReadError } from '../../engines/worker/protocol.js'
+import { transcriptReadIdentity } from './readIdentity.js'
import { enrichSubagentStats } from '../../engines/kit/history.js'
import { agyMessagesToEvents } from '../../engines/agy/normalizer.js'
import { ampMessagesToEvents } from '../../engines/amp/normalizer.js'
@@ -48,9 +50,9 @@ export interface HistoryDeps {
/** The conversations kept as stopped harnesses (lib/stoppedAgents.ts): a stop's, an exited engine's,
* and one a restart, a move or a restore had to leave for a new one. */
stopped: () => readonly RegisteredSession[]
- /** Claude Code's and Codex's pages, and every transcript's line count: one pager, so the line index it
- * keeps for a transcript serves both requests and is not built twice. */
+ /** Line counts, and the explicit inline compatibility path's pages. Isolated readers own their indexes. */
pages: Pick<TranscriptPager, 'claude' | 'codex' | 'lineCount'>
+ readerFor: (engine: string) => EngineTranscript | undefined
/** The database engines' stores. */
dbs: { opencode: string; kilo: string; devin: string }
/** Hermes keeps a store per profile: the one this session's lives in. */
@@ -138,7 +140,7 @@ function databasePage<M>(
}
}
-export function createHistory({ resolve, stopped, pages, dbs, hermesDb }: HistoryDeps) {
+export function createHistory({ resolve, stopped, pages, dbs, hermesDb, readerFor }: HistoryDeps) {
// Devin, OpenCode and Kilo keep one store on this machine. Hermes keeps one per HOME, so its path is
// the session's own (`hermesDb`) rather than this machine's default.
const databases = new Map<string, DatabasePage>([
@@ -148,6 +150,8 @@ export function createHistory({ resolve, stopped, pages, dbs, hermesDb }: Histor
['kilo', databasePage((s) => readKiloMessages(dbs.kilo, s.sessionId), kiloMessagesToEvents, windowKiloMessages)],
])
+ const lookup = (id: string) => resolve(id) ?? stopped().find((saved) => saved.sessionId === id)
+
/** The reply to a `session_get` request, for the socket to send as it is. */
const sessionGet = async (payload: Record<string, unknown>): Promise<Record<string, unknown>> => {
const sessionId = payload.sessionId as string | undefined
@@ -157,7 +161,7 @@ export function createHistory({ resolve, stopped, pages, dbs, hermesDb }: Histor
// file (that let a caller read any *.jsonl on the computer, incl. unshared claude history /
// traversal). A kept conversation used to answer NOT_FOUND, so a conversation the daemon had to
// leave for a new one could no longer be read at all (round 24).
- const s = resolve(sessionId) ?? stopped().find((saved) => saved.sessionId === sessionId)
+ const s = lookup(sessionId)
if (!s) return { error: 'NOT_FOUND' }
// The registry finds an agent by its agent id too, and the reply names the id it was asked by. What
// is read is the conversation's own, `s.sessionId`: an engine's store, Amp's export and Cursor's task
@@ -180,10 +184,17 @@ export function createHistory({ resolve, stopped, pages, dbs, hermesDb }: Histor
oldestCursor: null,
}
}
- const engine = engineFor(s.engine)
- if (engine) {
- const { events, timestamp, ...page } = await engine.transcript.historyPage(s, { limit, before }, pages)
- return { id: sessionId, title: projectDisplayName(s), events, timestamp, engine: s.engine, ...page }
+ const reader = readerFor(s.engine)
+ if (reader) {
+ const identity = transcriptReadIdentity(s)
+ try {
+ const { events, timestamp, ...page } = await reader.historyPage(s, { limit, before }, pages)
+ if (transcriptReadIdentity(lookup(sessionId)) !== identity) throw new EngineReadError('ENGINE_STALE_REPLY')
+ return { id: sessionId, title: projectDisplayName(s), events, timestamp, engine: s.engine, ...page }
+ } catch (error) {
+ const failed = error instanceof EngineReadError ? error : new EngineReadError('ENGINE_UNAVAILABLE')
+ return { error: failed.code, retryable: failed.retryable }
+ }
}
// Read from the end and bounded: these engines have no pages of their own yet, and one huge
// transcript read whole would take the whole daemon down (lib/transcriptTail.ts). History past
diff --git a/cli/src/core/transcripts/lastTurn.spec.ts b/cli/src/core/transcripts/lastTurn.spec.ts
index d8def278e..257666b51 100644
--- a/cli/src/core/transcripts/lastTurn.spec.ts
+++ b/cli/src/core/transcripts/lastTurn.spec.ts
@@ -1,3 +1,5 @@
+import { EngineReadError } from '../../engines/worker/protocol.js'
+import { engineTranscriptFor } from '../../engines/transcripts.js'
import { describe, expect, it, vi } from 'vitest'
import type { RegisteredSession } from '../../lib/registry.js'
import { createLastTurnReader } from './lastTurn.js'
@@ -38,6 +40,7 @@ async function reader(sessions: RegisteredSession[]) {
const bySession = new Map(sessions.map((s) => [s.sessionId, s]))
return create({
bySession: (sessionId) => bySession.get(sessionId),
+ readerFor: engineTranscriptFor,
dbs: { opencode: '/db/opencode.db', kilo: '/db/kilo.db', devin: '/db/devin.db' },
hermesDb: async (s) => `/db/hermes-${s.agentId}.db`,
})
@@ -73,3 +76,23 @@ describe('the last turn of each engine', () => {
expect(await read('terminal-s')).toEqual(text('raw: /t/shell.log capped'))
})
})
+
+
+it('drops a recap read when its session binding changes and contains worker failures', async () => {
+ const s = session('claude', '/read.jsonl')
+ const deps = { bySession: () => s, dbs: { opencode: '', kilo: '', devin: '' }, hermesDb: async () => '' }
+ const result = { userMessage: 'question', assistantText: 'answer' }
+ const readerFor = () => ({ historyPage: async () => ({ events: [], timestamp: '' }), lastTurnText: async () => {
+ s.transcriptPath = '/replacement.jsonl'
+ return result
+ } })
+ expect(await createLastTurnReader({ ...deps, readerFor })('claude-s')).toBeNull()
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ try {
+ for (const error of [new EngineReadError('ENGINE_BUSY'), new Error('transport')]) {
+ expect(await createLastTurnReader({ ...deps, readerFor: () => ({ ...readerFor(), lastTurnText: async () => { throw error } }) })('claude-s')).toBeNull()
+ }
+ expect(warn).toHaveBeenCalledWith('[engine claude] last turn unavailable · ENGINE_BUSY')
+ expect(warn).toHaveBeenCalledWith('[engine claude] last turn unavailable · ENGINE_UNAVAILABLE')
+ } finally { warn.mockRestore() }
+})
diff --git a/cli/src/core/transcripts/lastTurn.ts b/cli/src/core/transcripts/lastTurn.ts
index a5a2ba3e8..67faf8907 100644
--- a/cli/src/core/transcripts/lastTurn.ts
+++ b/cli/src/core/transcripts/lastTurn.ts
@@ -9,7 +9,9 @@
*/
import { lastAgyTurnText } from '../../engines/agy/normalizer.js'
import { lastAmpTurnText } from '../../engines/amp/normalizer.js'
-import { engineFor } from '../../engines/registry.js'
+import type { EngineTranscript } from '../../engines/facets/transcript.js'
+import { EngineReadError } from '../../engines/worker/protocol.js'
+import { transcriptReadIdentity } from './readIdentity.js'
import { lastCommandCodeTurnText } from '../../engines/commandcode/normalizer.js'
import { lastCopilotTurnText } from '../../engines/copilot/normalizer.js'
import { lastCursorTurnText } from '../../engines/cursor/normalizer.js'
@@ -30,18 +32,28 @@ import { tailFileCapped } from '../../lib/transcriptTail.js'
export interface LastTurnDeps {
bySession: (sessionId: string) => RegisteredSession | undefined
+ readerFor: (engine: string) => EngineTranscript | undefined
/** The database engines' stores. */
dbs: { opencode: string; kilo: string; devin: string }
/** Hermes keeps a store per profile: the one this session's lives in. */
hermesDb: (s: RegisteredSession) => Promise<string>
}
-export function createLastTurnReader({ bySession, dbs, hermesDb }: LastTurnDeps) {
+export function createLastTurnReader({ bySession, dbs, hermesDb, readerFor }: LastTurnDeps) {
return async (sessionId: string): Promise<LastTurnText | null> => {
const s = bySession(sessionId)
if (!s) return null
- const engine = engineFor(s.engine)
- if (engine) return engine.transcript.lastTurnText(s)
+ const reader = readerFor(s.engine)
+ if (reader) {
+ const identity = transcriptReadIdentity(s)
+ try {
+ const answer = await reader.lastTurnText(s)
+ return transcriptReadIdentity(bySession(sessionId)) === identity ? answer : null
+ } catch (error) {
+ console.warn(`[engine ${s.engine}] last turn unavailable · ${error instanceof EngineReadError ? error.code : 'ENGINE_UNAVAILABLE'}`)
+ return null
+ }
+ }
if (s.engine === 'opencode') return lastOpencodeTurnText(await readOpencodeMessages(dbs.opencode, sessionId))
if (s.engine === 'kilo') return lastKiloTurnText(await readKiloMessages(dbs.kilo, sessionId))
if (s.engine === 'hermes') return lastHermesTurnText(await readHermesMessages(await hermesDb(s), sessionId))
diff --git a/cli/src/core/transcripts/readIdentity.spec.ts b/cli/src/core/transcripts/readIdentity.spec.ts
new file mode 100644
index 000000000..270bdfb18
--- /dev/null
+++ b/cli/src/core/transcripts/readIdentity.spec.ts
@@ -0,0 +1,15 @@
+import { expect, it } from 'vitest'
+import type { RegisteredSession } from '../../lib/registry.js'
+import { transcriptReadIdentity } from './readIdentity.js'
+
+it('copies binding identity before yielding, ignoring ordinary activity updates', () => {
+ const session = { agentId: 'a', sessionId: 's', engine: 'claude', transcriptPath: '/t', codexHome: '/home', boundAt: 1,
+ processIdentity: { pid: 7, startTime: 'one' }, touchedAt: 1 } as unknown as RegisteredSession
+ const before = transcriptReadIdentity(session)
+ expect(transcriptReadIdentity(undefined)).toBe('')
+ session.touchedAt++
+ expect(transcriptReadIdentity(session)).toBe(before)
+ for (const field of ['agentId', 'sessionId', 'engine', 'transcriptPath', 'codexHome', 'boundAt', 'processIdentity']) {
+ expect(transcriptReadIdentity({ ...session, [field]: 'changed' }), field).not.toBe(before)
+ }
+})
diff --git a/cli/src/core/transcripts/readIdentity.ts b/cli/src/core/transcripts/readIdentity.ts
new file mode 100644
index 000000000..99372cc37
--- /dev/null
+++ b/cli/src/core/transcripts/readIdentity.ts
@@ -0,0 +1,7 @@
+import type { RegisteredSession } from '../../lib/registry.js'
+
+/** Copy before yielding: registry rows can be mutated in place while a worker is reading. */
+export function transcriptReadIdentity(session: RegisteredSession | undefined): string {
+ return session ? JSON.stringify([session.agentId, session.sessionId, session.engine, session.transcriptPath,
+ session.codexHome, session.boundAt, session.processIdentity]) : ''
+}
diff --git a/cli/src/engines/README.md b/cli/src/engines/README.md
index ae9548ad8..10392a541 100644
--- a/cli/src/engines/README.md
+++ b/cli/src/engines/README.md
@@ -17,8 +17,9 @@ that stream.
**The engine interface is being migrated in small batches.** Claude Code and Codex now own their
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. These adapters still run in
-the core process: the interface is a code boundary, not a separate worker process. The
+readers. Hook transport, process binding and event delivery stay with core. Claude Code and Codex history/last-turn reads run on demand in supervised workers; the other facets
+still run in core. Explicit inline mode and older masters retain inline readers. See the
+[reader pilot](../../../docs/design/2026-10-07-engine-readers.md) for limits and failure behavior. The
remaining facets and engines still use the shared paths below. This is an internal interface, not an
external plugin API. When extending a migrated facet, put engine behavior in its folder and shared
mechanics in `kit/`. See the [migration design](../../../docs/design/2026-10-05-engine-interface.md)
diff --git a/cli/src/engines/claude/claudeReaderProcess.ts b/cli/src/engines/claude/claudeReaderProcess.ts
new file mode 100644
index 000000000..83f088477
--- /dev/null
+++ b/cli/src/engines/claude/claudeReaderProcess.ts
@@ -0,0 +1,3 @@
+import { runEngineReader, type EngineProcessOptions } from '../worker/process.js'
+
+export const runClaudeReader = (options: EngineProcessOptions) => runEngineReader('claude', options)
diff --git a/cli/src/engines/codex/codexReaderProcess.ts b/cli/src/engines/codex/codexReaderProcess.ts
new file mode 100644
index 000000000..f3c04fc0e
--- /dev/null
+++ b/cli/src/engines/codex/codexReaderProcess.ts
@@ -0,0 +1,3 @@
+import { runEngineReader, type EngineProcessOptions } from '../worker/process.js'
+
+export const runCodexReader = (options: EngineProcessOptions) => runEngineReader('codex', options)
diff --git a/cli/src/engines/facets/transcript.ts b/cli/src/engines/facets/transcript.ts
index 531d80424..3e145f75d 100644
--- a/cli/src/engines/facets/transcript.ts
+++ b/cli/src/engines/facets/transcript.ts
@@ -3,6 +3,8 @@ import type { RegisteredSession } from '../../lib/registry.js'
import type { TranscriptPager } from '../../lib/transcriptPages.js'
export interface HistoryAsk { limit?: number; before?: string }
+/** The reader receives no mutable agent, process, terminal or turn state. */
+export type TranscriptSession = Pick<RegisteredSession, 'sessionId' | 'transcriptPath' | 'touchedAt' | 'codexHome'>
export interface HistoryAnswer {
events: SessionEvent[]
timestamp: string
@@ -11,6 +13,6 @@ export interface HistoryAnswer {
staleCursor?: true
}
export interface EngineTranscript {
- lastTurnText(session: RegisteredSession): Promise<LastTurnText | null>
- historyPage(session: RegisteredSession, ask: HistoryAsk, pages: Pick<TranscriptPager, 'claude' | 'codex'>): Promise<HistoryAnswer>
+ lastTurnText(session: TranscriptSession): Promise<LastTurnText | null>
+ historyPage(session: TranscriptSession, ask: HistoryAsk, pages: Pick<TranscriptPager, 'claude' | 'codex'>): Promise<HistoryAnswer>
}
diff --git a/cli/src/engines/kit/history.ts b/cli/src/engines/kit/history.ts
index 942c603b4..0c203cf13 100644
--- a/cli/src/engines/kit/history.ts
+++ b/cli/src/engines/kit/history.ts
@@ -3,8 +3,7 @@ import { join } from 'node:path'
import { SubagentStats, type SessionEvent } from '../../lib/normalize.js'
import { streamRecords } from '../../lib/transcriptTail.js'
import type { HistoryPage } from '../../lib/transcriptPages.js'
-import type { RegisteredSession } from '../../lib/registry.js'
-import type { HistoryAsk, HistoryAnswer } from '../facets/transcript.js'
+import type { HistoryAsk, HistoryAnswer, TranscriptSession } from '../facets/transcript.js'
/** Fill in missing sub-agent aggregates on tool_end events by reading the sub-agent's own transcript
* (`<session>/subagents/agent-<id>.jsonl`). Async/background launchers only record
@@ -30,7 +29,7 @@ export async function enrichSubagentStats(events: SessionEvent[], transcriptPath
}
/** Bounded paging is shared machinery; each engine supplies its pager and replay rules. */
-export async function pagedHistory(session: RegisteredSession, { limit, before }: HistoryAsk,
+export async function pagedHistory(session: TranscriptSession, { limit, before }: HistoryAsk,
page: (path: string, options: HistoryAsk) => Promise<HistoryPage>, replay: (lines: string[]) => SessionEvent[]): Promise<HistoryAnswer> {
if (!session.transcriptPath) return { events: [], timestamp: new Date(session.touchedAt).toISOString(), hasMore: false, oldestCursor: null }
const found = await page(session.transcriptPath, limit ? { limit, before } : {})
diff --git a/cli/src/engines/registry.spec.ts b/cli/src/engines/registry.spec.ts
index 52b3d20a0..1eee69304 100644
--- a/cli/src/engines/registry.spec.ts
+++ b/cli/src/engines/registry.spec.ts
@@ -6,14 +6,17 @@ import { copyFileSync, mkdtempSync, mkdirSync, rmSync, readFileSync } from 'node
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
+import { engineReaderRequests } from './worker/process.js'
+import { createEngineReaders } from '../core/engines/readers.js'
import { expect, it } from 'vitest'
+import { engineTranscriptFor } from './transcripts.js'
import { engineFor } from './registry.js'
import { createHistory } from '../core/transcripts/history.js'
import { createLastTurnReader } from '../core/transcripts/lastTurn.js'
import { TranscriptPager } from '../lib/transcriptPages.js'
import type { RegisteredSession } from '../lib/registry.js'
-it('preserves recorded history, cursors and last-turn replies for Claude Code and Codex', async () => {
+it.each(['inline', 'worker'])('preserves recorded history, cursors and last-turn replies for Claude Code and Codex (%s)', async (mode) => {
const root = mkdtempSync(join(tmpdir(), 'engine-oracle-'))
const answer: Record<string, unknown> = {}
try {
@@ -22,7 +25,10 @@ it('preserves recorded history, cursors and last-turn replies for Claude Code an
copyFileSync(fileURLToPath(new URL(fixture, import.meta.url)), transcriptPath)
const codexHome = join(root, 'codex-home'); mkdirSync(codexHome, { recursive: true })
const session = { agentId: 'agent', sessionId: 'session', engine, transcriptPath, touchedAt: 1791374400000, cwd: '/fixture', codexHome } as RegisteredSession
- const deps = { resolve: () => session, stopped: () => [], pages: new TranscriptPager(), dbs: { opencode: '', kilo: '', devin: '' }, hermesDb: async () => '' }
+ const requests = engineReaderRequests(engine as 'claude' | 'codex')
+ const port = createEngineReaders({ isolated: new Set([`engine-${engine}`]), call: async (_service, type, payload) => await requests[type](JSON.parse(JSON.stringify(payload)), { owner: true, local: true }) })
+ port.connected(`engine-${engine}`)
+ const deps = { readerFor: mode === 'worker' ? port.forEngine : engineTranscriptFor, resolve: () => session, stopped: () => [], pages: new TranscriptPager(), dbs: { opencode: '', kilo: '', devin: '' }, hermesDb: async () => '' }
const history = createHistory(deps)
const digest = (value: Record<string, unknown>) => {
const { timestamp, ...stable } = value
diff --git a/cli/src/engines/transcripts.ts b/cli/src/engines/transcripts.ts
new file mode 100644
index 000000000..e386d3386
--- /dev/null
+++ b/cli/src/engines/transcripts.ts
@@ -0,0 +1,9 @@
+import type { EngineTranscript } from './facets/transcript.js'
+import { transcript as claude } from './claude/transcript.js'
+import { transcript as codex } from './codex/transcript.js'
+
+/** Only for explicit inline compatibility and tests. Supervised core uses the reader port. */
+export function engineTranscriptFor(engine: string): EngineTranscript | undefined {
+ const transcripts = { claude, codex }
+ return Object.hasOwn(transcripts, engine) ? transcripts[engine as keyof typeof transcripts] : undefined
+}
diff --git a/cli/src/engines/worker/process.spec.ts b/cli/src/engines/worker/process.spec.ts
new file mode 100644
index 000000000..71dbd3c09
--- /dev/null
+++ b/cli/src/engines/worker/process.spec.ts
@@ -0,0 +1,130 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { Asker } from '../../core/api.js'
+import type { EngineTranscript } from '../facets/transcript.js'
+import { engineReaderRequests, runEngineReader } from './process.js'
+import { runClaudeReader } from '../claude/claudeReaderProcess.js'
+import { runCodexReader } from '../codex/codexReaderProcess.js'
+import { READER_HISTORY, READER_IN_FLIGHT, READER_LAST_TURN, READER_REPLY_BYTES, READER_WAIT_MS } from './protocol.js'
+
+vi.mock('../../services/process.js', async (real) => ({ ...await real<object>(), runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))
+const asker: Asker = { owner: true, local: true }
+const session = { sessionId: 'conversation', transcriptPath: '/private/read.jsonl', touchedAt: 1, codexHome: '/private/codex' }
+const page = { events: [], timestamp: '2026-10-07T00:00:00Z' }
+const answer = { userMessage: 'hello', assistantText: 'world' }
+const payload = { version: 1, session, ask: { limit: 3, before: 'cursor' } }
+const deferred = <T>() => { let resolve!: (value: T) => void; const promise = new Promise<T>((r) => { resolve = r }); return { promise, resolve } }
+const failed = (error: string, retryable = true) => ({ version: 1, error, retryable })
+
+function setup() {
+ const adapter = { historyPage: vi.fn(async () => page), lastTurnText: vi.fn(async () => answer) }
+ const load = vi.fn(async () => adapter)
+ const recycle = vi.fn()
+ const requests = engineReaderRequests('claude', { load, recycle })
+ return { requests, adapter, load, recycle, read: (data: Record<string, unknown> = payload, who = asker, signal?: AbortSignal) => requests[READER_HISTORY](data, who, signal) }
+}
+
+afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() })
+
+describe('read-only engine worker', () => {
+ it('loads on first read, shares one adapter and bounded pager, and only passes allowed snapshot fields', async () => {
+ const t = setup()
+ expect(t.load).not.toHaveBeenCalled()
+ expect(await t.read({ ...payload, session: { ...session, agentId: 'do-not-copy', processIdentity: {} } })).toEqual({ version: 1, answer: page })
+ expect(t.adapter.historyPage).toHaveBeenCalledWith(session, payload.ask, expect.objectContaining({}))
+ expect(await t.requests[READER_LAST_TURN]({ version: 1, session }, asker)).toEqual({ version: 1, answer })
+ expect(t.adapter.lastTurnText).toHaveBeenCalledWith(session)
+ expect(t.load).toHaveBeenCalledOnce()
+ expect(await t.read({ version: 1, session: { ...session, sessionId: '', transcriptPath: null, codexHome: undefined }, ask: {} })).toEqual({ version: 1, answer: page })
+ expect(await t.read({ version: 1, session: { ...session, codexHome: null } })).toEqual({ version: 1, answer: page })
+ expect(t.recycle).not.toHaveBeenCalled()
+ })
+
+ it('refuses public callers, unknown versions and invalid request fields before loading a reader', async () => {
+ const t = setup()
+ for (const who of [{ ...asker, owner: false }, { ...asker, local: false }, { ...asker, connection: 'client' }]) {
+ expect(await t.read(payload, who)).toEqual(failed('ENGINE_INVALID_REQUEST', false))
+ }
+ const badSessions = [undefined, null, [], {}, { ...session, sessionId: 1 }, { ...session, sessionId: null }, { ...session, sessionId: 'x'.repeat(201) },
+ ...['relative', '/a\0b', 1, 'x'.repeat(32769)].map(transcriptPath => ({ ...session, transcriptPath })),
+ ...[undefined, Infinity, 8.64e15 + 1].map(touchedAt => ({ ...session, touchedAt })),
+ { ...session, codexHome: 'relative' }]
+ for (const bad of badSessions) expect(await t.read({ ...payload, session: bad })).toEqual(failed('ENGINE_INVALID_REQUEST', false))
+ for (const ask of [null, [], { limit: '1' }, { limit: 0 }, { limit: 1.5 }, { limit: 501 }, { before: 3 }, { before: 'x'.repeat(2001) }]) {
+ expect(await t.read({ ...payload, ask })).toEqual(failed('ENGINE_INVALID_REQUEST', false))
+ }
+ expect(await t.read({ ...payload, version: 2 })).toEqual(failed('ENGINE_INVALID_REQUEST', false))
+ expect(t.load).not.toHaveBeenCalled()
+ })
+
+ it('bounds concurrent work, answers busy immediately, and drops answers for a departed connection', async () => {
+ const t = setup()
+ const work = deferred<typeof page>()
+ t.adapter.historyPage.mockImplementation(() => work.promise)
+ const controller = new AbortController()
+ controller.abort()
+ expect(await t.read(payload, asker, controller.signal)).toEqual(failed('ENGINE_UNAVAILABLE'))
+ const closed = new AbortController()
+ const reads = Array.from({ length: READER_IN_FLIGHT }, () => t.read(payload, asker, closed.signal))
+ expect(await t.read()).toEqual(failed('ENGINE_BUSY'))
+ closed.abort(); work.resolve(page)
+ for (const result of await Promise.all(reads)) expect(result).toEqual(failed('ENGINE_UNAVAILABLE'))
+ expect(await t.read()).toEqual({ version: 1, answer: page })
+ })
+
+ it('recycles a read that hangs asynchronously even while the process can still beat', async () => {
+ vi.useFakeTimers()
+ const t = setup(); const work = deferred<typeof page>()
+ t.adapter.historyPage.mockImplementation(() => work.promise)
+ const read = t.read()
+ await vi.advanceTimersByTimeAsync(READER_WAIT_MS - 1)
+ expect(t.recycle).not.toHaveBeenCalled()
+ await vi.advanceTimersByTimeAsync(1)
+ expect(await read).toEqual(failed('ENGINE_UNAVAILABLE'))
+ expect(t.recycle).toHaveBeenCalledOnce()
+ work.resolve(page)
+ })
+
+ it('uses process exit for the production deadline and cancels deadlines after errors', async () => {
+ vi.useFakeTimers()
+ const exit = vi.spyOn(process, 'exit').mockImplementation(() => undefined as never)
+ const work = deferred<EngineTranscript>()
+ const requests = engineReaderRequests('codex', { load: () => work.promise })
+ const read = requests[READER_LAST_TURN]({ version: 1, session }, asker)
+ await vi.advanceTimersByTimeAsync(READER_WAIT_MS)
+ expect(await read).toEqual(failed('ENGINE_UNAVAILABLE'))
+ expect(exit).toHaveBeenCalledWith(1)
+ work.resolve({ historyPage: async () => page, lastTurnText: async () => answer })
+ await vi.runAllTimersAsync()
+ const t = setup()
+ t.load.mockRejectedValueOnce(new Error('import failed'))
+ await expect(t.read()).rejects.toThrow('import failed')
+ expect(await t.read()).toEqual({ version: 1, answer: page })
+ expect(t.load).toHaveBeenCalledTimes(2)
+ t.adapter.historyPage.mockRejectedValueOnce(new Error('bad file'))
+ await expect(t.read()).rejects.toThrow('bad file')
+ await vi.advanceTimersByTimeAsync(READER_WAIT_MS)
+ expect(t.recycle).not.toHaveBeenCalled()
+ })
+
+ it('rejects oversized serialized replies before sending them to core', async () => {
+ const t = setup()
+ t.adapter.lastTurnText.mockResolvedValue({ ...answer, assistantText: '😺'.repeat(READER_REPLY_BYTES / 4) })
+ expect(await t.requests[READER_LAST_TURN]({ version: 1, session }, asker)).toEqual(failed('ENGINE_REPLY_TOO_LARGE', false))
+ })
+
+ it('uses real readers for both engines and gives each runner only its own authenticated link', async () => {
+ for (const engine of ['claude', 'codex'] as const) {
+ const requests = engineReaderRequests(engine)
+ expect(await requests[READER_LAST_TURN]({ version: 1, session: { ...session, transcriptPath: null } }, asker)).toEqual({ version: 1, answer: null })
+ }
+ const opts = { dataDir: '/private/data', socketPath: '/private/socket', machineId: 'machine', token: 'token' }
+ const requests = setup().requests
+ const run = vi.fn(() => ({ stop: vi.fn() }))
+ for (const [name, start] of [['claude', runClaudeReader], ['codex', runCodexReader]] as const) {
+ const process = start({ ...opts, requests, run })
+ expect(run).toHaveBeenLastCalledWith({ name: `engine-${name}`, socketPath: opts.socketPath, machineId: opts.machineId, token: opts.token, requests })
+ expect(process.stop).toBeTypeOf('function')
+ }
+ expect(runEngineReader('claude', opts).stop).toBeTypeOf('function')
+ })
+})
diff --git a/cli/src/engines/worker/process.ts b/cli/src/engines/worker/process.ts
new file mode 100644
index 000000000..d09bd30cb
--- /dev/null
+++ b/cli/src/engines/worker/process.ts
@@ -0,0 +1,89 @@
+/** One engine's read-only adapter, hosted by the master's existing service supervisor. */
+import { isAbsolute } from 'node:path'
+import type { ServiceRequests } from '../../core/api.js'
+import { TranscriptPager } from '../../lib/transcriptPages.js'
+import { runServiceProcess, type ServiceProcess } from '../../services/process.js'
+import type { ServiceProcessOptions } from '../../serviceProcess.js'
+import type { EngineTranscript, HistoryAsk, TranscriptSession } from '../facets/transcript.js'
+import {
+ EngineReadError, record, READER_HISTORY, READER_IN_FLIGHT, READER_LAST_TURN, READER_REPLY_BYTES,
+ READER_SERVICES, READER_VERSION, READER_WAIT_MS, type ReaderEngine, type ReaderErrorCode,
+} from './protocol.js'
+
+const loadReader = {
+ claude: async () => (await import('../claude/transcript.js')).transcript,
+ codex: async () => (await import('../codex/transcript.js')).transcript,
+}
+const path = (value: unknown): value is string => typeof value === 'string' && value.length <= 32_768
+ && !value.includes('\0') && isAbsolute(value)
+
+function sessionOf(value: unknown): TranscriptSession | null {
+ if (!record(value) || (typeof value.sessionId !== 'string' || value.sessionId.length > 200)
+ || (value.transcriptPath !== null && !path(value.transcriptPath))
+ || typeof value.touchedAt !== 'number' || !Number.isFinite(value.touchedAt) || Math.abs(value.touchedAt) > 8.64e15
+ || (value.codexHome != null && !path(value.codexHome))) return null
+ return { sessionId: value.sessionId, transcriptPath: value.transcriptPath,
+ touchedAt: value.touchedAt, ...(value.codexHome === undefined ? {} : { codexHome: value.codexHome }) }
+}
+
+function askOf(value: unknown): HistoryAsk | null {
+ if (value === undefined) return {}
+ if (!record(value) || (value.limit !== undefined && (typeof value.limit !== 'number' || !Number.isInteger(value.limit) || value.limit < 1 || value.limit > 500))
+ || (value.before !== undefined && (typeof value.before !== 'string' || value.before.length > 2_000))) return null
+ return { limit: value.limit as number | undefined, before: value.before as string | undefined }
+}
+
+export interface ReaderRequestDeps {
+ load?: () => Promise<EngineTranscript>
+ /** A timed-out async read may still hold resources while heartbeats look healthy. Recycle this
+ * worker rather than releasing its slot and accumulating abandoned reads. Never restarts core. */
+ recycle?: () => void
+}
+
+export function engineReaderRequests(engine: ReaderEngine, deps: ReaderRequestDeps = {}): ServiceRequests {
+ const load = deps.load ?? loadReader[engine]
+ const recycle = deps.recycle ?? (() => process.exit(1))
+ // The old shared pager held 256 indexes. Split that bound across the two reader processes.
+ const pages = new TranscriptPager({ capacity: 128 })
+ let reader: Promise<EngineTranscript> | null = null
+ let pending = 0
+ const failure = (code: ReaderErrorCode) => ({ version: READER_VERSION, error: code, retryable: new EngineReadError(code).retryable })
+ const handle = (type: string): ServiceRequests[string] => async (payload, asker, closed) => {
+ // Only core.call supplies an owner without a client connection. These methods are not public routes.
+ if (!asker.owner || !asker.local || asker.connection !== undefined || payload.version !== READER_VERSION) return failure('ENGINE_INVALID_REQUEST')
+ const session = sessionOf(payload.session)
+ const ask = askOf(payload.ask)
+ if (!session || !ask) return failure('ENGINE_INVALID_REQUEST')
+ if (closed?.aborted) return failure('ENGINE_UNAVAILABLE')
+ if (pending >= READER_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')); recycle() }, READER_WAIT_MS)
+ })
+ try {
+ return await Promise.race([deadline, (async () => {
+ // An import failure belongs to this worker; retry a later request if the import was transient.
+ const adapter = await (reader ??= load().catch((error) => { reader = null; throw error }))
+ const answer = type === READER_HISTORY ? await adapter.historyPage(session, ask, pages) : await adapter.lastTurnText(session)
+ if (closed?.aborted) return failure('ENGINE_UNAVAILABLE')
+ const result = { version: READER_VERSION, answer }
+ // Serialization and size accounting happen here, before the result can consume core's memory.
+ return Buffer.byteLength(JSON.stringify(result)) <= READER_REPLY_BYTES ? result : failure('ENGINE_REPLY_TOO_LARGE')
+ })()])
+ } finally { clearTimeout(timer); pending-- }
+ }
+ return { [READER_HISTORY]: handle(READER_HISTORY), [READER_LAST_TURN]: handle(READER_LAST_TURN) }
+}
+
+export interface EngineProcessOptions extends ServiceProcessOptions {
+ run?: typeof runServiceProcess
+ requests?: ServiceRequests
+}
+
+export function runEngineReader(engine: ReaderEngine, options: EngineProcessOptions): ServiceProcess {
+ return (options.run ?? runServiceProcess)({
+ name: READER_SERVICES[engine], socketPath: options.socketPath, machineId: options.machineId,
+ token: options.token, requests: options.requests ?? engineReaderRequests(engine),
+ })
+}
diff --git a/cli/src/engines/worker/protocol.spec.ts b/cli/src/engines/worker/protocol.spec.ts
new file mode 100644
index 000000000..27d9757c7
--- /dev/null
+++ b/cli/src/engines/worker/protocol.spec.ts
@@ -0,0 +1,53 @@
+import { expect, it } from 'vitest'
+import { EngineReadError, historyAnswer, lastTurnAnswer, readerEngine, record } from './protocol.js'
+
+const page = (event: unknown) => ({ timestamp: '2026-10-07T00:00:00Z', events: [event] })
+const events: Array<{ type: string; payload: Record<string, unknown> }> = [
+ { type: 'user_message', payload: { content: 'hello', images: [{ media_type: 'image/png', data: 'data' }] } },
+ { type: 'thinking_delta', payload: { content: 'thinking', thinkingId: 'id' } },
+ { type: 'thinking_title', payload: { title: 'title', thinkingId: 'id' } },
+ { type: 'text_delta', payload: { content: 'answer' } },
+ { type: 'tool_start', payload: { id: 'id', tool: 'Read', input: {}, parentToolUseId: 'parent' } },
+ { type: 'tool_end', payload: { id: 'id', tool: 'Read', output: 'output', summary: 'summary', isError: false,
+ parentToolUseId: 'parent', subagent: { agentId: 'id', agentType: 'type', totalTokens: 1, totalDurationMs: 2, totalToolUseCount: 3 }, durationSeconds: 2 } },
+ { type: 'context_compact', payload: { message: 'compacted', trigger: 'auto' } },
+ { type: 'done', payload: { result: 'done' } },
+]
+
+it('accepts replay events, including absent optional fields, and rejects malformed fields', () => {
+ const optional = new Set(['images', 'thinkingId', 'parentToolUseId', 'subagent', 'durationSeconds', 'trigger'])
+ for (const event of events) {
+ expect(historyAnswer(page(event)), event.type).toBe(true)
+ for (const key of Object.keys(event.payload)) {
+ if (key === 'input') continue // An engine's tool input is intentionally unknown.
+ expect(historyAnswer(page({ ...event, payload: { ...event.payload, [key]: null } })), `${event.type}.${key}`).toBe(false)
+ if (optional.has(key)) expect(historyAnswer(page({ ...event, payload: { ...event.payload, [key]: undefined } }))).toBe(true)
+ }
+ }
+ for (const images of [[null], [{ media_type: null, data: '' }], [{ media_type: '', data: false }]]) {
+ expect(historyAnswer(page({ type: 'user_message', payload: { content: '', images } }))).toBe(false)
+ }
+ const tool = events[5]
+ for (const field of ['agentId', 'agentType', 'totalTokens', 'totalDurationMs', 'totalToolUseCount']) {
+ expect(historyAnswer(page({ ...tool, payload: { ...tool.payload, subagent: { [field]: null } } }))).toBe(false)
+ }
+ expect(historyAnswer(page({ ...tool, payload: { ...tool.payload, subagent: {} } }))).toBe(true)
+ expect(historyAnswer(page({ ...tool, payload: { ...tool.payload, durationSeconds: Infinity } }))).toBe(false)
+ for (const invalid of [null, [], {}, { type: 'done', payload: [] }, { type: 'turn_ended', payload: {} }]) expect(historyAnswer(page(invalid))).toBe(false)
+})
+
+it('validates the envelope, cursor fields and last-turn text without accepting live state', () => {
+ const valid = { timestamp: '2026-10-07T00:00:00Z', events: [], hasMore: false, oldestCursor: 'cursor', staleCursor: true }
+ expect(historyAnswer(valid)).toBe(true)
+ expect(historyAnswer({ ...valid, oldestCursor: null })).toBe(true)
+ for (const invalid of [null, {}, { ...valid, timestamp: 1 }, { ...valid, timestamp: 'invalid' }, { ...valid, events: {} },
+ { ...valid, id: 'override-core-identity' }, { ...valid, engine: 'override' }, { ...valid, hasMore: 'yes' }, { ...valid, oldestCursor: 1 }, { ...valid, staleCursor: false }]) expect(historyAnswer(invalid)).toBe(false)
+ expect(lastTurnAnswer(null)).toBe(true)
+ expect(lastTurnAnswer({ userMessage: '', assistantText: '' })).toBe(true)
+ for (const invalid of [[], undefined, {}, { userMessage: '', assistantText: '', state: 'working' }, { userMessage: '' }, { userMessage: false, assistantText: '' }]) expect(lastTurnAnswer(invalid)).toBe(false)
+ for (const name of ['claude', 'codex']) expect(readerEngine(name)).toBe(true)
+ for (const name of ['', 'constructor', '__proto__', 'pi']) expect(readerEngine(name)).toBe(false)
+ expect(record([])).toBe(false)
+ for (const code of ['ENGINE_INVALID_REQUEST', 'ENGINE_REPLY_TOO_LARGE'] as const) expect(new EngineReadError(code).retryable).toBe(false)
+ expect(new EngineReadError('ENGINE_BUSY').retryable).toBe(true)
+})
diff --git a/cli/src/engines/worker/protocol.ts b/cli/src/engines/worker/protocol.ts
new file mode 100644
index 000000000..e067136ab
--- /dev/null
+++ b/cli/src/engines/worker/protocol.ts
@@ -0,0 +1,72 @@
+/** Private reader messages. These names are never added to the public request router. */
+import type { LastTurnText, SessionEvent } from '../../lib/normalize.js'
+import type { HistoryAnswer } from '../facets/transcript.js'
+
+export const READER_SERVICES = { claude: 'engine-claude', codex: 'engine-codex' } as const
+export type ReaderEngine = keyof typeof READER_SERVICES
+export const READER_VERSION = 1
+export const READER_HISTORY = 'engine_history_page'
+export const READER_LAST_TURN = 'engine_last_turn'
+/** Below the local service transport's 6 MiB ceiling, including its envelope and request id. */
+export const READER_REPLY_BYTES = 4 * 1024 * 1024
+export const READER_IN_FLIGHT = 4
+/** The existing link bounds cold start and execution separately: at most twice this when cold. */
+export const READER_WAIT_MS = 5_000
+
+export const READER_ERRORS = [
+ 'ENGINE_UNAVAILABLE', 'ENGINE_BUSY', 'ENGINE_INVALID_REQUEST', 'ENGINE_INVALID_REPLY',
+ 'ENGINE_REPLY_TOO_LARGE', 'ENGINE_STALE_REPLY',
+] as const
+export type ReaderErrorCode = typeof READER_ERRORS[number]
+
+export class EngineReadError extends Error {
+ constructor(readonly code: ReaderErrorCode) { super(code) }
+ get retryable(): boolean { return this.code !== 'ENGINE_INVALID_REQUEST' && this.code !== 'ENGINE_REPLY_TOO_LARGE' }
+}
+
+export function readerEngine(name: string): name is ReaderEngine { return Object.hasOwn(READER_SERVICES, name) }
+export function record(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
+}
+const optionalString = (value: unknown): boolean => value === undefined || typeof value === 'string'
+const optionalNumber = (value: unknown): boolean => value === undefined || (typeof value === 'number' && Number.isFinite(value))
+
+function subagent(value: unknown): boolean {
+ return value === undefined || (record(value) && optionalString(value.agentId) && optionalString(value.agentType)
+ && optionalNumber(value.totalTokens) && optionalNumber(value.totalDurationMs) && optionalNumber(value.totalToolUseCount))
+}
+
+/** Reject malformed adapter output before handing it to a window; never accept live turn mutations. */
+function event(value: unknown): value is SessionEvent {
+ if (!record(value) || !record(value.payload)) return false
+ const p = value.payload
+ switch (value.type) {
+ case 'user_message':
+ return typeof p.content === 'string' && (p.images === undefined || (Array.isArray(p.images)
+ && p.images.every((image) => record(image) && typeof image.media_type === 'string' && typeof image.data === 'string')))
+ case 'thinking_delta': return typeof p.content === 'string' && optionalString(p.thinkingId)
+ case 'thinking_title': return typeof p.title === 'string' && optionalString(p.thinkingId)
+ case 'text_delta': return typeof p.content === 'string'
+ case 'tool_start': return typeof p.id === 'string' && typeof p.tool === 'string' && optionalString(p.parentToolUseId)
+ case 'tool_end': return typeof p.id === 'string' && typeof p.tool === 'string' && typeof p.output === 'string'
+ && typeof p.summary === 'string' && typeof p.isError === 'boolean' && optionalString(p.parentToolUseId)
+ && subagent(p.subagent) && optionalNumber(p.durationSeconds)
+ case 'context_compact': return typeof p.message === 'string' && optionalString(p.trigger)
+ case 'done': return typeof p.result === 'string'
+ default: return false
+ }
+}
+
+export function historyAnswer(value: unknown): value is HistoryAnswer {
+ return record(value) && Object.keys(value).every(key => ['events', 'timestamp', 'hasMore', 'oldestCursor', 'staleCursor'].includes(key))
+ && typeof value.timestamp === 'string' && Number.isFinite(Date.parse(value.timestamp))
+ && Array.isArray(value.events) && value.events.every(event)
+ && (value.hasMore === undefined || typeof value.hasMore === 'boolean')
+ && (value.oldestCursor === undefined || value.oldestCursor === null || typeof value.oldestCursor === 'string')
+ && (value.staleCursor === undefined || value.staleCursor === true)
+}
+
+export function lastTurnAnswer(value: unknown): value is LastTurnText | null {
+ return value === null || (record(value) && Object.keys(value).every(key => key === 'userMessage' || key === 'assistantText')
+ && typeof value.userMessage === 'string' && typeof value.assistantText === 'string')
+}
diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.ts
index 57819b7be..a89da7629 100644
--- a/cli/src/harnessd/services.spec.ts
+++ b/cli/src/harnessd/services.spec.ts
@@ -302,6 +302,17 @@ describe('ServiceSupervisor', () => {
expect(supervisor.status().map((status) => status.state)).toEqual(['stopped', 'stopped'])
})
+ it('leaves the new reader workers off for old cores that already read inline, and starts only the requested engine', () => {
+ const specs = serviceSpecs({}, SERVICE_HOSTS).filter(spec => spec.name.startsWith('engine-'))
+ expect(specs.map(spec => spec.name)).toEqual(['engine-claude', 'engine-codex'])
+ const supervisor = make(specs)
+ supervisor.start()
+ for (const protocol of [0, 1, 2, 3, 4]) supervisor.unasked(protocol)
+ expect(children).toHaveLength(0)
+ supervisor.want('engine-codex')
+ expect(children.map(child => child.spec.name)).toEqual(['engine-codex'])
+ })
+
it('starts an experiment\'s process only once the core asks for one of its services, and keeps it like any other', () => {
const experiment: ServiceSpec = { name: 'experiments', services: ['orchestrator', 'teams'], heapLimitMiB: 256, rssLimitMiB: 512, onDemand: true }
const supervisor = make([search, experiment])
diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.ts
index 5f1e1785d..cef1df4f6 100644
--- a/cli/src/harnessd/services.ts
+++ b/cli/src/harnessd/services.ts
@@ -365,6 +365,11 @@ export type ServiceHostSpec = Omit<ServiceSpec, 'name'>
* would cost that four times.
*/
export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {
+ // New read-only workers have no older-core startup obligation: old cores read inline and never ask.
+ // Each holds at most four reads, a 128-entry pager and replies capped at 4 MiB. The heap limit
+ // contains transient parsing; RSS additionally bounds file buffers outside V8's heap.
+ 'engine-claude': { services: ['engine-claude'], heapLimitMiB: 512, rssLimitMiB: 1_024, onDemand: true, askedSince: 0 },
+ 'engine-codex': { services: ['engine-codex'], heapLimitMiB: 512, rssLimitMiB: 1_024, onDemand: true, askedSince: 0 },
search: { services: ['search'], heapLimitMiB: 1_024, rssLimitMiB: 2_048 },
// Its file watches on every harness's workspace; the viewer servers it starts are processes of their
// own, outside this budget. The Store beside them: its installs run git and the harnesses' toolchains
diff --git a/cli/src/leanEntry.spec.ts b/cli/src/leanEntry.spec.ts
index 86ad23648..78e16e07b 100644
--- a/cli/src/leanEntry.spec.ts
+++ b/cli/src/leanEntry.spec.ts
@@ -21,6 +21,8 @@ const CLI_ROOT = fileURLToPath(new URL('..', import.meta.url))
const ROLES = ['master', 'core', ...KNOWN_SERVICES, 'updater']
const RUNNER: Record<string, string> = { master: 'masterProcess', core: 'core-coreProcess' }
for (const name of [...KNOWN_SERVICES, 'updater']) RUNNER[name] = `${name}Process`
+RUNNER['engine-claude'] = 'claudeReaderProcess'
+RUNNER['engine-codex'] = 'codexReaderProcess'
describe('the lean bundle a release carries', () => {
let scratch = ''
@@ -117,7 +119,7 @@ describe('the lean bundle a release carries', () => {
it('brings no zod to the master, search, the updater or the edge host', () => {
expect(hasZod(new Set(files.keys())), 'the bundle still holds zod, for the services whose own code uses it').toBe(true)
// The edge host's services share one process: zod in any of them would be in all of them.
- for (const role of ['master', 'search', 'updater', ...SERVICE_HOSTS.edge.services]) expect(hasZod(loads(role)), role).toBe(false)
+ for (const role of ['master', 'search', 'updater', 'engine-claude', 'engine-codex', ...SERVICE_HOSTS.edge.services]) expect(hasZod(loads(role)), role).toBe(false)
})
it('brings the edge host no node:sqlite until it reads a store some engines keep a conversation in', () => {
diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.ts
index a949475b6..6ef72d565 100644
--- a/cli/src/serviceProcess.ts
+++ b/cli/src/serviceProcess.ts
@@ -28,6 +28,8 @@ const BESIDE_THE_CORE: ReadonlySet<string> = new Set(['updater'])
/** Every service this build can run in its own process, and how to load its runner alone. */
export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new Map<string, () => Promise<Runner>>([
+ ['engine-claude', async () => (await import('./engines/claude/claudeReaderProcess.js')).runClaudeReader],
+ ['engine-codex', async () => (await import('./engines/codex/codexReaderProcess.js')).runCodexReader],
['search', async () => (await import('./services/searchProcess.js')).runSearchService],
['viewers', async () => (await import('./services/viewersProcess.js')).runViewersService],
['workspaces', async () => (await import('./services/workspacesProcess.js')).runWorkspacesService],
diff --git a/cli/src/services/AGENTS.md b/cli/src/services/AGENTS.md
index dcf94d188..43c0c570e 100644
--- a/cli/src/services/AGENTS.md
+++ b/cli/src/services/AGENTS.md
@@ -51,6 +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/last-turn readers (`src/engines/worker/`) | engine parsing outside core; read-only snapshots and no core capabilities | 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 94aefde29..fc05a7908 100644
--- a/cli/src/services/inline.spec.ts
+++ b/cli/src/services/inline.spec.ts
@@ -1,4 +1,5 @@
import { describe, expect, it } from 'vitest'
+import { engineTranscriptFor } from '../engines/transcripts.js'
import { startGateway } from '../gateway/start.js'
import { startCommandBar } from './commandBar.js'
import { startDevices } from './devices.js'
@@ -22,6 +23,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({ startCommandBar, startDevices, startHandoff, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startSearch, startSharing, startShell, startStore, startTeamsInCore, startUsage, startViewers, startWifi, startWindowNames, startWorkspaces })
+ expect({ ...inline }).toEqual({ engineTranscriptFor, 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 4083a1ac8..8eac27305 100644
--- a/cli/src/services/inline.ts
+++ b/cli/src/services/inline.ts
@@ -12,6 +12,7 @@
* target, and its test"). The core still routes these services' requests and holds their fallbacks: both are
* declared in core/api.ts, which it loads either way.
*/
+export { engineTranscriptFor } from '../engines/transcripts.js'
export { startGateway } from '../gateway/start.js'
export { startCommandBar } from './commandBar.js'
export { startDevices } from './devices.js'
diff --git a/cli/src/testing/socketCore.ts b/cli/src/testing/socketCore.ts
index fabcd7200..6afe07965 100644
--- a/cli/src/testing/socketCore.ts
+++ b/cli/src/testing/socketCore.ts
@@ -16,6 +16,7 @@ import { createAgentList, type AgentListDeps } from '../core/agents/list.js'
import { createAgentUpdate } from '../core/agents/update.js'
import { createMessageRequest } from '../core/input.js'
import { createQuestionResponse } from '../core/questions.js'
+import { engineTranscriptFor } from '../engines/transcripts.js'
import { createHistory } from '../core/transcripts/history.js'
import { createTerminalRequests, type TerminalRequestDeps } from '../core/terminals/requests.js'
import { createCancelRequest } from '../core/turns/cancel.js'
@@ -32,6 +33,7 @@ import { tmuxPaneInfo } from '../lib/tmux.js'
* harnesses, and a pager of their own. */
export function bindHistory(socket: BackendSocket): void {
const history = createHistory({
+ readerFor: engineTranscriptFor,
resolve: (id) => registry.resolve(id),
stopped: () => stoppedAgents.list(),
pages: new TranscriptPager(),
diff --git a/docs/design/2026-10-05-engine-interface.md b/docs/design/2026-10-05-engine-interface.md
index 42e855d17..caa40c3a6 100644
--- a/docs/design/2026-10-05-engine-interface.md
+++ b/docs/design/2026-10-05-engine-interface.md
@@ -1,5 +1,10 @@
# Engines behind one interface
+> Process pilot: Claude Code and Codex history/last-turn reads now run in supervised workers. Other
+> facets remain in core. See [the reader contract](2026-10-07-engine-readers.md) for scope, limits,
+> failure behavior and compatibility. This is not complete engine isolation.
+
+
> **Status, 2026-10-07: resumed by the owner, a few engines per batch.** The first batch moves Claude
> Code and Codex launch contracts, paged history and last-turn reads behind an `Engine` interface. It
> preserves their existing argv and transcript behavior. The second batch moves their hook installation,
diff --git a/docs/design/2026-10-07-engine-readers.md b/docs/design/2026-10-07-engine-readers.md
new file mode 100644
index 000000000..16e85b1fd
--- /dev/null
+++ b/docs/design/2026-10-07-engine-readers.md
@@ -0,0 +1,51 @@
+# Engine reader process pilot
+
+[Issue #1014](https://github.com/autonomous-ai/openharness/issues/1014) records the private protocol
+before implementation. This is the first process boundary in the
+[engine interface migration](2026-10-05-engine-interface.md).
+
+Only Claude Code and Codex `historyPage` and `lastTurnText` run in these workers. Their recorded
+history, cursor and last-turn fixtures are the compatibility oracle. Launches, hooks, discovery,
+resume, live ingestion, screen/input and models have not moved to a worker. Core remains the sole
+owner of sessions, bindings, turns and terminal access.
+
+## Contract
+
+| ID | Guarantee |
+|---|---|
+| ER-001 | The master starts `engine-claude` or `engine-codex` on its first read. Each uses the existing service supervisor, authenticated local link, heartbeat watch, restart backoff and crash parking. An empty daemon starts neither worker. |
+| ER-002 | Private version 1 messages contain only session id, transcript path, touched time, optional Codex home, and pagination arguments. They carry no registry, turn, terminal, credentials or callable core capability. Core denies every query from these readers; clients cannot route these private request types. |
+| ER-003 | Core and worker each admit at most four concurrent reads per engine, rejecting excess with `ENGINE_BUSY`. There is no unbounded queue. A link waits at most five seconds for startup and five for execution. A worker recycles itself when an asynchronous read lasts five seconds; a blocked event loop is contained by the master's heartbeat watch. |
+| ER-004 | Each worker has a 512 MiB V8 heap limit and 1 GiB RSS budget. It owns a 128-entry pager. Existing bounded file readers remain bounded. Serialized replies over 4 MiB are rejected before transport, beneath the local service transport's 6 MiB ceiling. These are containment limits, not expected steady-state usage. |
+| ER-005 | Replies use the existing unique request id and private protocol version. Core validates their replay-event shape, rejects a reply from an earlier connection generation, and rejects a read when the requested session's binding changed while it was pending. Registry identity is copied before yielding because rows can mutate in place. |
+| ER-006 | Disconnects, timeouts and failed reads are not replayed or retried inline. History returns an explicit error and retryability. A missing last-turn read yields no recap text. After recovery, a new request may read again; no turn or input is replayed. |
+| ER-007 | Explicit inline mode and an older master that does not report hosting these readers retain the existing inline implementation. Capability is determined from the master's reported process list. These are new optional workers, so `askedSince: 0` prevents an old core from starting workers it cannot use; the existing protocol 4 `want` message needs no change. |
+
+`core/engines/readers.ts` is the injected port; `engines/worker/protocol.ts` is its small value-only
+contract; `engines/worker/process.ts` owns reader execution. The master imports none of them.
+`services/inline.ts` is the existing explicit compatibility import. Architecture and lean-bundle tests
+keep the worker and reader implementations outside supervised core's import closure.
+
+There is one intentional limit on formerly successful replies: a legacy full-history request whose
+normalized answer exceeds 4 MiB returns `ENGINE_REPLY_TOO_LARGE`, with `retryable: false`. Request a
+smaller page; retrying the same oversized read will not help. A single enormous event can exceed that
+limit even with a one-record page. This pilot does not silently truncate such an event or introduce a
+second streaming protocol.
+
+The process boundary contains crashes, allocation pressure and hangs. It is not an OS security
+sandbox: workers run as the same user and can read that user's files. Capability denial is an API
+ownership rule, not protection from arbitrary native code in the worker.
+
+## Proof and next boundary
+
+Unit tests cover malformed requests/replies, overload, worker deadlines, lost/replaced connections,
+changed bindings, private capability denial and the original recorded replies. The daemon test covers
+demand startup, normal pages and recap text, kill, freeze, memory restart and crash parking while
+core and engine processes survive. Soak/chaos includes both workers in every process/fault pair.
+The optional `PERF_READERS=1` workload adds history reads every two seconds and measures core plus
+reader CPU and RSS, together with request and turn latency. Reports identify the exact bundle; short
+runs do not establish long-term leak freedom. Validation results and durations belong in the PR.
+
+Moving live ingestion and hooks next requires a distinct transition contract: core-issued binding
+and turn generations, ordered events, bounded buffering, and replay/resynchronization rules. This
+read-only pilot does not establish those guarantees and is not complete engine isolation.