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.

Introduce engine contracts for Claude Code and Codex (#1010)

Dee9f0677f220df
diff --git a/cli/src/core/transcripts/history.ts b/cli/src/core/transcripts/history.ts
index ac88e87a0..beb94211a 100644
--- a/cli/src/core/transcripts/history.ts
+++ b/cli/src/core/transcripts/history.ts
@@ -14,12 +14,11 @@
* four database engines: each had its own copy of the same windowing, and they now share one.
*/
import { stat } from 'node:fs/promises'
-import { join } from 'node:path'
+import { engineFor } from '../../engines/registry.js'
+import { enrichSubagentStats } from '../../engines/kit/history.js'
import { agyMessagesToEvents } from '../../engines/agy/normalizer.js'
import { ampMessagesToEvents } from '../../engines/amp/normalizer.js'
import { ampThreadToEvents, readAmpThread } from '../../engines/amp/threadExport.js'
-import { codexMessagesToEvents } from '../../engines/codex/normalizer.js'
-import { codexSubagentResolverFor } from '../../engines/codex/subagent.js'
import { commandcodeMessagesToEvents, windowCommandCodeLines } from '../../engines/commandcode/normalizer.js'
import { copilotMessagesToEvents } from '../../engines/copilot/normalizer.js'
import { cursorConfigDir, cursorDataDir } from '../../engines/cursor/home.js'
@@ -38,10 +37,10 @@ import { readOpencodeMessages } from '../../engines/opencode/reader.js'
import { piMessagesToEvents, windowPiLines } from '../../engines/pi/normalizer.js'
import { sid } from '../../lib/log.js'
import { lastActivityAt } from '../../lib/agentFrame.js'
-import { messagesToEvents, SubagentStats, windowRawLines, type SessionEvent } from '../../lib/normalize.js'
+import { messagesToEvents, windowRawLines, type SessionEvent } from '../../lib/normalize.js'
import { projectDisplayName, type RegisteredSession } from '../../lib/registry.js'
import type { TranscriptPager } from '../../lib/transcriptPages.js'
-import { streamRecords, tailFileCapped, WHOLE_READ_CAP_BYTES } from '../../lib/transcriptTail.js'
+import { tailFileCapped, WHOLE_READ_CAP_BYTES } from '../../lib/transcriptTail.js'
export interface HistoryDeps {
/** The registry's lookup, by agent or session id. */
@@ -102,29 +101,6 @@ export function copilotHistoryPage(lines: string[], paginated: boolean):
return paginated ? { events, hasMore: false, oldestCursor: null } : { events }
}
-/** 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
- * `{status:'async_launched', agentId}` in the main transcript — without this join the delegation
- * card shows "0 tools · worked for 0s" forever. Best-effort per agent; missing files are skipped. */
-async function enrichSubagentStats(events: SessionEvent[], transcriptPath: string): Promise<void> {
- const subagentsDir = join(transcriptPath.replace(/\.jsonl$/, ''), 'subagents')
- for (const e of events) {
- if (e.type !== 'tool_end') continue
- const sub = e.payload.subagent
- if (!sub?.agentId || typeof sub.totalToolUseCount === 'number') continue
- try {
- // A line at a time: a long sub-agent's transcript is never held whole to count its calls.
- const file = join(subagentsDir, `agent-${sub.agentId}.jsonl`)
- const totals = new SubagentStats()
- await streamRecords(file, 0, (await stat(file)).size, (line) => { totals.push(line) }, () => true)
- const stats = totals.result()
- sub.totalToolUseCount = stats.totalToolUseCount
- if (sub.totalDurationMs === undefined) sub.totalDurationMs = stats.totalDurationMs
- if (sub.totalTokens === undefined) sub.totalTokens = stats.totalTokens
- } catch { /* subagent transcript absent (still spawning / pruned) — leave as-is */ }
- }
-}
-
/** What a window asks for: `limit` records before the `before` cursor. No limit asks for all of them. */
interface PageAsk { limit?: number; before?: string }
@@ -204,33 +180,10 @@ export function createHistory({ resolve, stopped, pages, dbs, hermesDb }: Histor
oldestCursor: null,
}
}
- if (s.engine === 'claude' || s.engine === 'codex') {
- // Only the page asked for is read (lib/transcriptPages.ts): the whole history of a long session
- // is more memory than the daemon has. Without a limit, the newest lines that fit a page, and
- // the cursor to the rest when they do not all fit — a cursor the full-transcript reply never had.
- const opts = limit ? { limit, before } : {}
- const page = s.engine === 'codex'
- ? await pages.codex(s.transcriptPath, opts)
- : await pages.claude(s.transcriptPath, opts)
- const st = await stat(s.transcriptPath).catch(() => null)
- const timestamp = new Date(st?.mtimeMs ?? Date.now()).toISOString()
- if (page.staleCursor) {
- return { id: sessionId, title: projectDisplayName(s), events: [], timestamp, engine: s.engine, hasMore: false, oldestCursor: null, staleCursor: true }
- }
- const events = s.engine === 'codex'
- ? codexMessagesToEvents(page.lines, codexSubagentResolverFor(s.codexHome))
- : messagesToEvents(page.lines)
- await enrichSubagentStats(events, s.transcriptPath)
- // Older pages must not inject a spurious end-of-transcript marker mid-scroll.
- if (limit && before && events[events.length - 1]?.type === 'done') events.pop()
- return {
- id: sessionId,
- title: projectDisplayName(s),
- events,
- timestamp,
- engine: s.engine,
- ...(limit || page.hasMore ? { hasMore: page.hasMore, oldestCursor: page.oldestCursor } : {}),
- }
+ 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 }
}
// 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.ts b/cli/src/core/transcripts/lastTurn.ts
index 2c6182b5b..a5a2ba3e8 100644
--- a/cli/src/core/transcripts/lastTurn.ts
+++ b/cli/src/core/transcripts/lastTurn.ts
@@ -9,7 +9,7 @@
*/
import { lastAgyTurnText } from '../../engines/agy/normalizer.js'
import { lastAmpTurnText } from '../../engines/amp/normalizer.js'
-import { readLastCodexTurnText } from '../../engines/codex/lastTurn.js'
+import { engineFor } from '../../engines/registry.js'
import { lastCommandCodeTurnText } from '../../engines/commandcode/normalizer.js'
import { lastCopilotTurnText } from '../../engines/copilot/normalizer.js'
import { lastCursorTurnText } from '../../engines/cursor/normalizer.js'
@@ -24,9 +24,9 @@ import { lastMuseTurnText } from '../../engines/muse/normalizer.js'
import { lastOpencodeTurnText } from '../../engines/opencode/normalizer.js'
import { readOpencodeMessages } from '../../engines/opencode/reader.js'
import { lastPiTurnText } from '../../engines/pi/normalizer.js'
-import { lastTurnTextFromRawLines, selectClaudeRecapLine, type LastTurnText } from '../../lib/normalize.js'
+import { lastTurnTextFromRawLines, type LastTurnText } from '../../lib/normalize.js'
import type { RegisteredSession } from '../../lib/registry.js'
-import { tailFileCapped, tailFileUntil } from '../../lib/transcriptTail.js'
+import { tailFileCapped } from '../../lib/transcriptTail.js'
export interface LastTurnDeps {
bySession: (sessionId: string) => RegisteredSession | undefined
@@ -40,14 +40,13 @@ export function createLastTurnReader({ bySession, dbs, hermesDb }: 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)
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))
if (s.engine === 'devin') return lastDevinTurnText(await readDevinMessages(dbs.devin, sessionId))
if (!s.transcriptPath) return null
- if (s.engine === 'codex') return readLastCodexTurnText(s.transcriptPath)
- // Its last turn, read backward — not the whole conversation once per turn end.
- if (s.engine === 'claude') return lastTurnTextFromRawLines(await tailFileUntil(s.transcriptPath, selectClaudeRecapLine))
// Bounded from the end like every whole read of an engine without pages (lib/transcriptTail.ts):
// the last turn is at the end, and a transcript past the cap would otherwise be read whole at
// every turn's end.
diff --git a/cli/src/dsh/adapters.ts b/cli/src/dsh/adapters.ts
index 2aae1307f..d908712a0 100644
--- a/cli/src/dsh/adapters.ts
+++ b/cli/src/dsh/adapters.ts
@@ -4,6 +4,8 @@
* support is an optional optimization rather than a condition for running a harness.
* Contracts and primary sources: store/spec/portability.md.
*/
+import { harnessAdapters } from '../engines/launches.js'
+export { codexEnvArgs } from '../engines/launches.js'
import type { AgentEngine, ProcessEngine } from '../engines/types.js'
export interface HarnessAdapter {
@@ -14,26 +16,8 @@ export interface HarnessAdapter {
envArgs?: (env: Record<string, string>) => string[]
}
-/** What `-c a.b.NAME=…` can address: Codex splits the key on dots, so a name must be a bare key. */
-const CODEX_ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/
-
-/**
- * Codex runs a session's commands in a shared app server (`codex app-server --managed-daemon`, codex-cli
- * 0.159.3), not under the process Harness launched, so they never see that process's environment.
- * Measured: HARNESS_CONTEXT_FILE and every manifest variable were unset in the agent's shell, and the
- * Model Manager ran without its instructions. `shell_environment_policy.set` is what Codex itself gives
- * every command, and `-c` carries it to whichever process runs them. The value is a JSON string, which
- * TOML reads as the same string.
- */
-export function codexEnvArgs(env: Record<string, string>): string[] {
- return Object.entries(env)
- .filter(([name]) => CODEX_ENV_NAME.test(name))
- .flatMap(([name, value]) => ['-c', `shell_environment_policy.set.${name}=${JSON.stringify(value)}`])
-}
-
export const HARNESS_ADAPTERS = {
- claude: { instructionFiles: ['CLAUDE.md'], contextArgs: (file: string) => ['--append-system-prompt', `Read the harness context at ${JSON.stringify(file)} before working.`] },
- codex: { instructionFiles: ['AGENTS.override.md', 'AGENTS.md'], envArgs: codexEnvArgs },
+ ...harnessAdapters,
cursor: { instructionFiles: ['AGENTS.md'] },
opencode: { instructionFiles: ['AGENTS.md', 'CLAUDE.md'] },
pi: { instructionFiles: ['AGENTS.md', 'CLAUDE.md'], contextArgs: (file: string) => ['--append-system-prompt', file] },
diff --git a/cli/src/engines/README.md b/cli/src/engines/README.md
index a3cc74ce9..8bfb4d6d9 100644
--- a/cli/src/engines/README.md
+++ b/cli/src/engines/README.md
@@ -14,13 +14,13 @@ agent already writes* and turns it into a live event stream: turns, tool calls,
sub-agents, questions, completion. An engine is the translator between your agent's transcript and
that stream.
-**Set expectations before you start.** This is not a plugin API. There is no registry to append to
-and no interface to implement in one file. The codebase branches on `session.engine` in about twenty
-shared files, and a new engine touches most of them. That is a real cost and we are not going to
-pretend otherwise — but it is a *known* list, not a search, and this page is that list in dependency
-order. Two engines were each added in a single commit — Muse Code (`b6c58e6`) and Amp (`f15924f`) —
-and reading either alongside this page shows every item below in context. Read Amp's if your agent
-does not write a transcript at all; see "When your agent writes nothing to disk".
+**The engine interface is being migrated in small batches.** Claude Code and Codex now own their
+launch contracts and the history/last-turn readers behind `Engine` (`engine.ts`). `registry.ts` selects
+those engines; `launches.ts` exposes their launch metadata without loading transcript readers. 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)
+for the remaining work.
**Launchers are not engines.** A wrapper that configures an environment and then hands the pane to a
vendor CLI — `ori claude`, an `env`-prefixed alias, a shell function — produces an agent of the
diff --git a/cli/src/engines/__fixtures__/transcript-contracts.json b/cli/src/engines/__fixtures__/transcript-contracts.json
new file mode 100644
index 000000000..b2f6750ad
--- /dev/null
+++ b/cli/src/engines/__fixtures__/transcript-contracts.json
@@ -0,0 +1,101 @@
+{
+ "claude": {
+ "whole": {
+ "sha256": "2823dd089ba9945ed35023c1f9daafc9d076b324ee6868806371fdee3d0be839",
+ "eventTypes": [
+ "user_message",
+ "tool_start",
+ "tool_end",
+ "tool_start",
+ "tool_end",
+ "tool_start",
+ "tool_end",
+ "text_delta",
+ "text_delta",
+ "text_delta",
+ "text_delta",
+ "done"
+ ],
+ "hasMore": null,
+ "oldestCursor": null
+ },
+ "latest": {
+ "sha256": "d231981690953025df01629ab9852098bf258c6974e2859c688370663802489a",
+ "eventTypes": [
+ "user_message",
+ "tool_start",
+ "tool_end",
+ "tool_start",
+ "tool_end",
+ "tool_start",
+ "tool_end",
+ "text_delta",
+ "text_delta",
+ "text_delta",
+ "text_delta",
+ "done"
+ ],
+ "hasMore": false,
+ "oldestCursor": "1fb3dd23-973c-4021-8ab4-e7b4ba90dd72"
+ },
+ "older": {
+ "sha256": "f60bb1820fb66bd91852af08030f45c1541dc6daf016975a8a5fcbec4d81f072",
+ "eventTypes": [],
+ "hasMore": false,
+ "oldestCursor": "1fb3dd23-973c-4021-8ab4-e7b4ba90dd72"
+ },
+ "stale": {
+ "sha256": "b68ad7d9e7a3a5f1a41946c3de08533975c510cf5b594d8bfba4f30086faea21",
+ "eventTypes": [],
+ "hasMore": false,
+ "oldestCursor": null
+ },
+ "lastTurn": {
+ "userMessage": "Chạy 3 sub-agent SONG SONG (launch cả 3 cùng một lượt), mỗi agent một việc độc lập rồi báo cáo lại:\n- Agent 1: Report giá coin BTC\n- Agent 2: Report giá coin ETH\n- Agent 3: Report giá coin BNB",
+ "assistantText": "Đã spawn 3 sub-agent song song cho BTC, ETH, BNB. Sẽ báo kết quả khi cả ba hoàn thành.\n\nSub-agent ETH xong: **~$1,860–$1,870** (~$225.36 tỷ vốn hóa). Đang chờ BTC, BNB.\n\nSub-agent BNB xong: **~$590.04** (+0.72% 24h). Chỉ còn chờ BTC.\n\nCả 3 sub-agent đã hoàn thành. Tổng hợp giá coin:\n\n| Coin | Giá (USD) | Thay đổi 24h | Vốn hóa thị trường |\n|---|---|---|---|\n| **BTC** | ~$63,500–$63,900 | +2.1% | ~$1,281 tỷ (#1) |\n| **ETH** | ~$1,860–$1,870 | ~+0.5–1.2% (chênh lệch giữa sàn) | ~$225.36 tỷ (#2) |\n| **BNB** | ~$590.04 | +0.72% | ~$78.57 tỷ (#4) |"
+ }
+ },
+ "codex": {
+ "whole": {
+ "sha256": "8181de8d8f57eafa6ca4fb01e94edf52abda2bc43611cb19533a9d8a7a03a169",
+ "eventTypes": [
+ "tool_start",
+ "tool_end",
+ "tool_start",
+ "tool_end",
+ "tool_start",
+ "tool_end",
+ "done"
+ ],
+ "hasMore": null,
+ "oldestCursor": null
+ },
+ "latest": {
+ "sha256": "07bd80e0799626ecb7a0f4393012df7ae0173db38a87687583293d8de6aa477f",
+ "eventTypes": [
+ "tool_start",
+ "tool_end",
+ "tool_start",
+ "tool_end",
+ "tool_start",
+ "tool_end",
+ "done"
+ ],
+ "hasMore": false,
+ "oldestCursor": "codex:0"
+ },
+ "older": {
+ "sha256": "268c766445dbece44dd2fae88f22669c88237bf5b4eb3e1bf3e07faf707ea8c8",
+ "eventTypes": [],
+ "hasMore": false,
+ "oldestCursor": "codex:0"
+ },
+ "stale": {
+ "sha256": "8c7f0262563ebce6a6af1d160fc65dc3f366d20d351fcd59e90d97126d54c575",
+ "eventTypes": [],
+ "hasMore": false,
+ "oldestCursor": null
+ },
+ "lastTurn": null
+ }
+}
diff --git a/cli/src/engines/claude/launch.ts b/cli/src/engines/claude/launch.ts
new file mode 100644
index 000000000..9112674b4
--- /dev/null
+++ b/cli/src/engines/claude/launch.ts
@@ -0,0 +1,16 @@
+import type { EngineLaunch } from '../facets/launch.js'
+
+// The existing CLI contracts: auto still runs Claude Code's safety checks; full is explicit.
+const permissionModes = {
+ auto: ['--permission-mode', 'auto'],
+ acceptEdits: ['--permission-mode', 'acceptEdits'],
+ plan: ['--permission-mode', 'plan'],
+ ask: [],
+ full: ['--dangerously-skip-permissions'],
+}
+export const launch: EngineLaunch = {
+ permissionModes, bypassPermission: permissionModes.auto,
+ firstPromptArgs: [], resumeArgs: ['--resume'], forkArgs: { lead: ['--resume'], after: ['--fork-session'] },
+ instructionFiles: ['CLAUDE.md'],
+ contextArgs: file => ['--append-system-prompt', `Read the harness context at ${JSON.stringify(file)} before working.`],
+}
diff --git a/cli/src/engines/claude/transcript.ts b/cli/src/engines/claude/transcript.ts
new file mode 100644
index 000000000..decab9115
--- /dev/null
+++ b/cli/src/engines/claude/transcript.ts
@@ -0,0 +1,11 @@
+import { lastTurnTextFromRawLines, messagesToEvents, selectClaudeRecapLine } from '../../lib/normalize.js'
+import { tailFileUntil } from '../../lib/transcriptTail.js'
+import type { EngineTranscript } from '../facets/transcript.js'
+import { pagedHistory } from '../kit/history.js'
+
+export const transcript: EngineTranscript = {
+ async lastTurnText(session) {
+ return session.transcriptPath ? lastTurnTextFromRawLines(await tailFileUntil(session.transcriptPath, selectClaudeRecapLine)) : null
+ },
+ historyPage: (session, ask, pages) => pagedHistory(session, ask, (path, options) => pages.claude(path, options), messagesToEvents),
+}
diff --git a/cli/src/engines/codex/launch.ts b/cli/src/engines/codex/launch.ts
new file mode 100644
index 000000000..ae88b503b
--- /dev/null
+++ b/cli/src/engines/codex/launch.ts
@@ -0,0 +1,30 @@
+import type { EngineLaunch } from '../facets/launch.js'
+
+/** What `-c a.b.NAME=…` can address: Codex splits the key on dots, so a name must be a bare key. */
+const CODEX_ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/
+
+/**
+ * Codex runs a session's commands in a shared app server (`codex app-server --managed-daemon`, codex-cli
+ * 0.159.3), not under the process Harness launched, so they never see that process's environment.
+ * Measured: HARNESS_CONTEXT_FILE and every manifest variable were unset in the agent's shell, and the
+ * Model Manager ran without its instructions. `shell_environment_policy.set` is what Codex itself gives
+ * every command, and `-c` carries it to whichever process runs them. The value is a JSON string, which
+ * TOML reads as the same string.
+ */
+export function codexEnvArgs(env: Record<string, string>): string[] {
+ return Object.entries(env)
+ .filter(([name]) => CODEX_ENV_NAME.test(name))
+ .flatMap(([name, value]) => ['-c', `shell_environment_policy.set.${name}=${JSON.stringify(value)}`])
+}
+
+const permissionModes = {
+ auto: ['--approve-for-me'],
+ readOnly: ['--sandbox', 'read-only'],
+ ask: [],
+ full: ['--dangerously-bypass-approvals-and-sandbox'],
+}
+export const launch: EngineLaunch = {
+ permissionModes, bypassPermission: permissionModes.auto,
+ firstPromptArgs: [], resumeArgs: ['resume'], forkArgs: { lead: ['fork'] },
+ instructionFiles: ['AGENTS.override.md', 'AGENTS.md'], envArgs: codexEnvArgs,
+}
diff --git a/cli/src/engines/codex/transcript.ts b/cli/src/engines/codex/transcript.ts
new file mode 100644
index 000000000..b5f30f7eb
--- /dev/null
+++ b/cli/src/engines/codex/transcript.ts
@@ -0,0 +1,11 @@
+import { readLastCodexTurnText } from './lastTurn.js'
+import { codexMessagesToEvents } from './normalizer.js'
+import { codexSubagentResolverFor } from './subagent.js'
+import type { EngineTranscript } from '../facets/transcript.js'
+import { pagedHistory } from '../kit/history.js'
+
+export const transcript: EngineTranscript = {
+ async lastTurnText(session) { return session.transcriptPath ? readLastCodexTurnText(session.transcriptPath) : null },
+ historyPage: (session, ask, pages) => pagedHistory(session, ask, (path, options) => pages.codex(path, options),
+ lines => codexMessagesToEvents(lines, codexSubagentResolverFor(session.codexHome))),
+}
diff --git a/cli/src/engines/engine.ts b/cli/src/engines/engine.ts
new file mode 100644
index 000000000..b227b79f3
--- /dev/null
+++ b/cli/src/engines/engine.ts
@@ -0,0 +1,10 @@
+import type { ProcessEngine } from './types.js'
+import type { EngineTranscript } from './facets/transcript.js'
+import type { EngineLaunch } from './facets/launch.js'
+
+/** The engine's own contracts. Migration begins with Claude Code and Codex, two facets at a time. */
+export interface Engine {
+ readonly name: ProcessEngine
+ readonly transcript: EngineTranscript
+ readonly launch: EngineLaunch
+}
diff --git a/cli/src/engines/facets/launch.ts b/cli/src/engines/facets/launch.ts
new file mode 100644
index 000000000..37a16add1
--- /dev/null
+++ b/cli/src/engines/facets/launch.ts
@@ -0,0 +1,11 @@
+/** Literal argv contracts copied from the existing launch paths. No engine version behavior changes. */
+export interface EngineLaunch {
+ permissionModes: Readonly<Record<string, readonly string[]>>
+ bypassPermission: string[]
+ firstPromptArgs: readonly string[]
+ resumeArgs: string[]
+ forkArgs: { lead: string[]; after?: string[] }
+ instructionFiles: readonly string[]
+ contextArgs?: (contextFile: string) => string[]
+ envArgs?: (env: Record<string, string>) => string[]
+}
diff --git a/cli/src/engines/facets/transcript.ts b/cli/src/engines/facets/transcript.ts
new file mode 100644
index 000000000..531d80424
--- /dev/null
+++ b/cli/src/engines/facets/transcript.ts
@@ -0,0 +1,16 @@
+import type { LastTurnText, SessionEvent } from '../../lib/normalize.js'
+import type { RegisteredSession } from '../../lib/registry.js'
+import type { TranscriptPager } from '../../lib/transcriptPages.js'
+
+export interface HistoryAsk { limit?: number; before?: string }
+export interface HistoryAnswer {
+ events: SessionEvent[]
+ timestamp: string
+ hasMore?: boolean
+ oldestCursor?: string | null
+ staleCursor?: true
+}
+export interface EngineTranscript {
+ lastTurnText(session: RegisteredSession): Promise<LastTurnText | null>
+ historyPage(session: RegisteredSession, 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
new file mode 100644
index 000000000..942c603b4
--- /dev/null
+++ b/cli/src/engines/kit/history.ts
@@ -0,0 +1,44 @@
+import { stat } from 'node:fs/promises'
+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'
+
+/** 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
+ * `{status:'async_launched', agentId}` in the main transcript — without this join the delegation
+ * card shows "0 tools · worked for 0s" forever. Best-effort per agent; missing files are skipped. */
+export async function enrichSubagentStats(events: SessionEvent[], transcriptPath: string): Promise<void> {
+ const subagentsDir = join(transcriptPath.replace(/\.jsonl$/, ''), 'subagents')
+ for (const e of events) {
+ if (e.type !== 'tool_end') continue
+ const sub = e.payload.subagent
+ if (!sub?.agentId || typeof sub.totalToolUseCount === 'number') continue
+ try {
+ // A line at a time: a long sub-agent's transcript is never held whole to count its calls.
+ const file = join(subagentsDir, `agent-${sub.agentId}.jsonl`)
+ const totals = new SubagentStats()
+ await streamRecords(file, 0, (await stat(file)).size, (line) => { totals.push(line) }, () => true)
+ const stats = totals.result()
+ sub.totalToolUseCount = stats.totalToolUseCount
+ if (sub.totalDurationMs === undefined) sub.totalDurationMs = stats.totalDurationMs
+ if (sub.totalTokens === undefined) sub.totalTokens = stats.totalTokens
+ } catch { /* subagent transcript absent (still spawning / pruned) — leave as-is */ }
+ }
+}
+
+/** Bounded paging is shared machinery; each engine supplies its pager and replay rules. */
+export async function pagedHistory(session: RegisteredSession, { 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 } : {})
+ const st = await stat(session.transcriptPath).catch(() => null)
+ const timestamp = new Date(st?.mtimeMs ?? Date.now()).toISOString()
+ if (found.staleCursor) return { events: [], timestamp, hasMore: false, oldestCursor: null, staleCursor: true }
+ const events = replay(found.lines)
+ await enrichSubagentStats(events, session.transcriptPath)
+ if (limit && before && events[events.length - 1]?.type === 'done') events.pop()
+ return { events, timestamp, ...(limit || found.hasMore ? { hasMore: found.hasMore, oldestCursor: found.oldestCursor } : {}) }
+}
diff --git a/cli/src/engines/launches.ts b/cli/src/engines/launches.ts
new file mode 100644
index 000000000..81405176f
--- /dev/null
+++ b/cli/src/engines/launches.ts
@@ -0,0 +1,17 @@
+import type { EngineLaunch } from './facets/launch.js'
+import { launch as claude } from './claude/launch.js'
+import { launch as codex } from './codex/launch.js'
+export { codexEnvArgs } from './codex/launch.js'
+
+/** Launch metadata has no transcript imports: preparing argv must not load transcript readers. */
+export const engineLaunches = { claude, codex }
+type MigratedEngine = keyof typeof engineLaunches
+
+/** Compatibility tables take their migrated entries from the same launch contract. */
+export function launchField<K extends keyof EngineLaunch>(key: K): Record<MigratedEngine, EngineLaunch[K]> {
+ return Object.fromEntries(Object.entries(engineLaunches).map(([name, launch]) => [name, launch[key]])) as Record<MigratedEngine, EngineLaunch[K]>
+}
+export const harnessAdapters = Object.fromEntries(Object.entries(engineLaunches).map(([name, launch]) => [name, {
+ instructionFiles: launch.instructionFiles, ...(launch.contextArgs ? { contextArgs: launch.contextArgs } : {}),
+ ...(launch.envArgs ? { envArgs: launch.envArgs } : {}),
+}])) as Record<MigratedEngine, Pick<EngineLaunch, 'instructionFiles' | 'contextArgs' | 'envArgs'>>
diff --git a/cli/src/engines/registry.spec.ts b/cli/src/engines/registry.spec.ts
new file mode 100644
index 000000000..52b3d20a0
--- /dev/null
+++ b/cli/src/engines/registry.spec.ts
@@ -0,0 +1,56 @@
+/** The pre-extraction reply, pinned on 557ea832a against recorded, sanitized sessions. Hashes include
+ * every event field and wire cursor, excluding only the fixture file's filesystem timestamp. This
+ * catches lost delegation/tool cards and subtle paging changes while the ownership moves. */
+import { createHash } from 'node:crypto'
+import { copyFileSync, mkdtempSync, mkdirSync, rmSync, readFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { fileURLToPath } from 'node:url'
+import { expect, it } from 'vitest'
+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 () => {
+ const root = mkdtempSync(join(tmpdir(), 'engine-oracle-'))
+ const answer: Record<string, unknown> = {}
+ try {
+ for (const [engine, fixture] of Object.entries({ claude: '../lib/__fixtures__/transcript-async-subagents.jsonl', codex: '../lib/fixtures/session-work-codex.jsonl' })) {
+ const transcriptPath = join(root, engine + '.jsonl')
+ 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 history = createHistory(deps)
+ const digest = (value: Record<string, unknown>) => {
+ const { timestamp, ...stable } = value
+ return { sha256: createHash('sha256').update(JSON.stringify(stable)).digest('hex'), eventTypes: (value.events as Array<{ type: string }>).map(e => e.type), hasMore: value.hasMore ?? null, oldestCursor: value.oldestCursor ?? null }
+ }
+ const whole = await history.sessionGet({ sessionId: 'session' })
+ const latest = await history.sessionGet({ sessionId: 'session', limit: 3 })
+ const older = await history.sessionGet({ sessionId: 'session', limit: 3, before: latest.oldestCursor! })
+ const stale = await history.sessionGet({ sessionId: 'session', limit: 3, before: 'missing-cursor' })
+ const readLast = createLastTurnReader({ ...deps, bySession: () => session })
+ answer[engine] = { whole: digest(whole), latest: digest(latest), older: digest(older), stale: digest(stale), lastTurn: await readLast('session') }
+ }
+ expect(answer).toEqual(JSON.parse(readFileSync(new URL('./__fixtures__/transcript-contracts.json', import.meta.url), 'utf8')))
+ } finally { rmSync(root, { recursive: true, force: true }) }
+})
+
+it('does not mistake unknown names or object prototype properties for an engine', () => {
+ for (const name of [null, undefined, '', 'future-engine', 'constructor', 'toString', '__proto__']) expect(engineFor(name)).toBeUndefined()
+ expect(engineFor('claude')?.name).toBe('claude')
+ expect(engineFor('codex')?.name).toBe('codex')
+})
+
+it('answers an unbound conversation without reading any engine home', async () => {
+ const pages = new TranscriptPager()
+ for (const name of ['claude', 'codex']) {
+ const session = { engine: name, touchedAt: 1791374400000 } as RegisteredSession
+ const transcript = engineFor(name)!.transcript
+ expect(await transcript.lastTurnText(session)).toBeNull()
+ expect(await transcript.historyPage(session, {}, pages)).toEqual({ events: [], timestamp: new Date(session.touchedAt).toISOString(), hasMore: false, oldestCursor: null })
+ }
+})
diff --git a/cli/src/engines/registry.ts b/cli/src/engines/registry.ts
new file mode 100644
index 000000000..7e7c0fbb6
--- /dev/null
+++ b/cli/src/engines/registry.ts
@@ -0,0 +1,15 @@
+import type { Engine } from './engine.js'
+import { engineLaunches } from './launches.js'
+import { transcript as claudeTranscript } from './claude/transcript.js'
+import { transcript as codexTranscript } from './codex/transcript.js'
+
+/** Only the migrated engines. Others keep their existing handlers until their own small batch. */
+const engines = {
+ claude: { name: 'claude', launch: engineLaunches.claude, transcript: claudeTranscript },
+ codex: { name: 'codex', launch: engineLaunches.codex, transcript: codexTranscript },
+} satisfies Record<string, Engine>
+type MigratedEngine = keyof typeof engines
+export function engineFor(name: string | null | undefined): Engine | undefined {
+ return name && Object.hasOwn(engines, name) ? engines[name as MigratedEngine] : undefined
+}
+
diff --git a/cli/src/lib/engineLaunch.ts b/cli/src/lib/engineLaunch.ts
index 7eb4e85e9..32e9956a9 100644
--- a/cli/src/lib/engineLaunch.ts
+++ b/cli/src/lib/engineLaunch.ts
@@ -5,6 +5,7 @@ import { homedir, userInfo } from 'node:os'
import { isAbsolute, basename, dirname, join } from 'node:path'
import { baseNode } from '../harnessd/baseNode.js'
import { env } from '../config/env.js'
+import { launchField } from '../engines/launches.js'
import { isTerminalEngine, type AgentEngine } from '../engines/types.js'
import { isOpencodeV2 } from '../engines/opencode/version.js'
import { binaryOnPath, resolveBinaryOnPath } from './binaryOnPath.js'
@@ -22,11 +23,7 @@ import { CODEX_STARTUP_RETRY_PROBE } from './codexStartupRetry.js'
* `null` = no known/safe flag — callers must hide the option rather than guess one.
*/
export const BYPASS_PERMISSION_FLAGS: Readonly<Record<AgentEngine, string[] | null>> = {
- // The engines' own auto modes, not their "skip every check" switches: Claude Code's auto mode
- // approves routine actions and still runs its safety checks on risky ones, and Codex routes each
- // approval to its automatic review and keeps commands in the workspace sandbox.
- claude: ['--permission-mode', 'auto'],
- codex: ['--approve-for-me'],
+ ...launchField('bypassPermission'),
cursor: ['--force'],
opencode: ['--auto'],
// No permission-prompt system to bypass (pi), or config-file based rather than a flag (hermes).
@@ -55,19 +52,7 @@ export const BYPASS_PERMISSION_FLAGS: Readonly<Record<AgentEngine, string[] | nu
* The desktop mirrors this table in `lib/core/permission_modes.dart` — keep both in step.
*/
export const PERMISSION_MODES: Readonly<Partial<Record<AgentEngine, Readonly<Record<string, readonly string[]>>>>> = {
- claude: {
- auto: ['--permission-mode', 'auto'],
- acceptEdits: ['--permission-mode', 'acceptEdits'],
- plan: ['--permission-mode', 'plan'],
- ask: [],
- full: ['--dangerously-skip-permissions'],
- },
- codex: {
- auto: ['--approve-for-me'],
- readOnly: ['--sandbox', 'read-only'],
- ask: [],
- full: ['--dangerously-bypass-approvals-and-sandbox'],
- },
+ ...launchField('permissionModes'),
cursor: { auto: ['--force'], ask: [] },
opencode: { auto: ['--auto'], ask: [] },
}
@@ -93,15 +78,11 @@ export function permissionModeApproves(mode: string): boolean {
* engine that reads a bare positional. Each entry cites where it was read from.
*/
export const FIRST_PROMPT_ARGS: Readonly<Record<AgentEngine, readonly string[] | null>> = {
+ ...launchField('firstPromptArgs'),
// `opencode --help`: `--prompt prompt to use`, a TUI flag — the interactive session starts with
// the message submitted. A flag rather than a positional because opencode's own positional is
// `[project]`, a directory: handed the text bare, it would try to open a folder by that name.
opencode: ['--prompt'],
- // `claude --help`: `Usage: claude [options] [command] [prompt]`, "prompt: Your prompt".
- claude: [],
- // Per vendor CLI help: `codex [OPTIONS] [PROMPT]`, the optional positional the interactive TUI
- // opens with. Not verified on a local install when this entry was written.
- codex: [],
// No documented first-prompt argument for an interactive launch. Not guessed.
cursor: null,
pi: null,
@@ -312,8 +293,7 @@ export interface LaunchCommandOptions {
* commands"); it must run in the session's own folder, or Devin asks which folder to use.
*/
export const LAUNCH_RESUME_FLAG: Readonly<Partial<Record<AgentEngine, string[]>>> = {
- claude: ['--resume'],
- codex: ['resume'],
+ ...launchField('resumeArgs'),
cursor: ['--resume'],
opencode: ['--session'],
kilo: ['--session'],
@@ -340,8 +320,7 @@ export const LAUNCH_RESUME_FLAG: Readonly<Partial<Record<AgentEngine, string[]>>
* one, and refuses otherwise — never a plain `--resume`, which would put two processes on ONE session.
*/
export const LAUNCH_FORK_FLAG: Readonly<Partial<Record<AgentEngine, { lead: string[]; after?: string[] }>>> = {
- claude: { lead: ['--resume'], after: ['--fork-session'] },
- codex: { lead: ['fork'] },
+ ...launchField('forkArgs'),
}
/** Whether a relaunch can reopen this engine's previous conversation — see [LAUNCH_RESUME_FLAG].
diff --git a/docs/design/2026-10-05-engine-interface.md b/docs/design/2026-10-05-engine-interface.md
index 8d1a1fe33..9d5ed36a3 100644
--- a/docs/design/2026-10-05-engine-interface.md
+++ b/docs/design/2026-10-05-engine-interface.md
@@ -1,8 +1,13 @@
# Engines behind one interface
-> **Status, 2026-10-07: paused by the owner.** Steps 1–5 and lanes S, B, H, L and I+O+U are on unmerged
-> branches (`engine-interface-1..5`, `engine-lane-*`), and step 1 is in draft PR #842. Claude Code and
-> Codex come first when it resumes; the owner names the next engine.
+> **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. Launch metadata loads separately from readers.
+> Hooks, discovery/resume, live ingestion, screen/input, models and one-shot handling remain to migrate.
+> The older all-engine branches (`engine-interface-1..5`, `engine-lane-*`, draft PR #842) are retained as
+> reference work; they are not the implementation currently landing. The phased plan below is the
+> target architecture, not a claim that all facets or engine isolation are already complete.
+
Status: plan, approved for implementation on 2026-10-05. Scope: `cli/` (the daemon, harnessd).
@@ -913,14 +918,11 @@ imports and identifiers as what they are.
3. **The bar for each step:** `tsc`; `npm run test:core` and `npm run test:harnessd` at 100% per file;
the full unit suite; the e2e files that exercise the moved code, from the bundle
(`E2E_BUNDLE=1 E2E_WORKERS=2`); the rule test's counts do not rise.
-4. **One group at a time, every engine at once.** Why not engine by engine: moving Claude Code's
- behaviour everywhere, then Codex's, would touch every shared file fourteen times and leave each call
- site half-branching, half-interface while it happened; the core would be more tangled in the middle
- than it is now. Group by group touches each call site once, gives each step a small set of files, and
- lets the e2e suite prove the Claude Code and Codex half of every step while the pinned unit tests
- prove the other twelve. Claude Code and Codex still come first in the sense that matters: they are
- the engines the first steps are proven on end to end, the two built into the registry from step 1,
- and the first two folders written in full.
+4. **A few popular engines per batch (owner direction, 2026-10-07).** Start with Claude Code and Codex
+ and move coherent facets with their existing behavior pinned. Shared callers retain explicit legacy
+ paths for engines outside the current batch. This supersedes the original all-fourteen-at-once
+ migration rule; it does not relax the boundary, fallback or validation requirements. Add subsequent
+ engines in small reviewed batches rather than carrying every recovered lane into one change.
5. **While the moves run, facets are tables.** Each facet has a table file in `src/engines/`
(`transcripts.ts`, `screens.ts`, …) mapping every engine to its facet object, and `registry.ts`
assembles an `Engine` from the tables. A lane adds its own table file, its facet files in each engine