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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Extract Claude Code and Codex live transcript facets (#1017)
Deeea23a06f782e
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex 102013be4..1e3fc1a9e 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -197,6 +197,16 @@ describe('the daemon\'s shape', () => {expect(wrong, 'The core calls services only through CorePorts, and is handed the socket\'s pieces as dependencies (src/core/AGENTS.md).').toEqual([])})+ it('live transcript coordination depends on engine contracts, with neutral folding mechanics', () => {+ const owners = new Set(['core/transcripts/attach.ts', 'core/transcripts/ingest.ts', 'core/transcripts/normalizers.ts'])+ const wrong = importsIn('core').filter(({ file, from, typeOnly }) => owners.has(file) && !typeOnly+ && (/engines\/(claude|codex)\//.test(from) || /lib\/normalize\.js$/.test(from) || /engines\/live\.js$/.test(from)))+ expect(wrong, 'Inject the live facet; do not construct or edit an engine parser in core.').toEqual([])+ for (const entry of ['lib/attachTranscript.ts', 'engines/kit/events.ts', 'engines/kit/transcriptFold.ts']) {+ expect([...closureOf(entry).keys()].filter(file => /^engines\/(claude|codex)\//.test(file)), entry).toEqual([])+ }+ })+it('the gateway reaches the core only through core/api.ts: never a core module, the registry, cli.ts or the socket', () => {// It speaks to the core through GatewayPort and GatewayEvents alone, so that it can run in a process of// its own (step 10, R2) without taking any of the core with it.diff --git a/cli/src/core/AGENTS.md b/cli/src/core/AGENTS.mdindex 3ebeeadc9..c7c9dc044 100644--- a/cli/src/core/AGENTS.md+++ b/cli/src/core/AGENTS.md@@ -25,6 +25,9 @@ questions. Everything else is a service ([../services/AGENTS.md](../services/AGE- `agents/`: create, fork, restart, retarget, stop, resume, close, discovery, adoption, binding, the list.- `transcripts/`: attach (bounded reads from the end), ingest, live tail, relaunch marks, normalizers.+ Claude Code/Codex live interpretation is injected through `Engine.live`; core keeps parser handles+ and immutable turn snapshots, never edits their engine state. Live parsers are still in process+ pending the transport in [the live design](../../../docs/design/2026-10-07-engine-live.md).- `turns/`: working/idle, the event funnel, cancel, heartbeats, hooks, and `recaps.ts`, the core's wholeside 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`),diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex 65b2d956e..dc655bf29 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -25,6 +25,7 @@ import { registry, projectDisplayName, validTranscriptPath, type RegisteredSessiimport { engineSessionTitle } from '../lib/sessionTitle.js'import { machineNames } from '../lib/machineNames.js'import { engineHooks as engineHookFacets } from '../engines/hooks.js'+import { liveFor } from '../engines/live.js'import { DAEMON_LOG_FILE, PID_FILE, daemonPort, isAlive, readPid, LEGACY_LOG_FILE, MACHINE_NAME_FILE, tildify, computerId, thisDeviceLabel } from '../lib/daemonState.js'import { clearSafeModeMarker, safeModeDisposition, safeModeStatusBody, SafeModeRequest, writeSafeModeMarker } from '../lib/daemonSafeMode.js'import { awakeTimeout } from '../lib/sleepAware.js'@@ -955,6 +956,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Following a session: its history read into its engine's normalizer, then its tail// (core/transcripts/attach.ts).const attach = createAttach({+ liveFor,terminalGone: terminalControl.terminalGone,normalizers,watcher,@@ -1751,6 +1753,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// Each transcript line, through its engine's normalizer, into the funnel (core/transcripts/ingest.ts).const ingest = createIngest({+ liveFor,has: (sessionId) => registry.has(sessionId),bySession: (sessionId) => registry.bySession(sessionId),tokenUsage: agentTokenUsage,diff --git a/cli/src/core/transcripts/attach.spec.ts b/cli/src/core/transcripts/attach.spec.tsindex 09bbc1930..6ae57f522 100644--- a/cli/src/core/transcripts/attach.spec.ts+++ b/cli/src/core/transcripts/attach.spec.ts@@ -1,3 +1,4 @@+import { liveFor } from '../../engines/live.js'import { mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'@@ -74,6 +75,7 @@ function setup(over: Partial<AttachDeps> = {}) {const service = { needsTranscript: vi.fn(() => false), observeTranscript: vi.fn() }const profile = { ingest: vi.fn(), commit: vi.fn() }const deps: AttachDeps = {+ liveFor,terminalGone: vi.fn(async () => false),normalizers,watcher: { addSession: vi.fn(async () => {}), hold: vi.fn(async () => null), tails: vi.fn(() => false) },@@ -151,6 +153,15 @@ describe('attaching a session', () => {})describe('a first attach', () => {+ it('keeps an unknown engine registered without inventing a Claude parser for its file', async () => {+ const run = setup()+ const s = session('future-engine', transcript([CLAUDE_PROMPT]))+ expect(await run.attach.attachSession(s)).toBe(true)+ expect(run.normalizers.hasState(s.sessionId)).toBe(false)+ expect(run.deps.emit).not.toHaveBeenCalled()+ expect(run.deps.watcher.addSession).toHaveBeenCalledWith(s, {})+ })+it('reads Claude Code from the end, hands the tail the byte it stopped at, and replays a turn left open', async () => {const log = vi.spyOn(console, 'log').mockImplementation(() => {})const run = setup()@@ -158,7 +169,7 @@ describe('attaching a session', () => {expect(await run.attach.attachSession(s)).toBe(true)const [, from] = vi.mocked(run.deps.watcher.addSession).mock.calls[0]expect(from).toEqual({ fromOffset: expect.any(Number) })- expect(run.normalizers.turnStates.get(s.sessionId)?.turnOpen).toBe(true)+ expect(run.normalizers.liveParsers.get(s.sessionId)?.turnOpen).toBe(true)expect(run.profile.commit).toHaveBeenCalled()expect(run.deps.emit).toHaveBeenCalledWith(s.sessionId, [expect.objectContaining({ type: 'turn_started' })], { resumed: true })expect(run.attach.replayedFirstTurn.has(s.sessionId)).toBe(true)@@ -172,7 +183,9 @@ describe('attaching a session', () => {const s = session('codex', transcript([{ type: 'event_msg', payload: { type: 'user_message', message: 'go' } }]))await run.attach.attachSession(s)const [codex] = made('codex')- expect(run.normalizers.codexNormalizers.get(s.sessionId)).toBe(codex)+ expect(run.normalizers.liveParsers.get(s.sessionId)?.turnOpen).toBe(codex.turnOpen)+ codex.turnOpen = true+ expect(run.normalizers.liveParsers.get(s.sessionId)?.snapshot().turnOpen).toBe(true)expect(codex.thinkingPrefix).toMatch(/^thinking-codex-/)})@@ -180,7 +193,7 @@ describe('attaching a session', () => {vi.spyOn(console, 'log').mockImplementation(() => {})const run = setup()expect(await run.attach.attachSession(session('codex'))).toBe(true)- expect(run.normalizers.codexNormalizers.get('codex-s')).toBe(made('codex')[0])+ expect(run.normalizers.liveParsers.get('codex-s')?.turnOpen).toBe(made('codex')[0].turnOpen)expect(run.attach.neverFoldedHistory.has('codex-s')).toBe(true)})@@ -282,7 +295,7 @@ describe('attaching a session', () => {expect.stringContaining('the re-read could not read the transcript'),expect.stringContaining('the re-read outlasted its hold on the tail'),])- expect(run.normalizers.turnStates.has('late')).toBe(false)+ expect(run.normalizers.liveParsers.has('late')).toBe(false)})it('replays a first turn already on disk when the transcript was born after its agent', async () => {@@ -331,13 +344,13 @@ describe('attaching a session', () => {expect(restarted.deps.emit).not.toHaveBeenCalled()expect(log.mock.calls.some(([line]) => String(line).includes('left the turn open at attach as history'))).toBe(true)// Closed where the next message is read, too: its start must not first end a turn nobody saw start.- expect(restarted.normalizers.turnStates.get(s.sessionId)?.turnOpen).toBe(false)- expect(survived.normalizers.turnStates.get(s.sessionId)?.turnOpen).toBe(true)+ expect(restarted.normalizers.liveParsers.get(s.sessionId)?.turnOpen).toBe(false)+ expect(survived.normalizers.liveParsers.get(s.sessionId)?.turnOpen).toBe(true)// Codex's own normalizer, likewise.const codex = session('codex', transcript([{ open: true }]))const resumed = setup({ relaunchMarks: { take: () => ({ offset: statSync(codex.transcriptPath!).size, engineStarted: true }) } })await resumed.attach.attachSession(codex)- expect(resumed.normalizers.codexNormalizers.get(codex.sessionId)?.turnOpen).toBe(false)+ expect(resumed.normalizers.liveParsers.get(codex.sessionId)?.turnOpen).toBe(false)})it('replays a Claude Code first turn live when born after its agent, unless a held tail already delivered it', async () => {@@ -462,7 +475,7 @@ describe('attaching a session', () => {vi.spyOn(console, 'log').mockImplementation(() => {})const run = setup()await run.attach.attachSession(session('terminal', transcript(['{}'])))- expect(run.normalizers.turnStates.has('terminal-s')).toBe(true)+ expect(run.normalizers.liveParsers.has('terminal-s')).toBe(true)expect(run.deps.questionWatcher.start).not.toHaveBeenCalled()})diff --git a/cli/src/core/transcripts/attach.ts b/cli/src/core/transcripts/attach.tsindex 35a149820..0fe0e7c50 100644--- a/cli/src/core/transcripts/attach.ts+++ b/cli/src/core/transcripts/attach.ts@@ -10,8 +10,7 @@import { AgyNormalizer } from '../../engines/agy/normalizer.js'import { agyPaneIdle } from '../../engines/agy/runtimeProfile.js'import { AmpNormalizer } from '../../engines/amp/normalizer.js'-import { CodexNormalizer } from '../../engines/codex/normalizer.js'-import { codexSubagentResolverFor } from '../../engines/codex/subagent.js'+import type { LiveFor } from '../../engines/facets/live.js'import { CommandCodeNormalizer } from '../../engines/commandcode/normalizer.js'import { CopilotNormalizer, copilotHistoryTurnOpen } from '../../engines/copilot/normalizer.js'import type { CursorTranscriptDiscovery } from '../../engines/cursor/discovery.js'@@ -25,11 +24,12 @@ import { OpencodeReader } from '../../engines/opencode/reader.js'import { PiNormalizer } from '../../engines/pi/normalizer.js'import type { AgentEngine } from '../../engines/types.js'import { pollsQuestions, type QuestionWatcher } from '../../lib/askQuestion.js'-import { attachTranscript, claudeAttachRules, codexAttachRules, type AttachRead } from '../../lib/attachTranscript.js'+import { attachTranscript, type AttachRead } from '../../lib/attachTranscript.js'import { AttachTracker } from '../../lib/attachTracker.js'import type { WifiFeed } from '../wifi.js'import { sid } from '../../lib/log.js'-import { foldTranscript, lineToEvents, newTurnState, TranscriptFold, type LiveEvent } from '../../lib/normalize.js'+import { foldTranscript, TranscriptFold } from '../../engines/kit/transcriptFold.js'+import type { LiveEvent } from '../../engines/kit/events.js'import type { RegisteredSession } from '../../lib/registry.js'import type { RuntimeField, RuntimeProfileManager } from '../../lib/runtimeProfile.js'import { tailFileCapped, WHOLE_READ_CAP_BYTES } from '../../lib/transcriptTail.js'@@ -39,6 +39,7 @@ import type { RelaunchMarks } from './relaunch.js'import { createSideReads } from './sideReads.js'export interface AttachDeps {+ liveFor: LiveFor/** Whether the session's terminal is known to be gone (core/terminals/control.ts `terminalGone`). */terminalGone: (session: RegisteredSession) => Promise<boolean>normalizers: SessionNormalizers@@ -69,12 +70,12 @@ export interface AttachDeps {}export function createAttach({- terminalGone, normalizers, watcher, cursorDiscovery, device, runtimeProfiles, captureTerminal, emit,+ liveFor, terminalGone, normalizers, watcher, cursorDiscovery, device, runtimeProfiles, captureTerminal, emit,announceTurnAborted, questionWatcher, terminalLabel, dbs, devinHome, hermesDb, concurrency, relaunchMarks,wholeReadCapBytes = WHOLE_READ_CAP_BYTES, settled,}: AttachDeps) {const {- turnStates, codexNormalizers, cursorNormalizers, opencodeReaders, kiloReaders, museNormalizers, ampNormalizers,+ liveParsers, cursorNormalizers, opencodeReaders, kiloReaders, museNormalizers, ampNormalizers,grokNormalizers, agyNormalizers, copilotNormalizers, piNormalizers, hermesReaders, devinReaders, commandcodeNormalizers,} = normalizersconst sideRead = createSideReads()@@ -183,16 +184,13 @@ export function createAttach({// the chips and a continuing /goal still need — never the whole conversation, which on a long session// cost the daemon more memory than it has (lib/attachTranscript.ts). Their normalizers exist before// the read because they fold as the records stream in. The other engines still fold everything.- const codexNormalizer = session.engine === 'codex'- ? new CodexNormalizer('live', codexSubagentResolverFor(session.codexHome))- : null- const claudeState = session.engine === 'claude' ? newTurnState() : null+ const adapter = liveFor(session.engine)+ const parser = adapter?.create(session)const fields = (line: string): readonly RuntimeField[] => runtimeProfiles.transcriptFields(session, line)- const fromEndFold = codexNormalizer- ? { rules: codexAttachRules(fields), ingest: (line: string) => codexNormalizer.ingest(line), turnOpen: () => codexNormalizer.turnOpen }- : claudeState- ? { rules: claudeAttachRules(fields), ingest: (line: string) => lineToEvents(line, claudeState), turnOpen: () => claudeState.turnOpen }- : null+ const rules = adapter?.attachRules?.(fields)+ const fromEndFold = parser && rules+ ? { rules, ingest: (line: string) => parser.ingest(line).events, turnOpen: () => parser.turnOpen }+ : nulllet fromEnd: AttachRead | null = null// A reset keeps the normalizer it meant to replace when its read failed, or outlasted the hold on the// tail — which then let go, and delivery went back to that normalizer: it has seen every record since,@@ -214,11 +212,7 @@ export function createAttach({const profile = runtimeProfiles.beginHydrate(session)const read = await attachTranscript(session.transcriptPath, fromEndFold.rules, {// Ids named for this window cannot repeat ones another fold of the session sent.- start: (span) => {- const prefix = `${span.turnFrom.toString(36)}-`- if (codexNormalizer) codexNormalizer.thinkingPrefix = `thinking-codex-${prefix}`- if (claudeState) claudeState.thinkingPrefix = `thinking-live-${prefix}`- },+ start: (span) => parser!.windowStart(span.turnFrom),profile: (line) => profile.ingest(line),fold: (line) => stream.push(line),observe,@@ -251,9 +245,9 @@ export function createAttach({if (handover.hold?.expired) return keepLiveNormalizer('outlasted its hold on the tail')const fold = (ingest: (line: string) => LiveEvent[], turnOpenAfter: () => boolean): boolean =>take(foldTranscript(ingest, lines, turnOpenAfter, { live: replayLive }))- if (codexNormalizer) {- // Folded above, from the end, when there is a rollout; without one there is nothing to fold.- codexNormalizers.set(session.sessionId, codexNormalizer)+ if (parser) {+ if (!fromEnd) historyTurnOpen = fold((line) => parser.ingest(line).events, () => parser.turnOpen)+ liveParsers.set(session.sessionId, parser)} else if (session.engine === 'cursor') {const normalizer = new CursorNormalizer('live', session.sessionId)historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)@@ -373,10 +367,6 @@ export function createAttach({// Hydrate state silently; never replay history live — except a turn left open, below.historyTurnOpen = fold((line) => normalizer.ingest(line), () => normalizer.turnOpen)commandcodeNormalizers.set(session.sessionId, normalizer)- } else {- const state = claudeState ?? newTurnState()- if (!fromEnd) historyTurnOpen = fold((line) => lineToEvents(line, state), () => state.turnOpen)- turnStates.set(session.sessionId, state)}if (session.transcriptPath) {neverFoldedHistory.delete(session.sessionId)@@ -424,11 +414,10 @@ export function createAttach({// Closed in the normalizer too, and as silently. Left open, the next message's start ended it first:// a turn_ended for a turn no client saw start (a "done" and its notification), a team's or the// orchestrator's delivery read as ended before it started, and the agent working until then.- const folds: Array<Map<string, { closeTurn(): unknown }>> = [codexNormalizers, cursorNormalizers, museNormalizers, ampNormalizers,+ const folds: Array<Map<string, { closeTurn(): unknown }>> = [cursorNormalizers, museNormalizers, ampNormalizers,grokNormalizers, agyNormalizers, copilotNormalizers, piNormalizers, commandcodeNormalizers]for (const fold of folds) fold.get(session.sessionId)?.closeTurn()- const state = turnStates.get(session.sessionId)- if (state) { state.turnOpen = false; state.pendingTools.clear() }+ liveParsers.get(session.sessionId)?.closeTurn('abandoned')} else if (historyTurnOpen && !handover.hold) {const opened = historyEvents.findLast((event) => event.type === 'turn_started')if (opened) {diff --git a/cli/src/core/transcripts/history.spec.ts b/cli/src/core/transcripts/history.spec.tsindex 09762a313..929bb7ea7 100644--- a/cli/src/core/transcripts/history.spec.ts+++ b/cli/src/core/transcripts/history.spec.ts@@ -73,7 +73,7 @@ vi.mock('../../engines/cursor/subagent.js', async (real) => ({ ...await real<objvi.mock('../../engines/cursor/home.js', async (real) => ({ ...await real<object>(), cursorConfigDir: vi.fn(() => '/cursor/config'), cursorDataDir: vi.fn(() => '/cursor/data') }))vi.mock('../../engines/codex/normalizer.js', async (real) => ({ ...await real<object>(), codexMessagesToEvents: vi.fn((lines: unknown[]) => fake.replay('codex')(lines)) }))vi.mock('../../engines/codex/subagent.js', async (real) => ({ ...await real<object>(), codexSubagentResolverFor: vi.fn(() => fake.resolver) }))-vi.mock('../../lib/normalize.js', async (real) => ({ ...await real<object>(), messagesToEvents: vi.fn(fake.replay('claude')), windowRawLines: vi.fn(fake.windowOf('raw')) }))+vi.mock('../../engines/claude/normalize.js', async (real) => ({ ...await real<object>(), messagesToEvents: vi.fn(fake.replay('claude')), windowRawLines: vi.fn(fake.windowOf('raw')) }))vi.mock('../../lib/agentFrame.js', async (real) => ({ ...await real<object>(), lastActivityAt: vi.fn(async () => Date.parse('2026-10-05T08:45:00.000Z')) }))vi.mock('../../lib/transcriptTail.js', async (real) => {const actual = await real<typeof import('../../lib/transcriptTail.js')>()diff --git a/cli/src/core/transcripts/ingest.spec.ts b/cli/src/core/transcripts/ingest.spec.tsindex 25e18ac6c..dd875e98a 100644--- a/cli/src/core/transcripts/ingest.spec.ts+++ b/cli/src/core/transcripts/ingest.spec.ts@@ -1,8 +1,8 @@+import { liveFor } from '../../engines/live.js'import { EventEmitter } from 'node:events'import { afterEach, describe, expect, it, vi } from 'vitest'import { AgyNormalizer } from '../../engines/agy/normalizer.js'import { AmpNormalizer } from '../../engines/amp/normalizer.js'-import { CodexNormalizer } from '../../engines/codex/normalizer.js'import { CommandCodeNormalizer } from '../../engines/commandcode/normalizer.js'import { CopilotNormalizer } from '../../engines/copilot/normalizer.js'import { CursorNormalizer } from '../../engines/cursor/normalizer.js'@@ -24,6 +24,7 @@ function setup(engines: Record<string, string>, over: Partial<IngestDeps> = {})const normalizers = createSessionNormalizers()const service = { needsTranscript: vi.fn(() => false), observeTranscript: vi.fn() }const deps: IngestDeps = {+ liveFor,has: (sessionId) => sessions.has(sessionId),bySession: (sessionId) => sessions.get(sessionId),tokenUsage: { changed: vi.fn() },@@ -102,12 +103,12 @@ describe('ingesting a transcript line', () => {it('creates each file engine\'s normalizer on the session\'s first line, and keeps it', () => {const engines = {- codex: CodexNormalizer, cursor: CursorNormalizer, muse: MuseNormalizer, amp: AmpNormalizer, grok: GrokNormalizer,+ cursor: CursorNormalizer, muse: MuseNormalizer, amp: AmpNormalizer, grok: GrokNormalizer,agy: AgyNormalizer, copilot: CopilotNormalizer, pi: PiNormalizer, commandcode: CommandCodeNormalizer,} as constconst run = setup(Object.fromEntries(Object.keys(engines).map((engine) => [engine, engine])))const maps = {- codex: run.normalizers.codexNormalizers, cursor: run.normalizers.cursorNormalizers, muse: run.normalizers.museNormalizers,+ cursor: run.normalizers.cursorNormalizers, muse: run.normalizers.museNormalizers,amp: run.normalizers.ampNormalizers, grok: run.normalizers.grokNormalizers, agy: run.normalizers.agyNormalizers,copilot: run.normalizers.copilotNormalizers, pi: run.normalizers.piNormalizers, commandcode: run.normalizers.commandcodeNormalizers,} as Record<keyof typeof engines, Map<string, unknown>>@@ -120,15 +121,15 @@ describe('ingesting a transcript line', () => {}})- it('reads Claude Code and any other engine with the turn state, created once', () => {+ it('creates a live parser once, preserving the terminal fallback', () => {const run = setup({ s1: 'claude', s2: 'terminal' })const events = run.ingest.ingestLine(line('s1', 'claude', CLAUDE_PROMPT))!expect(events.map((event) => event.type)).toContain('turn_started')- const state = run.normalizers.turnStates.get('s1')+ const state = run.normalizers.liveParsers.get('s1')run.ingest.ingestLine(line('s1', 'claude', '{}'))- expect(run.normalizers.turnStates.get('s1')).toBe(state)+ expect(run.normalizers.liveParsers.get('s1')).toBe(state)run.ingest.ingestLine(line('s2', 'terminal', '{}'))- expect(run.normalizers.turnStates.has('s2')).toBe(true)+ expect(run.normalizers.liveParsers.has('s2')).toBe(true)})it('announces the reason a Codex or Command Code turn failed', () => {@@ -142,6 +143,24 @@ describe('ingesting a transcript line', () => {['cc', 'commandcode', 'Error: 500\nTrace ID: 932a', 'Error: 500'],])})++ it('leaves a database engine to its reader when a file line is delivered for it', () => {+ const run = setup({ db: 'opencode' })+ expect(run.ingest.ingestLine(line('db', 'opencode', CLAUDE_PROMPT))).toEqual([])+ expect(run.normalizers.hasState('db')).toBe(false)+ })++ it('replaces a parser when the same session id is rebound to another engine', () => {+ const run = setup({ s1: 'claude' })+ run.ingest.ingestLine(line('s1', 'claude', CLAUDE_PROMPT))+ const previous = run.normalizers.liveParsers.get('s1')!+ run.sessions.get('s1')!.engine = 'codex'+ const prompt = JSON.stringify({ type: 'event_msg', payload: { type: 'user_message', message: 'new engine' } })+ expect(run.ingest.ingestLine(line('s1', 'codex', prompt))?.find(event => event.type === 'turn_started')?.payload).toEqual({ userMessage: 'new engine' })+ expect(run.normalizers.liveParsers.get('s1')).not.toBe(previous)+ expect(run.normalizers.liveParsers.get('s1')!.engine).toBe('codex')+ expect(previous.turnOpen).toBe(true)+ })})describe('the watcher wiring', () => {diff --git a/cli/src/core/transcripts/ingest.ts b/cli/src/core/transcripts/ingest.tsindex 5cf415f0e..258c29ecc 100644--- a/cli/src/core/transcripts/ingest.ts+++ b/cli/src/core/transcripts/ingest.ts@@ -10,8 +10,7 @@*/import { AgyNormalizer } from '../../engines/agy/normalizer.js'import { AmpNormalizer } from '../../engines/amp/normalizer.js'-import { CodexNormalizer, codexTaskError } from '../../engines/codex/normalizer.js'-import { codexSubagentResolverFor } from '../../engines/codex/subagent.js'+import type { LiveFor } from '../../engines/facets/live.js'import { CommandCodeNormalizer, commandCodeRunError, commandCodeRunErrorSummary } from '../../engines/commandcode/normalizer.js'import { CopilotNormalizer } from '../../engines/copilot/normalizer.js'import { CursorNormalizer } from '../../engines/cursor/normalizer.js'@@ -20,7 +19,7 @@ import { MuseNormalizer } from '../../engines/muse/normalizer.js'import { PiNormalizer } from '../../engines/pi/normalizer.js'import type { WifiFeed } from '../wifi.js'import { sid } from '../../lib/log.js'-import { lineToEvents, newTurnState, type LiveEvent } from '../../lib/normalize.js'+import type { LiveEvent } from '../../engines/kit/events.js'import type { RegisteredSession } from '../../lib/registry.js'import type { RuntimeProfileManager } from '../../lib/runtimeProfile.js'import type { HistoryEvent, LineEvent, RewrittenEvent, Watcher } from '../../watcher/watcher.js'@@ -28,6 +27,7 @@ import type { SessionNormalizers } from './normalizers.js'import { createSideReads } from './sideReads.js'export interface IngestDeps {+ liveFor: LiveForhas: (sessionId: string) => booleanbySession: (sessionId: string) => RegisteredSession | undefinedtokenUsage: { changed(session: RegisteredSession): void }@@ -41,10 +41,10 @@ export interface IngestDeps {}export function createIngest({- has, bySession, tokenUsage, device, runtimeProfiles, normalizers, announceTurnAborted, emit, attachSession,+ liveFor, has, bySession, tokenUsage, device, runtimeProfiles, normalizers, announceTurnAborted, emit, attachSession,}: IngestDeps) {const {- turnStates, codexNormalizers, cursorNormalizers, museNormalizers, ampNormalizers, grokNormalizers, agyNormalizers,+ liveParsers, cursorNormalizers, museNormalizers, ampNormalizers, grokNormalizers, agyNormalizers,copilotNormalizers, piNormalizers, commandcodeNormalizers,} = normalizersconst sideRead = createSideReads()@@ -64,16 +64,14 @@ export function createIngest({}})sideRead('runtime profile', evt.sessionId, () => runtimeProfiles.ingest(session, evt.text))- let events- if (session.engine === 'codex') {- let normalizer = codexNormalizers.get(evt.sessionId)- if (!normalizer) { normalizer = new CodexNormalizer('live', codexSubagentResolverFor(session.codexHome)); codexNormalizers.set(evt.sessionId, normalizer) }- events = normalizer.ingest(evt.text)- // Codex rides its failure ON task_complete, so the turn closes by itself — but with no text and- // no reason, which reads as "the agent answered nothing". Announce the reason ahead of the- // turn_ended that `events` carries.- const taskError = codexTaskError(evt.text)- if (taskError !== null) announceTurnAborted(evt.sessionId, 'codex', taskError)+ let events: LiveEvent[]+ const adapter = liveFor(session.engine)+ if (adapter) {+ let parser = liveParsers.get(evt.sessionId)+ if (!parser || parser.engine !== session.engine) { parser = adapter.create(session); liveParsers.set(evt.sessionId, parser) }+ const read = parser.ingest(evt.text)+ events = read.events+ if (read.failure !== undefined) announceTurnAborted(evt.sessionId, session.engine, read.failure)} else if (session.engine === 'cursor') {let normalizer = cursorNormalizers.get(evt.sessionId)if (!normalizer) {@@ -117,9 +115,7 @@ export function createIngest({announceTurnAborted(evt.sessionId, 'commandcode', runError, commandCodeRunErrorSummary(runError))}} else {- let st = turnStates.get(evt.sessionId)- if (!st) { st = newTurnState(); turnStates.set(evt.sessionId, st) }- events = lineToEvents(evt.text, st)+ events = []}return events}diff --git a/cli/src/core/transcripts/lastTurn.spec.ts b/cli/src/core/transcripts/lastTurn.spec.tsindex 257666b51..26265c933 100644--- a/cli/src/core/transcripts/lastTurn.spec.ts+++ b/cli/src/core/transcripts/lastTurn.spec.ts@@ -19,7 +19,7 @@ vi.mock('../../lib/transcriptTail.js', () => ({tailFileCapped: vi.fn(async (path: string) => ({ lines: [`${path} capped`], truncated: false })),tailFileUntil: vi.fn(async (path: string) => [`${path} back to the last turn`]),}))-vi.mock('../../lib/normalize.js', () => ({+vi.mock('../../engines/claude/normalize.js', () => ({lastTurnTextFromRawLines: vi.fn((lines: string[]) => ({ text: `raw: ${lines[0]}` })),selectClaudeRecapLine: vi.fn(),}))diff --git a/cli/src/core/transcripts/normalizers.spec.ts b/cli/src/core/transcripts/normalizers.spec.tsindex 5a756b874..cc605d14f 100644--- a/cli/src/core/transcripts/normalizers.spec.ts+++ b/cli/src/core/transcripts/normalizers.spec.ts@@ -1,10 +1,9 @@import { describe, expect, it, vi } from 'vitest'-import type { TurnState } from '../../lib/normalize.js'import { createSessionNormalizers, type SessionNormalizers } from './normalizers.js'/** Every engine map in the table, in the order a turn's state is looked up. */const ENGINE_MAPS = [- 'codexNormalizers', 'cursorNormalizers', 'opencodeReaders', 'kiloReaders', 'piNormalizers', 'museNormalizers',+ 'liveParsers', 'cursorNormalizers', 'opencodeReaders', 'kiloReaders', 'piNormalizers', 'museNormalizers','ampNormalizers', 'grokNormalizers', 'agyNormalizers', 'copilotNormalizers', 'hermesReaders', 'devinReaders','commandcodeNormalizers',] as const@@ -23,8 +22,6 @@ describe('the session normalizer table', () => {it('has state for a session that any engine map holds, and none for one that none does', () => {const table = createSessionNormalizers()expect(table.hasState('s')).toBe(false)- table.turnStates.set('s', { turnOpen: false } as TurnState)- expect(table.hasState('s')).toBe(true)for (const map of ENGINE_MAPS) {const one = createSessionNormalizers()put(one, map, 's', fake())@@ -33,7 +30,7 @@ describe('the session normalizer table', () => {}})- it('reads whether a turn is open from Claude Code\'s state first, then each engine in turn', () => {+ it('reads whether a turn is open from each parser or reader', () => {const table = createSessionNormalizers()expect(table.sessionTurnState('s')).toBeUndefined()expect(table.sessionTurnOpen('s')).toBe(false)@@ -43,20 +40,16 @@ describe('the session normalizer table', () => {expect(one.sessionTurnState('s'), map).toBe(true)expect(one.sessionTurnOpen('s'), map).toBe(true)}- // The first engine that knows wins, even when it says closed: Claude Code's state before Codex's, Codex- // before Cursor, and so on down the list.- table.turnStates.set('s', { turnOpen: false } as TurnState)- put(table, 'codexNormalizers', 's', fake(true))+ // A closed live parser is authoritative even when an old reader still reports an open turn.+ put(table, 'liveParsers', 's', fake(false))+ put(table, 'cursorNormalizers', 's', fake(true))expect(table.sessionTurnState('s')).toBe(false)- table.turnStates.delete('s')- put(table, 'cursorNormalizers', 's', fake(false))+ table.liveParsers.delete('s')expect(table.sessionTurnState('s')).toBe(true)})it('forgets a session in every map, stopping its database readers, and leaves other sessions alone', () => {const table = createSessionNormalizers()- table.turnStates.set('s', { turnOpen: true } as TurnState)- table.turnStates.set('keep', { turnOpen: true } as TurnState)const entries = new Map<EngineMap, Fake>()for (const map of ENGINE_MAPS) {entries.set(map, fake())@@ -65,7 +58,6 @@ describe('the session normalizer table', () => {}table.forget('s')expect(table.hasState('s')).toBe(false)- expect(table.turnStates.has('keep')).toBe(true)for (const map of ENGINE_MAPS) {expect(table[map].has('keep'), map).toBe(true)expect(entries.get(map)!.stop, map).toHaveBeenCalledTimes(DATABASE_READERS.includes(map) ? 1 : 0)@@ -75,18 +67,16 @@ describe('the session normalizer table', () => {it('closes a cancelled turn in every engine', () => {const table = createSessionNormalizers()- const state = { turnOpen: true } as TurnState- table.turnStates.set('s', state)const entries = new Map<EngineMap, Fake>()for (const map of ENGINE_MAPS) {entries.set(map, fake(true))put(table, map, 's', entries.get(map)!)}table.closeTurns('s')- expect(state.turnOpen).toBe(false)for (const map of ENGINE_MAPS) {// Kilo's included: it used to be missed, so a cancelled Kilo agent could go on showing as working.expect(entries.get(map)!.closeTurn, map).toHaveBeenCalledTimes(1)+ if (map === 'liveParsers') expect(entries.get(map)!.closeTurn).toHaveBeenCalledWith('cancel')}expect(() => table.closeTurns('never-seen')).not.toThrow()})diff --git a/cli/src/core/transcripts/normalizers.ts b/cli/src/core/transcripts/normalizers.tsindex b23d73057..ba2cd3887 100644--- a/cli/src/core/transcripts/normalizers.ts+++ b/cli/src/core/transcripts/normalizers.ts@@ -1,5 +1,5 @@/**- * Each session's engine state: Claude Code's turn state, and the normalizer (an engine with a+ * Each session's engine state: a live parser, and the normalizer (an engine with a* transcript file) or reader (an engine with a database) that folds every other engine's history.* One table instead of fourteen maps, so the questions asked of all of them — does this session have* any, is its turn open, forget it, close its turn, stop the pollers — each have one answer.@@ -11,7 +11,7 @@*/import type { AgyNormalizer } from '../../engines/agy/normalizer.js'import type { AmpNormalizer } from '../../engines/amp/normalizer.js'-import type { CodexNormalizer } from '../../engines/codex/normalizer.js'+import type { LiveParser } from '../../engines/facets/live.js'import type { CommandCodeNormalizer } from '../../engines/commandcode/normalizer.js'import type { CopilotNormalizer } from '../../engines/copilot/normalizer.js'import type { CursorNormalizer } from '../../engines/cursor/normalizer.js'@@ -22,12 +22,10 @@ import type { KiloReader } from '../../engines/kilo/reader.js'import type { MuseNormalizer } from '../../engines/muse/normalizer.js'import type { OpencodeReader } from '../../engines/opencode/reader.js'import type { PiNormalizer } from '../../engines/pi/normalizer.js'-import type { TurnState } from '../../lib/normalize.js'export function createSessionNormalizers() {// Per-session web turn-lifecycle state; the device mirror keeps its own state + recap.- const turnStates = new Map<string, TurnState>()- const codexNormalizers = new Map<string, CodexNormalizer>()+ const liveParsers = new Map<string, LiveParser>()const cursorNormalizers = new Map<string, CursorNormalizer>()const opencodeReaders = new Map<string, OpencodeReader>()const kiloReaders = new Map<string, KiloReader>()@@ -43,8 +41,7 @@ export function createSessionNormalizers() {/** Whether this session's engine state says a turn is open right now, whichever engine it is. */const sessionTurnState = (sessionId: string): boolean | undefined =>- turnStates.get(sessionId)?.turnOpen- ?? codexNormalizers.get(sessionId)?.turnOpen+ liveParsers.get(sessionId)?.turnOpen?? cursorNormalizers.get(sessionId)?.turnOpen?? opencodeReaders.get(sessionId)?.turnOpen?? kiloReaders.get(sessionId)?.turnOpen@@ -61,8 +58,7 @@ export function createSessionNormalizers() {/** Whether any engine state exists for this session: an attach that finds some is not a first one. */const hasState = (sessionId: string): boolean =>- turnStates.has(sessionId)- || codexNormalizers.has(sessionId)+ liveParsers.has(sessionId)|| cursorNormalizers.has(sessionId)|| opencodeReaders.has(sessionId)|| kiloReaders.has(sessionId)@@ -78,8 +74,7 @@ export function createSessionNormalizers() {/** Drop all of a forgotten session's engine state, stopping its database readers' pollers. */const forget = (sessionId: string): void => {- turnStates.delete(sessionId)- codexNormalizers.delete(sessionId)+ liveParsers.delete(sessionId)cursorNormalizers.delete(sessionId)opencodeReaders.get(sessionId)?.stop()opencodeReaders.delete(sessionId)@@ -101,9 +96,7 @@ export function createSessionNormalizers() {/** Mark the session's turn closed in whichever engine holds it (a cancel). What a closing* normalizer returns is not emitted: a cancel sends no turn end. */const closeTurns = (sessionId: string): void => {- const st = turnStates.get(sessionId)- if (st) st.turnOpen = false- codexNormalizers.get(sessionId)?.closeTurn()+ liveParsers.get(sessionId)?.closeTurn('cancel')cursorNormalizers.get(sessionId)?.closeTurn()opencodeReaders.get(sessionId)?.closeTurn()kiloReaders.get(sessionId)?.closeTurn()@@ -127,7 +120,7 @@ export function createSessionNormalizers() {}return {- turnStates, codexNormalizers, cursorNormalizers, opencodeReaders, kiloReaders, piNormalizers,+ liveParsers, cursorNormalizers, opencodeReaders, kiloReaders, piNormalizers,museNormalizers, ampNormalizers, grokNormalizers, agyNormalizers, copilotNormalizers, hermesReaders,devinReaders, commandcodeNormalizers,sessionTurnState, sessionTurnOpen, hasState, forget, closeTurns, stopPollers,diff --git a/cli/src/core/turns/turnHooks.spec.ts b/cli/src/core/turns/turnHooks.spec.tsindex 840c06fa9..77fa88223 100644--- a/cli/src/core/turns/turnHooks.spec.ts+++ b/cli/src/core/turns/turnHooks.spec.ts@@ -1,3 +1,4 @@+import type { LiveParser } from '../../engines/facets/live.js'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { removeCursorPendingTasks } from '../../engines/cursor/pendingTasks.js'import type { TurnState } from '../../lib/normalize.js'@@ -5,6 +6,7 @@ import type { RegisteredSession } from '../../lib/registry.js'import { createSessionNormalizers } from '../transcripts/normalizers.js'import { createTurnHooks, STOP_HOOK_GRACE_MS, type TurnHookDeps } from './turnHooks.js'import { engineHooks } from '../../engines/hooks.js'+import type { HookTurnContext } from '../../engines/facets/hooks.js'vi.mock('../../engines/cursor/pendingTasks.js', () => ({ removeCursorPendingTasks: vi.fn(async () => {}) }))@@ -42,6 +44,21 @@ function setup(engine: string, over: Partial<TurnHookDeps> = {}) {return { deps, normalizers, hooks: createTurnHooks(deps) }}+// Existing hook scenarios control transcript arrival without exposing mutable state through the port.+let generation = 0+function parserOf(state: TurnState): LiveParser {+ const identity = ++generation+ return {+ engine: 'claude',+ get turnOpen() { return state.turnOpen },+ snapshot: () => ({ identity: `${identity}:${state.opened ?? 0}`, turnOpen: state.turnOpen, continued: state.continued === true }),+ closeTurn: () => { state.turnOpen = false; state.pendingTools.clear() },+ ingest: () => ({ events: [] }),+ windowStart: () => {},+ }+}+const setState = (run: ReturnType<typeof setup>, state: TurnState) => run.normalizers.liveParsers.set('s1', parserOf(state))+const put = (map: Map<string, unknown>, state: unknown) => map.set('s1', state)describe('turn hooks', () => {@@ -95,12 +112,39 @@ describe('turn hooks', () => {expect(error).toHaveBeenCalledWith('[hooks] claude stop hook failed:', 'engine failed')})+ it('refuses an engine closure for a replaced turn, changed engine or forgotten session', () => {+ let context!: HookTurnContext+ vi.spyOn(engineHooks.claude, 'onStop').mockImplementationOnce((value) => { context = value })+ const row = { sessionId: 's1', engine: 'claude' } as RegisteredSession+ const run = setup('claude', { resolve: (id) => id === 's1' ? row : undefined })+ const state = { turnOpen: true, opened: 1, pendingTools: new Set() } as TurnState+ setState(run, state)+ run.hooks.onTurnStop({ sessionId: 's1' })+ const first = context.turnState('s1')!+ state.opened = 2+ expect(context.closeTurn('s1', first.identity)).toBe(false)+ expect(state.turnOpen).toBe(true)+ row.engine = 'codex'+ expect(context.turnState('s1')).toBeUndefined()+ expect(context.closeTurn('s1', first.identity)).toBe(false)+ row.engine = 'claude'+ expect(context.closeTurn('s1', context.turnState('s1')!.identity)).toBe(true)+ expect(state.turnOpen).toBe(false)+ run.normalizers.forget('s1')+ expect(context.turnState('s1')).toBeUndefined()+ expect(context.closeTurn('s1', first.identity)).toBe(false)+ // A parser whose registry binding disappeared cannot authorize a closure either.+ run.normalizers.liveParsers.set('unbound', parserOf(state))+ expect(context.turnState('unbound')).toBeUndefined()+ expect(context.closeTurn('unbound', first.identity)).toBe(false)+ })+describe('Claude Code', () => {it('lets the transcript close the turn when it can, and closes a wedged one after the grace', async () => {const log = vi.spyOn(console, 'log').mockImplementation(() => {})const run = setup('claude')const state = { turnOpen: true, pendingTools: new Map([['t', {}]]) } as unknown as TurnState- run.normalizers.turnStates.set('s1', state)+ setState(run, state)run.hooks.onTurnStop({ sessionId: 's1', status: 'error' })await vi.advanceTimersByTimeAsync(0)expect(run.deps.mirror.noteEngineStopped).toHaveBeenCalledWith('s1')@@ -126,7 +170,7 @@ describe('turn hooks', () => {const log = vi.spyOn(console, 'log').mockImplementation(() => {})const run = setup('claude')const state = { turnOpen: true, pendingTools: new Map(), continued: true } as unknown as TurnState- run.normalizers.turnStates.set('s1', state)+ setState(run, state)run.hooks.onTurnStop({ sessionId: 's1' })await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS)expect(run.deps.mirror.noteEngineStopped).toHaveBeenCalledWith('s1')@@ -152,7 +196,7 @@ describe('turn hooks', () => {const run = setup('claude')// The Stop's own turn closed already; the drain reads the next prompt's turn opening.const state = { turnOpen: false, opened: 1, pendingTools: new Map() } as unknown as TurnState- run.normalizers.turnStates.set('s1', state)+ setState(run, state)vi.mocked(run.deps.drain).mockImplementationOnce(async () => { state.turnOpen = true; state.opened = 2 })run.hooks.onTurnStop({ sessionId: 's1' })await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS * 2)@@ -165,13 +209,13 @@ describe('turn hooks', () => {expect(state.turnOpen).toBe(true)expect(run.deps.emit).not.toHaveBeenCalled()// The engine's state started over meanwhile (the session attached again): not the turn the Stop found.- run.normalizers.turnStates.set('s1', { turnOpen: true, opened: 3, pendingTools: new Map() } as unknown as TurnState)- vi.mocked(run.deps.drain).mockImplementationOnce(async () => { run.normalizers.turnStates.set('s1', { ...state }) })+ setState(run, { turnOpen: true, opened: 3, pendingTools: new Map() } as unknown as TurnState)+ vi.mocked(run.deps.drain).mockImplementationOnce(async () => { setState(run, { ...state }) })run.hooks.onTurnStop({ sessionId: 's1' })await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS * 2)expect(run.deps.emit).not.toHaveBeenCalled()// A StopFailure closes whatever is open.- run.normalizers.turnStates.set('s1', state)+ setState(run, state)run.hooks.onTurnStop({ sessionId: 's1', status: 'error' })await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS * 2)expect(state.turnOpen).toBe(false)@@ -183,7 +227,7 @@ describe('turn hooks', () => {const log = vi.spyOn(console, 'log').mockImplementation(() => {})const run = setup('claude')const state = { turnOpen: true, opened: 2, pendingTools: new Map() } as unknown as TurnState- run.normalizers.turnStates.set('s1', state)+ setState(run, state)run.hooks.onPromptHook('s1', 2_000)// An older prompt hook, arriving late, does not move it back.run.hooks.onPromptHook('s1', 1_500)@@ -209,7 +253,7 @@ describe('turn hooks', () => {it('says Stop for a clean stop', async () => {const log = vi.spyOn(console, 'log').mockImplementation(() => {})const run = setup('claude')- run.normalizers.turnStates.set('s1', { turnOpen: true, pendingTools: new Map() } as unknown as TurnState)+ setState(run, { turnOpen: true, pendingTools: new Map() } as unknown as TurnState)run.hooks.onTurnStop({ sessionId: 's1' })await vi.advanceTimersByTimeAsync(STOP_HOOK_GRACE_MS)expect(String(log.mock.calls[0][0])).toContain('force-closed by Stop hook')diff --git a/cli/src/core/turns/turnHooks.ts b/cli/src/core/turns/turnHooks.tsindex 39434b88e..2666ad48d 100644--- a/cli/src/core/turns/turnHooks.ts+++ b/cli/src/core/turns/turnHooks.ts@@ -47,7 +47,7 @@ export function createTurnHooks({resolve, normalizers, emit, drain, onCursorTaskStart, cursorTaskHooks, cursorSubagents, announceTurnAborted,armAgyIdleWatch, clearAgyIdleWatch, mirror, dataDir,}: TurnHookDeps) {- const { turnStates, commandcodeNormalizers, cursorNormalizers, devinReaders, copilotNormalizers, agyNormalizers, grokNormalizers } = normalizers+ const { liveParsers, commandcodeNormalizers, cursorNormalizers, devinReaders, copilotNormalizers, agyNormalizers, grokNormalizers } = normalizers// Command Code's PreToolUse — the one live "a turn is running" signal this engine has. Without it the// adapter only learned of a turn from Stop, and emitted turn_started+turn_ended in the same// millisecond, so the device tile jumped from idle straight to the recap with no working state.@@ -68,7 +68,16 @@ export function createTurnHooks({if (promptFiredAt.size > PROMPT_HOOKS_KEPT) promptFiredAt.delete(promptFiredAt.keys().next().value!)}const hookTurns: HookTurnContext = {- turnState: (sessionId) => turnStates.get(sessionId),+ turnState: (sessionId) => {+ const parser = liveParsers.get(sessionId)+ return parser && parser.engine === resolve(sessionId)?.engine ? parser.snapshot() : undefined+ },+ closeTurn: (sessionId, identity) => {+ const parser = liveParsers.get(sessionId)+ if (!parser || parser.engine !== resolve(sessionId)?.engine || parser.snapshot().identity !== identity) return false+ parser.closeTurn('hook')+ return true+ },latestPromptAt: (sessionId) => promptFiredAt.get(sessionId),drain,noteEngineStopped: (sessionId) => mirror.noteEngineStopped(sessionId),diff --git a/cli/src/engines/claude/attach.ts b/cli/src/engines/claude/attach.tsnew file mode 100644index 000000000..92e6e70bc--- /dev/null+++ b/cli/src/engines/claude/attach.ts@@ -0,0 +1,22 @@+import { claudeToolLinks, startsClaudeTurn } from './normalize.js'+import type { AttachRules } from '../../lib/attachTranscript.js'+import type { RuntimeField } from '../../lib/runtimeProfile.js'++const bytes = (...markers: string[]): Buffer[] => markers.map((marker) => Buffer.from(marker))++/**+ * Claude Code: a turn opens on a real user prompt, always a `"type":"user"` record. Its results name+ * their tool from the call that made it, so calls the turn answers are reached for. The chips read+ * only the model from the transcript — the attach takes effort from Claude's settings straight after —+ * and `Set model to` is matched case-insensitively, so field records are asked for without a byte test.+ */+export function claudeAttachRules(fields: (line: string) => readonly RuntimeField[]): AttachRules {+ return {+ startsTurn: startsClaudeTurn,+ turnMarkers: bytes('"user"'),+ fields,+ required: ['model'],+ links: claudeToolLinks,+ linkMarkers: bytes('tool_use', 'tool_result'),+ }+}diff --git a/cli/src/engines/claude/hooks.ts b/cli/src/engines/claude/hooks.tsindex ad23b79a1..84bb7a334 100644--- a/cli/src/engines/claude/hooks.ts+++ b/cli/src/engines/claude/hooks.ts@@ -1,7 +1,7 @@import { existsSync } from 'node:fs'import { basename, join } from 'node:path'import { sid } from '../../lib/log.js'-import type { TurnState } from '../../lib/normalize.js'+import type { LiveTurn } from '../facets/live.js'import type { EngineHooks, HookSession, HookStop, HookTurnContext } from '../facets/hooks.js'import { installSessionHooks } from './installHooks.js'@@ -24,13 +24,13 @@ export function transcriptFor(body: HookSession, agent: HookSession | undefined)/** Capture the arrival's turn before the first await: a drain can open the next turn. */async function onStop(- { turnState, latestPromptAt, drain, noteEngineStopped, emit, graceMs }: HookTurnContext,+ { turnState, closeTurn, latestPromptAt, drain, noteEngineStopped, emit, graceMs }: HookTurnContext,{ sessionId, status, firedAt }: HookStop,): Promise<void> {// A pass a blocking Stop hook continued (a /goal loop) is the transcript's to close, by its end_turn or// turn_duration: the Stop of the pass before it reached the daemon 520 ms after it began (end to end,// under load) and force-closed it while it ran. Only a StopFailure still closes one here.- const leftToTranscript = (st: TurnState): boolean => st.continued === true && status !== 'error'+ const leftToTranscript = (st: LiveTurn): boolean => st.continued === true && status !== 'error'// A Stop closes only the turn it is about. Found by the soak run (e2e/endurance.e2e.ts): under load a turn's// Stop reached the daemon 6 s late, after the next prompt's turn had opened, and force-closed that turn// with a question open in it, which was then never shown. So:@@ -41,8 +41,8 @@ async function onStop(// A turn left open with no end of its own is closed by the next prompt (lib/normalize.ts).const stale = firedAt !== undefined && (latestPromptAt(sessionId) ?? 0) > firedAtconst arrived = turnState(sessionId)- const about = arrived?.turnOpen ? arrived.opened ?? 0 : null- const itsTurn = (st: TurnState): boolean => !stale && (status === 'error' || (st === arrived && about !== null && (st.opened ?? 0) === about))+ const about = arrived?.turnOpen ? arrived.identity : null+ const itsTurn = (st: LiveTurn): boolean => !stale && (status === 'error' || (about !== null && st.identity === about))await drain(sessionId)// A Stop hook is the one precise "the engine stopped writing" signal we get. When the mirror is// HOLDING a turn-end for finished async sub-agents, this is what tells it the wrap-up message is@@ -56,9 +56,7 @@ async function onStop(await new Promise((r) => setTimeout(r, graceMs))await drain(sessionId)const st = turnState(sessionId)- if (st?.turnOpen && !leftToTranscript(st) && itsTurn(st)) {- st.turnOpen = false- st.pendingTools.clear()+ if (st?.turnOpen && !leftToTranscript(st) && itsTurn(st) && closeTurn(sessionId, st.identity)) {console.log(`[turn] ${sid(sessionId)} force-closed by ${status === 'error' ? 'StopFailure' : 'Stop'} hook (after grace)`)emit(sessionId, [{ type: 'turn_ended', payload: {} }])}diff --git a/cli/src/engines/claude/live.ts b/cli/src/engines/claude/live.tsnew file mode 100644index 000000000..5fdc99a7d--- /dev/null+++ b/cli/src/engines/claude/live.ts@@ -0,0 +1,23 @@+import { randomUUID } from 'node:crypto'+import type { EngineLive, LiveParser } from '../facets/live.js'+import { claudeAttachRules } from './attach.js'+import { lineToEvents, newTurnState } from './normalize.js'++function create(session: Parameters<EngineLive['create']>[0]): LiveParser {+ const state = newTurnState()+ const generation = randomUUID()+ return {+ engine: session.engine,+ get turnOpen() { return state.turnOpen },+ ingest: (line) => ({ events: lineToEvents(line, state) }),+ snapshot: () => ({ identity: `${generation}:${state.opened ?? 0}`, turnOpen: state.turnOpen, continued: state.continued === true }),+ closeTurn(reason) {+ state.turnOpen = false+ // A cancel has historically kept tool links and pending calls; a relaunch or Stop clears them.+ if (reason !== 'cancel') state.pendingTools.clear()+ },+ windowStart: (offset) => { state.thinkingPrefix = `thinking-live-${offset.toString(36)}-` },+ }+}++export const live: EngineLive = { create, attachRules: claudeAttachRules }diff --git a/cli/src/engines/claude/normalize.ts b/cli/src/engines/claude/normalize.tsnew file mode 100644index 000000000..1da9b63ad--- /dev/null+++ b/cli/src/engines/claude/normalize.ts@@ -0,0 +1,977 @@+/**+ * Claude-Code JSONL → web ServerEvent normalizer.+ *+ * Self-contained port of the hosted runtime’s replay normalizer+ * (`the hosted runtime`: transformCCMessageToSessionMessage,+ * sessionMessagesToEvents, stripContextSummary/stripSystemBlocks + tool-summary)+ * — this package has no dependency outside itself.+ *+ * Two entry points:+ * - messagesToEvents(rawLines) → full SessionEvent[] replay for `session_get`.+ * - lineToEvents(rawLine, state) → incremental events for live tailing, PLUS a derived+ * turn lifecycle (turn_started / turn_ended) so a prompt typed directly in the terminal+ * renders identically to one sent from the web (mirror-all).+ */++import { harnessWebTool } from '../../lib/harnessWebTools.js'++import type { SubagentSummary, SessionEvent, LiveEvent, LastTurnText } from '../kit/events.js'++interface RawContentBlock {+ type: 'text' | 'tool_use' | 'tool_result' | 'thinking' | 'image'+ text?: string+ thinking?: string+ id?: string+ name?: string+ input?: unknown+ tool_use_id?: string+ content?: string | Array<{ type: string; text?: string }>+ is_error?: boolean+ source?: { type: string; media_type: string; data: string }+}++interface NormalizedMessage {+ type: 'user' | 'assistant'+ message?: { role: 'user' | 'assistant'; content: RawContentBlock[] }+ toolUseResult?: SubagentSummary & { status?: string; durationSeconds?: number }+ /** Raw Anthropic stop_reason from the assistant line (drives turn_ended). */+ stopReason?: string | null+}++const MAX_OUTPUT = 2000+const MAX_THINKING = 500+const MAX_DIFF_SIDE = 1500+const PREVIEW_LINES = 8++// ── Text cleanup (ported verbatim) ────────────────────────────────────────────────────────────────++/** Strip the compaction-injected context summary; null if the whole message was summary. */+export function stripContextSummary(text: string): string | null {+ const endMarker = '<!-- END CONTEXT SUMMARY -->'+ const idx = text.indexOf(endMarker)+ if (idx === -1) return text+ let remaining = text.slice(idx + endMarker.length)+ remaining = remaining.replace(/^\s*---\s*Now,?\s*continuing.*?:\s*/is, '')+ remaining = remaining.trim()+ return remaining || null+}++/** Strip system-injected blocks not meant for UI display. */+export function stripSystemBlocks(text: string): string {+ return text+ .replace(/<task-notification>[\s\S]*?<\/task-notification>\s*/g, '')+ .replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g, '')+ .replace(/<goal-context>[\s\S]*?<\/goal-context>\s*/g, '')+ .replace(/<dev-server-context>[\s\S]*?<\/dev-server-context>\s*/g, '')+ .replace(/<available-deferred-tools>[\s\S]*?<\/available-deferred-tools>\s*/g, '')+ .replace(/<local-command-caveat>[\s\S]*?<\/local-command-caveat>\s*/g, '')+ .replace(/<command-name>[\s\S]*?<\/command-name>\s*/g, '')+ .replace(/<command-message>[\s\S]*?<\/command-message>\s*/g, '')+ .replace(/<command-args>[\s\S]*?<\/command-args>\s*/g, '')+ .replace(/<local-command-stdout>[\s\S]*?<\/local-command-stdout>\s*/g, '')+ .replace(/Read the output file to retrieve the result:[^\n]*/g, '')+ .trim()+}++/**+ * Bash mode (`!command` in Claude Code) writes the command and its output back into the transcript as a+ * `type:'user'` line — `<bash-input>…</bash-input>` and the `<bash-stdout>`/`<bash-stderr>` that follow.+ * It is the person running a local shell, NOT a prompt to the agent, so it must not open a turn: if it+ * did, the per-turn recap would summarise shell mechanics ("paste the command on one line") instead of+ * what the agent is actually working on, and the tile would drift off-task with every `!`. Stripped ONLY+ * for the turn-detection decision (see `realUserText`), never for display — the transcript still shows+ * the commands. A line carrying real prose ALONGSIDE a bash block keeps counting; only a bash-only line+ * is skipped.+ */+export function stripBashModeBlocks(text: string): string {+ return text+ .replace(/<bash-input>[\s\S]*?<\/bash-input>\s*/g, '')+ .replace(/<bash-stdout>[\s\S]*?<\/bash-stdout>\s*/g, '')+ .replace(/<bash-stderr>[\s\S]*?<\/bash-stderr>\s*/g, '')+ .trim()+}++// Built-in CLI commands that only drive the local TUI and never dispatch an agent turn. Surfacing+// them as a user prompt would open a turn nothing ever closes (device tile stuck busy), so they stay+// invisible — same as before. Anything else (a custom `~/.claude/commands/*.md`, `/goal`, `/review`,+// a plugin skill) DOES run a turn and must be visible.+const LOCAL_ONLY_COMMANDS = new Set([+ 'add-dir', 'agents', 'bug', 'clear', 'compact', 'config', 'context', 'copy', 'cost', 'desktop',+ 'doctor', 'effort', 'exit', 'export', 'help', 'hooks', 'ide', 'login', 'logout', 'mcp', 'memory',+ 'model', 'output-style', 'permissions', 'privacy-settings', 'quit', 'release-notes',+ 'reload-plugins', 'resume', 'skills', 'statusline', 'status', 'terminal-setup', 'todos',+ 'upgrade', 'vim',+])++/** A whole prompt that is one of LOCAL_ONLY_COMMANDS, typed plainly: `/compact`, `/model opus`. */+function isLocalOnlyCommandLine(text: string): boolean {+ const name = /^\/([A-Za-z][\w-]*)(?:\s|$)/.exec(text.trim())?.[1]+ return name !== undefined && LOCAL_ONLY_COMMANDS.has(name.toLowerCase())+}++/**+ * `<command-name>/goal</command-name>…<command-args>x</command-args>` → `/goal x`.+ *+ * Claude Code records a slash command ONLY as these tags (the expansion it actually sends to the+ * model is written as a separate `isMeta` line, which we suppress). `stripSystemBlocks` erases the+ * tags, so without this the whole line normalizes to "" → `realUserText` returns null → NO+ * `turn_started` is ever emitted for a command prompt. That broke the device's goal mode: the+ * injected `/goal <text>` ran fine in the terminal, but `SessionInputController` never saw the turn+ * open and reported "The agent did not accept the message" after its submit retries — and the recap+ * had no user message to lead with.+ */+function commandPromptText(text: string): string | null {+ const name = text.match(/<command-name>\s*([^<]*?)\s*<\/command-name>/)?.[1]+ if (!name) return null+ const bare = name.replace(/^\//, '').trim()+ if (!bare || LOCAL_ONLY_COMMANDS.has(bare.toLowerCase())) return null+ const args = text.match(/<command-args>([\s\S]*?)<\/command-args>/)?.[1]?.trim() ?? ''+ return args ? `/${bare} ${args}` : `/${bare}`+}++/** Short title heuristic for a thinking block (first 3-8 words of the first line). */+function extractThinkingTitle(thinking: string): string | null {+ const trimmed = thinking.trim()+ if (!trimmed || trimmed.length < 10) return null+ const firstLine = trimmed.split('\n')[0].replace(/^[\s#*\->]+/, '').trim()+ if (!firstLine) return null+ const words = firstLine.split(/\s+/).slice(0, 8)+ if (words.length < 2) return null+ let title = words.join(' ').replace(/[.,:;!?]+$/, '')+ if (title.length > 60) title = title.slice(0, 57) + '...'+ return title+}++/** The short ⎿ label shown after a tool finishes (e.g. "Read 247 lines"). */+function computeToolSummary(toolName: string, rawOutput: string, isError: boolean): string {+ if (isError) return rawOutput.split('\n')[0]?.slice(0, 80) || 'Error'+ switch (toolName) {+ case 'Bash': {+ const match = rawOutput.match(/^Exit code (\d+)/)+ return match ? `Exit ${match[1]}` : 'Done'+ }+ case 'Read': {+ const lineCount = (rawOutput.match(/^\s*\d+→/gm) || []).length+ return lineCount > 0 ? `Read ${lineCount} lines` : 'Read'+ }+ case 'Write':+ case 'WriteFile':+ return rawOutput.includes('successfully') ? 'Written' : rawOutput.slice(0, 60)+ case 'Edit':+ case 'EditFile':+ return rawOutput.includes('successfully') ? 'Updated' : rawOutput.slice(0, 60)+ case 'Glob': {+ const count = rawOutput.trim() ? rawOutput.trim().split('\n').length : 0+ return `${count} file${count !== 1 ? 's' : ''}`+ }+ case 'Grep': {+ const count = rawOutput.trim() ? rawOutput.trim().split('\n').length : 0+ return `${count} match${count !== 1 ? 'es' : ''}`+ }+ case 'WebFetch':+ case 'WebSearch':+ return 'Fetched'+ case 'TodoRead':+ case 'TodoWrite':+ return 'Done'+ default:+ return rawOutput.split('\n')[0]?.slice(0, 80) || 'Done'+ }+}++// ── Raw JSONL line → normalized message (port of transformCCMessageToSessionMessage) ─────────────++function smartWriteInput(input: Record<string, unknown>): Record<string, unknown> {+ const raw = input.content as string+ const lines = raw.split('\n')+ const preview = lines.slice(0, PREVIEW_LINES).join('\n')+ return {+ ...input,+ content: undefined,+ content_stats: {+ lines: lines.length,+ chars: raw.length,+ preview: preview + (lines.length > PREVIEW_LINES ? '\n…' : ''),+ },+ }+}++function smartEditInput(input: Record<string, unknown>): Record<string, unknown> {+ const truncSide = (s: unknown): unknown => {+ if (typeof s !== 'string') return s+ if (s.length <= MAX_DIFF_SIDE) return s+ const half = Math.floor(MAX_DIFF_SIDE / 2)+ return s.slice(0, half) + '\n…\n' + s.slice(s.length - half)+ }+ return { ...input, old_string: truncSide(input.old_string), new_string: truncSide(input.new_string) }+}++function mapContentItem(item: unknown): RawContentBlock {+ const c = (item ?? {}) as Record<string, unknown> // a null content block must not throw on `.type`+ const type = (c.type || 'text') as RawContentBlock['type']++ if (type === 'image') {+ return { type: 'image', source: c.source as RawContentBlock['source'] }+ }++ let resultContent = c.content as RawContentBlock['content']+ if (type === 'tool_result' && typeof resultContent === 'string' && resultContent.length > MAX_OUTPUT) {+ resultContent = resultContent.slice(0, MAX_OUTPUT) + '\n…[truncated]'+ }++ let toolInput = c.input as Record<string, unknown> | undefined+ let toolName = c.name as string | undefined+ // On a Local model the web tools come from the `harness` MCP server; the transcript should not+ // look different for it, so they take the native cards here, at the one raw→normalized point.+ const webTool = type === 'tool_use' ? harnessWebTool(toolName, toolInput) : null+ if (webTool) {+ toolName = webTool.tool+ toolInput = webTool.input+ }+ if (type === 'tool_use' && toolInput) {+ if ((toolName === 'Write' || toolName === 'WriteFile') && typeof toolInput.content === 'string' && toolInput.content.length > 500) {+ toolInput = smartWriteInput(toolInput)+ } else if (+ (toolName === 'Edit' || toolName === 'EditFile') &&+ (((toolInput.old_string as string)?.length ?? 0) > MAX_DIFF_SIDE || ((toolInput.new_string as string)?.length ?? 0) > MAX_DIFF_SIDE)+ ) {+ toolInput = smartEditInput(toolInput)+ }+ }++ return {+ type,+ text: c.text as string | undefined,+ thinking: c.thinking as string | undefined,+ id: c.id as string | undefined,+ name: toolName,+ input: toolInput,+ tool_use_id: c.tool_use_id as string | undefined,+ content: resultContent,+ is_error: c.is_error as boolean | undefined,+ }+}++/** Parse one raw JSONL entry into a normalized user/assistant message (null for other types). */+export function transformLine(rawMessage: Record<string, unknown>): NormalizedMessage | null {+ const type = rawMessage.type as string+ if (type !== 'user' && type !== 'assistant') return null++ const messageObj = rawMessage.message as Record<string, unknown> | undefined+ let messageContent: RawContentBlock[] | undefined++ if (messageObj) {+ const role = messageObj.role as string+ const content = messageObj.content+ if (role === 'user' || role === 'assistant') {+ if (typeof content === 'string') {+ messageContent = [{ type: 'text', text: content }]+ } else if (Array.isArray(content)) {+ messageContent = content.length > 0 ? content.map(mapContentItem) : [{ type: 'text', text: '' }]+ } else if (content === null || content === undefined) {+ messageContent = [{ type: 'text', text: '' }]+ }+ }+ } else if (type === 'user') {+ const directContent = rawMessage.content+ if (typeof directContent === 'string') {+ messageContent = [{ type: 'text', text: directContent }]+ } else if (Array.isArray(directContent)) {+ messageContent = directContent.map(mapContentItem)+ }+ }++ let toolUseResult: NormalizedMessage['toolUseResult']+ if (rawMessage.tool_use_result || rawMessage.toolUseResult) {+ const tr = (rawMessage.tool_use_result || rawMessage.toolUseResult) as Record<string, unknown>+ toolUseResult = {+ status: (tr.status || 'complete') as string,+ agentId: (tr.agentId ?? tr.agent_id) as string | undefined,+ agentType: (tr.agentType ?? tr.agent_type) as string | undefined,+ totalTokens: tr.totalTokens as number | undefined,+ totalDurationMs: tr.totalDurationMs as number | undefined,+ totalToolUseCount: tr.totalToolUseCount as number | undefined,+ // WebSearch carries its search time here (the CLI's "Did 1 search in Ns" line).+ durationSeconds: typeof tr.durationSeconds === 'number' ? tr.durationSeconds : undefined,+ }+ }++ const role = (messageObj?.role || (type === 'user' ? 'user' : 'assistant')) as 'user' | 'assistant'++ if (role === 'user' && messageContent) {+ for (const block of messageContent) {+ if (block.type !== 'text' || !block.text) continue+ // A typed slash command survives as `/name args`; everything else is stripped as before.+ block.text = commandPromptText(block.text) ?? stripSystemBlocks(block.text)+ }+ }++ if (messageContent === undefined) messageContent = [{ type: 'text', text: '' }]++ return {+ type: type as 'user' | 'assistant',+ message: { role, content: messageContent },+ toolUseResult,+ stopReason: (messageObj?.stop_reason as string | null | undefined) ?? null,+ }+}++// ── Shared per-message event emission ─────────────────────────────────────────────────────────────++// Auto-fix / platform prompts filtered from replay (sent by the platform, not the user).+const SYSTEM_PROMPT_PATTERNS = [+ 'The dev server is running but the app has an error:',+ 'Please fix this code issue. Check the page component, routing, and any compile errors.',+ '<!-- CONTEXT SUMMARY',+ 'This session is being continued from a previous conversation',+ '<local-command-stdout>Compacted',+]++function isSystemPrompt(content: RawContentBlock[]): boolean {+ const text = content.filter((c) => c.type === 'text' && c.text).map((c) => c.text!).join('')+ return SYSTEM_PROMPT_PATTERNS.some((p) => text.includes(p))+}++/** A REAL user prompt (not a tool_result echo, not a platform prompt). Returns the cleaned text or null. */+/**+ * An ESC interrupt (terminal, or a Stop from the web/device) is written to the transcript as a plain user+ * line — `type:'user'`, `userType:'external'`, no `isMeta`, no flag of ANY kind — so its text is the only+ * thing distinguishing it from something the user typed. Treating it as a prompt opened a brand-new turn at+ * the instant a turn was cancelled, and the device then counted seconds forever on a turn no assistant+ * would ever answer. Covers the `for tool use` variant too. A user who literally types this loses one turn+ * card; that is the cheaper failure.+ */+const INTERRUPT_MARKER = /^\[Request interrupted by user[^\]]*\]$/++/** The user-authored text of a line, before interrupt markers are judged. null = not a user prompt. */+function userTextRaw(msg: NormalizedMessage): string | null {+ if (msg.type !== 'user' || !msg.message) return null+ const content = msg.message.content+ if (isSystemPrompt(content)) return null+ if (content.some((c) => c.type === 'tool_result')) return null+ const parts: string[] = []+ for (const block of content) {+ if (block.type !== 'text' || !block.text) continue+ let cleaned = stripContextSummary(block.text)+ if (cleaned) cleaned = stripSystemBlocks(cleaned)+ if (cleaned && !cleaned.match(/^\[Image: original \d+x\d+/)) parts.push(cleaned)+ }+ const text = parts.join('\n')+ return text || null+}++/**+ * An async sub-agent's REAL completion. Claude's `Agent` tool returns in milliseconds with+ * "Async agent launched successfully." — that `tool_result` is a launch ack, not a result, and taking it+ * for one made the device tick a sub-agent off the moment it started. The actual finish arrives much+ * later as a `type:"user"` record the CLI injects into the parent transcript:+ *+ * <task-notification><task-id>…</task-id><tool-use-id>toolu_018wkW…</tool-use-id>+ * <output-file>…</output-file><status>completed</status><summary>Agent "…" finished…+ *+ * `stripSystemBlocks` erases the whole block, so it correctly starts no turn — but that also meant the+ * only signal a sub-agent had finished was being thrown away. Read it here, keyed by tool-use-id.+ *+ * Takes the RAW record, not a NormalizedMessage: `transformLine` already ran the strip (line ~304), so by+ * then the text block is empty and there is nothing left to parse.+ */+function taskNotificationEvent(raw: Record<string, unknown>): LiveEvent | null {+ // One that finishes while its parent still works comes as a `queued_command` attachment, the more common+ // delivery (real 2.1.270–2.1.287). Read from user records alone, it never finished on the dial.+ const attachment = raw.type === 'attachment' ? raw.attachment as { type?: unknown; prompt?: unknown } | undefined : undefined+ if (raw.type !== 'user' && attachment?.type !== 'queued_command') return null+ const content = attachment ? attachment.prompt : (raw.message as { content?: unknown } | undefined)?.content ?? raw.content+ let text = ''+ if (typeof content === 'string') text = content+ else if (Array.isArray(content)) {+ text = content+ .map((b) => (typeof b === 'string' ? b : (b as RawContentBlock)?.type === 'text' ? String((b as RawContentBlock).text ?? '') : ''))+ .join('\n')+ }+ if (!text.includes('<task-notification>')) return null+ const id = text.match(/<tool-use-id>([^<]+)<\/tool-use-id>/)?.[1]?.trim()+ if (!id) return null+ const status = text.match(/<status>([^<]+)<\/status>/)?.[1]?.trim() || 'completed'+ const summary = text.match(/<summary>([\s\S]*?)(?:<\/summary>|$)/)?.[1]?.trim()+ return { type: 'subagent_finished', payload: { id, status, ...(summary ? { summary } : {}) } }+}++/** True for the synthetic line an interrupt leaves behind. It ends a turn; it never starts one. */+function isInterruptLine(msg: NormalizedMessage): boolean {+ const text = userTextRaw(msg)+ return text !== null && INTERRUPT_MARKER.test(text)+}++// Every caller of this asks "is this a prompt the user made?" — turn slicing for replay and the recap's+// user-message source as well as the live turn lifecycle — and an interrupt marker is not one of those.+function realUserText(msg: NormalizedMessage): string | null {+ const text = userTextRaw(msg)+ if (text === null || INTERRUPT_MARKER.test(text)) return null+ // Claude Code 2.1.290 also writes a built-in command it runs itself as a plain user line ("/compact"),+ // ahead of the tagged record `commandPromptText` already keeps out. Taken as a prompt, it opened a turn+ // nothing ever closed: after a /compact the agent read working, then unknown, until the next message+ // (found by daemon QA). The same list decides both forms.+ if (isLocalOnlyCommandLine(text)) return null+ // A `!command` line is not a prompt — skip it so the turn (and its recap) stays anchored to the last+ // real ask. Only when nothing but bash blocks remain: a message that also carries prose still counts.+ if (!stripBashModeBlocks(text)) return null+ return text+}++/**+ * Extract the last real user prompt and the assistant text that followed it from+ * raw Claude JSONL. This is the recap source of truth: it matches replay parsing+ * rules, skips tool_result echoes / platform prompts / compact metadata, and only+ * summarizes assistant text blocks.+ */+export function lastTurnTextFromRawLines(rawLines: string[]): LastTurnText | null {+ let userMessage = ''+ // What the assistant said AFTER its last tool call: the answer. Everything before it is narration of+ // the work ("Let me check the logs"), kept aside because a turn that never reached an answer (it ended+ // on a tool call, or was interrupted) still has something to summarize.+ let assistantParts: string[] = []+ let narration: string[] = []++ for (const line of rawLines) {+ if (!line.trim()) continue+ let raw: Record<string, unknown>+ try { raw = JSON.parse(line) as Record<string, unknown> } catch { continue }+ const compact = compactEventFromRaw(raw)+ if (compact !== undefined) continue++ const msg = transformLine(raw)+ if (!msg?.message) continue++ const userText = realUserText(msg)+ if (userText !== null) {+ userMessage = userText+ assistantParts = []+ narration = []+ continue+ }++ if (msg.type !== 'assistant') continue+ const text = msg.message.content+ .filter((c) => c.type === 'text' && c.text)+ .map((c) => c.text!)+ .join('')+ .trim()+ if (text) assistantParts.push(text)+ // A tool call closes the stretch of text before it: that was narration, and the answer is what comes+ // after the last one. Without this a long working turn is summarized by its FIRST line, so the+ // dial and the reader show "Let me look at the logs" instead of what was found.+ if (msg.message.content.some((c) => c.type === 'tool_use')) {+ narration = narration.concat(assistantParts)+ assistantParts = []+ }+ }++ const assistantText = (assistantParts.length ? assistantParts : narration).join('\n\n').trim()+ return assistantText ? { userMessage, assistantText } : null+}++/** Aggregates computed from a sub-agent's OWN transcript. Async/background agents never get totals+ * in the launcher's toolUseResult (it only records `{isAsync, status:'async_launched', agentId}` at+ * launch) — the real numbers live in `<session>/subagents/agent-<id>.jsonl`. totalTokens mirrors the+ * CLI's definition: input + output + cache_read + cache_creation summed over assistant turns. Taken a+ * line at a time, so a long transcript is never held whole. */+export class SubagentStats {+ private toolCount = 0+ private tokens = 0+ private first: number | undefined+ private last: number | undefined++ push(line: string): void {+ if (!line.trim()) return+ let raw: Record<string, unknown>+ try { raw = JSON.parse(line) as Record<string, unknown> } catch { return }+ if (!raw || typeof raw !== 'object') return+ const ts = typeof raw.timestamp === 'string' ? Date.parse(raw.timestamp) : NaN+ if (!Number.isNaN(ts)) { if (this.first === undefined) this.first = ts; this.last = ts }+ if (raw.type !== 'assistant') return+ const msg = raw.message as { content?: unknown; usage?: Record<string, unknown> } | undefined+ if (!msg) return+ if (Array.isArray(msg.content)) {+ for (const b of msg.content) if ((b as { type?: string }).type === 'tool_use') this.toolCount+++ }+ const u = msg.usage+ if (u) {+ this.tokens += (Number(u.input_tokens) || 0) + (Number(u.output_tokens) || 0)+ + (Number(u.cache_read_input_tokens) || 0) + (Number(u.cache_creation_input_tokens) || 0)+ }+ }++ result(): { totalToolUseCount: number; totalDurationMs?: number; totalTokens?: number } {+ const { first, last } = this+ return {+ totalToolUseCount: this.toolCount,+ totalDurationMs: first !== undefined && last !== undefined && last > first ? last - first : undefined,+ totalTokens: this.tokens || undefined,+ }+ }+}++export function subagentStatsFromRawLines(rawLines: string[]): { totalToolUseCount: number; totalDurationMs?: number; totalTokens?: number } {+ const stats = new SubagentStats()+ for (const line of rawLines) stats.push(line)+ return stats.result()+}++/** Emit tool_end events for a user message's tool_result blocks. */+function toolResultEvents(msg: NormalizedMessage, toolIdToName: Map<string, string>): SessionEvent[] {+ const events: SessionEvent[] = []+ if (!msg.message) return events+ for (const block of msg.message.content) {+ if (block.type !== 'tool_result') continue+ const toolUseId = block.tool_use_id || ''+ const isError = block.is_error === true+ let rawOutput = ''+ if (typeof block.content === 'string') {+ rawOutput = block.content+ } else if (Array.isArray(block.content)) {+ rawOutput = block.content.filter((c) => c.type === 'text' && c.text).map((c) => c.text!).join('')+ }+ const toolName = toolIdToName.get(toolUseId) || ''+ const summary = computeToolSummary(toolName, rawOutput, isError)+ if (rawOutput.length > MAX_OUTPUT) rawOutput = rawOutput.slice(0, MAX_OUTPUT) + '\n…[truncated]'+ const agg = msg.toolUseResult+ const subagent = agg?.agentId+ ? { agentId: agg.agentId, agentType: agg.agentType, totalTokens: agg.totalTokens, totalDurationMs: agg.totalDurationMs, totalToolUseCount: agg.totalToolUseCount }+ : undefined+ events.push({+ type: 'tool_end',+ payload: {+ id: toolUseId, tool: toolName, output: rawOutput, isError, summary,+ ...(subagent ? { subagent } : {}),+ ...(typeof agg?.durationSeconds === 'number' ? { durationSeconds: agg.durationSeconds } : {}),+ },+ })+ }+ return events+}++/** Emit thinking/text/tool_start events for an assistant message's blocks. */+function assistantEvents(+ msg: NormalizedMessage,+ toolIdToName: Map<string, string>,+ thinkingIdPrefix: string,+ thinkingCounterStart = 0,+): SessionEvent[] {+ const events: SessionEvent[] = []+ if (!msg.message) return events+ let thinkingCounter = thinkingCounterStart+ for (const block of msg.message.content) {+ if (block.type === 'thinking' && block.thinking) {+ const thinkingId = `${thinkingIdPrefix}${thinkingCounter++}`+ const thinkingContent = block.thinking.length > MAX_THINKING+ ? block.thinking.slice(0, MAX_THINKING) + '\n…[truncated]'+ : block.thinking+ events.push({ type: 'thinking_delta', payload: { content: thinkingContent, thinkingId } })+ const title = extractThinkingTitle(block.thinking)+ if (title) events.push({ type: 'thinking_title', payload: { thinkingId, title } })+ } else if (block.type === 'text' && block.text) {+ events.push({ type: 'text_delta', payload: { content: block.text } })+ } else if (block.type === 'tool_use') {+ const toolId = block.id || ''+ const toolName = block.name || ''+ toolIdToName.set(toolId, toolName)+ let toolInput = block.input+ if (toolInput && typeof toolInput === 'object') {+ const inputCopy = { ...(toolInput as Record<string, unknown>) }+ for (const [key, val] of Object.entries(inputCopy)) {+ if (typeof val === 'string' && val.length > MAX_OUTPUT) {+ inputCopy[key] = val.slice(0, MAX_OUTPUT) + '\n…[truncated]'+ }+ }+ toolInput = inputCopy+ }+ events.push({ type: 'tool_start', payload: { id: toolId, tool: toolName, input: toolInput } })+ }+ }+ return events+}++// ── Compaction lines ────────────────────────────────────────────────────────────────────────────+//+// When a tmux claude session compacts (auto or `/compact`), it does an IN-FILE compact: the JSONL+// keeps the SAME sessionId and is append-only (pre-compact history stays on disk), so the byte-offset+// tail streams straight through — there is no dead file to re-point at and no truncation to re-read.+// The compact only injects a few bookkeeping lines we must handle so the stream stays clean:+// • `system` / `subtype:"compact_boundary"` (+ `compactMetadata.trigger`) → one `context_compact`+// indicator (purely a UI hint; the actual stream continuity is already guaranteed by the tail).+// • the injected `isCompactSummary` user line (the big "This session is being continued…" summary)+// and any `isMeta` bookkeeping line → suppressed via the AUTHORITATIVE flags (not a fragile+// English-string match), so the summary is never rendered as a giant fake user turn / new turn.+//+// Returns the events to emit for a compact line (possibly `[]` to suppress it), or `undefined` when+// `raw` is not a compact line and should fall through to the normal user/assistant path.+export function compactEventFromRaw(raw: Record<string, unknown>): SessionEvent[] | undefined {+ if (raw.type === 'system' && raw.subtype === 'compact_boundary') {+ const meta = raw.compactMetadata as { trigger?: string } | undefined+ return [{+ type: 'context_compact',+ payload: {+ message: 'Context was compacted — the previous conversation has been summarized to free up space.',+ ...(meta?.trigger ? { trigger: meta.trigger } : {}),+ },+ }]+ }+ if (raw.isCompactSummary === true) return []+ if (raw.isMeta === true) {+ // NOT all isMeta user lines are bookkeeping. A `/loop` iteration is a REAL prompt that Claude+ // submits on the user's behalf every time the loop fires, and it is written as isMeta — so blanket+ // suppression made every iteration after the first invisible: no turn_started, therefore no recap,+ // therefore nothing on the device, while the loop kept running perfectly in the terminal.+ //+ // The discriminator is `promptSource`, which Claude sets authoritatively (same principle as the+ // flags above — never an English-string match):+ // 'typed' + no isMeta → the human typed it+ // 'system' + isMeta → submitted programmatically: a loop iteration. This IS a turn.+ // (absent) + isMeta → real bookkeeping: a compact summary, or a slash command's expansion+ // text. Still suppressed, so one `/goal` is not three user turns.+ if (raw.type === 'user' && raw.promptSource === 'system') return undefined+ return []+ }+ return undefined+}++// ── Full replay (session_get) ─────────────────────────────────────────────────────────────────────++/** Convert a whole session's raw JSONL lines to replay events (same render path as streaming). */+/**+ * A message the person typed while Claude Code was working. Claude Code delivers it into the running+ * turn as a `queued_command` attachment, not a prompt record. The live view leaves it out on purpose+ * (it opens no turn there), but the history must show it: without it a reopened conversation answered a+ * question it never showed (found by daemon QA with Claude Code 2.1.290). Sub-agent hand-backs and+ * Claude's own continuations arrive the same way, and they are not the person's words.+ */+function queuedHumanPrompt(raw: Record<string, unknown>): string | null {+ if (raw.type !== 'attachment') return null+ const attachment = raw.attachment as { type?: unknown; commandMode?: unknown; prompt?: unknown; origin?: { kind?: unknown } } | undefined+ if (attachment?.type !== 'queued_command' || attachment.commandMode !== 'prompt' || attachment.origin?.kind !== 'human') return null+ const prompt = attachment.prompt+ const text = typeof prompt === 'string' ? prompt+ : Array.isArray(prompt) ? prompt.map((block) => (block as { type?: unknown; text?: unknown })?.type === 'text' ? String((block as { text?: unknown }).text ?? '') : '').join('\n')+ : ''+ return text.trim() ? text : null+}++export function messagesToEvents(rawLines: string[]): SessionEvent[] {+ const events: SessionEvent[] = []+ const toolIdToName = new Map<string, string>()+ let thinkingCounter = 0+ let inAutoFixSequence = false+ let continuedAt = -1++ for (const line of rawLines) {+ if (!line.trim()) continue+ let raw: Record<string, unknown>+ try { raw = JSON.parse(line) as Record<string, unknown> } catch { continue }+ const compact = compactEventFromRaw(raw)+ if (compact) { events.push(...compact); continue } // compact boundary → indicator; summary/meta → suppressed+ const queued = queuedHumanPrompt(raw)+ if (queued) { events.push({ type: 'user_message', payload: { content: queued } }); continue }+ // A pass a blocking Stop hook continued, as the live view starts it (lineToEvents), once per pass.+ const continued = stopHookContinuation(raw)+ if (continued !== null) {+ if (continuedAt !== events.length - 1) events.push({ type: 'user_message', payload: { content: continued } })+ continuedAt = events.length - 1+ continue+ }+ const msg = transformLine(raw)+ if (!msg?.message) continue++ if (msg.type === 'user') {+ const content = msg.message.content+ if (isSystemPrompt(content)) { inAutoFixSequence = true; continue }+ const hasToolResult = content.some((c) => c.type === 'tool_result')+ const hasUserText = content.some((c) => c.type === 'text' && c.text?.trim())+ if (inAutoFixSequence && hasToolResult && !hasUserText) continue+ if (inAutoFixSequence) inAutoFixSequence = false++ if (!hasToolResult) {+ const textParts: string[] = []+ const images: Array<{ media_type: string; data: string }> = []+ for (const block of content) {+ if (block.type === 'text' && block.text) {+ let cleaned = stripContextSummary(block.text)+ if (cleaned) cleaned = stripSystemBlocks(cleaned)+ if (cleaned && !cleaned.match(/^\[Image: original \d+x\d+/)) textParts.push(cleaned)+ } else if (block.type === 'image' && block.source) {+ images.push({ media_type: block.source.media_type, data: block.source.data })+ }+ }+ const textContent = textParts.join('\n')+ if (textContent || images.length > 0) {+ events.push({ type: 'user_message', payload: { content: textContent, ...(images.length > 0 ? { images } : {}) } })+ }+ continue+ }++ events.push(...toolResultEvents(msg, toolIdToName))+ continue+ }++ // assistant+ if (inAutoFixSequence) continue+ const before = events.length+ events.push(...assistantEvents(msg, toolIdToName, 'thinking-hist-', thinkingCounter))+ // keep the per-session thinking counter monotonic across messages+ thinkingCounter += events.slice(before).filter((e) => e.type === 'thinking_delta').length+ }++ events.push({ type: 'done', payload: { result: 'success' } })+ return events+}++/**+ * Turn-snapped pagination window over raw JSONL lines, for `session_get` with `{limit, before}`.+ * `before` = uuid of the oldest line the client already holds (exclusive upper bound). Returns the+ * line slice to feed `messagesToEvents` plus cursor metadata.+ *+ * The window START is snapped back to a real user-prompt line so a window never splits an assistant+ * turn's `tool_use` from its `tool_result`: `messagesToEvents` is stateful (`toolIdToName` carries a+ * tool_use id → name across lines so the later tool_result renders the tool name), so a mid-turn cut+ * would drop tool names. A user-prompt line never sits between a tool_use and its tool_result, so+ * snapping there keeps every turn whole.+ */+/**+ * What a Claude history page knows of one line: the cursor that names it, and whether a page may start+ * there — a real user prompt, so a turn is never split. Shared by `windowRawLines` and the bounded pager+ * (lib/transcriptPages.ts), so the two cannot drift apart.+ */+export function claudePageLine(line: string): { cursor: string | null; startsPage: boolean } {+ if (!line.trim()) return { cursor: null, startsPage: false }+ let raw: Record<string, unknown>+ try { raw = JSON.parse(line) as Record<string, unknown> } catch { return { cursor: null, startsPage: false } }+ const cursor = (raw.uuid ?? raw.id ?? raw.message_id ?? null) as string | null+ const msg = transformLine(raw)+ return { cursor, startsPage: msg ? realUserText(msg) !== null : false }+}++export function windowRawLines(+ rawLines: string[],+ opts: { limit: number; before?: string },+): { window: string[]; hasMore: boolean; oldestCursor: string | null; staleCursor?: boolean } {+ // Per-line uuid + whether the line is a real user-prompt turn start (parse each line once).+ const meta = rawLines.map((line) => {+ const { cursor, startsPage } = claudePageLine(line)+ return { uuid: cursor, turnStart: startsPage }+ })++ let endIndex = rawLines.length+ if (opts.before) {+ const ci = meta.findIndex((m) => m.uuid === opts.before)+ // Cursor no longer in the file (should not happen — the transcript is append-only) → signal a+ // full reload rather than returning a wrong window.+ if (ci < 0) return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }+ endIndex = ci // exclusive: the client already holds this line+ }++ let start = Math.max(0, endIndex - opts.limit)+ while (start > 0 && !meta[start].turnStart) start--++ return {+ window: rawLines.slice(start, endIndex),+ hasMore: start > 0,+ oldestCursor: meta[start]?.uuid ?? null,+ }+}++// ── Live tailing (watcher lines) with derived turn lifecycle ──────────────────────────────────────++export interface TurnState {+ turnOpen: boolean+ toolIdToName: Map<string, string>+ /** tool_use ids started but not yet resolved by a tool_result. */+ pendingTools: Set<string>+ thinkingCounter: number+ /** Before the counter in a live thinking id. A fold that starts mid-transcript names its window here+ * (lib/attachTranscript.ts), so its ids cannot repeat ones another fold of the same session sent. */+ thinkingPrefix?: string+ /** The open turn is one a blocking Stop hook continued (`stopHookContinuation`), not a prompt's. */+ continued?: boolean+ /** How many turns this state has opened: a Stop hook closes only the turn that was open as it arrived+ * (core/turns/turnHooks.ts). */+ opened?: number+}++/**+ * The turn a Stop hook that blocked keeps going, or null. `/goal` is built on such a hook, and people write+ * their own. Claude Code writes the hook's feedback as a hidden `isMeta` user line, then one of these, then+ * works on in the SAME turn with no prompt line between (real 2.1.282/2.1.283):+ * {"type":"attachment","attachment":{"type":"goal_status","met":false,"condition":"…","reason":"…"}}+ * {"type":"attachment","attachment":{"type":"hook_blocking_error","hookEvent":"Stop","blockingError":{"blockingError":"…"}}}+ * The pass's end_turn had closed the turn, so the rest ran with none open: no turn_ended, no recap, and+ * idle whenever a tool outlasted the work lease. A `sentinel` goal_status restates an active goal at start.+ * The label matches the Codex normalizer's goal continuations.+ */+export function stopHookContinuation(raw: Record<string, unknown>): string | null {+ if (raw.type !== 'attachment') return null+ const attachment = raw.attachment as Record<string, unknown> | undefined+ if (attachment?.type === 'goal_status' && attachment.met === false && attachment.sentinel !== true) {+ const condition = typeof attachment.condition === 'string' ? attachment.condition.trim() : ''+ return condition ? `Continuing goal: ${condition}` : 'Continuing goal'+ }+ if (attachment?.type === 'hook_blocking_error' && attachment.hookEvent === 'Stop') {+ const blocking = attachment.blockingError as { blockingError?: unknown } | undefined+ const reason = typeof blocking?.blockingError === 'string' ? blocking.blockingError.trim().split('\n')[0].trim() : ''+ return reason ? `Continuing: ${reason.length > 200 ? `${reason.slice(0, 197)}...` : reason}` : 'Continuing'+ }+ return null+}++export function newTurnState(): TurnState {+ return { turnOpen: false, toolIdToName: new Map(), pendingTools: new Set(), thinkingCounter: 0 }+}++// Terminal assistant stop reasons that close a turn. `tool_use` is deliberately absent (the turn+// continues into the tool). `pause_turn` is absent too — it may legitimately resume; the Stop hook+// (which only fires when the agent is truly done) is the authoritative catch-all for that case.+// `max_tokens`/`refusal` are included so a turn that ends on them still closes from the JSONL alone.+const TERMINAL_STOP_REASONS = new Set(['end_turn', 'stop_sequence', 'max_tokens', 'refusal'])++/**+ * Convert ONE appended JSONL line into live events. Derives turn_started/turn_ended from content:+ * - a real user prompt → (turn_ended if one was open) + turn_started{userMessage}+ * - assistant blocks → thinking/text/tool_start (tool ids tracked as pending)+ * - user tool_results → tool_end (resolves pending ids)+ * - assistant stop_reason in TERMINAL_STOP_REASONS with no pending tools → turn_ended+ */+export function lineToEvents(rawLine: string, state: TurnState): LiveEvent[] {+ if (!rawLine.trim()) return []+ let raw: Record<string, unknown>+ try { raw = JSON.parse(rawLine) as Record<string, unknown> } catch { return [] }+ // A valid-JSON but non-object line (the literal `null`, a number, a bare string) would make the+ // property access in compactEventFromRaw / transformLine throw — and on the unguarded watcher path+ // that kills the daemon. Any non-object line has nothing to emit.+ if (!raw || typeof raw !== 'object') return []+ // Compaction: emit the boundary indicator; suppress the injected summary/meta lines. The turn state+ // is left untouched, so an auto-compact that fires MID-TURN keeps the open turn open (the assistant+ // continuation after the boundary just streams under it) instead of the summary opening a fake turn.+ const compact = compactEventFromRaw(raw)+ if (compact) return compact+ // Sub-agent finished. Deliberately does NOT touch the turn state: the parent turn already closed on the+ // launch ack, and this record is not a prompt.+ const finished = taskNotificationEvent(raw)+ if (finished) return [finished]+ // A Stop hook that blocked: the pass's end_turn closed the turn Claude Code works on in. Open it again.+ const continued = stopHookContinuation(raw)+ if (continued !== null) {+ if (state.turnOpen) return []+ state.turnOpen = true+ state.opened = (state.opened ?? 0) + 1+ state.pendingTools.clear()+ state.continued = true+ return [{ type: 'turn_started', payload: { userMessage: continued } }]+ }+ // Claude Code's own record that its turn is over. A continued pass can end with no output: when the hook+ // refuses again, Claude Code pauses the goal and writes only notices and this (real 2.1.283), with no+ // end_turn or Stop to close what was opened above. Every other turn is closed as before.+ if (raw.type === 'system' && raw.subtype === 'turn_duration') {+ if (!state.turnOpen || !state.continued) return []+ state.turnOpen = false+ state.pendingTools.clear()+ return [{ type: 'turn_ended', payload: {} }]+ }+ const msg = transformLine(raw)+ if (!msg?.message) return []++ const events: LiveEvent[] = []++ if (msg.type === 'user') {+ // Interrupt: close the open turn and start NOTHING. This is also the only signal for an ESC pressed+ // straight in the terminal — no cancel frame reaches the adapter there — so the turn has to end here.+ if (isInterruptLine(msg)) {+ if (!state.turnOpen) return []+ state.turnOpen = false+ state.pendingTools.clear()+ return [{ type: 'turn_ended', payload: { aborted: true } }]+ }+ const userText = realUserText(msg)+ if (userText !== null) {+ // New prompt (typed in the terminal OR injected from the web) — starts a turn.+ if (state.turnOpen) events.push({ type: 'turn_ended', payload: {} })+ state.turnOpen = true+ state.opened = (state.opened ?? 0) + 1+ state.pendingTools.clear()+ state.continued = false+ events.push({ type: 'turn_started', payload: { userMessage: userText } })+ return events+ }+ // tool_result echoes: resolve pending tools.+ const ends = toolResultEvents(msg, state.toolIdToName)+ for (const e of ends) {+ if (e.type === 'tool_end') state.pendingTools.delete(e.payload.id)+ }+ events.push(...ends)+ return events+ }++ // assistant+ const before = events.length+ events.push(...assistantEvents(msg, state.toolIdToName, state.thinkingPrefix ?? 'thinking-live-', state.thinkingCounter))+ state.thinkingCounter += events.slice(before).filter((e) => e.type === 'thinking_delta').length+ for (const e of events) {+ if (e.type === 'tool_start') state.pendingTools.add(e.payload.id)+ }++ const stop = msg.stopReason+ if (state.turnOpen && stop && TERMINAL_STOP_REASONS.has(stop) && state.pendingTools.size === 0) {+ state.turnOpen = false+ events.push({ type: 'turn_ended', payload: {} })+ }+ return events+}++function parseRecord(rawLine: string): Record<string, unknown> | null {+ if (!rawLine.trim()) return null+ try {+ const raw = JSON.parse(rawLine) as unknown+ return raw && typeof raw === 'object' ? raw as Record<string, unknown> : null+ } catch { return null }+}++/**+ * The record `lineToEvents` opens a turn on — a real user prompt — decided from the record alone, as+ * `lineToEvents` decides it whatever came before. Attaching reads a transcript backward to the last+ * one of these and folds only from there (lib/attachTranscript.ts): every turn-scoped piece of+ * `TurnState` is reset by it, so the fold from here ends exactly where the whole-history fold does.+ */+export function startsClaudeTurn(rawLine: string): boolean {+ const raw = parseRecord(rawLine)+ if (!raw || compactEventFromRaw(raw) || taskNotificationEvent(raw)) return false+ const msg = transformLine(raw)+ if (!msg?.message || msg.type !== 'user' || isInterruptLine(msg)) return false+ return realUserText(msg) !== null+}++/**+ * The tool calls a Claude record makes (`defines`) and the earlier calls whose results it carries+ * (`references`), decided along `lineToEvents`' own branches. A result names its tool from the call+ * `lineToEvents` saw earlier, so an attach that starts mid-transcript reaches back for the calls its+ * turn's results answer (lib/attachTranscript.ts).+ */+export function claudeToolLinks(rawLine: string): { defines: string[]; references: string[] } {+ const raw = parseRecord(rawLine)+ if (!raw || compactEventFromRaw(raw) || taskNotificationEvent(raw)) return { defines: [], references: [] }+ const msg = transformLine(raw)+ if (!msg?.message) return { defines: [], references: [] }+ if (msg.type === 'assistant') {+ return { defines: msg.message.content.filter((block) => block.type === 'tool_use').map((block) => block.id || ''), references: [] }+ }+ if (isInterruptLine(msg) || realUserText(msg) !== null) return { defines: [], references: [] }+ return { defines: [], references: msg.message.content.filter((block) => block.type === 'tool_result').map((block) => block.tool_use_id || '') }+}++/** `tailFileUntil` selector for `lastTurnTextFromRawLines`: stop on the prompt it resets on, keep the+ * assistant records it reads after that, and drop everything else it ignores — so a recap reads the+ * last turn's text instead of the whole conversation. */+export function selectClaudeRecapLine(line: string): 'keep' | 'skip' | 'stop' {+ const raw = parseRecord(line)+ if (!raw || compactEventFromRaw(raw) !== undefined) return 'skip'+ const msg = transformLine(raw)+ if (!msg?.message) return 'skip'+ if (realUserText(msg) !== null) return 'stop'+ return msg.type === 'assistant' ? 'keep' : 'skip'+}diff --git a/cli/src/engines/claude/transcript.ts b/cli/src/engines/claude/transcript.tsindex decab9115..0e579ceea 100644--- a/cli/src/engines/claude/transcript.ts+++ b/cli/src/engines/claude/transcript.ts@@ -1,4 +1,4 @@-import { lastTurnTextFromRawLines, messagesToEvents, selectClaudeRecapLine } from '../../lib/normalize.js'+import { lastTurnTextFromRawLines, messagesToEvents, selectClaudeRecapLine } from './normalize.js'import { tailFileUntil } from '../../lib/transcriptTail.js'import type { EngineTranscript } from '../facets/transcript.js'import { pagedHistory } from '../kit/history.js'diff --git a/cli/src/engines/codex/attach.ts b/cli/src/engines/codex/attach.tsnew file mode 100644index 000000000..6d47117e2--- /dev/null+++ b/cli/src/engines/codex/attach.ts@@ -0,0 +1,28 @@+import { codexGoalOf, codexTaskBoundary, startsCodexTurn } from './normalizer.js'+import type { AttachRules } from '../../lib/attachTranscript.js'+import type { RuntimeField } from '../../lib/runtimeProfile.js'++const bytes = (...markers: string[]): Buffer[] => markers.map((marker) => Buffer.from(marker))++/**+ * Codex: a turn opens on a user message (`user_message`, or `UserMessage` inside `item_completed`) or a+ * `/goal` injection, and its task began at the `task_started` before it. Model, effort and mode arrive+ * together in `turn_context` and `thread_settings_applied`, written just before the turn's first+ * message. A continuing goal's label depends on the goal before it.+ */+export function codexAttachRules(fields: (line: string) => readonly RuntimeField[]): AttachRules {+ return {+ startsTurn: startsCodexTurn,+ turnMarkers: bytes('user_message', 'UserMessage', 'codex_internal_context'),+ turnBegin: {+ begins: (line) => codexTaskBoundary(line) === 'begins',+ ends: (line) => codexTaskBoundary(line) === 'ends',+ markers: bytes('task_started', 'task_complete', 'turn_aborted'),+ },+ fields,+ fieldMarkers: bytes('turn_context', 'thread_settings_applied'),+ required: ['model', 'effort', 'mode'],+ seedFor: (opener) => (codexGoalOf(opener) === null ? null : (line) => codexGoalOf(line) !== null),+ seedMarkers: bytes('codex_internal_context'),+ }+}diff --git a/cli/src/engines/codex/live.ts b/cli/src/engines/codex/live.tsnew file mode 100644index 000000000..6c50091cd--- /dev/null+++ b/cli/src/engines/codex/live.ts@@ -0,0 +1,27 @@+import { randomUUID } from 'node:crypto'+import type { EngineLive } from '../facets/live.js'+import { codexAttachRules } from './attach.js'+import { CodexNormalizer, codexTaskError } from './normalizer.js'+import { codexSubagentResolverFor } from './subagent.js'++export const live: EngineLive = {+ attachRules: codexAttachRules,+ create(session) {+ const normalizer = new CodexNormalizer('live', codexSubagentResolverFor(session.codexHome))+ const generation = randomUUID()+ let turn = 0+ return {+ engine: session.engine,+ get turnOpen() { return normalizer.turnOpen },+ ingest(line) {+ const events = normalizer.ingest(line)+ for (const event of events) if (event.type === 'turn_started') turn+++ const failure = codexTaskError(line)+ return { events, ...(failure === null ? {} : { failure }) }+ },+ snapshot: () => ({ identity: `${generation}:${turn}`, turnOpen: normalizer.turnOpen, continued: false }),+ closeTurn: () => { normalizer.closeTurn() },+ windowStart: (offset) => { normalizer.thinkingPrefix = `thinking-codex-${offset.toString(36)}-` },+ }+ },+}diff --git a/cli/src/engines/engine.ts b/cli/src/engines/engine.tsindex 19b6f87c9..c2a07510f 100644--- a/cli/src/engines/engine.ts+++ b/cli/src/engines/engine.ts@@ -2,6 +2,7 @@ import type { ProcessEngine } from './types.js'import type { EngineTranscript } from './facets/transcript.js'import type { EngineLaunch } from './facets/launch.js'import type { EngineHooks } from './facets/hooks.js'+import type { EngineLive } from './facets/live.js'/** The engine's own contracts. Claude Code and Codex migrate one small batch at a time. */export interface Engine {@@ -9,4 +10,5 @@ export interface Engine {readonly transcript: EngineTranscriptreadonly launch: EngineLaunchreadonly hooks: EngineHooks+ readonly live: EngineLive}diff --git a/cli/src/engines/facets/hooks.ts b/cli/src/engines/facets/hooks.tsindex 9a349e765..0993338b1 100644--- a/cli/src/engines/facets/hooks.ts+++ b/cli/src/engines/facets/hooks.ts@@ -1,4 +1,5 @@-import type { LiveEvent, TurnState } from '../../lib/normalize.js'+import type { LiveEvent } from '../kit/events.js'+import type { LiveTurn } from './live.js'/** Only the session facts a hook needs; transport authentication and process binding stay in core. */export interface HookSession {@@ -8,9 +9,11 @@ export interface HookSession {export interface HookStop { sessionId: string; status?: string; firedAt?: number }-/** Core owns the state and event funnel. The engine decides what its Stop means. */+/** Core supplies immutable observations and owns the event funnel. The engine decides what its Stop means. */export interface HookTurnContext {- turnState(sessionId: string): TurnState | undefined+ turnState(sessionId: string): LiveTurn | undefined+ /** Atomically close only this observed turn; a rejected stale proposal emits nothing. */+ closeTurn(sessionId: string, identity: string): booleanlatestPromptAt(sessionId: string): number | undefineddrain(sessionId: string): Promise<void>noteEngineStopped(sessionId: string): voiddiff --git a/cli/src/engines/facets/live.ts b/cli/src/engines/facets/live.tsnew file mode 100644index 000000000..a5789d764--- /dev/null+++ b/cli/src/engines/facets/live.ts@@ -0,0 +1,36 @@+import type { AttachRules } from '../../lib/attachTranscript.js'+import type { RegisteredSession } from '../../lib/registry.js'+import type { RuntimeField } from '../../lib/runtimeProfile.js'+import type { LiveEvent } from '../kit/events.js'++/** A value, not an engine's mutable parser state. Identity changes with both parser and turn. */+export interface LiveTurn {+ readonly identity: string+ readonly turnOpen: boolean+ readonly continued: boolean+}++export interface LiveRead {+ events: LiveEvent[]+ /** Announced before this record's events, which may include its turn end. */+ failure?: string+}++/** Stateful interpretation owned by an engine. Core never edits a parser's fields. */+export interface LiveParser {+ /** The binding this parser interprets. A session id reused by another engine needs a fresh parser. */+ readonly engine: string+ readonly turnOpen: boolean+ ingest(line: string): LiveRead+ snapshot(): LiveTurn+ closeTurn(reason: 'cancel' | 'abandoned' | 'hook'): void+ windowStart(offset: number): void+}++export interface EngineLive {+ create(session: Pick<RegisteredSession, 'engine' | 'codexHome'>): LiveParser+ /** Absent for the legacy fallback that folds its whole, bounded file. */+ attachRules?(fields: (line: string) => readonly RuntimeField[]): AttachRules+}++export type LiveFor = (engine: string) => EngineLive | undefineddiff --git a/cli/src/engines/hooks.spec.ts b/cli/src/engines/hooks.spec.tsindex 898533807..843e2c25d 100644--- a/cli/src/engines/hooks.spec.ts+++ b/cli/src/engines/hooks.spec.ts@@ -5,6 +5,7 @@ import { fileURLToPath } from 'node:url'import { afterEach, expect, it, vi } from 'vitest'import { admitHook, engineHooks, hooksFor } from './hooks.js'import { engineFor } from './registry.js'+import { liveFor } from './live.js'afterEach(() => vi.restoreAllMocks())@@ -55,3 +56,17 @@ it('rejects a hook when its engine admission check throws, and leaves other engiexpect(admitHook('claude', {})).toEqual({ accepted: true })expect(console.warn).toHaveBeenCalledWith('[hooks] codex admission failed:', 'reader failed')})++it('does not emit an end when core rejects a stale closure proposal', async () => {+ const parser = liveFor('claude')!.create({ engine: 'claude' })+ parser.ingest(JSON.stringify({ type: 'user', message: { role: 'user', content: 'go' } }))+ const emit = vi.fn()+ const closeTurn = vi.fn(() => false)+ await engineHooks.claude.onStop!({+ turnState: () => parser.snapshot(), closeTurn, latestPromptAt: () => undefined,+ drain: async () => {}, noteEngineStopped: () => {}, emit, graceMs: 0,+ }, { sessionId: 'session' })+ expect(closeTurn).toHaveBeenCalledWith('session', parser.snapshot().identity)+ expect(emit).not.toHaveBeenCalled()+ expect(parser.turnOpen).toBe(true)+})diff --git a/cli/src/engines/kit/events.ts b/cli/src/engines/kit/events.tsnew file mode 100644index 000000000..82edd7669--- /dev/null+++ b/cli/src/engines/kit/events.ts@@ -0,0 +1,32 @@+/** Engine-independent events delivered to the core and its consumers. */+export interface SubagentSummary {+ agentId?: string+ agentType?: string+ totalTokens?: number+ totalDurationMs?: number+ totalToolUseCount?: number+}++export type SessionEvent =+ | { type: 'user_message'; payload: { content: string; images?: Array<{ media_type: string; data: string }> } }+ | { type: 'thinking_delta'; payload: { content: string; thinkingId?: string } }+ | { type: 'thinking_title'; payload: { thinkingId?: string; title: string } }+ | { type: 'text_delta'; payload: { content: string } }+ | { type: 'tool_start'; payload: { id: string; tool: string; input: unknown; parentToolUseId?: string } }+ | { type: 'tool_end'; payload: { id: string; tool: string; output: string; isError: boolean; summary: string; parentToolUseId?: string; subagent?: SubagentSummary; durationSeconds?: number } }+ | { type: 'context_compact'; payload: { message: string; trigger?: string } }+ | { type: 'done'; payload: { result: string } }++/** Live-stream events: replay events + the derived turn lifecycle. */+export type LiveEvent =+ | SessionEvent+ | { type: 'turn_started'; payload: { userMessage: string } }+ | { type: 'turn_ended'; payload: { aborted?: true } } // aborted = killed by an interrupt, no recap+ // An ASYNC sub-agent actually finished. `id` is the spawning tool_use id, so it pairs with the+ // `tool_start`/`tool_end` of the same sub-agent (see taskNotificationEvent).+ | { type: 'subagent_finished'; payload: { id: string; status: string; summary?: string } }++export interface LastTurnText {+ userMessage: string+ assistantText: string+}diff --git a/cli/src/engines/kit/transcriptFold.ts b/cli/src/engines/kit/transcriptFold.tsnew file mode 100644index 000000000..4a08b16ef--- /dev/null+++ b/cli/src/engines/kit/transcriptFold.ts@@ -0,0 +1,62 @@+import type { LiveEvent } from './events.js'++/**+ * Fold a transcript that already exists into a fresh normalizer, and say whether what came out is+ * HISTORY (to be swallowed) or the LIVE conversation (to be emitted).+ *+ * Attaching to a session normally means catching up on turns the user has already seen elsewhere, so the+ * events are dropped and only a turn left half-open is replayed. That assumption breaks when the agent+ * exists BEFORE its session: the first prompt is what makes the engine open the transcript, so by the+ * time anything binds it, the whole first turn — question, tools and answer — can already be on disk.+ * Folded as history it is lost silently, and silently is literal: no `turn_started` means no+ * `turn_ended` and no recap either, so nothing in the log records that a turn ever happened.+ *+ * `live` picks the destination. It also forces `turnOpen` to false, because the caller's mid-turn rescue+ * ("replay the last turn_started") would otherwise emit that event a second time on top of the events+ * returned here.+ */+export function foldTranscript(+ ingest: (line: string) => LiveEvent[],+ lines: string[],+ turnOpenAfter: () => boolean,+ opts: { live: boolean },+): { history: LiveEvent[]; live: LiveEvent[]; turnOpen: boolean } {+ const folded: LiveEvent[] = []+ for (const line of lines) folded.push(...ingest(line))+ return {+ history: opts.live ? [] : folded,+ live: opts.live ? folded : [],+ turnOpen: !opts.live && turnOpenAfter(),+ }+}++/**+ * `foldTranscript` one record at a time, for a transcript streamed in rather than loaded+ * (lib/attachTranscript.ts). History keeps only its last `turn_started` — the one event an attach ever+ * replays from it — so folding a long turn holds nothing but that.+ */+export class TranscriptFold {+ private lastStarted: LiveEvent | null = null+ private readonly folded: LiveEvent[] = []++ constructor(+ private readonly ingest: (line: string) => LiveEvent[],+ private readonly turnOpenAfter: () => boolean,+ private readonly live: boolean,+ ) {}++ push(line: string): void {+ for (const event of this.ingest(line)) {+ if (this.live) this.folded.push(event)+ else if (event.type === 'turn_started') this.lastStarted = event+ }+ }++ finish(): { history: LiveEvent[]; live: LiveEvent[]; turnOpen: boolean } {+ return {+ history: this.lastStarted ? [this.lastStarted] : [],+ live: this.folded,+ turnOpen: !this.live && this.turnOpenAfter(),+ }+ }+}diff --git a/cli/src/engines/live.spec.ts b/cli/src/engines/live.spec.tsnew file mode 100644index 000000000..d3ea87a93--- /dev/null+++ b/cli/src/engines/live.spec.ts@@ -0,0 +1,82 @@+import { readFileSync } from 'node:fs'+import { describe, expect, it } from 'vitest'+import { newFold } from '../testing/transcriptOracle.js'+import { liveFor } from './live.js'+import { engineFor } from './registry.js'++const prompt = (text: string) => JSON.stringify({ type: 'user', message: { role: 'user', content: text } })+const continuation = JSON.stringify({ type: 'attachment', attachment: { type: 'goal_status', met: false, condition: 'finish' } })++describe('the live engine facet', () => {+ it.each(['claude', 'codex'] as const)('%s preserves every recorded live event and turn state', (engine) => {+ const fixture = engine === 'claude' ? '../lib/__fixtures__/transcript-async-subagents.jsonl' : '../lib/fixtures/session-work-codex.jsonl'+ const lines = readFileSync(new URL(fixture, import.meta.url), 'utf8').split('\n')+ const parser = liveFor(engine)!.create({ engine, codexHome: '/nonexistent/engine-live-oracle' })+ expect(engineFor(engine)!.live).toBe(liveFor(engine))+ const oracle = newFold(engine)+ parser.windowStart(128); oracle.name(128)+ for (const line of lines) {+ expect(parser.ingest(line).events).toEqual(oracle.ingest(line))+ expect(parser.turnOpen).toBe(oracle.turnOpen())+ }+ parser.closeTurn('abandoned')+ expect(parser.turnOpen).toBe(false)+ expect(parser.snapshot().turnOpen).toBe(false)+ })++ it('reports a Codex failure separately so its reason can precede its closing event', () => {+ const parser = liveFor('codex')!.create({ engine: 'codex' })+ const before = parser.snapshot()+ parser.ingest(JSON.stringify({ type: 'event_msg', payload: { type: 'user_message', message: 'go' } }))+ const open = parser.snapshot()+ expect(open.identity).not.toBe(before.identity)+ expect(open.turnOpen).toBe(true)+ const read = parser.ingest(JSON.stringify({ type: 'event_msg', payload: { type: 'task_complete', error: { message: 'rate limited' } } }))+ expect(read.failure).toBe('rate limited')+ expect(read.events.some(event => event.type === 'turn_ended')).toBe(true)+ expect(parser.snapshot().turnOpen).toBe(false)+ expect(parser.ingest('{}').failure).toBeUndefined()+ })++ it('gives each parser and each turn a distinct immutable identity, including a continuation', () => {+ const parser = liveFor('claude')!.create({ engine: 'claude' })+ const idle = parser.snapshot()+ parser.ingest(prompt('one'))+ const one = parser.snapshot()+ expect(one.turnOpen).toBe(true)+ expect(one.identity).not.toBe(idle.identity)+ parser.ingest(prompt('two'))+ const two = parser.snapshot()+ expect(two.identity).not.toBe(one.identity)+ expect(one).toEqual({ identity: one.identity, turnOpen: true, continued: false })+ parser.closeTurn('hook')+ expect(two.turnOpen).toBe(true)+ parser.ingest(continuation)+ const continued = parser.snapshot()+ expect(continued.continued).toBe(true)+ expect(continued.identity).not.toBe(two.identity)+ expect(liveFor('claude')!.create({ engine: 'claude' }).snapshot().identity).not.toBe(idle.identity)+ expect(idle.turnOpen).toBe(false)+ })++ it('keeps the previous cancel semantics, but clears abandoned tools on relaunch or Stop', () => {+ const call = JSON.stringify({ type: 'assistant', message: { role: 'assistant', content: [{ type: 'tool_use', id: 'tool', name: 'Read', input: {} }] } })+ const end = JSON.stringify({ type: 'assistant', message: { role: 'assistant', content: [{ type: 'text', text: 'done' }], stop_reason: 'end_turn' } })+ for (const reason of ['cancel', 'abandoned', 'hook'] as const) {+ const parser = liveFor('claude')!.create({ engine: 'claude' })+ parser.ingest(prompt('go')); parser.ingest(call); parser.closeTurn(reason)+ expect(parser.turnOpen).toBe(false)+ // A continuation reopens without replacing the parser. Pending calls are cleared by its own+ // opener too; cancellation must still preserve the old tool-name link for a late result.+ const result = parser.ingest(JSON.stringify({ type: 'user', message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'tool', content: 'late' }] } }))+ expect(result.events.find(event => event.type === 'tool_end')?.payload).toMatchObject({ tool: 'Read', output: 'late' })+ expect(parser.ingest(end).failure).toBeUndefined()+ }+ })++ it('retains the terminal fallback without end-first rules and refuses unknown/prototype names', () => {+ expect(liveFor('terminal')?.attachRules).toBeUndefined()+ expect(liveFor('terminal')!.create({ engine: 'terminal' }).ingest(prompt('go')).events.some(event => event.type === 'turn_started')).toBe(true)+ for (const engine of ['cursor', 'future', '__proto__', 'constructor', 'toString']) expect(liveFor(engine)).toBeUndefined()+ })+})diff --git a/cli/src/engines/live.ts b/cli/src/engines/live.tsnew file mode 100644index 000000000..42749f660--- /dev/null+++ b/cli/src/engines/live.ts@@ -0,0 +1,10 @@+/** In-process composition for the live-facet migration. The worker port will replace this in core. */+import { live as claude } from './claude/live.js'+import { live as codex } from './codex/live.js'+import type { EngineLive, LiveFor } from './facets/live.js'++// Preserve the old terminal fallback while moving parser ownership. A plain terminal does not+// normally have a transcript; it must not acquire Claude's read-from-end attach behavior.+const terminal: EngineLive = { create: claude.create }+const adapters: Readonly<Record<string, EngineLive>> = { claude, codex, terminal }+export const liveFor: LiveFor = (engine) => Object.hasOwn(adapters, engine) ? adapters[engine] : undefineddiff --git a/cli/src/engines/registry.ts b/cli/src/engines/registry.tsindex 820bf4ab5..7ad6906c7 100644--- a/cli/src/engines/registry.ts+++ b/cli/src/engines/registry.ts@@ -3,11 +3,13 @@ import { engineLaunches } from './launches.js'import { engineHooks } from './hooks.js'import { transcript as claudeTranscript } from './claude/transcript.js'import { transcript as codexTranscript } from './codex/transcript.js'+import { live as claudeLive } from './claude/live.js'+import { live as codexLive } from './codex/live.js'/** Only the migrated engines. Others keep their existing handlers until their own small batch. */const engines = {- claude: { name: 'claude', launch: engineLaunches.claude, transcript: claudeTranscript, hooks: engineHooks.claude },- codex: { name: 'codex', launch: engineLaunches.codex, transcript: codexTranscript, hooks: engineHooks.codex },+ claude: { name: 'claude', launch: engineLaunches.claude, transcript: claudeTranscript, hooks: engineHooks.claude, live: claudeLive },+ codex: { name: 'codex', launch: engineLaunches.codex, transcript: codexTranscript, hooks: engineHooks.codex, live: codexLive },} satisfies Record<string, Engine>type MigratedEngine = keyof typeof enginesexport function engineFor(name: string | null | undefined): Engine | undefined {diff --git a/cli/src/lib/attachTranscript.spec.ts b/cli/src/lib/attachTranscript.spec.tsindex 59bc849fd..f48ecab6b 100644--- a/cli/src/lib/attachTranscript.spec.ts+++ b/cli/src/lib/attachTranscript.spec.ts@@ -1,3 +1,5 @@+import { claudeAttachRules } from '../engines/claude/attach.js'+import { codexAttachRules } from '../engines/codex/attach.js'import { appendFileSync, chmodSync, mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'@@ -7,8 +9,6 @@ import { canonical, fromTheEnd, goalForgotten, newFold, session, wholeHistory }import { claude, claudeScenario, codex, codexScenario, cx } from '../testing/transcriptScenarios.js'import {attachTranscript,- claudeAttachRules,- codexAttachRules,HEAD_RECORD_LIMIT,isWholeRecord,locateAttachSpan,diff --git a/cli/src/lib/attachTranscript.ts b/cli/src/lib/attachTranscript.tsindex e83b5eb7c..39246549b 100644--- a/cli/src/lib/attachTranscript.ts+++ b/cli/src/lib/attachTranscript.ts@@ -28,8 +28,6 @@* ended on the copied parent's `session_meta`.*/import { stat } from 'node:fs/promises'-import { codexGoalOf, codexTaskBoundary, startsCodexTurn } from '../engines/codex/normalizer.js'-import { claudeToolLinks, startsClaudeTurn } from './normalize.js'import { scanRecordsBackward, streamRecords } from './transcriptTail.js'import type { RuntimeField } from './runtimeProfile.js'@@ -279,45 +277,3 @@ export async function attachTranscript(return { ...(span ?? wholeFile(end)), next: end, records: 0, content: end > 0, failed: true }}}--const bytes = (...markers: string[]): Buffer[] => markers.map((marker) => Buffer.from(marker))--/**- * Claude Code: a turn opens on a real user prompt, always a `"type":"user"` record. Its results name- * their tool from the call that made it, so calls the turn answers are reached for. The chips read- * only the model from the transcript — the attach takes effort from Claude's settings straight after —- * and `Set model to` is matched case-insensitively, so field records are asked for without a byte test.- */-export function claudeAttachRules(fields: (line: string) => readonly RuntimeField[]): AttachRules {- return {- startsTurn: startsClaudeTurn,- turnMarkers: bytes('"user"'),- fields,- required: ['model'],- links: claudeToolLinks,- linkMarkers: bytes('tool_use', 'tool_result'),- }-}--/**- * Codex: a turn opens on a user message (`user_message`, or `UserMessage` inside `item_completed`) or a- * `/goal` injection, and its task began at the `task_started` before it. Model, effort and mode arrive- * together in `turn_context` and `thread_settings_applied`, written just before the turn's first- * message. A continuing goal's label depends on the goal before it.- */-export function codexAttachRules(fields: (line: string) => readonly RuntimeField[]): AttachRules {- return {- startsTurn: startsCodexTurn,- turnMarkers: bytes('user_message', 'UserMessage', 'codex_internal_context'),- turnBegin: {- begins: (line) => codexTaskBoundary(line) === 'begins',- ends: (line) => codexTaskBoundary(line) === 'ends',- markers: bytes('task_started', 'task_complete', 'turn_aborted'),- },- fields,- fieldMarkers: bytes('turn_context', 'thread_settings_applied'),- required: ['model', 'effort', 'mode'],- seedFor: (opener) => (codexGoalOf(opener) === null ? null : (line) => codexGoalOf(line) !== null),- seedMarkers: bytes('codex_internal_context'),- }-}diff --git a/cli/src/lib/normalize.ts b/cli/src/lib/normalize.tsindex 5416e348f..e20f720fe 100644--- a/cli/src/lib/normalize.ts+++ b/cli/src/lib/normalize.ts@@ -1,1070 +1,4 @@-/**- * Claude-Code JSONL → web ServerEvent normalizer.- *- * Self-contained port of the hosted runtime’s replay normalizer- * (`the hosted runtime`: transformCCMessageToSessionMessage,- * sessionMessagesToEvents, stripContextSummary/stripSystemBlocks + tool-summary)- * — this package has no dependency outside itself.- *- * Two entry points:- * - messagesToEvents(rawLines) → full SessionEvent[] replay for `session_get`.- * - lineToEvents(rawLine, state) → incremental events for live tailing, PLUS a derived- * turn lifecycle (turn_started / turn_ended) so a prompt typed directly in the terminal- * renders identically to one sent from the web (mirror-all).- */--import { harnessWebTool } from './harnessWebTools.js'--// ── Event shapes (match the server’s SessionEvent contract SessionEvent + live turn frames) ──────--export interface SubagentSummary {- agentId?: string- agentType?: string- totalTokens?: number- totalDurationMs?: number- totalToolUseCount?: number-}--export type SessionEvent =- | { type: 'user_message'; payload: { content: string; images?: Array<{ media_type: string; data: string }> } }- | { type: 'thinking_delta'; payload: { content: string; thinkingId?: string } }- | { type: 'thinking_title'; payload: { thinkingId?: string; title: string } }- | { type: 'text_delta'; payload: { content: string } }- | { type: 'tool_start'; payload: { id: string; tool: string; input: unknown; parentToolUseId?: string } }- | { type: 'tool_end'; payload: { id: string; tool: string; output: string; isError: boolean; summary: string; parentToolUseId?: string; subagent?: SubagentSummary; durationSeconds?: number } }- | { type: 'context_compact'; payload: { message: string; trigger?: string } }- | { type: 'done'; payload: { result: string } }--/** Live-stream events: replay events + the derived turn lifecycle. */-export type LiveEvent =- | SessionEvent- | { type: 'turn_started'; payload: { userMessage: string } }- | { type: 'turn_ended'; payload: { aborted?: true } } // aborted = killed by an interrupt, no recap- // An ASYNC sub-agent actually finished. `id` is the spawning tool_use id, so it pairs with the- // `tool_start`/`tool_end` of the same sub-agent (see taskNotificationEvent).- | { type: 'subagent_finished'; payload: { id: string; status: string; summary?: string } }--export interface LastTurnText {- userMessage: string- assistantText: string-}--interface RawContentBlock {- type: 'text' | 'tool_use' | 'tool_result' | 'thinking' | 'image'- text?: string- thinking?: string- id?: string- name?: string- input?: unknown- tool_use_id?: string- content?: string | Array<{ type: string; text?: string }>- is_error?: boolean- source?: { type: string; media_type: string; data: string }-}--interface NormalizedMessage {- type: 'user' | 'assistant'- message?: { role: 'user' | 'assistant'; content: RawContentBlock[] }- toolUseResult?: SubagentSummary & { status?: string; durationSeconds?: number }- /** Raw Anthropic stop_reason from the assistant line (drives turn_ended). */- stopReason?: string | null-}--const MAX_OUTPUT = 2000-const MAX_THINKING = 500-const MAX_DIFF_SIDE = 1500-const PREVIEW_LINES = 8--// ── Text cleanup (ported verbatim) ────────────────────────────────────────────────────────────────--/** Strip the compaction-injected context summary; null if the whole message was summary. */-export function stripContextSummary(text: string): string | null {- const endMarker = '<!-- END CONTEXT SUMMARY -->'- const idx = text.indexOf(endMarker)- if (idx === -1) return text- let remaining = text.slice(idx + endMarker.length)- remaining = remaining.replace(/^\s*---\s*Now,?\s*continuing.*?:\s*/is, '')- remaining = remaining.trim()- return remaining || null-}--/** Strip system-injected blocks not meant for UI display. */-export function stripSystemBlocks(text: string): string {- return text- .replace(/<task-notification>[\s\S]*?<\/task-notification>\s*/g, '')- .replace(/<system-reminder>[\s\S]*?<\/system-reminder>\s*/g, '')- .replace(/<goal-context>[\s\S]*?<\/goal-context>\s*/g, '')- .replace(/<dev-server-context>[\s\S]*?<\/dev-server-context>\s*/g, '')- .replace(/<available-deferred-tools>[\s\S]*?<\/available-deferred-tools>\s*/g, '')- .replace(/<local-command-caveat>[\s\S]*?<\/local-command-caveat>\s*/g, '')- .replace(/<command-name>[\s\S]*?<\/command-name>\s*/g, '')- .replace(/<command-message>[\s\S]*?<\/command-message>\s*/g, '')- .replace(/<command-args>[\s\S]*?<\/command-args>\s*/g, '')- .replace(/<local-command-stdout>[\s\S]*?<\/local-command-stdout>\s*/g, '')- .replace(/Read the output file to retrieve the result:[^\n]*/g, '')- .trim()-}--/**- * Bash mode (`!command` in Claude Code) writes the command and its output back into the transcript as a- * `type:'user'` line — `<bash-input>…</bash-input>` and the `<bash-stdout>`/`<bash-stderr>` that follow.- * It is the person running a local shell, NOT a prompt to the agent, so it must not open a turn: if it- * did, the per-turn recap would summarise shell mechanics ("paste the command on one line") instead of- * what the agent is actually working on, and the tile would drift off-task with every `!`. Stripped ONLY- * for the turn-detection decision (see `realUserText`), never for display — the transcript still shows- * the commands. A line carrying real prose ALONGSIDE a bash block keeps counting; only a bash-only line- * is skipped.- */-export function stripBashModeBlocks(text: string): string {- return text- .replace(/<bash-input>[\s\S]*?<\/bash-input>\s*/g, '')- .replace(/<bash-stdout>[\s\S]*?<\/bash-stdout>\s*/g, '')- .replace(/<bash-stderr>[\s\S]*?<\/bash-stderr>\s*/g, '')- .trim()-}--// Built-in CLI commands that only drive the local TUI and never dispatch an agent turn. Surfacing-// them as a user prompt would open a turn nothing ever closes (device tile stuck busy), so they stay-// invisible — same as before. Anything else (a custom `~/.claude/commands/*.md`, `/goal`, `/review`,-// a plugin skill) DOES run a turn and must be visible.-const LOCAL_ONLY_COMMANDS = new Set([- 'add-dir', 'agents', 'bug', 'clear', 'compact', 'config', 'context', 'copy', 'cost', 'desktop',- 'doctor', 'effort', 'exit', 'export', 'help', 'hooks', 'ide', 'login', 'logout', 'mcp', 'memory',- 'model', 'output-style', 'permissions', 'privacy-settings', 'quit', 'release-notes',- 'reload-plugins', 'resume', 'skills', 'statusline', 'status', 'terminal-setup', 'todos',- 'upgrade', 'vim',-])--/** A whole prompt that is one of LOCAL_ONLY_COMMANDS, typed plainly: `/compact`, `/model opus`. */-function isLocalOnlyCommandLine(text: string): boolean {- const name = /^\/([A-Za-z][\w-]*)(?:\s|$)/.exec(text.trim())?.[1]- return name !== undefined && LOCAL_ONLY_COMMANDS.has(name.toLowerCase())-}--/**- * `<command-name>/goal</command-name>…<command-args>x</command-args>` → `/goal x`.- *- * Claude Code records a slash command ONLY as these tags (the expansion it actually sends to the- * model is written as a separate `isMeta` line, which we suppress). `stripSystemBlocks` erases the- * tags, so without this the whole line normalizes to "" → `realUserText` returns null → NO- * `turn_started` is ever emitted for a command prompt. That broke the device's goal mode: the- * injected `/goal <text>` ran fine in the terminal, but `SessionInputController` never saw the turn- * open and reported "The agent did not accept the message" after its submit retries — and the recap- * had no user message to lead with.- */-function commandPromptText(text: string): string | null {- const name = text.match(/<command-name>\s*([^<]*?)\s*<\/command-name>/)?.[1]- if (!name) return null- const bare = name.replace(/^\//, '').trim()- if (!bare || LOCAL_ONLY_COMMANDS.has(bare.toLowerCase())) return null- const args = text.match(/<command-args>([\s\S]*?)<\/command-args>/)?.[1]?.trim() ?? ''- return args ? `/${bare} ${args}` : `/${bare}`-}--/** Short title heuristic for a thinking block (first 3-8 words of the first line). */-function extractThinkingTitle(thinking: string): string | null {- const trimmed = thinking.trim()- if (!trimmed || trimmed.length < 10) return null- const firstLine = trimmed.split('\n')[0].replace(/^[\s#*\->]+/, '').trim()- if (!firstLine) return null- const words = firstLine.split(/\s+/).slice(0, 8)- if (words.length < 2) return null- let title = words.join(' ').replace(/[.,:;!?]+$/, '')- if (title.length > 60) title = title.slice(0, 57) + '...'- return title-}--/** The short ⎿ label shown after a tool finishes (e.g. "Read 247 lines"). */-function computeToolSummary(toolName: string, rawOutput: string, isError: boolean): string {- if (isError) return rawOutput.split('\n')[0]?.slice(0, 80) || 'Error'- switch (toolName) {- case 'Bash': {- const match = rawOutput.match(/^Exit code (\d+)/)- return match ? `Exit ${match[1]}` : 'Done'- }- case 'Read': {- const lineCount = (rawOutput.match(/^\s*\d+→/gm) || []).length- return lineCount > 0 ? `Read ${lineCount} lines` : 'Read'- }- case 'Write':- case 'WriteFile':- return rawOutput.includes('successfully') ? 'Written' : rawOutput.slice(0, 60)- case 'Edit':- case 'EditFile':- return rawOutput.includes('successfully') ? 'Updated' : rawOutput.slice(0, 60)- case 'Glob': {- const count = rawOutput.trim() ? rawOutput.trim().split('\n').length : 0- return `${count} file${count !== 1 ? 's' : ''}`- }- case 'Grep': {- const count = rawOutput.trim() ? rawOutput.trim().split('\n').length : 0- return `${count} match${count !== 1 ? 'es' : ''}`- }- case 'WebFetch':- case 'WebSearch':- return 'Fetched'- case 'TodoRead':- case 'TodoWrite':- return 'Done'- default:- return rawOutput.split('\n')[0]?.slice(0, 80) || 'Done'- }-}--// ── Raw JSONL line → normalized message (port of transformCCMessageToSessionMessage) ─────────────--function smartWriteInput(input: Record<string, unknown>): Record<string, unknown> {- const raw = input.content as string- const lines = raw.split('\n')- const preview = lines.slice(0, PREVIEW_LINES).join('\n')- return {- ...input,- content: undefined,- content_stats: {- lines: lines.length,- chars: raw.length,- preview: preview + (lines.length > PREVIEW_LINES ? '\n…' : ''),- },- }-}--function smartEditInput(input: Record<string, unknown>): Record<string, unknown> {- const truncSide = (s: unknown): unknown => {- if (typeof s !== 'string') return s- if (s.length <= MAX_DIFF_SIDE) return s- const half = Math.floor(MAX_DIFF_SIDE / 2)- return s.slice(0, half) + '\n…\n' + s.slice(s.length - half)- }- return { ...input, old_string: truncSide(input.old_string), new_string: truncSide(input.new_string) }-}--function mapContentItem(item: unknown): RawContentBlock {- const c = (item ?? {}) as Record<string, unknown> // a null content block must not throw on `.type`- const type = (c.type || 'text') as RawContentBlock['type']-- if (type === 'image') {- return { type: 'image', source: c.source as RawContentBlock['source'] }- }-- let resultContent = c.content as RawContentBlock['content']- if (type === 'tool_result' && typeof resultContent === 'string' && resultContent.length > MAX_OUTPUT) {- resultContent = resultContent.slice(0, MAX_OUTPUT) + '\n…[truncated]'- }-- let toolInput = c.input as Record<string, unknown> | undefined- let toolName = c.name as string | undefined- // On a Local model the web tools come from the `harness` MCP server; the transcript should not- // look different for it, so they take the native cards here, at the one raw→normalized point.- const webTool = type === 'tool_use' ? harnessWebTool(toolName, toolInput) : null- if (webTool) {- toolName = webTool.tool- toolInput = webTool.input- }- if (type === 'tool_use' && toolInput) {- if ((toolName === 'Write' || toolName === 'WriteFile') && typeof toolInput.content === 'string' && toolInput.content.length > 500) {- toolInput = smartWriteInput(toolInput)- } else if (- (toolName === 'Edit' || toolName === 'EditFile') &&- (((toolInput.old_string as string)?.length ?? 0) > MAX_DIFF_SIDE || ((toolInput.new_string as string)?.length ?? 0) > MAX_DIFF_SIDE)- ) {- toolInput = smartEditInput(toolInput)- }- }-- return {- type,- text: c.text as string | undefined,- thinking: c.thinking as string | undefined,- id: c.id as string | undefined,- name: toolName,- input: toolInput,- tool_use_id: c.tool_use_id as string | undefined,- content: resultContent,- is_error: c.is_error as boolean | undefined,- }-}--/** Parse one raw JSONL entry into a normalized user/assistant message (null for other types). */-export function transformLine(rawMessage: Record<string, unknown>): NormalizedMessage | null {- const type = rawMessage.type as string- if (type !== 'user' && type !== 'assistant') return null-- const messageObj = rawMessage.message as Record<string, unknown> | undefined- let messageContent: RawContentBlock[] | undefined-- if (messageObj) {- const role = messageObj.role as string- const content = messageObj.content- if (role === 'user' || role === 'assistant') {- if (typeof content === 'string') {- messageContent = [{ type: 'text', text: content }]- } else if (Array.isArray(content)) {- messageContent = content.length > 0 ? content.map(mapContentItem) : [{ type: 'text', text: '' }]- } else if (content === null || content === undefined) {- messageContent = [{ type: 'text', text: '' }]- }- }- } else if (type === 'user') {- const directContent = rawMessage.content- if (typeof directContent === 'string') {- messageContent = [{ type: 'text', text: directContent }]- } else if (Array.isArray(directContent)) {- messageContent = directContent.map(mapContentItem)- }- }-- let toolUseResult: NormalizedMessage['toolUseResult']- if (rawMessage.tool_use_result || rawMessage.toolUseResult) {- const tr = (rawMessage.tool_use_result || rawMessage.toolUseResult) as Record<string, unknown>- toolUseResult = {- status: (tr.status || 'complete') as string,- agentId: (tr.agentId ?? tr.agent_id) as string | undefined,- agentType: (tr.agentType ?? tr.agent_type) as string | undefined,- totalTokens: tr.totalTokens as number | undefined,- totalDurationMs: tr.totalDurationMs as number | undefined,- totalToolUseCount: tr.totalToolUseCount as number | undefined,- // WebSearch carries its search time here (the CLI's "Did 1 search in Ns" line).- durationSeconds: typeof tr.durationSeconds === 'number' ? tr.durationSeconds : undefined,- }- }-- const role = (messageObj?.role || (type === 'user' ? 'user' : 'assistant')) as 'user' | 'assistant'-- if (role === 'user' && messageContent) {- for (const block of messageContent) {- if (block.type !== 'text' || !block.text) continue- // A typed slash command survives as `/name args`; everything else is stripped as before.- block.text = commandPromptText(block.text) ?? stripSystemBlocks(block.text)- }- }-- if (messageContent === undefined) messageContent = [{ type: 'text', text: '' }]-- return {- type: type as 'user' | 'assistant',- message: { role, content: messageContent },- toolUseResult,- stopReason: (messageObj?.stop_reason as string | null | undefined) ?? null,- }-}--// ── Shared per-message event emission ─────────────────────────────────────────────────────────────--// Auto-fix / platform prompts filtered from replay (sent by the platform, not the user).-const SYSTEM_PROMPT_PATTERNS = [- 'The dev server is running but the app has an error:',- 'Please fix this code issue. Check the page component, routing, and any compile errors.',- '<!-- CONTEXT SUMMARY',- 'This session is being continued from a previous conversation',- '<local-command-stdout>Compacted',-]--function isSystemPrompt(content: RawContentBlock[]): boolean {- const text = content.filter((c) => c.type === 'text' && c.text).map((c) => c.text!).join('')- return SYSTEM_PROMPT_PATTERNS.some((p) => text.includes(p))-}--/** A REAL user prompt (not a tool_result echo, not a platform prompt). Returns the cleaned text or null. */-/**- * An ESC interrupt (terminal, or a Stop from the web/device) is written to the transcript as a plain user- * line — `type:'user'`, `userType:'external'`, no `isMeta`, no flag of ANY kind — so its text is the only- * thing distinguishing it from something the user typed. Treating it as a prompt opened a brand-new turn at- * the instant a turn was cancelled, and the device then counted seconds forever on a turn no assistant- * would ever answer. Covers the `for tool use` variant too. A user who literally types this loses one turn- * card; that is the cheaper failure.- */-const INTERRUPT_MARKER = /^\[Request interrupted by user[^\]]*\]$/--/** The user-authored text of a line, before interrupt markers are judged. null = not a user prompt. */-function userTextRaw(msg: NormalizedMessage): string | null {- if (msg.type !== 'user' || !msg.message) return null- const content = msg.message.content- if (isSystemPrompt(content)) return null- if (content.some((c) => c.type === 'tool_result')) return null- const parts: string[] = []- for (const block of content) {- if (block.type !== 'text' || !block.text) continue- let cleaned = stripContextSummary(block.text)- if (cleaned) cleaned = stripSystemBlocks(cleaned)- if (cleaned && !cleaned.match(/^\[Image: original \d+x\d+/)) parts.push(cleaned)- }- const text = parts.join('\n')- return text || null-}--/**- * An async sub-agent's REAL completion. Claude's `Agent` tool returns in milliseconds with- * "Async agent launched successfully." — that `tool_result` is a launch ack, not a result, and taking it- * for one made the device tick a sub-agent off the moment it started. The actual finish arrives much- * later as a `type:"user"` record the CLI injects into the parent transcript:- *- * <task-notification><task-id>…</task-id><tool-use-id>toolu_018wkW…</tool-use-id>- * <output-file>…</output-file><status>completed</status><summary>Agent "…" finished…- *- * `stripSystemBlocks` erases the whole block, so it correctly starts no turn — but that also meant the- * only signal a sub-agent had finished was being thrown away. Read it here, keyed by tool-use-id.- *- * Takes the RAW record, not a NormalizedMessage: `transformLine` already ran the strip (line ~304), so by- * then the text block is empty and there is nothing left to parse.- */-function taskNotificationEvent(raw: Record<string, unknown>): LiveEvent | null {- // One that finishes while its parent still works comes as a `queued_command` attachment, the more common- // delivery (real 2.1.270–2.1.287). Read from user records alone, it never finished on the dial.- const attachment = raw.type === 'attachment' ? raw.attachment as { type?: unknown; prompt?: unknown } | undefined : undefined- if (raw.type !== 'user' && attachment?.type !== 'queued_command') return null- const content = attachment ? attachment.prompt : (raw.message as { content?: unknown } | undefined)?.content ?? raw.content- let text = ''- if (typeof content === 'string') text = content- else if (Array.isArray(content)) {- text = content- .map((b) => (typeof b === 'string' ? b : (b as RawContentBlock)?.type === 'text' ? String((b as RawContentBlock).text ?? '') : ''))- .join('\n')- }- if (!text.includes('<task-notification>')) return null- const id = text.match(/<tool-use-id>([^<]+)<\/tool-use-id>/)?.[1]?.trim()- if (!id) return null- const status = text.match(/<status>([^<]+)<\/status>/)?.[1]?.trim() || 'completed'- const summary = text.match(/<summary>([\s\S]*?)(?:<\/summary>|$)/)?.[1]?.trim()- return { type: 'subagent_finished', payload: { id, status, ...(summary ? { summary } : {}) } }-}--/** True for the synthetic line an interrupt leaves behind. It ends a turn; it never starts one. */-function isInterruptLine(msg: NormalizedMessage): boolean {- const text = userTextRaw(msg)- return text !== null && INTERRUPT_MARKER.test(text)-}--// Every caller of this asks "is this a prompt the user made?" — turn slicing for replay and the recap's-// user-message source as well as the live turn lifecycle — and an interrupt marker is not one of those.-function realUserText(msg: NormalizedMessage): string | null {- const text = userTextRaw(msg)- if (text === null || INTERRUPT_MARKER.test(text)) return null- // Claude Code 2.1.290 also writes a built-in command it runs itself as a plain user line ("/compact"),- // ahead of the tagged record `commandPromptText` already keeps out. Taken as a prompt, it opened a turn- // nothing ever closed: after a /compact the agent read working, then unknown, until the next message- // (found by daemon QA). The same list decides both forms.- if (isLocalOnlyCommandLine(text)) return null- // A `!command` line is not a prompt — skip it so the turn (and its recap) stays anchored to the last- // real ask. Only when nothing but bash blocks remain: a message that also carries prose still counts.- if (!stripBashModeBlocks(text)) return null- return text-}--/**- * Extract the last real user prompt and the assistant text that followed it from- * raw Claude JSONL. This is the recap source of truth: it matches replay parsing- * rules, skips tool_result echoes / platform prompts / compact metadata, and only- * summarizes assistant text blocks.- */-export function lastTurnTextFromRawLines(rawLines: string[]): LastTurnText | null {- let userMessage = ''- // What the assistant said AFTER its last tool call: the answer. Everything before it is narration of- // the work ("Let me check the logs"), kept aside because a turn that never reached an answer (it ended- // on a tool call, or was interrupted) still has something to summarize.- let assistantParts: string[] = []- let narration: string[] = []-- for (const line of rawLines) {- if (!line.trim()) continue- let raw: Record<string, unknown>- try { raw = JSON.parse(line) as Record<string, unknown> } catch { continue }- const compact = compactEventFromRaw(raw)- if (compact !== undefined) continue-- const msg = transformLine(raw)- if (!msg?.message) continue-- const userText = realUserText(msg)- if (userText !== null) {- userMessage = userText- assistantParts = []- narration = []- continue- }-- if (msg.type !== 'assistant') continue- const text = msg.message.content- .filter((c) => c.type === 'text' && c.text)- .map((c) => c.text!)- .join('')- .trim()- if (text) assistantParts.push(text)- // A tool call closes the stretch of text before it: that was narration, and the answer is what comes- // after the last one. Without this a long working turn is summarized by its FIRST line, so the- // dial and the reader show "Let me look at the logs" instead of what was found.- if (msg.message.content.some((c) => c.type === 'tool_use')) {- narration = narration.concat(assistantParts)- assistantParts = []- }- }-- const assistantText = (assistantParts.length ? assistantParts : narration).join('\n\n').trim()- return assistantText ? { userMessage, assistantText } : null-}--/** Aggregates computed from a sub-agent's OWN transcript. Async/background agents never get totals- * in the launcher's toolUseResult (it only records `{isAsync, status:'async_launched', agentId}` at- * launch) — the real numbers live in `<session>/subagents/agent-<id>.jsonl`. totalTokens mirrors the- * CLI's definition: input + output + cache_read + cache_creation summed over assistant turns. Taken a- * line at a time, so a long transcript is never held whole. */-export class SubagentStats {- private toolCount = 0- private tokens = 0- private first: number | undefined- private last: number | undefined-- push(line: string): void {- if (!line.trim()) return- let raw: Record<string, unknown>- try { raw = JSON.parse(line) as Record<string, unknown> } catch { return }- if (!raw || typeof raw !== 'object') return- const ts = typeof raw.timestamp === 'string' ? Date.parse(raw.timestamp) : NaN- if (!Number.isNaN(ts)) { if (this.first === undefined) this.first = ts; this.last = ts }- if (raw.type !== 'assistant') return- const msg = raw.message as { content?: unknown; usage?: Record<string, unknown> } | undefined- if (!msg) return- if (Array.isArray(msg.content)) {- for (const b of msg.content) if ((b as { type?: string }).type === 'tool_use') this.toolCount++- }- const u = msg.usage- if (u) {- this.tokens += (Number(u.input_tokens) || 0) + (Number(u.output_tokens) || 0)- + (Number(u.cache_read_input_tokens) || 0) + (Number(u.cache_creation_input_tokens) || 0)- }- }-- result(): { totalToolUseCount: number; totalDurationMs?: number; totalTokens?: number } {- const { first, last } = this- return {- totalToolUseCount: this.toolCount,- totalDurationMs: first !== undefined && last !== undefined && last > first ? last - first : undefined,- totalTokens: this.tokens || undefined,- }- }-}--export function subagentStatsFromRawLines(rawLines: string[]): { totalToolUseCount: number; totalDurationMs?: number; totalTokens?: number } {- const stats = new SubagentStats()- for (const line of rawLines) stats.push(line)- return stats.result()-}--/** Emit tool_end events for a user message's tool_result blocks. */-function toolResultEvents(msg: NormalizedMessage, toolIdToName: Map<string, string>): SessionEvent[] {- const events: SessionEvent[] = []- if (!msg.message) return events- for (const block of msg.message.content) {- if (block.type !== 'tool_result') continue- const toolUseId = block.tool_use_id || ''- const isError = block.is_error === true- let rawOutput = ''- if (typeof block.content === 'string') {- rawOutput = block.content- } else if (Array.isArray(block.content)) {- rawOutput = block.content.filter((c) => c.type === 'text' && c.text).map((c) => c.text!).join('')- }- const toolName = toolIdToName.get(toolUseId) || ''- const summary = computeToolSummary(toolName, rawOutput, isError)- if (rawOutput.length > MAX_OUTPUT) rawOutput = rawOutput.slice(0, MAX_OUTPUT) + '\n…[truncated]'- const agg = msg.toolUseResult- const subagent = agg?.agentId- ? { agentId: agg.agentId, agentType: agg.agentType, totalTokens: agg.totalTokens, totalDurationMs: agg.totalDurationMs, totalToolUseCount: agg.totalToolUseCount }- : undefined- events.push({- type: 'tool_end',- payload: {- id: toolUseId, tool: toolName, output: rawOutput, isError, summary,- ...(subagent ? { subagent } : {}),- ...(typeof agg?.durationSeconds === 'number' ? { durationSeconds: agg.durationSeconds } : {}),- },- })- }- return events-}--/** Emit thinking/text/tool_start events for an assistant message's blocks. */-function assistantEvents(- msg: NormalizedMessage,- toolIdToName: Map<string, string>,- thinkingIdPrefix: string,- thinkingCounterStart = 0,-): SessionEvent[] {- const events: SessionEvent[] = []- if (!msg.message) return events- let thinkingCounter = thinkingCounterStart- for (const block of msg.message.content) {- if (block.type === 'thinking' && block.thinking) {- const thinkingId = `${thinkingIdPrefix}${thinkingCounter++}`- const thinkingContent = block.thinking.length > MAX_THINKING- ? block.thinking.slice(0, MAX_THINKING) + '\n…[truncated]'- : block.thinking- events.push({ type: 'thinking_delta', payload: { content: thinkingContent, thinkingId } })- const title = extractThinkingTitle(block.thinking)- if (title) events.push({ type: 'thinking_title', payload: { thinkingId, title } })- } else if (block.type === 'text' && block.text) {- events.push({ type: 'text_delta', payload: { content: block.text } })- } else if (block.type === 'tool_use') {- const toolId = block.id || ''- const toolName = block.name || ''- toolIdToName.set(toolId, toolName)- let toolInput = block.input- if (toolInput && typeof toolInput === 'object') {- const inputCopy = { ...(toolInput as Record<string, unknown>) }- for (const [key, val] of Object.entries(inputCopy)) {- if (typeof val === 'string' && val.length > MAX_OUTPUT) {- inputCopy[key] = val.slice(0, MAX_OUTPUT) + '\n…[truncated]'- }- }- toolInput = inputCopy- }- events.push({ type: 'tool_start', payload: { id: toolId, tool: toolName, input: toolInput } })- }- }- return events-}--// ── Compaction lines ────────────────────────────────────────────────────────────────────────────-//-// When a tmux claude session compacts (auto or `/compact`), it does an IN-FILE compact: the JSONL-// keeps the SAME sessionId and is append-only (pre-compact history stays on disk), so the byte-offset-// tail streams straight through — there is no dead file to re-point at and no truncation to re-read.-// The compact only injects a few bookkeeping lines we must handle so the stream stays clean:-// • `system` / `subtype:"compact_boundary"` (+ `compactMetadata.trigger`) → one `context_compact`-// indicator (purely a UI hint; the actual stream continuity is already guaranteed by the tail).-// • the injected `isCompactSummary` user line (the big "This session is being continued…" summary)-// and any `isMeta` bookkeeping line → suppressed via the AUTHORITATIVE flags (not a fragile-// English-string match), so the summary is never rendered as a giant fake user turn / new turn.-//-// Returns the events to emit for a compact line (possibly `[]` to suppress it), or `undefined` when-// `raw` is not a compact line and should fall through to the normal user/assistant path.-export function compactEventFromRaw(raw: Record<string, unknown>): SessionEvent[] | undefined {- if (raw.type === 'system' && raw.subtype === 'compact_boundary') {- const meta = raw.compactMetadata as { trigger?: string } | undefined- return [{- type: 'context_compact',- payload: {- message: 'Context was compacted — the previous conversation has been summarized to free up space.',- ...(meta?.trigger ? { trigger: meta.trigger } : {}),- },- }]- }- if (raw.isCompactSummary === true) return []- if (raw.isMeta === true) {- // NOT all isMeta user lines are bookkeeping. A `/loop` iteration is a REAL prompt that Claude- // submits on the user's behalf every time the loop fires, and it is written as isMeta — so blanket- // suppression made every iteration after the first invisible: no turn_started, therefore no recap,- // therefore nothing on the device, while the loop kept running perfectly in the terminal.- //- // The discriminator is `promptSource`, which Claude sets authoritatively (same principle as the- // flags above — never an English-string match):- // 'typed' + no isMeta → the human typed it- // 'system' + isMeta → submitted programmatically: a loop iteration. This IS a turn.- // (absent) + isMeta → real bookkeeping: a compact summary, or a slash command's expansion- // text. Still suppressed, so one `/goal` is not three user turns.- if (raw.type === 'user' && raw.promptSource === 'system') return undefined- return []- }- return undefined-}--// ── Full replay (session_get) ─────────────────────────────────────────────────────────────────────--/** Convert a whole session's raw JSONL lines to replay events (same render path as streaming). */-/**- * A message the person typed while Claude Code was working. Claude Code delivers it into the running- * turn as a `queued_command` attachment, not a prompt record. The live view leaves it out on purpose- * (it opens no turn there), but the history must show it: without it a reopened conversation answered a- * question it never showed (found by daemon QA with Claude Code 2.1.290). Sub-agent hand-backs and- * Claude's own continuations arrive the same way, and they are not the person's words.- */-function queuedHumanPrompt(raw: Record<string, unknown>): string | null {- if (raw.type !== 'attachment') return null- const attachment = raw.attachment as { type?: unknown; commandMode?: unknown; prompt?: unknown; origin?: { kind?: unknown } } | undefined- if (attachment?.type !== 'queued_command' || attachment.commandMode !== 'prompt' || attachment.origin?.kind !== 'human') return null- const prompt = attachment.prompt- const text = typeof prompt === 'string' ? prompt- : Array.isArray(prompt) ? prompt.map((block) => (block as { type?: unknown; text?: unknown })?.type === 'text' ? String((block as { text?: unknown }).text ?? '') : '').join('\n')- : ''- return text.trim() ? text : null-}--export function messagesToEvents(rawLines: string[]): SessionEvent[] {- const events: SessionEvent[] = []- const toolIdToName = new Map<string, string>()- let thinkingCounter = 0- let inAutoFixSequence = false- let continuedAt = -1-- for (const line of rawLines) {- if (!line.trim()) continue- let raw: Record<string, unknown>- try { raw = JSON.parse(line) as Record<string, unknown> } catch { continue }- const compact = compactEventFromRaw(raw)- if (compact) { events.push(...compact); continue } // compact boundary → indicator; summary/meta → suppressed- const queued = queuedHumanPrompt(raw)- if (queued) { events.push({ type: 'user_message', payload: { content: queued } }); continue }- // A pass a blocking Stop hook continued, as the live view starts it (lineToEvents), once per pass.- const continued = stopHookContinuation(raw)- if (continued !== null) {- if (continuedAt !== events.length - 1) events.push({ type: 'user_message', payload: { content: continued } })- continuedAt = events.length - 1- continue- }- const msg = transformLine(raw)- if (!msg?.message) continue-- if (msg.type === 'user') {- const content = msg.message.content- if (isSystemPrompt(content)) { inAutoFixSequence = true; continue }- const hasToolResult = content.some((c) => c.type === 'tool_result')- const hasUserText = content.some((c) => c.type === 'text' && c.text?.trim())- if (inAutoFixSequence && hasToolResult && !hasUserText) continue- if (inAutoFixSequence) inAutoFixSequence = false-- if (!hasToolResult) {- const textParts: string[] = []- const images: Array<{ media_type: string; data: string }> = []- for (const block of content) {- if (block.type === 'text' && block.text) {- let cleaned = stripContextSummary(block.text)- if (cleaned) cleaned = stripSystemBlocks(cleaned)- if (cleaned && !cleaned.match(/^\[Image: original \d+x\d+/)) textParts.push(cleaned)- } else if (block.type === 'image' && block.source) {- images.push({ media_type: block.source.media_type, data: block.source.data })- }- }- const textContent = textParts.join('\n')- if (textContent || images.length > 0) {- events.push({ type: 'user_message', payload: { content: textContent, ...(images.length > 0 ? { images } : {}) } })- }- continue- }-- events.push(...toolResultEvents(msg, toolIdToName))- continue- }-- // assistant- if (inAutoFixSequence) continue- const before = events.length- events.push(...assistantEvents(msg, toolIdToName, 'thinking-hist-', thinkingCounter))- // keep the per-session thinking counter monotonic across messages- thinkingCounter += events.slice(before).filter((e) => e.type === 'thinking_delta').length- }-- events.push({ type: 'done', payload: { result: 'success' } })- return events-}--/**- * Turn-snapped pagination window over raw JSONL lines, for `session_get` with `{limit, before}`.- * `before` = uuid of the oldest line the client already holds (exclusive upper bound). Returns the- * line slice to feed `messagesToEvents` plus cursor metadata.- *- * The window START is snapped back to a real user-prompt line so a window never splits an assistant- * turn's `tool_use` from its `tool_result`: `messagesToEvents` is stateful (`toolIdToName` carries a- * tool_use id → name across lines so the later tool_result renders the tool name), so a mid-turn cut- * would drop tool names. A user-prompt line never sits between a tool_use and its tool_result, so- * snapping there keeps every turn whole.- */-/**- * What a Claude history page knows of one line: the cursor that names it, and whether a page may start- * there — a real user prompt, so a turn is never split. Shared by `windowRawLines` and the bounded pager- * (lib/transcriptPages.ts), so the two cannot drift apart.- */-export function claudePageLine(line: string): { cursor: string | null; startsPage: boolean } {- if (!line.trim()) return { cursor: null, startsPage: false }- let raw: Record<string, unknown>- try { raw = JSON.parse(line) as Record<string, unknown> } catch { return { cursor: null, startsPage: false } }- const cursor = (raw.uuid ?? raw.id ?? raw.message_id ?? null) as string | null- const msg = transformLine(raw)- return { cursor, startsPage: msg ? realUserText(msg) !== null : false }-}--export function windowRawLines(- rawLines: string[],- opts: { limit: number; before?: string },-): { window: string[]; hasMore: boolean; oldestCursor: string | null; staleCursor?: boolean } {- // Per-line uuid + whether the line is a real user-prompt turn start (parse each line once).- const meta = rawLines.map((line) => {- const { cursor, startsPage } = claudePageLine(line)- return { uuid: cursor, turnStart: startsPage }- })-- let endIndex = rawLines.length- if (opts.before) {- const ci = meta.findIndex((m) => m.uuid === opts.before)- // Cursor no longer in the file (should not happen — the transcript is append-only) → signal a- // full reload rather than returning a wrong window.- if (ci < 0) return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }- endIndex = ci // exclusive: the client already holds this line- }-- let start = Math.max(0, endIndex - opts.limit)- while (start > 0 && !meta[start].turnStart) start---- return {- window: rawLines.slice(start, endIndex),- hasMore: start > 0,- oldestCursor: meta[start]?.uuid ?? null,- }-}--// ── Live tailing (watcher lines) with derived turn lifecycle ──────────────────────────────────────--export interface TurnState {- turnOpen: boolean- toolIdToName: Map<string, string>- /** tool_use ids started but not yet resolved by a tool_result. */- pendingTools: Set<string>- thinkingCounter: number- /** Before the counter in a live thinking id. A fold that starts mid-transcript names its window here- * (lib/attachTranscript.ts), so its ids cannot repeat ones another fold of the same session sent. */- thinkingPrefix?: string- /** The open turn is one a blocking Stop hook continued (`stopHookContinuation`), not a prompt's. */- continued?: boolean- /** How many turns this state has opened: a Stop hook closes only the turn that was open as it arrived- * (core/turns/turnHooks.ts). */- opened?: number-}--/**- * The turn a Stop hook that blocked keeps going, or null. `/goal` is built on such a hook, and people write- * their own. Claude Code writes the hook's feedback as a hidden `isMeta` user line, then one of these, then- * works on in the SAME turn with no prompt line between (real 2.1.282/2.1.283):- * {"type":"attachment","attachment":{"type":"goal_status","met":false,"condition":"…","reason":"…"}}- * {"type":"attachment","attachment":{"type":"hook_blocking_error","hookEvent":"Stop","blockingError":{"blockingError":"…"}}}- * The pass's end_turn had closed the turn, so the rest ran with none open: no turn_ended, no recap, and- * idle whenever a tool outlasted the work lease. A `sentinel` goal_status restates an active goal at start.- * The label matches the Codex normalizer's goal continuations.- */-export function stopHookContinuation(raw: Record<string, unknown>): string | null {- if (raw.type !== 'attachment') return null- const attachment = raw.attachment as Record<string, unknown> | undefined- if (attachment?.type === 'goal_status' && attachment.met === false && attachment.sentinel !== true) {- const condition = typeof attachment.condition === 'string' ? attachment.condition.trim() : ''- return condition ? `Continuing goal: ${condition}` : 'Continuing goal'- }- if (attachment?.type === 'hook_blocking_error' && attachment.hookEvent === 'Stop') {- const blocking = attachment.blockingError as { blockingError?: unknown } | undefined- const reason = typeof blocking?.blockingError === 'string' ? blocking.blockingError.trim().split('\n')[0].trim() : ''- return reason ? `Continuing: ${reason.length > 200 ? `${reason.slice(0, 197)}...` : reason}` : 'Continuing'- }- return null-}--export function newTurnState(): TurnState {- return { turnOpen: false, toolIdToName: new Map(), pendingTools: new Set(), thinkingCounter: 0 }-}--/**- * Fold a transcript that already exists into a fresh normalizer, and say whether what came out is- * HISTORY (to be swallowed) or the LIVE conversation (to be emitted).- *- * Attaching to a session normally means catching up on turns the user has already seen elsewhere, so the- * events are dropped and only a turn left half-open is replayed. That assumption breaks when the agent- * exists BEFORE its session: the first prompt is what makes the engine open the transcript, so by the- * time anything binds it, the whole first turn — question, tools and answer — can already be on disk.- * Folded as history it is lost silently, and silently is literal: no `turn_started` means no- * `turn_ended` and no recap either, so nothing in the log records that a turn ever happened.- *- * `live` picks the destination. It also forces `turnOpen` to false, because the caller's mid-turn rescue- * ("replay the last turn_started") would otherwise emit that event a second time on top of the events- * returned here.- */-export function foldTranscript(- ingest: (line: string) => LiveEvent[],- lines: string[],- turnOpenAfter: () => boolean,- opts: { live: boolean },-): { history: LiveEvent[]; live: LiveEvent[]; turnOpen: boolean } {- const folded: LiveEvent[] = []- for (const line of lines) folded.push(...ingest(line))- return {- history: opts.live ? [] : folded,- live: opts.live ? folded : [],- turnOpen: !opts.live && turnOpenAfter(),- }-}--/**- * `foldTranscript` one record at a time, for a transcript streamed in rather than loaded- * (lib/attachTranscript.ts). History keeps only its last `turn_started` — the one event an attach ever- * replays from it — so folding a long turn holds nothing but that.- */-export class TranscriptFold {- private lastStarted: LiveEvent | null = null- private readonly folded: LiveEvent[] = []-- constructor(- private readonly ingest: (line: string) => LiveEvent[],- private readonly turnOpenAfter: () => boolean,- private readonly live: boolean,- ) {}-- push(line: string): void {- for (const event of this.ingest(line)) {- if (this.live) this.folded.push(event)- else if (event.type === 'turn_started') this.lastStarted = event- }- }-- finish(): { history: LiveEvent[]; live: LiveEvent[]; turnOpen: boolean } {- return {- history: this.lastStarted ? [this.lastStarted] : [],- live: this.folded,- turnOpen: !this.live && this.turnOpenAfter(),- }- }-}--// Terminal assistant stop reasons that close a turn. `tool_use` is deliberately absent (the turn-// continues into the tool). `pause_turn` is absent too — it may legitimately resume; the Stop hook-// (which only fires when the agent is truly done) is the authoritative catch-all for that case.-// `max_tokens`/`refusal` are included so a turn that ends on them still closes from the JSONL alone.-const TERMINAL_STOP_REASONS = new Set(['end_turn', 'stop_sequence', 'max_tokens', 'refusal'])--/**- * Convert ONE appended JSONL line into live events. Derives turn_started/turn_ended from content:- * - a real user prompt → (turn_ended if one was open) + turn_started{userMessage}- * - assistant blocks → thinking/text/tool_start (tool ids tracked as pending)- * - user tool_results → tool_end (resolves pending ids)- * - assistant stop_reason in TERMINAL_STOP_REASONS with no pending tools → turn_ended- */-export function lineToEvents(rawLine: string, state: TurnState): LiveEvent[] {- if (!rawLine.trim()) return []- let raw: Record<string, unknown>- try { raw = JSON.parse(rawLine) as Record<string, unknown> } catch { return [] }- // A valid-JSON but non-object line (the literal `null`, a number, a bare string) would make the- // property access in compactEventFromRaw / transformLine throw — and on the unguarded watcher path- // that kills the daemon. Any non-object line has nothing to emit.- if (!raw || typeof raw !== 'object') return []- // Compaction: emit the boundary indicator; suppress the injected summary/meta lines. The turn state- // is left untouched, so an auto-compact that fires MID-TURN keeps the open turn open (the assistant- // continuation after the boundary just streams under it) instead of the summary opening a fake turn.- const compact = compactEventFromRaw(raw)- if (compact) return compact- // Sub-agent finished. Deliberately does NOT touch the turn state: the parent turn already closed on the- // launch ack, and this record is not a prompt.- const finished = taskNotificationEvent(raw)- if (finished) return [finished]- // A Stop hook that blocked: the pass's end_turn closed the turn Claude Code works on in. Open it again.- const continued = stopHookContinuation(raw)- if (continued !== null) {- if (state.turnOpen) return []- state.turnOpen = true- state.opened = (state.opened ?? 0) + 1- state.pendingTools.clear()- state.continued = true- return [{ type: 'turn_started', payload: { userMessage: continued } }]- }- // Claude Code's own record that its turn is over. A continued pass can end with no output: when the hook- // refuses again, Claude Code pauses the goal and writes only notices and this (real 2.1.283), with no- // end_turn or Stop to close what was opened above. Every other turn is closed as before.- if (raw.type === 'system' && raw.subtype === 'turn_duration') {- if (!state.turnOpen || !state.continued) return []- state.turnOpen = false- state.pendingTools.clear()- return [{ type: 'turn_ended', payload: {} }]- }- const msg = transformLine(raw)- if (!msg?.message) return []-- const events: LiveEvent[] = []-- if (msg.type === 'user') {- // Interrupt: close the open turn and start NOTHING. This is also the only signal for an ESC pressed- // straight in the terminal — no cancel frame reaches the adapter there — so the turn has to end here.- if (isInterruptLine(msg)) {- if (!state.turnOpen) return []- state.turnOpen = false- state.pendingTools.clear()- return [{ type: 'turn_ended', payload: { aborted: true } }]- }- const userText = realUserText(msg)- if (userText !== null) {- // New prompt (typed in the terminal OR injected from the web) — starts a turn.- if (state.turnOpen) events.push({ type: 'turn_ended', payload: {} })- state.turnOpen = true- state.opened = (state.opened ?? 0) + 1- state.pendingTools.clear()- state.continued = false- events.push({ type: 'turn_started', payload: { userMessage: userText } })- return events- }- // tool_result echoes: resolve pending tools.- const ends = toolResultEvents(msg, state.toolIdToName)- for (const e of ends) {- if (e.type === 'tool_end') state.pendingTools.delete(e.payload.id)- }- events.push(...ends)- return events- }-- // assistant- const before = events.length- events.push(...assistantEvents(msg, state.toolIdToName, state.thinkingPrefix ?? 'thinking-live-', state.thinkingCounter))- state.thinkingCounter += events.slice(before).filter((e) => e.type === 'thinking_delta').length- for (const e of events) {- if (e.type === 'tool_start') state.pendingTools.add(e.payload.id)- }-- const stop = msg.stopReason- if (state.turnOpen && stop && TERMINAL_STOP_REASONS.has(stop) && state.pendingTools.size === 0) {- state.turnOpen = false- events.push({ type: 'turn_ended', payload: {} })- }- return events-}--function parseRecord(rawLine: string): Record<string, unknown> | null {- if (!rawLine.trim()) return null- try {- const raw = JSON.parse(rawLine) as unknown- return raw && typeof raw === 'object' ? raw as Record<string, unknown> : null- } catch { return null }-}--/**- * The record `lineToEvents` opens a turn on — a real user prompt — decided from the record alone, as- * `lineToEvents` decides it whatever came before. Attaching reads a transcript backward to the last- * one of these and folds only from there (lib/attachTranscript.ts): every turn-scoped piece of- * `TurnState` is reset by it, so the fold from here ends exactly where the whole-history fold does.- */-export function startsClaudeTurn(rawLine: string): boolean {- const raw = parseRecord(rawLine)- if (!raw || compactEventFromRaw(raw) || taskNotificationEvent(raw)) return false- const msg = transformLine(raw)- if (!msg?.message || msg.type !== 'user' || isInterruptLine(msg)) return false- return realUserText(msg) !== null-}--/**- * The tool calls a Claude record makes (`defines`) and the earlier calls whose results it carries- * (`references`), decided along `lineToEvents`' own branches. A result names its tool from the call- * `lineToEvents` saw earlier, so an attach that starts mid-transcript reaches back for the calls its- * turn's results answer (lib/attachTranscript.ts).- */-export function claudeToolLinks(rawLine: string): { defines: string[]; references: string[] } {- const raw = parseRecord(rawLine)- if (!raw || compactEventFromRaw(raw) || taskNotificationEvent(raw)) return { defines: [], references: [] }- const msg = transformLine(raw)- if (!msg?.message) return { defines: [], references: [] }- if (msg.type === 'assistant') {- return { defines: msg.message.content.filter((block) => block.type === 'tool_use').map((block) => block.id || ''), references: [] }- }- if (isInterruptLine(msg) || realUserText(msg) !== null) return { defines: [], references: [] }- return { defines: [], references: msg.message.content.filter((block) => block.type === 'tool_result').map((block) => block.tool_use_id || '') }-}--/** `tailFileUntil` selector for `lastTurnTextFromRawLines`: stop on the prompt it resets on, keep the- * assistant records it reads after that, and drop everything else it ignores — so a recap reads the- * last turn's text instead of the whole conversation. */-export function selectClaudeRecapLine(line: string): 'keep' | 'skip' | 'stop' {- const raw = parseRecord(line)- if (!raw || compactEventFromRaw(raw) !== undefined) return 'skip'- const msg = transformLine(raw)- if (!msg?.message) return 'skip'- if (realUserText(msg) !== null) return 'stop'- return msg.type === 'assistant' ? 'keep' : 'skip'-}+/** Compatibility exports. Engine-neutral consumers import engines/kit directly. */+export * from '../engines/kit/events.js'+export * from '../engines/kit/transcriptFold.js'+export * from '../engines/claude/normalize.js'diff --git a/cli/src/testing/transcriptOracle.ts b/cli/src/testing/transcriptOracle.tsindex 07e390e4a..e4b6c52f9 100644--- a/cli/src/testing/transcriptOracle.ts+++ b/cli/src/testing/transcriptOracle.ts@@ -1,10 +1,12 @@+import { claudeAttachRules } from '../engines/claude/attach.js'+import { codexAttachRules } from '../engines/codex/attach.js'/*** The whole-history attach that `lib/attachTranscript.ts` replaced, kept as the oracle the end-first* read is checked against — by the unit suite on synthetic transcripts and by the opt-in real-data* suite on this computer's own (`attachTranscript.real.spec.ts`).*/import { CodexNormalizer, codexGoalOf, startsCodexTurn } from '../engines/codex/normalizer.js'-import { attachTranscript, claudeAttachRules, codexAttachRules } from '../lib/attachTranscript.js'+import { attachTranscript } from '../lib/attachTranscript.js'import { foldTranscript, lineToEvents, newTurnState, TranscriptFold, type LiveEvent } from '../lib/normalize.js'import type { RegisteredSession } from '../lib/registry.js'import { RuntimeProfileManager } from '../lib/runtimeProfile.js'diff --git a/docs/design/2026-10-07-engine-live.md b/docs/design/2026-10-07-engine-live.mdnew file mode 100644index 000000000..02842f29b--- /dev/null+++ b/docs/design/2026-10-07-engine-live.md@@ -0,0 +1,68 @@+# Live engine interpretation outside core++Tracking: [#1016](https://github.com/autonomous-ai/openharness/issues/1016).+Follows the [reader pilot](2026-10-07-engine-readers.md) and the+[engine interface inventory](2026-10-05-engine-interface.md).++## Current increment++Claude Code's normalizer now belongs to `engines/claude/normalize.ts`. Claude Code+and Codex own their attach rules and live-parser factories. The `Engine.live`+facet exposes ingestion, a read-only turn snapshot, explicit closure, and the+start offset used to name thinking blocks. Event types and transcript folding+are engine-neutral kit modules; the backward file reader takes injected rules.++Core's attach and ingest modules receive a `LiveFor` dependency. The normalizer+table keeps a `LiveParser` handle per migrated session, without Claude's tool+maps or Codex's concrete normalizer type. A parser reports a failure separately+from its events so core can announce the reason before the corresponding turn+end. Other file engines and database readers retain their existing adapters.+A file line for a database engine cannot create a Claude parser for that engine.+The old plain-terminal fallback remains explicit in the temporary live lookup;+it does not acquire end-first attach rules.++**This increment still runs live parsers in core's process.** `engines/live.ts`+is temporary composition while the live transport is built. `lib/normalize.ts`+is a compatibility export used by consumers still being migrated. The existing+supervised workers still isolate history and last-turn reads only.++## Preserved requirements++- **EL-001 — Arrival identity.** A turn snapshot is a value. Its identity includes+ both a parser instance and its turn counter. A normal Stop cannot close a turn+ opened after its arrival or a turn in a replacement parser. StopFailure keeps+ its existing exception; a hook older than the latest prompt hook closes nothing.+ Core also checks the engine binding and expected turn identity at closure, and+ a rejected proposal emits no end event. Reusing a session id under another+ engine replaces its parser before ingestion.+- **EL-002 — Tail handover.** Attach holds delivery, rebuilds up to the held byte,+ and installs the replacement before releasing the hold. A failed read or expired+ hold preserves the old parser. No await is introduced into that final swap.+- **EL-003 — Event order.** The record's failure is announced before its events.+ First-turn replay, history replay and a resumed open turn remain distinct.+- **EL-004 — Closure semantics.** Cancellation preserves Claude's pending-call+ behavior. Relaunch and forced Stop clear pending calls. Tool-name links survive+ for late results. Core asks for closure; only the engine edits parser state.+- **EL-005 — Scope evidence.** Recorded transcript oracles, attach/hook race tests,+ the local core coverage gate and private-daemon tests validate this extraction.+ They do not establish live-process isolation.++## Remaining isolation audit++| Area | Current evidence / remaining work |+| --- | --- |+| History and last turn | Worker isolation merged in #1015; keep its reply, deadline and stale-binding guards. |+| Live transcripts | Typed parser and attach rules extracted here. Move state, file following and ordered delivery to workers, with bounded backpressure and restart reconstruction. |+| Hooks | Engine admission, path resolution and installers have engine homes but still execute in core. Stop still coordinates through an in-process facet. |+| Launch and sessions | Launch facets exist; preparation, homes, discovery/process recognition, resume/fork and binding repair still need a runtime boundary. |+| Screen and input | Pane interpretation, questions, acceptance and input preparation still contain engine behavior. Core must retain terminal/input authority. |+| Runtime profiles and models | Transcript/config interpretation and switching remain in shared core-reachable helpers. Core should read reported state and validate proposed actions. |+| Other helpers | Audit title, usage, search, one-shot, transcript-reader and compatible-format consumers, including transitive imports through `lib/normalize.ts`. |+| Completion proof | Require the complete C&C runtime closure to be outside normal core, plus fault, reconnect, stale-generation and cleanup evidence. File moves alone are insufficient. |++The live transport must carry binding and connection generations and preserve+the acknowledged transcript position across a worker restart. It must neither+queue unbounded per-line RPC calls nor silently fall back to inline parsing when+an isolated worker fails. Core remains authoritative for agents, session binding,+terminals, turns, input and questions. The existing master supervises one worker+per engine type; no per-agent worker process or new supervisor is planned.