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
Core boundary, part 2: input, questions, turns and the event funnel become modules (#717)
Deefe4423bebf81
diff --git a/cli/e2e/bounded.e2e.ts b/cli/e2e/bounded.e2e.tsindex a6def0647..7f4a0eab4 100644--- a/cli/e2e/bounded.e2e.ts+++ b/cli/e2e/bounded.e2e.ts@@ -3,9 +3,10 @@* daemon at its 4 GB heap: attaching read the whole transcript. These run the daemon under a heap far* smaller than the transcripts it serves.*/-import { mkdirSync, statSync, truncateSync } from 'node:fs'+import { mkdirSync, statSync, statfsSync, truncateSync } from 'node:fs'+import { tmpdir } from 'node:os'import { join } from 'node:path'-import { afterEach, describe, expect, it, onTestFailed } from 'vitest'+import { afterEach, beforeAll, describe, expect, it, onTestFailed } from 'vitest'import { LocalClient, type Frame } from './harness/client.js'import { IsolatedDaemon, until } from './harness/daemon.js'@@ -14,6 +15,13 @@ const TRANSCRIPT_MIB = 300describe('bounded memory', () => {let daemon: IsolatedDaemon | undefined+ // Each test writes a transcript this size, and on a nearly full disk the fake engine dies mid-write:+ // the turn then never ends and the test times out saying nothing about why (measured: 499 MiB free).+ beforeAll(() => {+ const disk = statfsSync(tmpdir())+ const freeMiB = Math.floor(disk.bavail * disk.bsize / (1024 * 1024))+ if (freeMiB < 4 * TRANSCRIPT_MIB) throw new Error(`these tests need ${4 * TRANSCRIPT_MIB} MiB free in ${tmpdir()}; ${freeMiB} MiB is`)+ })afterEach(async () => { await daemon?.close(); daemon = undefined })it.each(['claude', 'codex'] as const)(`%s: a ${TRANSCRIPT_MIB} MiB transcript re-attaches under a ${HEAP_MIB} MiB heap`, async (engine) => {diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex 8bf742eec..3e13d3081 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -176,6 +176,13 @@ import { connectToMaster } from './harnessd/coreLink.js'import { createTerminalControl } from './core/terminals/control.js'import { createAgentEvents } from './core/agents/events.js'import { createSessionNormalizers } from './core/transcripts/normalizers.js'+import { createInput } from './core/input.js'+import { createQuestions } from './core/questions.js'+import { createTurnActivity } from './core/turns/activity.js'+import { createLastTurnReader } from './core/transcripts/lastTurn.js'+import { createRecaps } from './core/turns/recaps.js'+import { createHeartbeats } from './core/turns/heartbeats.js'+import { createEventFunnel } from './core/turns/funnel.js'import { describeMasterStatus, readStatusFile, runMaster } from './harnessd/master.js'import { CORE_EXIT_STOP, CORE_EXIT_UPDATE } from './harnessd/protocol.js'import { isLocalSocketName, localSocketPath, type LocalSocketServer } from './lib/localSocket.js'@@ -2195,63 +2202,28 @@ async function runForeground(session: AuthSession | null): Promise<void> {const sessionTurnState = normalizers.sessionTurnStateconst sessionTurnOpen = normalizers.sessionTurnOpenconst watcher = new Watcher()- const codexActivity = new CodexActivityReader()- const runtimeActivity = new RuntimeActivityReader({- codex: session => codexActivity.read(session),- capture: async session => {- const screen = await terminals.capture(session, { mode: 'visible', ansi: true })- return screen.state === 'succeeded' ? screen.value : null- },- })- const turnActivity = new TurnActivity({- runtime: sessionId => {- const session = registry.bySession(sessionId)- return session?.active ? { key: activityRuntimeKey(session), turnOpen: sessionTurnOpen(sessionId) } : undefined- },- drain: sessionId => watcher.pollSession(sessionId),- probe: async sessionId => {- const session = registry.bySession(sessionId)- return session?.active ? runtimeActivity.read(session) : 'unknown'- },+ // Whether a turn is really working, beyond its transcript (core/turns/activity.ts).+ const activity = createTurnActivity({+ terminals,+ bySession: (sessionId) => registry.bySession(sessionId),+ sessionTurnOpen,+ drain: (sessionId) => watcher.pollSession(sessionId),})- activityFrameContextRef = session => isTerminalEngine(session.engine) ? null : turnActivity.snapshot(session.sessionId) ?? null+ const codexActivity = activity.codexActivity+ const runtimeActivity = activity.runtimeActivity+ const turnActivity = activity.turnActivity+ activityFrameContextRef = activity.activityFramebackend.activityFrameProvider = activityFrameContextRef- const queuedSessionEvents: Array<{- sessionId: string- events: ReturnType<CursorNormalizer['ingest']>- opts?: { resumed?: boolean; replay?: boolean }- }> = []- // Hook registration can race the rest of daemon initialization immediately after the localhost- // server binds. Queue those first records until input/mirror/heartbeat dependencies are ready.- let emitSessionEvents = (- sessionId: string,- events: ReturnType<CursorNormalizer['ingest']>,- opts?: { resumed?: boolean; replay?: boolean },- ): void => {- if (events.length) queuedSessionEvents.push({ sessionId, events, opts })- }- /**- * A turn died inside the engine instead of finishing. Neither devin nor commandcode has a StopFailure- * hook, so nothing else would tell the clients: the web would sit on the typing indicator and the- * device tile would stay "Working…". Surface the failure to both; the CALLER closes the turn (the devin- * reader and the commandcode normalizer each own their own turn state).- */- const announceTurnAborted = (- sessionId: string,- engine: string,- message: string,- deviceMessage = message,- ): void => {- console.log(`[turn] ${sid(sessionId)} aborted by ${engine} error · ${preview(message)}`)- backend.send({ type: 'error', agentId: agentIdFor(sessionId), dbSessionId: sessionId, payload: { message } })- backend.sendCommander({- type: 'commander_event',- agentId: agentIdFor(sessionId),- dbSessionId: sessionId,- payload: { kind: 'error', text: deviceErrorText(deviceMessage, engine) },- })- }+ // The event funnel (core/turns/funnel.ts). Hook registration can race the rest of daemon+ // initialization immediately after the localhost server binds: events wait until it is armed below.+ const funnel = createEventFunnel({+ clients: backend,+ // Declared further down: read when a turn aborts, never now.+ agentIdFor: (sessionId) => agentIdFor(sessionId),+ })+ const emitSessionEvents = funnel.emit+ const announceTurnAborted = funnel.announceTurnAbortedconst cursorDiscovery = new CursorTranscriptDiscovery(cursorDataDir(), (sessionId, transcriptPath) => {const existing = registry.bySession(sessionId)if (!existing || existing.engine !== 'cursor' || existing.transcriptPath === transcriptPath) return@@ -2609,66 +2581,29 @@ async function runForeground(session: AuthSession | null): Promise<void> {handover.hold?.release(handover.next)}})- const input: SessionInputController = new SessionInputController({- beforeSubmit: (id, text, tabId, deliveryId) => backend.swarmPromptScopes.prepare(id, text, tabId, deliveryId),- getSession: (id) => registry.resolve(id),- onDelivery: (event) => {- autonomousDeviceService?.delivery(event)- backend.orchestratorDelivery(event)- backend.teamDelivery(event)- },- beforeTeamWrite: async session => {- const capture = await captureTerminal(session.agentId)- return teamWriteHold(session.engine, capture)- },- validateRuntime: validateTerminal,- inject: (id, text) => deviceInput.legacyWrite(id, () => submitTerminalAction(id, text)),- injectTeam: (id, text, deliveryId) => deviceInput.legacyWrite(id, async () => {- const session = registry.resolve(id)- const reason = session ? teamWriteHold(session.engine, await captureTerminal(id)) : 'team_waiting_unavailable'- if (reason) return { state: 'failed', dispatch: 'not_started', reason }- if (!backend.teamCanWrite(deliveryId)) return terminalActionNotStarted('team_waiting_control')- return submitTerminalAction(id, text)- }),- sendKey: (id, key) => deviceInput.legacyWrite(id, () => keyTerminalAction(id, key)),- capture: captureTerminal,- onError: (sessionId, message) => {- backend.send({ type: 'error', agentId: agentIdFor(sessionId), dbSessionId: sessionId, payload: { message } })- const engine = registry.resolve(sessionId)?.engine- backend.sendCommander({ type: 'commander_event', agentId: agentIdFor(sessionId), dbSessionId: sessionId, payload: { kind: 'error', text: deviceErrorText(message, engine) } })- },- // Command Code writes its transcript only once the turn is OVER, so a turn that calls no tool has- // nothing to announce it: measured on 1.28.4, "hi" produced turn_started and turn_ended 1ms apart- // and neither web nor device ever showed the agent working. Our own paste is the one moment a turn- // is known to have started — and the only one that also knows the text.- onSubmitted: (id, content) => {- // `id` is whatever the caller addressed the agent by — in the inject path it is the AGENT id, not- // the session id, and the normalizer map is keyed by session. Resolve before looking anything up.- const session = registry.resolve(id)- if (session?.engine !== 'commandcode' || !session.sessionId) return- const normalizer = commandcodeNormalizers.get(session.sessionId)- if (!normalizer) return- emitSessionEvents(session.sessionId, normalizer.openTurn(content))- },- })- const deviceInput: AutonomousDeviceInput = new AutonomousDeviceInput({- getSession: id => registry.resolve(id),- validateRuntime: validateTerminal,- inject: submitTerminalAction,- sendKey: keyTerminalAction,- capture: captureTerminal,- isAwaitingUser: async session => {- const pane = await captureTerminal(session.agentId)- return pane === null || parseEngineQuestionPane(session.engine, pane) !== null+ // Everything the core writes into a pane, and the device's pane lock (core/input.ts).+ const inputs = createInput({+ resolve: (id) => registry.resolve(id),+ byAgent: (agentId) => registry.byAgent(agentId),+ terminal: terminalControl,+ teams: {+ prepare: (id, text, tabId, deliveryId) => backend.swarmPromptScopes.prepare(id, text, tabId, deliveryId),+ delivery: (event) => {+ backend.orchestratorDelivery(event)+ backend.teamDelivery(event)+ },+ canWrite: (deliveryId) => backend.teamCanWrite(deliveryId),},- acquireControl: id => input.acquireControl(id, { forAnswer: true }),- legacySubmit: (id, text, deliveryId) => input.submit(id, text, deliveryId),- legacyCancel: id => input.cancelDelivery(id),- onDelivery: event => autonomousDeviceService?.delivery(event),- onDispatch: (id, deliveryId, text) => autonomousDeviceService?.inputDispatched(id, deliveryId, text, registry.byAgent(id)?.sessionId),- onInputStatus: event => autonomousDeviceService?.inputStatus(event),- onForget: id => autonomousDeviceService?.agentGone(id),+ device: () => autonomousDeviceService,+ clients: backend,+ // Declared further down: read when an error is reported, never now.+ agentIdFor: (sessionId) => agentIdFor(sessionId),+ commandcode: (sessionId) => commandcodeNormalizers.get(sessionId),+ // Reassigned further down (the funnel): always the current one.+ emit: (sessionId, events) => emitSessionEvents(sessionId, events),})+ const input = inputs.input+ const deviceInput = inputs.deviceInput/*** agy only: close a turn whose final `Stop` never came.@@ -2718,194 +2653,57 @@ async function runForeground(session: AuthSession | null): Promise<void> {agyIdleWatch.set(sessionId, { timer, checks: checks + 1 })}- const acquireTerminalControl = (id: string, opts?: { forAnswer?: boolean }): (() => void) | null => {- const agentId = registry.resolve(id)?.agentId ?? id- const releaseInput = input.acquireControl(agentId, opts)- if (!releaseInput) return null- const releaseTerminal = pinTerminalControl(agentId)- if (!releaseTerminal) {- releaseInput()- return null- }- return () => {- releaseTerminal()- releaseInput()- }- }- // AskUserQuestion bridge: mirrors the question to the device's question screen, and keys the device's- // answer back into the CLI's own terminal dialog.- const questions = new AskQuestionController({- getSession: (id) => registry.resolve(id),- capture: captureTerminal,- sendText: submitTerminal,- sendKey: keyTerminal,- acquireControl: acquireTerminalControl,+ const acquireTerminalControl = inputs.acquireTerminalControl+ // Questions an agent asks the person: shown on the dial and the window, answered from anywhere+ // (core/questions.ts).+ const asking = createQuestions({+ resolve: (id) => registry.resolve(id),+ terminal: terminalControl,+ acquireTerminalControl,+ clients: backend,+ // Declared further down: read when a question is shown, never now.+ agentIdFor: (sessionId) => agentIdFor(sessionId),+ sessionTurnOpen,+ someoneCanAnswer,+ deviceInput,})- // Command Code ENDS its turn in order to ask (its Stop hook fires, the dialog goes up, and the answer- // opens a NEW turn). With the turn closed the device tile falls back to the PREVIOUS task's recap — so- // mid-question the screen showed a finished summary while the user was still being asked. Keep the tile- // visibly working for as long as the exchange lasts. The device's own busy-timeout watchdog bounds this,- // so an abandoned question cannot pin the tile forever.- const showAwaitingAnswer = (sessionId: string): void => {- backend.sendCommander({- type: 'commander_event',- agentId: agentIdFor(sessionId),- dbSessionId: sessionId,- payload: { kind: 'processing', text: 'Waiting for your answer' },- })- }- backend.onQuestionAnswer = (payload) => {- // Hold the working state across the gap too: the CLI needs a moment to move to the next question, and- // that gap is exactly where the stale recap used to flash back.- const target = payload.sessionId || payload.agentId- if (typeof target === 'string' && target) showAwaitingAnswer(target)- // Returned so the client that answered hears a refusal — STALE_QUESTION when the dialog changed- // before its answer arrived — as `question_response_result`.- return questions.answer(payload)- }- // What is still being asked, by session — handed to a window that connects later (openQuestions below).- const openQuestions = new Map<string, Record<string, unknown>>()- backend.monitorActivityProvider = sessionId => openQuestions.has(sessionId)- ? 'needsInput' : sessionTurnOpen(sessionId) ? 'working' : 'idle'- const agentNotifications = new AgentNotifications()- const questionWatcher = new QuestionWatcher({- getSession: (id) => registry.resolve(id),- capture: captureTerminal,- hasDevice: () => someoneCanAnswer(),- isDriving: (sessionId) => questions.isDriving(sessionId),- onQuestion: (sessionId, requestId, shaped, detail) => {- deviceInput.setUserAction(agentIdFor(sessionId), true)- questions.remember(requestId, sessionId)- showAwaitingAnswer(sessionId)- const asked = {- type: 'commander_question',- agentId: agentIdFor(sessionId),- dbSessionId: sessionId,- payload: { requestId, questions: shaped, notification: agentNotifications.asked(sessionId, requestId) },- }- backend.sendCommander(asked)- // ...and to the window on this computer. `sendCommander` is `webEligible: false`, so until this- // second call the app could not learn that an agent was blocked even though the question had- // already been shaped for the dial.- //- // `sendLocal`, not `send`: the question and its option labels are user content, and the only- // audience `send` would add beyond loopback is the cloud leg, where this frame would travel- // PLAINTEXT — `commander_question` is deliberately absent from ENCRYPTED_UP_TYPES, and putting it- // there means re-deriving an interop hash pinned by the browser client and the device firmware in- // two other repositories. Loopback needs no envelope, and it costs nothing that is reachable- // today: a remote machine's watcher is gated on ITS OWN audience, which a window attached over- // here is not part of either way.- backend.sendLocal(asked)- openQuestions.set(sessionId, asked)- console.log(`[question] ${sid(sessionId)} asking the user · "${preview(shaped[0]?.q ?? '')}" · req=${requestId}`)- },- // Answered somewhere else — the app, or the pane by hand. Every client drawing it is told to stop- // waiting, down the SAME path the question itself took, so the dial and the WiFi device cannot- // disagree about whether a question is still open.- onQuestionGone: (sessionId, requestId) => {- agentNotifications.answered(sessionId, requestId)- deviceInput.setUserAction(agentIdFor(sessionId), false)- const closed = {- type: 'commander_question_close',- agentId: agentIdFor(sessionId),- dbSessionId: sessionId,- payload: { requestId },- }- backend.sendCommander(closed)- // Down the SAME two paths the question took, so no client is left drawing a dialog that another- // one already answered. This is the mechanism behind "answer anywhere": the dial is cabled to- // this very computer, so the dial and this window are always the same machine's audience.- backend.sendLocal(closed)- openQuestions.delete(sessionId)- console.log(`[question] ${sid(sessionId)} answered elsewhere · closing on every client · req=${requestId}`)- },+ const questions = asking.questions+ backend.onQuestionAnswer = asking.answer+ const openQuestions = asking.openQuestions+ backend.monitorActivityProvider = asking.monitorActivity+ const agentNotifications = asking.agentNotifications+ const questionWatcher = asking.questionWatcher+++ // The turn's last text, for its recap, whatever the engine (core/transcripts/lastTurn.ts).+ const readLastTurn = createLastTurnReader({+ bySession: (sessionId) => registry.bySession(sessionId),+ dbs: { opencode: OPENCODE_DB, kilo: KILO_DB, devin: DEVIN_DB },+ hermesDb: (s) => hermesDbForSession(s),})--- // The recap is an excerpt of the answer, cut the moment the turn ends — no model in the loop. The- // window, the phone and the dial show it beside the whole answer, so a model's rewrite (which cost- // about 9 s of every turn) said again what the screen already showed.- const summarizer: Pick<CommanderMirrorOpts, 'summarize' | 'summarizeIsLocal'> = {- summarize: async (text) => deriveTurnSummary(text),- summarizeIsLocal: true,- }- /**- * A turn that belongs to a SUB-AGENT: an Orchestrator specialist, or its Director while specialists- * are still out.- *- * Hoisted out of the commander's options because the dial is no longer the only screen that has to- * know. The cable learns it as `silent` on the summary card; the window and the phone learn it as- * `subagent` on `turn_ended` (see emitSessionEvents) — the phone notifies on neither. One rule, asked twice — the two surfaces used to disagree- * here, and a four-specialist project put ONE row on the dial and FIVE marks in the window.- *- * ⚠️ The commander ORs this with its own `abandoned` state — a held turn released because a- * sub-agent went silent — which lives inside it and is not reachable from here. That case is rare- * (a killed or crashed sub-agent) and costs the window one extra mark, not five.- */- const isSubagentSession = (sessionId: string): boolean => {- const agentId = registry.bySession(sessionId)?.agentId- if (!agentId) return false- const role = backend.orchestratorRoleOf(agentId)- return role?.role === 'worker' || (role?.role === 'director' && role.busy)- }- const mirror = new CommanderMirror({+ // Recaps: turn cards on the dial and the window, notifications on the phone (core/turns/recaps.ts).+ const recaps = createRecaps({notifications: agentNotifications,- notifyWithoutDevice: true,- verifiedWorking: sessionId => turnActivity.snapshot(sessionId)?.state === 'working',- send: (frame) => backend.sendCommander(frame),- sendWeb: (frame) => backend.send(frame), // turn_summary_pending / turn_summary → web indicator- hasDevice: () => deviceIsWatching(), // device-gate the LLM recap (mirror node)- // Live cards stream to whatever is actually rendering. The dial has one screen and it is always the- // one in front of the user, so a cable session counts as active by construction.- active: () => backend.hasActiveCommander() || cableWatchingLocal(),- ...summarizer,- nameFor: (sessionId) => { const s = registry.bySession(sessionId); return s ? projectDisplayName(s) : undefined },- agentIdFor: (sessionId) => registry.bySession(sessionId)?.agentId,- // An Orchestrator specialist's turn end, or the Director's while specialists are still out, is not- // announced: the person asked to hear from the main agent once, not from every sub-agent.- isSubagent: (sessionId: string) => isSubagentSession(sessionId),- // A claude sub-agent still at work is one whose transcript is still growing:- // `<session>/subagents/agent-<id>.jsonl` beside the parent's (the same file enrichSubagentStats- // reads). Written in the last SUBAGENT_IDLE_MS = alive; the held turn end waits for it.- subagentActive: (sessionId, agentId) => {- const transcriptPath = registry.bySession(sessionId)?.transcriptPath- if (!transcriptPath) return false- try {- const at = statSync(join(transcriptPath.replace(/\.jsonl$/, ''), 'subagents', `agent-${agentId}.jsonl`)).mtimeMs- return Date.now() - at < SUBAGENT_IDLE_MS- } catch { return false }- },- readLastTurn: async (sessionId) => {- const s = registry.bySession(sessionId)- if (!s) return null- if (s.engine === 'opencode') return lastOpencodeTurnText(await readOpencodeMessages(OPENCODE_DB, sessionId))- if (s.engine === 'kilo') return lastKiloTurnText(await readKiloMessages(KILO_DB, sessionId))- if (s.engine === 'hermes') return lastHermesTurnText(await readHermesMessages(await hermesDbForSession(s), sessionId))- if (s.engine === 'devin') return lastDevinTurnText(await readDevinMessages(DEVIN_DB, sessionId))- if (!s.transcriptPath) return null- if (s.engine === 'codex') return readLastCodexTurnText(s.transcriptPath)- // Its last turn, read backward — not the whole conversation once per turn end.- if (s.engine === 'claude') return lastTurnTextFromRawLines(await tailFileUntil(s.transcriptPath, selectClaudeRecapLine))- const lines = await tailFile(s.transcriptPath, Infinity)- if (s.engine === 'cursor') return lastCursorTurnText(lines)- if (s.engine === 'muse') return lastMuseTurnText(lines)- if (s.engine === 'amp') return lastAmpTurnText(lines)- if (s.engine === 'grok') return lastGrokTurnText(lines)- if (s.engine === 'agy') return lastAgyTurnText(lines)- if (s.engine === 'copilot') return lastCopilotTurnText(lines)- if (s.engine === 'pi') return lastPiTurnText(lines)- if (s.engine === 'commandcode') return lastCommandCodeTurnText(lines)- return lastTurnTextFromRawLines(lines)- },+ turnActivity,+ clients: backend,+ deviceIsWatching,+ cableWatchingLocal,+ bySession: (sessionId) => registry.bySession(sessionId),+ resolve: (id) => registry.resolve(id),+ stopped: (agentId) => stoppedAgents.get(agentId),+ orchestratorRoleOf: (agentId) => backend.orchestratorRoleOf(agentId),+ readLastTurn,dataDir: env.ADAPTER_DATA_DIR,recapForce: env.RECAP_FORCE,- alwaysGenerate: () => env.RECAP_WITHOUT_DEVICE,+ recapWithoutDevice: () => env.RECAP_WITHOUT_DEVICE,})+ const isSubagentSession = recaps.isSubagentSession+ const mirror = recaps.mirror// Recaps are STORED under the engine session id — that is what lets `--resume` bring the last recap// back under a brand-new agent — but they are ASKED FOR by agent id, which is the only id the device// and the voice router know. Resolve across the two, or every tile restores empty.- backend.recentProvider = (id, n) => mirror.recent(registry.resolve(id)?.sessionId || stoppedAgents.get(id)?.sessionId || id, n)- backend.recentAsksProvider = (id, n) => mirror.recentAsks(registry.resolve(id)?.sessionId || stoppedAgents.get(id)?.sessionId || id, n)+ backend.recentProvider = recaps.recent+ backend.recentAsksProvider = recaps.recentAsks// The engines that keep a conversation in a database instead of a transcript file, read through// the same readers and replay normalizers as `session_get`.@@ -3041,111 +2839,39 @@ async function runForeground(session: AuthSession | null): Promise<void> {if (session) syncSession(session)}- // A timer is an opportunity to inspect work, not proof that work is happening.- // Keep polling unfinished transcripts even when their activity lease expires:- // a missed file notification or a later completion must still be discovered.- const TURN_HEARTBEAT_MS = 5000- const heartbeats = new Map<string, NodeJS.Timeout>()- const turnStartedAt = new Map<string, number>()- const stopHeartbeat = (sessionId: string): void => {- runtimeActivity.forget(sessionId)- const timer = heartbeats.get(sessionId)- if (timer) { clearInterval(timer); heartbeats.delete(sessionId) }- }- const startHeartbeat = (sessionId: string): void => {- stopHeartbeat(sessionId)- const beat = async () => {- if (!registry.bySession(sessionId)?.active) {- stopHeartbeat(sessionId); turnActivity.forget(sessionId); return- }- if (sessionTurnOpen(sessionId)) await turnActivity.check(sessionId)- if (!heartbeats.has(sessionId)) return- const activity = turnActivity.snapshot(sessionId)- if (activity) {- backend.send(correlateAgentEvent({ type: 'agent_activity', payload: { activity } }, sessionId, agentIdFor(sessionId)))- if (activity.state === 'working') backend.send(turnHeartbeatFrame(sessionId, agentIdFor(sessionId), activity))- }- const deviceBusy = mirror.heartbeat(sessionId)- if (!sessionTurnOpen(sessionId) && !deviceBusy) stopHeartbeat(sessionId)- }- const timer = setInterval(() => { void beat().catch(error => console.error('[activity] probe failed:', String(error))) }, TURN_HEARTBEAT_MS)- heartbeats.set(sessionId, timer)- }-- emitSessionEvents = (sessionId: string, events: ReturnType<CursorNormalizer['ingest']>, opts?: { resumed?: boolean; replay?: boolean }): void => {- if (!events.length || !registry.bySession(sessionId)?.active) return- const usageSession = registry.bySession(sessionId)- if (usageSession?.engine === 'opencode') agentTokenUsage.changed(usageSession)- for (const [eventIndex, event] of events.entries()) {- const agentId = agentIdFor(sessionId)- const replay = !!(opts?.resumed || opts?.replay)- turnActivity.observe(sessionId, event.type, replay)- const frame = correlateAgentEvent({ ...event, payload: { ...event.payload, activity: turnActivity.snapshot(sessionId) } }, sessionId, agentId)- // A `turn_started` that is not a turn starting NOW — a turn picked back up at attach, or a prompt- // re-read from a transcript that was already on disk — says so in the clear, beside `agentId`- // (the payload is E2EE; the backend can only read the envelope). The backend's daily turn count- // skips these; every other consumer ignores an unknown field. Measured before this existed: one- // agent credited with 42 turns in a single second, all re-reads.- if (replay) { frame.replay = true; frame.payload.replay = true }- // The end of a turn carries the two facts an app needs to decide whether it is NEWS, in the clear- // beside `agentId` for the same reason `replay` is — the payload is E2EE and the apps read this- // without opening it:- // `replay` — a turn re-read from disk, not one finishing now;- // `subagent` — a specialist's turn nobody asked to hear about, the dial's `silent`. The dial has- // always been told and the window never was, so an Orchestrator project of four- // specialists put ONE row on the dial and FIVE marks in the window. Same predicate- // for every screen now — see isSubagentSession.- // The phone notifies on neither. Absent = false, so a client that predates these reads every end as- // it always did.- if (event.type === 'turn_ended') {- if (opts?.resumed || opts?.replay) frame.replay = true- if (isSubagentSession(sessionId)) frame.subagent = true- }- backend.send(frame)- if (event.type === 'turn_started' || event.type === 'turn_ended') sessionSearch?.touch(sessionId)- if (event.type === 'turn_started') {- turnStartedAt.set(sessionId, Date.now())- console.log(`[turn] ${sid(sessionId)} started · engine=${registry.bySession(sessionId)?.engine ?? 'claude'} · bytes=${Buffer.byteLength(event.payload.userMessage, 'utf8')}`)- input.onTurnStarted(agentIdFor(sessionId), event.payload.userMessage)- if (!opts?.resumed && !opts?.replay) backend.swarmPromptScopes.started(agentId, event.payload.userMessage, 'transcript', registry.bySession(sessionId)?.engine)- deviceInput.onTurnStarted(agentId, event.payload.userMessage)- autonomousDeviceService?.turnStarted(agentId)- startHeartbeat(sessionId)- questionWatcher.start(sessionId) // Claude opens its dialog INSIDE a turn- // ...and anything already drawn belongs to the turn BEFORE this one — unless this is a turn the- // daemon is picking back up at attach: a dialog on the pane then is THIS turn's, still waiting,- // and marking it pre-turn is how a restarted daemon never announced a question Codex had open.- if (!opts?.resumed) questionWatcher.noteTurnStart(sessionId)- } else if (event.type === 'turn_ended') {- const startedAt = turnStartedAt.get(sessionId)- turnStartedAt.delete(sessionId)- // Say when a turn was KILLED. The log previously showed an interrupt as a fresh `[turn] started- // "[Request interrupted by user]"`, which read like a new prompt and hid the bug for weeks.- console.log(- `[turn] ${sid(sessionId)} ended${event.payload.aborted ? ' · aborted (interrupted)' : ''}` +- `${startedAt ? ` · ${Date.now() - startedAt}ms` : ''}`,- )- // Filter only the Device receipt view; shared normalizers, mirror, and local input stay unchanged.- if (!isDeviceInputBoundary(usageSession?.engine ?? '', events, eventIndex)) {- autonomousDeviceService?.turnEnded(agentId, event.payload.aborted === true)- deviceInput.onTurnEnded(agentId)- }- input.onTurnEnded(agentIdFor(sessionId))- // Command Code asks AFTER the turn: `ask_user_question` ends the turn (its Stop hook fires), the- // dialog goes up, and the answer opens a NEW turn. Stopping the watcher here is what left the- // terminal sitting on a question the device never showed. Its watcher runs off the session, not- // the turn — see the attach path — so leave it alone.- if (registry.bySession(sessionId)?.engine !== 'commandcode') questionWatcher.stop(sessionId)- // Do NOT stop the heartbeat here: the turn is closed but the device summarize is just starting- // (mirror sets summarizing=true in the mirror.ingest below). The timer keeps fanning "Summarizing…"- // to the device and self-cancels once mirror.heartbeat() reports idle (summary done).- }- }- mirror.ingest(events, sessionId, { replay: !!(opts?.resumed || opts?.replay) })- // Subscribed devices only (lib/autonomous-device/stream.ts). A transcript re-read is history, not live.- if (!opts?.replay) autonomousDeviceService?.stream(agentIdFor(sessionId), events)- }- for (const queued of queuedSessionEvents.splice(0)) emitSessionEvents(queued.sessionId, queued.events, queued.opts)+ // Turn heartbeats (core/turns/heartbeats.ts).+ const turnBeats = createHeartbeats({+ bySession: (sessionId) => registry.bySession(sessionId),+ sessionTurnOpen,+ agentIdFor,+ runtimeActivity,+ turnActivity,+ mirror,+ clients: backend,+ })+ const heartbeats = turnBeats.heartbeats+ const turnStartedAt = turnBeats.turnStartedAt+ const stopHeartbeat = turnBeats.stopHeartbeat+ const startHeartbeat = turnBeats.startHeartbeat++ // Everything the funnel feeds exists now: install it, and deliver what waited.+ funnel.arm({+ bySession: (sessionId) => registry.bySession(sessionId),+ tokenUsage: agentTokenUsage,+ agentIdFor,+ turnActivity,+ isSubagentSession,+ clients: backend,+ search: sessionSearch,+ turnStartedAt,+ input,+ teams: backend.swarmPromptScopes,+ deviceInput,+ device: () => autonomousDeviceService,+ startHeartbeat,+ questionWatcher,+ mirror,+ })const cursorSubagents = new CursorSubagentManager(cursorConfigDir(), emitSessionEvents, cursorDataDir())const cursorTaskHooks = new CursorTaskHookQueue({drainTranscript: (sessionId) => watcher.pollSession(sessionId),@@ -6218,21 +5944,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {}})- const submitAgent = (id: string, content: string, deliveryId?: string, tabId?: string): void => {- const record = registry.resolve(id)- const sessionId = record?.sessionId ?? id- const engine = record?.engine ?? 'claude'- // The backend prepends `/goal ` or `/loop ` without knowing the engine (on the routed path it has- // not picked an agent yet when the mode is chosen). This is the one place that always knows, so the- // per-engine adaptation happens here — an unknown slash command would otherwise land as a visible- // error in the user's terminal instead of running their turn.- const adapted = adaptSlashCommand(content, engine)- if (adapted !== content) {- console.log(`[msg] ${sid(sessionId)} slash-command adapted for engine=${engine}`)- }- console.log(`[msg] ${sid(sessionId)} recv · engine=${engine} · bytes=${Buffer.byteLength(adapted, 'utf8')}`)- input.submit(record?.agentId ?? sessionId, adapted, deliveryId, tabId)- }+ const submitAgent = inputs.submitAgentbackend.onMessage = (id, content, deliveryId, tabId) => submitAgent(id, content, deliveryId, tabId)backend.onCancelOrchestratorMessage = id => input.cancelDelivery(id)backend.readChannelDesk = async () => {diff --git a/cli/src/core/input.spec.ts b/cli/src/core/input.spec.tsnew file mode 100644index 000000000..152b88815--- /dev/null+++ b/cli/src/core/input.spec.ts@@ -0,0 +1,239 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { CommandCodeNormalizer } from '../engines/commandcode/normalizer.js'+import type { AutonomousDeviceInput } from '../lib/autonomous-device/input.js'+import { deviceErrorText } from '../lib/deviceErrors.js'+import type { RegisteredSession } from '../lib/registry.js'+import type { SessionInputDelivery } from '../lib/sessionInput.js'+import type { TerminalActionResult } from '../lib/terminalTypes.js'+import { createInput, deviceInputDeps, sessionInputDeps, type InputDeps } from './input.js'++const ok: TerminalActionResult = { state: 'succeeded', dispatch: 'executed' }+/** A Claude Code composer that is empty and idle: ready for a team write. */+const READY_PANE = '────────────\n❯\n────────────\n ? for shortcuts'++const agents = new Map<string, RegisteredSession>([+ ['a1', { agentId: 'a1', sessionId: 's1', engine: 'claude' } as RegisteredSession],+ ['s1', { agentId: 'a1', sessionId: 's1', engine: 'claude' } as RegisteredSession],+ ['cc', { agentId: 'cc', sessionId: 'cc-s', engine: 'commandcode' } as RegisteredSession],+ ['cc-new', { agentId: 'cc-new', sessionId: '', engine: 'commandcode' } as RegisteredSession],+ ['cc-none', { agentId: 'cc-none', sessionId: 'cc-none-s', engine: 'commandcode' } as RegisteredSession],+])++function deps(over: Partial<InputDeps> = {}) {+ const calls: string[] = []+ const device = {+ delivery: vi.fn((event: SessionInputDelivery) => { calls.push(`device delivery ${event.deliveryId}`) }),+ inputDispatched: vi.fn(),+ inputStatus: vi.fn(),+ agentGone: vi.fn(),+ }+ const normalizer = { openTurn: vi.fn((text: string) => [{ type: 'turn_started', text }]) }+ let pane: string | null = READY_PANE+ const base: InputDeps = {+ resolve: (id) => agents.get(id),+ byAgent: (agentId) => agents.get(agentId),+ terminal: {+ captureTerminal: vi.fn(async () => pane),+ validateTerminal: vi.fn(async () => true),+ submitTerminalAction: vi.fn(async (id: string, text: string) => { calls.push(`submit ${id} ${text}`); return ok }),+ keyTerminalAction: vi.fn(async (id: string, key: string) => { calls.push(`key ${id} ${key}`); return ok }),+ pinTerminalControl: vi.fn(() => () => { calls.push('unpin') }),+ },+ teams: {+ prepare: vi.fn(() => () => {}),+ delivery: vi.fn((event: SessionInputDelivery) => { calls.push(`teams delivery ${event.deliveryId}`) }),+ canWrite: vi.fn(() => true),+ },+ device: () => device,+ clients: { send: vi.fn(), sendCommander: vi.fn() },+ agentIdFor: (sessionId) => agents.get(sessionId)?.agentId ?? sessionId,+ commandcode: (sessionId) => sessionId === 'cc-s' ? normalizer as unknown as CommandCodeNormalizer : undefined,+ emit: vi.fn(),+ ...over,+ }+ return { deps: base, calls, device, normalizer, setPane: (next: string | null) => { pane = next } }+}++/** A device pane lock that runs each write at once and remembers whose pane it was. */+const lock = (calls: string[]): Pick<AutonomousDeviceInput, 'legacyWrite'> => ({+ legacyWrite: <T,>(id: string, write: () => Promise<T>): Promise<T> => {+ calls.push(`lock ${id}`)+ return write()+ },+})++const delivery = (deliveryId: string) => ({ deliveryId }) as unknown as SessionInputDelivery++describe('the session input controller\'s dependencies', () => {+ afterEach(() => vi.restoreAllMocks())++ it('scopes a prompt, finds a session and checks its pane through what it was given', async () => {+ const { deps: given } = deps()+ const wired = sessionInputDeps(given, () => lock([]))+ wired.beforeSubmit!('a1', 'hello', 'tab', 'd1')+ expect(given.teams.prepare).toHaveBeenCalledWith('a1', 'hello', 'tab', 'd1')+ expect(wired.getSession('s1')?.agentId).toBe('a1')+ expect(wired.validateRuntime).toBe(given.terminal.validateTerminal)+ expect(wired.capture).toBe(given.terminal.captureTerminal)+ expect(await wired.beforeTeamWrite!(agents.get('a1')!)).toBeNull()+ })++ it('tells the device of a delivery first, then the teams; the teams alone without a device', () => {+ const one = deps()+ sessionInputDeps(one.deps, () => lock([])).onDelivery!(delivery('d1'))+ expect(one.calls).toEqual(['device delivery d1', 'teams delivery d1'])+ const two = deps({ device: () => undefined })+ sessionInputDeps(two.deps, () => lock([])).onDelivery!(delivery('d2'))+ expect(two.calls).toEqual(['teams delivery d2'])+ })++ it('writes and keys through the device\'s pane lock', async () => {+ const { deps: given, calls } = deps()+ const wired = sessionInputDeps(given, () => lock(calls))+ expect(await wired.inject('a1', 'hello')).toBe(ok)+ expect(await wired.sendKey('a1', 'enter')).toBe(ok)+ expect(calls).toEqual(['lock a1', 'submit a1 hello', 'lock a1', 'key a1 enter'])+ })++ it('writes a team turn only into a ready pane whose delivery still holds control', async () => {+ const run = deps()+ const wired = sessionInputDeps(run.deps, () => lock(run.calls))+ expect(await wired.injectTeam!('nobody', 'hi', 'd1')).toEqual({ state: 'failed', dispatch: 'not_started', reason: 'team_waiting_unavailable' })+ run.setPane(null)+ expect(await wired.injectTeam!('a1', 'hi', 'd1')).toEqual({ state: 'failed', dispatch: 'not_started', reason: 'team_waiting_unavailable' })+ run.setPane(READY_PANE)+ vi.mocked(run.deps.teams.canWrite).mockReturnValueOnce(false)+ expect(await wired.injectTeam!('a1', 'hi', 'd1')).toEqual({ state: 'failed', dispatch: 'not_started', reason: 'team_waiting_control' })+ expect(await wired.injectTeam!('a1', 'hi', 'd1')).toBe(ok)+ expect(run.calls.filter((call) => call.startsWith('submit'))).toEqual(['submit a1 hi'])+ })++ it('reports an error to the app and, in the device\'s words, to the dial', () => {+ const { deps: given } = deps()+ sessionInputDeps(given, () => lock([])).onError('s1', 'the pane is gone')+ expect(given.clients.send).toHaveBeenCalledWith({ type: 'error', agentId: 'a1', dbSessionId: 's1', payload: { message: 'the pane is gone' } })+ expect(given.clients.sendCommander).toHaveBeenCalledWith({+ type: 'commander_event', agentId: 'a1', dbSessionId: 's1',+ payload: { kind: 'error', text: deviceErrorText('the pane is gone', 'claude') },+ })+ })++ it('opens a Command Code turn on our own paste, and nobody else\'s', () => {+ const { deps: given, normalizer } = deps()+ const wired = sessionInputDeps(given, () => lock([]))+ for (const id of ['a1', 'nobody', 'cc-new', 'cc-none']) wired.onSubmitted!(id, 'hi')+ expect(given.emit).not.toHaveBeenCalled()+ wired.onSubmitted!('cc', 'hi')+ expect(normalizer.openTurn).toHaveBeenCalledWith('hi')+ expect(given.emit).toHaveBeenCalledWith('cc-s', [{ type: 'turn_started', text: 'hi' }])+ })+})++describe('the device input\'s dependencies', () => {+ it('reaches the terminal directly', async () => {+ const { deps: given } = deps()+ const wired = deviceInputDeps(given, () => ({ acquireControl: vi.fn(), submit: vi.fn(), cancelDelivery: vi.fn() }))+ expect(wired.getSession('a1')?.sessionId).toBe('s1')+ expect(wired.validateRuntime).toBe(given.terminal.validateTerminal)+ expect(wired.inject).toBe(given.terminal.submitTerminalAction)+ expect(wired.sendKey).toBe(given.terminal.keyTerminalAction)+ expect(wired.capture).toBe(given.terminal.captureTerminal)+ })++ it('waits for the person when the pane cannot be read or asks a question', async () => {+ const run = deps()+ const wired = deviceInputDeps(run.deps, () => ({ acquireControl: vi.fn(), submit: vi.fn(), cancelDelivery: vi.fn() }))+ run.setPane(null)+ expect(await wired.isAwaitingUser!(agents.get('a1')!)).toBe(true)+ run.setPane(READY_PANE)+ expect(await wired.isAwaitingUser!(agents.get('a1')!)).toBe(false)+ })++ it('hands queued input to the controller, answering control included', () => {+ const { deps: given } = deps()+ const controller = { acquireControl: vi.fn(() => null), submit: vi.fn(), cancelDelivery: vi.fn(() => true) }+ const wired = deviceInputDeps(given, () => controller)+ wired.acquireControl('a1')+ wired.legacySubmit('a1', 'hi', 'd1')+ expect(wired.legacyCancel('d1')).toBe(true)+ expect(controller.acquireControl).toHaveBeenCalledWith('a1', { forAnswer: true })+ expect(controller.submit).toHaveBeenCalledWith('a1', 'hi', 'd1')+ expect(controller.cancelDelivery).toHaveBeenCalledWith('d1')+ })++ it('tells the device service what happened, when there is one', () => {+ const run = deps()+ const wired = deviceInputDeps(run.deps, () => ({ acquireControl: vi.fn(), submit: vi.fn(), cancelDelivery: vi.fn() }))+ const status = { agentId: 'a1' } as unknown as Parameters<NonNullable<typeof wired.onInputStatus>>[0]+ wired.onDelivery(delivery('d1'))+ wired.onDispatch!('a1', 'd1', 'hi')+ wired.onDispatch!('nobody', 'd2', 'hi')+ wired.onInputStatus(status)+ wired.onForget!('a1')+ expect(run.device.delivery).toHaveBeenCalledTimes(1)+ expect(run.device.inputDispatched.mock.calls).toEqual([['a1', 'd1', 'hi', 's1'], ['nobody', 'd2', 'hi', undefined]])+ expect(run.device.inputStatus).toHaveBeenCalledWith(status)+ expect(run.device.agentGone).toHaveBeenCalledWith('a1')+ const none = deviceInputDeps(deps({ device: () => undefined }).deps, () => ({ acquireControl: vi.fn(), submit: vi.fn(), cancelDelivery: vi.fn() }))+ expect(() => {+ none.onDelivery(delivery('d3'))+ none.onDispatch!('a1', 'd3', 'hi')+ none.onInputStatus(status)+ none.onForget!('a1')+ }).not.toThrow()+ })+})++describe('createInput', () => {+ afterEach(() => vi.restoreAllMocks())++ it('wires the two controllers to each other: a queued write takes the device lock, a device answer takes queue control', async () => {+ const run = deps()+ const inputs = createInput(run.deps)+ const lockWrite = vi.spyOn(inputs.deviceInput, 'legacyWrite')+ const acquire = vi.spyOn(inputs.input, 'acquireControl')+ // What each controller was given (its constructor's dependencies) reaches the other one.+ const given = (controller: object) => (controller as unknown as { deps: Record<string, (...args: unknown[]) => unknown> }).deps+ expect(await given(inputs.input).inject('a1', 'hello')).toBe(ok)+ expect(lockWrite).toHaveBeenCalledWith('a1', expect.any(Function))+ const release = given(inputs.deviceInput).acquireControl('a1') as (() => void) | null+ expect(acquire).toHaveBeenCalledWith('a1', { forAnswer: true })+ expect(release).toBeTypeOf('function')+ release!()+ })++ it('takes control of a pane only when both the queue and the terminal grant it, and gives both back', () => {+ const run = deps()+ const inputs = createInput(run.deps)+ const released: string[] = []+ const acquire = vi.spyOn(inputs.input, 'acquireControl')+ acquire.mockReturnValueOnce(null)+ expect(inputs.acquireTerminalControl('s1')).toBeNull()+ expect(acquire).toHaveBeenLastCalledWith('a1', undefined)+ acquire.mockReturnValueOnce(() => { released.push('input') })+ vi.mocked(run.deps.terminal.pinTerminalControl).mockReturnValueOnce(null)+ expect(inputs.acquireTerminalControl('a1', { forAnswer: true })).toBeNull()+ expect(released).toEqual(['input'])+ acquire.mockReturnValueOnce(() => { released.push('input') })+ vi.mocked(run.deps.terminal.pinTerminalControl).mockReturnValueOnce(() => { released.push('terminal') })+ const release = inputs.acquireTerminalControl('unknown-agent')!+ expect(acquire).toHaveBeenLastCalledWith('unknown-agent', undefined)+ release()+ expect(released).toEqual(['input', 'terminal', 'input'])+ })++ it('submits a message under the agent\'s id, adapting a slash command its engine lacks', () => {+ const inputs = createInput(deps().deps)+ const submit = vi.spyOn(inputs.input, 'submit').mockImplementation(() => {})+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ inputs.submitAgent('s1', 'hello', 'd1', 'tab')+ inputs.submitAgent('cc', '/loop fix it')+ inputs.submitAgent('nobody', 'hi')+ expect(submit.mock.calls).toEqual([+ ['a1', 'hello', 'd1', 'tab'],+ ['cc', 'fix it', undefined, undefined],+ ['nobody', 'hi', undefined, undefined],+ ])+ expect(log.mock.calls.flat().filter((line) => String(line).includes('slash-command adapted'))).toHaveLength(1)+ })+})diff --git a/cli/src/core/input.ts b/cli/src/core/input.tsnew file mode 100644index 000000000..98d8be49a--- /dev/null+++ b/cli/src/core/input.ts@@ -0,0 +1,162 @@+/**+ * Input: everything the core writes into an agent's pane. Messages, team turns and keys go through one+ * controller (`SessionInputController`, a per-pane queue while a turn is busy); the Harness device's own+ * route (`AutonomousDeviceInput`) owns the pane writer lock, and every write from the controller takes it+ * first (`legacyWrite`), so a person answering on a device and the core never interleave in one pane.+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 5: docs/design/2026-10-03-harnessd.md);+ * what it reaches in the registry, the terminal, the teams and device features and the clients is passed+ * in. The two controllers' dependencies are built by `sessionInputDeps` and `deviceInputDeps`, each given+ * the other controller lazily: each one calls into the other.+ */+import { AutonomousDeviceInput, type DeviceInputDeps } from '../lib/autonomous-device/input.js'+import type { AutonomousDeviceService } from '../lib/autonomous-device/service.js'+import type { CommandCodeNormalizer } from '../engines/commandcode/normalizer.js'+import { parseEngineQuestionPane } from '../lib/askQuestion.js'+import { deviceErrorText } from '../lib/deviceErrors.js'+import { adaptSlashCommand } from '../lib/goalCommand.js'+import { sid } from '../lib/log.js'+import type { LiveEvent } from '../lib/normalize.js'+import type { RegisteredSession } from '../lib/registry.js'+import { SessionInputController, type SessionInputDelivery, type SessionInputDeps } from '../lib/sessionInput.js'+import { terminalActionNotStarted } from '../lib/terminalTypes.js'+import { teamWriteHold } from '../teams/preflight.js'+import type { TerminalControl } from './terminals/control.js'++type Frame = { type: string; agentId?: string; dbSessionId?: string; payload: Record<string, unknown> }++export interface InputDeps {+ resolve: (id: string) => RegisteredSession | undefined+ byAgent: (agentId: string) => RegisteredSession | undefined+ terminal: Pick<TerminalControl, 'captureTerminal' | 'validateTerminal' | 'submitTerminalAction' | 'keyTerminalAction' | 'pinTerminalControl'>+ /** The teams and orchestrator features. */+ teams: {+ /** Before a paste: record where the prompt came from (BackendSocket.swarmPromptScopes.prepare). */+ prepare: (agentId: string, content: string, tabId?: string, deliveryId?: string) => () => void+ /** A delivery settled: the orchestrator hears of it, then the team. */+ delivery: (event: SessionInputDelivery) => void+ /** Whether a team delivery still holds control of its pane. */+ canWrite: (deliveryId: string) => boolean+ }+ /** The Harness device service, once it exists. */+ device: () => Pick<AutonomousDeviceService, 'delivery' | 'inputDispatched' | 'inputStatus' | 'agentGone'> | undefined+ /** The app (`send`) and the dial (`sendCommander`). */+ clients: { send(frame: Frame): void; sendCommander(frame: Frame): void }+ agentIdFor: (sessionId: string) => string+ /** Command Code's normalizer for a session, which opens its turn on our paste. */+ commandcode: (sessionId: string) => CommandCodeNormalizer | undefined+ emit: (sessionId: string, events: LiveEvent[]) => void+}++/** What `SessionInputController` is given: every write takes the device's pane lock first. */+export function sessionInputDeps(+ { resolve, terminal, teams, device, clients, agentIdFor, commandcode, emit }: InputDeps,+ deviceInput: () => Pick<AutonomousDeviceInput, 'legacyWrite'>,+): SessionInputDeps {+ const { captureTerminal, validateTerminal, submitTerminalAction, keyTerminalAction } = terminal+ return {+ beforeSubmit: (id, text, tabId, deliveryId) => teams.prepare(id, text, tabId, deliveryId),+ getSession: (id) => resolve(id),+ onDelivery: (event) => {+ device()?.delivery(event)+ teams.delivery(event)+ },+ beforeTeamWrite: async session => {+ const capture = await captureTerminal(session.agentId)+ return teamWriteHold(session.engine, capture)+ },+ validateRuntime: validateTerminal,+ inject: (id, text) => deviceInput().legacyWrite(id, () => submitTerminalAction(id, text)),+ injectTeam: (id, text, deliveryId) => deviceInput().legacyWrite(id, async () => {+ const session = resolve(id)+ const reason = session ? teamWriteHold(session.engine, await captureTerminal(id)) : 'team_waiting_unavailable'+ if (reason) return { state: 'failed', dispatch: 'not_started', reason }+ if (!teams.canWrite(deliveryId)) return terminalActionNotStarted('team_waiting_control')+ return submitTerminalAction(id, text)+ }),+ sendKey: (id, key) => deviceInput().legacyWrite(id, () => keyTerminalAction(id, key)),+ capture: captureTerminal,+ onError: (sessionId, message) => {+ clients.send({ type: 'error', agentId: agentIdFor(sessionId), dbSessionId: sessionId, payload: { message } })+ const engine = resolve(sessionId)?.engine+ clients.sendCommander({ type: 'commander_event', agentId: agentIdFor(sessionId), dbSessionId: sessionId, payload: { kind: 'error', text: deviceErrorText(message, engine) } })+ },+ // Command Code writes its transcript only once the turn is OVER, so a turn that calls no tool has+ // nothing to announce it: measured on 1.28.4, "hi" produced turn_started and turn_ended 1ms apart+ // and neither web nor device ever showed the agent working. Our own paste is the one moment a turn+ // is known to have started — and the only one that also knows the text.+ onSubmitted: (id, content) => {+ // `id` is whatever the caller addressed the agent by — in the inject path it is the AGENT id, not+ // the session id, and the normalizer map is keyed by session. Resolve before looking anything up.+ const session = resolve(id)+ if (session?.engine !== 'commandcode' || !session.sessionId) return+ const normalizer = commandcode(session.sessionId)+ if (!normalizer) return+ emit(session.sessionId, normalizer.openTurn(content))+ },+ }+}++/** What `AutonomousDeviceInput` is given: the terminal directly, and the controller for queued input. */+export function deviceInputDeps(+ { resolve, byAgent, terminal, device }: InputDeps,+ input: () => Pick<SessionInputController, 'acquireControl' | 'submit' | 'cancelDelivery'>,+): DeviceInputDeps {+ const { captureTerminal, validateTerminal, submitTerminalAction, keyTerminalAction } = terminal+ return {+ getSession: id => resolve(id),+ validateRuntime: validateTerminal,+ inject: submitTerminalAction,+ sendKey: keyTerminalAction,+ capture: captureTerminal,+ isAwaitingUser: async session => {+ const pane = await captureTerminal(session.agentId)+ return pane === null || parseEngineQuestionPane(session.engine, pane) !== null+ },+ acquireControl: id => input().acquireControl(id, { forAnswer: true }),+ legacySubmit: (id, text, deliveryId) => input().submit(id, text, deliveryId),+ legacyCancel: id => input().cancelDelivery(id),+ onDelivery: event => device()?.delivery(event),+ onDispatch: (id, deliveryId, text) => device()?.inputDispatched(id, deliveryId, text, byAgent(id)?.sessionId),+ onInputStatus: event => device()?.inputStatus(event),+ onForget: id => device()?.agentGone(id),+ }+}++export function createInput(deps: InputDeps) {+ const { resolve, terminal: { pinTerminalControl } } = deps+ const input: SessionInputController = new SessionInputController(sessionInputDeps(deps, () => deviceInput))+ const deviceInput: AutonomousDeviceInput = new AutonomousDeviceInput(deviceInputDeps(deps, () => input))+ const acquireTerminalControl = (id: string, opts?: { forAnswer?: boolean }): (() => void) | null => {+ const agentId = resolve(id)?.agentId ?? id+ const releaseInput = input.acquireControl(agentId, opts)+ if (!releaseInput) return null+ const releaseTerminal = pinTerminalControl(agentId)+ if (!releaseTerminal) {+ releaseInput()+ return null+ }+ return () => {+ releaseTerminal()+ releaseInput()+ }+ }+ const submitAgent = (id: string, content: string, deliveryId?: string, tabId?: string): void => {+ const record = resolve(id)+ const sessionId = record?.sessionId ?? id+ const engine = record?.engine ?? 'claude'+ // The backend prepends `/goal ` or `/loop ` without knowing the engine (on the routed path it has+ // not picked an agent yet when the mode is chosen). This is the one place that always knows, so the+ // per-engine adaptation happens here — an unknown slash command would otherwise land as a visible+ // error in the user's terminal instead of running their turn.+ const adapted = adaptSlashCommand(content, engine)+ if (adapted !== content) {+ console.log(`[msg] ${sid(sessionId)} slash-command adapted for engine=${engine}`)+ }+ console.log(`[msg] ${sid(sessionId)} recv · engine=${engine} · bytes=${Buffer.byteLength(adapted, 'utf8')}`)+ input.submit(record?.agentId ?? sessionId, adapted, deliveryId, tabId)+ }+ return { input, deviceInput, acquireTerminalControl, submitAgent }+}++export type Input = ReturnType<typeof createInput>diff --git a/cli/src/core/questions.spec.ts b/cli/src/core/questions.spec.tsnew file mode 100644index 000000000..1c5e17443--- /dev/null+++ b/cli/src/core/questions.spec.ts@@ -0,0 +1,107 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { RegisteredSession } from '../lib/registry.js'+import { createQuestions, type QuestionDeps } from './questions.js'++const agents = new Map<string, RegisteredSession>([+ ['s1', { agentId: 'a1', sessionId: 's1', engine: 'claude' } as RegisteredSession],+ ['a1', { agentId: 'a1', sessionId: 's1', engine: 'claude' } as RegisteredSession],+])++function setup(over: Partial<QuestionDeps> = {}) {+ const deps: QuestionDeps = {+ resolve: (id) => agents.get(id),+ terminal: {+ captureTerminal: vi.fn(async () => 'pane'),+ submitTerminal: vi.fn(async () => true),+ keyTerminal: vi.fn(async () => true),+ },+ acquireTerminalControl: vi.fn(() => () => {}),+ clients: { sendCommander: vi.fn(), sendLocal: vi.fn() },+ agentIdFor: (sessionId) => agents.get(sessionId)?.agentId ?? sessionId,+ sessionTurnOpen: (sessionId) => sessionId === 'busy',+ someoneCanAnswer: () => true,+ deviceInput: { setUserAction: vi.fn() },+ ...over,+ }+ return { deps, asking: createQuestions(deps) }+}++/** What a controller was constructed with. */+const given = (controller: object) => (controller as unknown as { deps: Record<string, (...args: unknown[]) => unknown> }).deps++const waiting = (sessionId: string, agentId = sessionId) => ({+ type: 'commander_event', agentId, dbSessionId: sessionId, payload: { kind: 'processing', text: 'Waiting for your answer' },+})++describe('questions', () => {+ afterEach(() => vi.restoreAllMocks())++ it('drives the pane through the terminal it was given, holding it for the whole answer', () => {+ const { deps, asking } = setup()+ const controller = given(asking.questions)+ expect((controller.getSession('s1') as RegisteredSession).agentId).toBe('a1')+ expect(controller.capture).toBe(deps.terminal.captureTerminal)+ expect(controller.sendText).toBe(deps.terminal.submitTerminal)+ expect(controller.sendKey).toBe(deps.terminal.keyTerminal)+ expect(controller.acquireControl).toBe(deps.acquireTerminalControl)+ const watcher = given(asking.questionWatcher)+ expect((watcher.getSession('a1') as RegisteredSession).sessionId).toBe('s1')+ expect(watcher.capture).toBe(deps.terminal.captureTerminal)+ expect(watcher.hasDevice()).toBe(true)+ const driving = vi.spyOn(asking.questions, 'isDriving').mockReturnValue(true)+ expect(watcher.isDriving('s1')).toBe(true)+ expect(driving).toHaveBeenCalledWith('s1')+ })++ it('keeps the dial working while an answer is on its way, and returns the answer\'s result', async () => {+ const { deps, asking } = setup()+ const answer = vi.spyOn(asking.questions, 'answer').mockResolvedValue({ ok: true })+ expect(await asking.answer({ sessionId: 's1', requestId: 'r1', answers: {} })).toEqual({ ok: true })+ await asking.answer({ agentId: 'a2', requestId: 'r2' })+ await asking.answer({ sessionId: '', requestId: 'r3' })+ await asking.answer({ requestId: 'r4' })+ expect(vi.mocked(deps.clients.sendCommander).mock.calls).toEqual([[waiting('s1', 'a1')], [waiting('a2')]])+ expect(answer).toHaveBeenCalledTimes(4)+ })++ it('reports an agent as needing input while it asks, working while its turn is open, idle otherwise', () => {+ const { asking } = setup()+ asking.openQuestions.set('s1', {})+ expect(asking.monitorActivity('s1')).toBe('needsInput')+ expect(asking.monitorActivity('busy')).toBe('working')+ expect(asking.monitorActivity('quiet')).toBe('idle')+ })++ it('shows a question on the dial and the window on this computer, and remembers it for windows that come later', () => {+ const { deps, asking } = setup()+ const remember = vi.spyOn(asking.questions, 'remember')+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const shaped = [{ q: 'Ship it?', options: [] }]+ given(asking.questionWatcher).onQuestion('s1', 'r1', shaped)+ expect(deps.deviceInput.setUserAction).toHaveBeenCalledWith('a1', true)+ expect(remember).toHaveBeenCalledWith('r1', 's1')+ const asked = vi.mocked(deps.clients.sendLocal).mock.calls[0][0]+ expect(asked).toMatchObject({ type: 'commander_question', agentId: 'a1', dbSessionId: 's1', payload: { requestId: 'r1', questions: shaped } })+ expect(vi.mocked(deps.clients.sendCommander).mock.calls).toEqual([[waiting('s1', 'a1')], [asked]])+ expect(asking.openQuestions.get('s1')).toBe(asked)+ expect(log.mock.calls[0][0]).toContain('asking the user · "Ship it?" · req=r1')+ // A question with nothing shaped still goes out, and still says so.+ given(asking.questionWatcher).onQuestion('s1', 'r2', [])+ expect(log.mock.calls[1][0]).toContain('asking the user · "" · req=r2')+ })++ it('closes a question answered elsewhere on every client it was shown on', () => {+ const { deps, asking } = setup()+ const answered = vi.spyOn(asking.agentNotifications, 'answered')+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ asking.openQuestions.set('s1', {})+ given(asking.questionWatcher).onQuestionGone('s1', 'r1')+ const closed = { type: 'commander_question_close', agentId: 'a1', dbSessionId: 's1', payload: { requestId: 'r1' } }+ expect(answered).toHaveBeenCalledWith('s1', 'r1')+ expect(deps.deviceInput.setUserAction).toHaveBeenCalledWith('a1', false)+ expect(deps.clients.sendCommander).toHaveBeenCalledWith(closed)+ expect(deps.clients.sendLocal).toHaveBeenCalledWith(closed)+ expect(asking.openQuestions.has('s1')).toBe(false)+ expect(log.mock.calls[0][0]).toContain('answered elsewhere · closing on every client · req=r1')+ })+})diff --git a/cli/src/core/questions.ts b/cli/src/core/questions.tsnew file mode 100644index 000000000..4cb3b6332--- /dev/null+++ b/cli/src/core/questions.ts@@ -0,0 +1,128 @@+/**+ * Questions: an agent asking the person something (AskUserQuestion, a permission dialog). The watcher+ * spots a dialog in the pane and puts it in front of the dial and the window on this computer; an answer+ * from any of them is keyed back into the pane; a dialog answered anywhere, or by hand, is closed on+ * every client down the same paths it was opened on.+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 6: docs/design/2026-10-03-harnessd.md).+ * The socket's two handlers stay bound there: `answer` (question_response) and `monitorActivity`.+ */+import { AgentNotifications } from '../lib/agentNotifications.js'+import { AskQuestionController, QuestionWatcher, type QuestionAnswerPayload, type QuestionAnswerResult } from '../lib/askQuestion.js'+import type { AutonomousDeviceInput } from '../lib/autonomous-device/input.js'+import { preview, sid } from '../lib/log.js'+import type { RegisteredSession } from '../lib/registry.js'+import type { TerminalControl } from './terminals/control.js'++type Frame = { type: string; agentId?: string; dbSessionId?: string; payload: Record<string, unknown> }++export interface QuestionDeps {+ resolve: (id: string) => RegisteredSession | undefined+ terminal: Pick<TerminalControl, 'captureTerminal' | 'submitTerminal' | 'keyTerminal'>+ /** Holds a pane, queue and terminal both, for the whole multi-step answer (Input.acquireTerminalControl). */+ acquireTerminalControl: (id: string, opts?: { forAnswer?: boolean }) => (() => void) | null+ /** The dial (`sendCommander`) and the window on this computer (`sendLocal`). */+ clients: { sendCommander(frame: Frame): void; sendLocal(frame: Frame): void }+ agentIdFor: (sessionId: string) => string+ sessionTurnOpen: (sessionId: string) => boolean+ /** Whether anyone could answer right now: a device watching, or a window on this computer. */+ someoneCanAnswer: () => boolean+ deviceInput: Pick<AutonomousDeviceInput, 'setUserAction'>+}++export function createQuestions({+ resolve, terminal, acquireTerminalControl, clients, agentIdFor, sessionTurnOpen, someoneCanAnswer, deviceInput,+}: QuestionDeps) {+ const { captureTerminal, submitTerminal, keyTerminal } = terminal+ // AskUserQuestion bridge: mirrors the question to the device's question screen, and keys the device's+ // answer back into the CLI's own terminal dialog.+ const questions = new AskQuestionController({+ getSession: (id) => resolve(id),+ capture: captureTerminal,+ sendText: submitTerminal,+ sendKey: keyTerminal,+ acquireControl: acquireTerminalControl,+ })+ // Command Code ENDS its turn in order to ask (its Stop hook fires, the dialog goes up, and the answer+ // opens a NEW turn). With the turn closed the device tile falls back to the PREVIOUS task's recap — so+ // mid-question the screen showed a finished summary while the user was still being asked. Keep the tile+ // visibly working for as long as the exchange lasts. The device's own busy-timeout watchdog bounds this,+ // so an abandoned question cannot pin the tile forever.+ const showAwaitingAnswer = (sessionId: string): void => {+ clients.sendCommander({+ type: 'commander_event',+ agentId: agentIdFor(sessionId),+ dbSessionId: sessionId,+ payload: { kind: 'processing', text: 'Waiting for your answer' },+ })+ }+ const answer = (payload: QuestionAnswerPayload): Promise<QuestionAnswerResult> => {+ // Hold the working state across the gap too: the CLI needs a moment to move to the next question, and+ // that gap is exactly where the stale recap used to flash back.+ const target = payload.sessionId || payload.agentId+ if (typeof target === 'string' && target) showAwaitingAnswer(target)+ // Returned so the client that answered hears a refusal — STALE_QUESTION when the dialog changed+ // before its answer arrived — as `question_response_result`.+ return questions.answer(payload)+ }+ // What is still being asked, by session — handed to a window that connects later (openQuestions below).+ const openQuestions = new Map<string, Record<string, unknown>>()+ const monitorActivity = (sessionId: string): 'needsInput' | 'working' | 'idle' => openQuestions.has(sessionId)+ ? 'needsInput' : sessionTurnOpen(sessionId) ? 'working' : 'idle'+ const agentNotifications = new AgentNotifications()+ const questionWatcher = new QuestionWatcher({+ getSession: (id) => resolve(id),+ capture: captureTerminal,+ hasDevice: () => someoneCanAnswer(),+ isDriving: (sessionId) => questions.isDriving(sessionId),+ onQuestion: (sessionId, requestId, shaped, detail) => {+ deviceInput.setUserAction(agentIdFor(sessionId), true)+ questions.remember(requestId, sessionId)+ showAwaitingAnswer(sessionId)+ const asked = {+ type: 'commander_question',+ agentId: agentIdFor(sessionId),+ dbSessionId: sessionId,+ payload: { requestId, questions: shaped, notification: agentNotifications.asked(sessionId, requestId) },+ }+ clients.sendCommander(asked)+ // ...and to the window on this computer. `sendCommander` is `webEligible: false`, so until this+ // second call the app could not learn that an agent was blocked even though the question had+ // already been shaped for the dial.+ //+ // `sendLocal`, not `send`: the question and its option labels are user content, and the only+ // audience `send` would add beyond loopback is the cloud leg, where this frame would travel+ // PLAINTEXT — `commander_question` is deliberately absent from ENCRYPTED_UP_TYPES, and putting it+ // there means re-deriving an interop hash pinned by the browser client and the device firmware in+ // two other repositories. Loopback needs no envelope, and it costs nothing that is reachable+ // today: a remote machine's watcher is gated on ITS OWN audience, which a window attached over+ // here is not part of either way.+ clients.sendLocal(asked)+ openQuestions.set(sessionId, asked)+ console.log(`[question] ${sid(sessionId)} asking the user · "${preview(shaped[0]?.q ?? '')}" · req=${requestId}`)+ },+ // Answered somewhere else — the app, or the pane by hand. Every client drawing it is told to stop+ // waiting, down the SAME path the question itself took, so the dial and the WiFi device cannot+ // disagree about whether a question is still open.+ onQuestionGone: (sessionId, requestId) => {+ agentNotifications.answered(sessionId, requestId)+ deviceInput.setUserAction(agentIdFor(sessionId), false)+ const closed = {+ type: 'commander_question_close',+ agentId: agentIdFor(sessionId),+ dbSessionId: sessionId,+ payload: { requestId },+ }+ clients.sendCommander(closed)+ // Down the SAME two paths the question took, so no client is left drawing a dialog that another+ // one already answered. This is the mechanism behind "answer anywhere": the dial is cabled to+ // this very computer, so the dial and this window are always the same machine's audience.+ clients.sendLocal(closed)+ openQuestions.delete(sessionId)+ console.log(`[question] ${sid(sessionId)} answered elsewhere · closing on every client · req=${requestId}`)+ },+ })+ return { questions, showAwaitingAnswer, answer, openQuestions, monitorActivity, agentNotifications, questionWatcher }+}++export type Questions = ReturnType<typeof createQuestions>diff --git a/cli/src/core/transcripts/lastTurn.spec.ts b/cli/src/core/transcripts/lastTurn.spec.tsnew file mode 100644index 000000000..6804ca01d--- /dev/null+++ b/cli/src/core/transcripts/lastTurn.spec.ts@@ -0,0 +1,75 @@+import { describe, expect, it, vi } from 'vitest'+import type { RegisteredSession } from '../../lib/registry.js'+import { createLastTurnReader } from './lastTurn.js'++// Every engine's own reader is tested with that engine; this file checks that each engine is read its own way.+const text = (from: string) => ({ text: from })+vi.mock('../../engines/opencode/reader.js', () => ({ readOpencodeMessages: vi.fn(async (db: string, id: string) => [`opencode ${db} ${id}`]) }))+vi.mock('../../engines/opencode/normalizer.js', () => ({ lastOpencodeTurnText: vi.fn((rows: string[]) => ({ text: rows[0] })) }))+vi.mock('../../engines/kilo/reader.js', () => ({ readKiloMessages: vi.fn(async (db: string, id: string) => [`kilo ${db} ${id}`]) }))+vi.mock('../../engines/kilo/normalizer.js', () => ({ lastKiloTurnText: vi.fn((rows: string[]) => ({ text: rows[0] })) }))+vi.mock('../../engines/hermes/reader.js', () => ({ readHermesMessages: vi.fn(async (db: string, id: string) => [`hermes ${db} ${id}`]) }))+vi.mock('../../engines/hermes/normalizer.js', () => ({ lastHermesTurnText: vi.fn((rows: string[]) => ({ text: rows[0] })) }))+vi.mock('../../engines/devin/reader.js', () => ({ readDevinMessages: vi.fn(async (db: string, id: string) => [`devin ${db} ${id}`]) }))+vi.mock('../../engines/devin/normalizer.js', () => ({ lastDevinTurnText: vi.fn((rows: string[]) => ({ text: rows[0] })) }))+vi.mock('../../engines/codex/lastTurn.js', () => ({ readLastCodexTurnText: vi.fn(async (path: string) => ({ text: `codex ${path}` })) }))+vi.mock('../../lib/transcriptTail.js', () => ({+ tailFile: vi.fn(async (path: string, n: number) => [`${path} last ${n}`]),+ tailFileUntil: vi.fn(async (path: string) => [`${path} back to the last turn`]),+}))+vi.mock('../../lib/normalize.js', () => ({+ lastTurnTextFromRawLines: vi.fn((lines: string[]) => ({ text: `raw: ${lines[0]}` })),+ selectClaudeRecapLine: vi.fn(),+}))+vi.mock('../../engines/cursor/normalizer.js', () => ({ lastCursorTurnText: vi.fn((lines: string[]) => ({ text: `cursor: ${lines[0]}` })) }))+vi.mock('../../engines/muse/normalizer.js', () => ({ lastMuseTurnText: vi.fn((lines: string[]) => ({ text: `muse: ${lines[0]}` })) }))+vi.mock('../../engines/amp/normalizer.js', () => ({ lastAmpTurnText: vi.fn((lines: string[]) => ({ text: `amp: ${lines[0]}` })) }))+vi.mock('../../engines/grok/normalizer.js', () => ({ lastGrokTurnText: vi.fn((lines: string[]) => ({ text: `grok: ${lines[0]}` })) }))+vi.mock('../../engines/agy/normalizer.js', () => ({ lastAgyTurnText: vi.fn((lines: string[]) => ({ text: `agy: ${lines[0]}` })) }))+vi.mock('../../engines/copilot/normalizer.js', () => ({ lastCopilotTurnText: vi.fn((lines: string[]) => ({ text: `copilot: ${lines[0]}` })) }))+vi.mock('../../engines/pi/normalizer.js', () => ({ lastPiTurnText: vi.fn((lines: string[]) => ({ text: `pi: ${lines[0]}` })) }))+vi.mock('../../engines/commandcode/normalizer.js', () => ({ lastCommandCodeTurnText: vi.fn((lines: string[]) => ({ text: `commandcode: ${lines[0]}` })) }))++const session = (engine: string, transcriptPath?: string): RegisteredSession =>+ ({ agentId: `${engine}-agent`, sessionId: `${engine}-s`, engine, transcriptPath }) as RegisteredSession++async function reader(sessions: RegisteredSession[]) {+ const create = createLastTurnReader+ const bySession = new Map(sessions.map((s) => [s.sessionId, s]))+ return create({+ bySession: (sessionId) => bySession.get(sessionId),+ dbs: { opencode: '/db/opencode.db', kilo: '/db/kilo.db', devin: '/db/devin.db' },+ hermesDb: async (s) => `/db/hermes-${s.agentId}.db`,+ })+}++describe('the last turn of each engine', () => {+ it('is nothing for a session it does not know, or a file engine without a transcript yet', async () => {+ const read = await reader([session('cursor')])+ expect(await read('nobody')).toBeNull()+ expect(await read('cursor-s')).toBeNull()+ })++ it('is read from the store of each database engine', async () => {+ const read = await reader([session('opencode'), session('kilo'), session('hermes'), session('devin')])+ expect(await read('opencode-s')).toEqual(text('opencode /db/opencode.db opencode-s'))+ expect(await read('kilo-s')).toEqual(text('kilo /db/kilo.db kilo-s'))+ expect(await read('hermes-s')).toEqual(text('hermes /db/hermes-hermes-agent.db hermes-s'))+ expect(await read('devin-s')).toEqual(text('devin /db/devin.db devin-s'))+ })++ it('is read backward for Claude Code, from the rollout for Codex, and from the whole transcript for the rest', async () => {+ const engines = ['cursor', 'muse', 'amp', 'grok', 'agy', 'copilot', 'pi', 'commandcode']+ const read = await reader([+ session('claude', '/t/claude.jsonl'), session('codex', '/t/codex.jsonl'), session('terminal', '/t/shell.log'),+ ...engines.map((engine) => session(engine, `/t/${engine}.jsonl`)),+ ])+ expect(await read('claude-s')).toEqual(text('raw: /t/claude.jsonl back to the last turn'))+ expect(await read('codex-s')).toEqual(text('codex /t/codex.jsonl'))+ for (const engine of engines) {+ expect(await read(`${engine}-s`), engine).toEqual(text(`${engine}: /t/${engine}.jsonl last Infinity`))+ }+ // An engine with no reader of its own: its raw lines.+ expect(await read('terminal-s')).toEqual(text('raw: /t/shell.log last Infinity'))+ })+})diff --git a/cli/src/core/transcripts/lastTurn.ts b/cli/src/core/transcripts/lastTurn.tsnew file mode 100644index 000000000..d70ec1b36--- /dev/null+++ b/cli/src/core/transcripts/lastTurn.ts@@ -0,0 +1,62 @@+/**+ * The text of an agent's last turn, for its recap: from the database engines' stores, Codex's rollout,+ * Claude Code's transcript read backward from its end, and every other engine's transcript.+ *+ * The file engines other than Claude Code and Codex still read the whole transcript here, once per turn+ * end (docs/research/2026-10-04-whole-history-reads.md); bounding them is the next engine work.+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 7: docs/design/2026-10-03-harnessd.md).+ */+import { lastAgyTurnText } from '../../engines/agy/normalizer.js'+import { lastAmpTurnText } from '../../engines/amp/normalizer.js'+import { readLastCodexTurnText } from '../../engines/codex/lastTurn.js'+import { lastCommandCodeTurnText } from '../../engines/commandcode/normalizer.js'+import { lastCopilotTurnText } from '../../engines/copilot/normalizer.js'+import { lastCursorTurnText } from '../../engines/cursor/normalizer.js'+import { lastDevinTurnText } from '../../engines/devin/normalizer.js'+import { readDevinMessages } from '../../engines/devin/reader.js'+import { lastGrokTurnText } from '../../engines/grok/normalizer.js'+import { lastHermesTurnText } from '../../engines/hermes/normalizer.js'+import { readHermesMessages } from '../../engines/hermes/reader.js'+import { lastKiloTurnText } from '../../engines/kilo/normalizer.js'+import { readKiloMessages } from '../../engines/kilo/reader.js'+import { lastMuseTurnText } from '../../engines/muse/normalizer.js'+import { lastOpencodeTurnText } from '../../engines/opencode/normalizer.js'+import { readOpencodeMessages } from '../../engines/opencode/reader.js'+import { lastPiTurnText } from '../../engines/pi/normalizer.js'+import { lastTurnTextFromRawLines, selectClaudeRecapLine, type LastTurnText } from '../../lib/normalize.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { tailFile, tailFileUntil } from '../../lib/transcriptTail.js'++export interface LastTurnDeps {+ bySession: (sessionId: string) => RegisteredSession | undefined+ /** The database engines' stores. */+ dbs: { opencode: string; kilo: string; devin: string }+ /** Hermes keeps a store per profile: the one this session's lives in. */+ hermesDb: (s: RegisteredSession) => Promise<string>+}++export function createLastTurnReader({ bySession, dbs, hermesDb }: LastTurnDeps) {+ return async (sessionId: string): Promise<LastTurnText | null> => {+ const s = bySession(sessionId)+ if (!s) return null+ if (s.engine === 'opencode') return lastOpencodeTurnText(await readOpencodeMessages(dbs.opencode, sessionId))+ if (s.engine === 'kilo') return lastKiloTurnText(await readKiloMessages(dbs.kilo, sessionId))+ if (s.engine === 'hermes') return lastHermesTurnText(await readHermesMessages(await hermesDb(s), sessionId))+ if (s.engine === 'devin') return lastDevinTurnText(await readDevinMessages(dbs.devin, sessionId))+ if (!s.transcriptPath) return null+ if (s.engine === 'codex') return readLastCodexTurnText(s.transcriptPath)+ // Its last turn, read backward — not the whole conversation once per turn end.+ if (s.engine === 'claude') return lastTurnTextFromRawLines(await tailFileUntil(s.transcriptPath, selectClaudeRecapLine))+ const lines = await tailFile(s.transcriptPath, Infinity)+ if (s.engine === 'cursor') return lastCursorTurnText(lines)+ if (s.engine === 'muse') return lastMuseTurnText(lines)+ if (s.engine === 'amp') return lastAmpTurnText(lines)+ if (s.engine === 'grok') return lastGrokTurnText(lines)+ if (s.engine === 'agy') return lastAgyTurnText(lines)+ if (s.engine === 'copilot') return lastCopilotTurnText(lines)+ if (s.engine === 'pi') return lastPiTurnText(lines)+ if (s.engine === 'commandcode') return lastCommandCodeTurnText(lines)+ return lastTurnTextFromRawLines(lines)+ }+}diff --git a/cli/src/core/turns/activity.spec.ts b/cli/src/core/turns/activity.spec.tsnew file mode 100644index 000000000..4e80755f4--- /dev/null+++ b/cli/src/core/turns/activity.spec.ts@@ -0,0 +1,64 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { RegisteredSession } from '../../lib/registry.js'+import { activityRuntimeKey } from '../../lib/runtimeActivity.js'+import type { ActivityFrame } from '../../lib/turnActivity.js'+import { createTurnActivity, type TurnActivityDeps } from './activity.js'++const live = { agentId: 'a1', sessionId: 's1', engine: 'claude', active: true } as RegisteredSession+const idle = { agentId: 'a2', sessionId: 's2', engine: 'claude', active: false } as RegisteredSession+const shell = { agentId: 'a3', sessionId: 's3', engine: 'terminal', active: true } as RegisteredSession+const sessions = new Map([[live.sessionId, live], [idle.sessionId, idle], [shell.sessionId, shell]])++function setup(over: Partial<TurnActivityDeps> = {}) {+ const deps: TurnActivityDeps = {+ terminals: { capture: vi.fn(async () => ({ state: 'succeeded' as const, value: 'screen' })) },+ bySession: (sessionId) => sessions.get(sessionId),+ sessionTurnOpen: (sessionId) => sessionId === 's1',+ drain: vi.fn(async () => {}),+ ...over,+ }+ return { deps, readers: createTurnActivity(deps) }+}++/** What a reader was constructed with. */+const given = (reader: object) => (reader as unknown as { deps: Record<string, (...args: unknown[]) => unknown> }).deps++describe('turn activity', () => {+ afterEach(() => vi.restoreAllMocks())++ it('checks only an active session, keyed to the runtime that runs it', async () => {+ const { deps, readers } = setup()+ const turn = given(readers.turnActivity)+ expect(turn.runtime('s1')).toEqual({ key: activityRuntimeKey(live), turnOpen: true })+ expect(turn.runtime('s2')).toBeUndefined()+ expect(turn.runtime('nobody')).toBeUndefined()+ await turn.drain('s1')+ expect(deps.drain).toHaveBeenCalledWith('s1')+ const read = vi.spyOn(readers.runtimeActivity, 'read').mockResolvedValue('working')+ expect(await turn.probe('s1')).toBe('working')+ expect(read).toHaveBeenCalledWith(live)+ expect(await turn.probe('s2')).toBe('unknown')+ })++ it('reads Codex\'s activity from Codex, and every other runtime from what its pane shows', async () => {+ const { deps, readers } = setup()+ const runtime = given(readers.runtimeActivity)+ const codex = vi.spyOn(readers.codexActivity, 'read').mockResolvedValue('idle' as never)+ expect(await runtime.codex(live)).toBe('idle')+ expect(codex).toHaveBeenCalledWith(live)+ expect(await runtime.capture(live)).toBe('screen')+ expect(deps.terminals.capture).toHaveBeenCalledWith(live, { mode: 'visible', ansi: true })+ vi.mocked(deps.terminals.capture).mockResolvedValueOnce({ state: 'failed', reason: 'no pane' })+ expect(await runtime.capture(live)).toBeNull()+ })++ it('shows the app an agent\'s activity, and none for a plain terminal', () => {+ const { readers } = setup()+ const frame = { state: 'working' } as ActivityFrame+ const snapshot = vi.spyOn(readers.turnActivity, 'snapshot').mockReturnValueOnce(frame).mockReturnValueOnce(undefined)+ expect(readers.activityFrame(live)).toBe(frame)+ expect(readers.activityFrame(live)).toBeNull()+ expect(readers.activityFrame(shell)).toBeNull()+ expect(snapshot).toHaveBeenCalledTimes(2)+ })+})diff --git a/cli/src/core/turns/activity.ts b/cli/src/core/turns/activity.tsnew file mode 100644index 000000000..94c984125--- /dev/null+++ b/cli/src/core/turns/activity.ts@@ -0,0 +1,48 @@+/**+ * Turn activity: whether an agent is really working, beyond what its transcript says. A turn's+ * transcript can go quiet while the agent thinks or runs a long tool, so an open turn is checked against+ * the runtime: Codex's own activity file, or what the pane shows.+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 7: docs/design/2026-10-03-harnessd.md).+ */+import { isTerminalEngine } from '../../engines/types.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { CodexActivityReader, RuntimeActivityReader, activityRuntimeKey } from '../../lib/runtimeActivity.js'+import type { TerminalBackendCoordinator } from '../../lib/terminalBackendCoordinator.js'+import { TurnActivity, type ActivityFrame } from '../../lib/turnActivity.js'++export interface TurnActivityDeps {+ terminals: Pick<TerminalBackendCoordinator, 'capture'>+ bySession: (sessionId: string) => RegisteredSession | undefined+ sessionTurnOpen: (sessionId: string) => boolean+ /** Read whatever the session's transcript has that the tail has not delivered yet (Watcher.pollSession). */+ drain: (sessionId: string) => Promise<void>+}++export function createTurnActivity({ terminals, bySession, sessionTurnOpen, drain }: TurnActivityDeps) {+ const codexActivity = new CodexActivityReader()+ const runtimeActivity = new RuntimeActivityReader({+ codex: session => codexActivity.read(session),+ capture: async session => {+ const screen = await terminals.capture(session, { mode: 'visible', ansi: true })+ return screen.state === 'succeeded' ? screen.value : null+ },+ })+ const turnActivity = new TurnActivity({+ runtime: sessionId => {+ const session = bySession(sessionId)+ return session?.active ? { key: activityRuntimeKey(session), turnOpen: sessionTurnOpen(sessionId) } : undefined+ },+ drain: sessionId => drain(sessionId),+ probe: async sessionId => {+ const session = bySession(sessionId)+ return session?.active ? runtimeActivity.read(session) : 'unknown'+ },+ })+ /** The activity the app shows for an agent; none for a plain terminal. */+ const activityFrame = (session: RegisteredSession): ActivityFrame | null =>+ isTerminalEngine(session.engine) ? null : turnActivity.snapshot(session.sessionId) ?? null+ return { codexActivity, runtimeActivity, turnActivity, activityFrame }+}++export type TurnActivityReaders = ReturnType<typeof createTurnActivity>diff --git a/cli/src/core/turns/funnel.spec.ts b/cli/src/core/turns/funnel.spec.tsnew file mode 100644index 000000000..22e7f1a8a--- /dev/null+++ b/cli/src/core/turns/funnel.spec.ts@@ -0,0 +1,188 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { deviceErrorText } from '../../lib/deviceErrors.js'+import type { RegisteredSession } from '../../lib/registry.js'+import { createEventFunnel, funnelFor, type FunnelDeps } from './funnel.js'++type Event = Parameters<ReturnType<typeof funnelFor>>[1][number]+const started = (userMessage = 'go'): Event => ({ type: 'turn_started', payload: { userMessage } }) as Event+const text = (value = 'working on it'): Event => ({ type: 'text_delta', payload: { content: value } })+const ended = (aborted = false): Event => ({ type: 'turn_ended', payload: { aborted } }) as Event++/**+ * Every collaborator writes to one log, so a test reads the order the funnel called them in, across all+ * of them — the order is the funnel's contract.+ */+function setup(engine = 'claude', over: Partial<FunnelDeps> = {}) {+ const calls: string[] = []+ const log = (entry: string) => () => { calls.push(entry) }+ const session = { agentId: 'a1', sessionId: 's1', engine, active: true } as RegisteredSession+ const deps: FunnelDeps = {+ bySession: (sessionId) => sessionId === 's1' ? session : sessionId === 'off' ? ({ ...session, active: false }) : undefined,+ tokenUsage: { changed: vi.fn(log('usage')) },+ agentIdFor: () => 'a1',+ turnActivity: { observe: vi.fn(), snapshot: vi.fn(() => undefined) },+ isSubagentSession: vi.fn(() => false),+ clients: { send: vi.fn((frame: { type: string }) => { calls.push(`send ${frame.type}`) }) },+ search: { touch: vi.fn(log('search')) },+ turnStartedAt: new Map(),+ input: { onTurnStarted: vi.fn(log('input started')), onTurnEnded: vi.fn(log('input ended')) },+ teams: { started: vi.fn(log('teams started')) },+ deviceInput: { onTurnStarted: vi.fn(log('deviceInput started')), onTurnEnded: vi.fn(log('deviceInput ended')) },+ device: () => ({ turnStarted: vi.fn(log('device started')), turnEnded: vi.fn(log('device ended')), stream: vi.fn(log('device stream')) }),+ startHeartbeat: vi.fn(log('heartbeat')),+ questionWatcher: { start: vi.fn(log('questions start')), noteTurnStart: vi.fn(log('questions pre-turn')), stop: vi.fn(log('questions stop')) },+ mirror: { ingest: vi.fn(log('mirror')) },+ ...over,+ }+ return { deps, calls, funnel: funnelFor(deps), session }+}++describe('the event funnel', () => {+ afterEach(() => vi.restoreAllMocks())++ it('fans a live turn out in its exact order: the app first, the recaps after the batch, the device stream last', () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const { funnel, calls } = setup()+ funnel('s1', [started(), text(), ended()])+ expect(calls).toEqual([+ 'send turn_started', 'search',+ 'input started', 'teams started', 'deviceInput started', 'device started', 'heartbeat', 'questions start', 'questions pre-turn',+ 'send text_delta',+ 'send turn_ended', 'search',+ 'device ended', 'deviceInput ended', 'input ended', 'questions stop',+ 'mirror', 'device stream',+ ])+ })++ it('marks a turn picked up at attach as such, and still streams it to the device', () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const { funnel, calls, deps } = setup()+ funnel('s1', [started()], { resumed: true })+ // Not a turn starting now: the teams do not count it, and a dialog already up belongs to it.+ expect(calls).toEqual([+ 'send turn_started', 'search',+ 'input started', 'deviceInput started', 'device started', 'heartbeat', 'questions start',+ 'mirror', 'device stream',+ ])+ const frame = vi.mocked(deps.clients.send).mock.calls[0][0] as Record<string, any>+ expect(frame.replay).toBe(true)+ expect(frame.payload.replay).toBe(true)+ expect(vi.mocked(deps.mirror.ingest).mock.calls[0][2]).toEqual({ replay: true })+ })++ it('re-reads a transcript as history: no team count, and nothing streamed to the device', () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const { funnel, calls, deps } = setup()+ funnel('s1', [started(), ended()], { replay: true })+ expect(calls).not.toContain('teams started')+ expect(calls).not.toContain('device stream')+ expect(calls).toContain('questions pre-turn')+ const end = vi.mocked(deps.clients.send).mock.calls[1][0] as Record<string, any>+ expect(end.replay).toBe(true)+ })++ it('tells every screen a sub-agent\'s turn end is one, and times a live turn', () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const { funnel, deps } = setup('claude', { isSubagentSession: vi.fn(() => true) })+ funnel('s1', [started('a long one')])+ funnel('s1', [ended(true)])+ const end = vi.mocked(deps.clients.send).mock.calls[1][0] as Record<string, any>+ expect(end.subagent).toBe(true)+ expect(end.replay).toBeUndefined()+ expect(deps.turnStartedAt.has('s1')).toBe(false)+ expect(log.mock.calls.map(([line]) => String(line))).toEqual([+ expect.stringMatching(/started · engine=claude · bytes=10$/),+ expect.stringMatching(/ended · aborted \(interrupted\) · \d+ms$/),+ ])+ })++ it('leaves the device\'s input alone across a native turn boundary, and Command Code\'s question watcher running', () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const native = setup('codex')+ native.funnel('s1', [ended(), started()])+ expect(native.calls.slice(0, 4)).toEqual(['send turn_ended', 'search', 'input ended', 'questions stop'])+ const commandcode = setup('commandcode')+ commandcode.funnel('s1', [ended()])+ expect(commandcode.calls).not.toContain('questions stop')+ expect(commandcode.calls).toContain('device ended')+ })++ it('carries the turn\'s activity, says when a turn ends without a start, and counts OpenCode\'s usage', () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const run = setup('opencode')+ vi.mocked(run.deps.turnActivity.snapshot).mockReturnValue({ state: 'working' } as never)+ run.funnel('s1', [text(), ended()])+ expect(run.calls[0]).toBe('usage')+ expect((vi.mocked(run.deps.clients.send).mock.calls[0][0] as Record<string, any>).payload.activity).toEqual({ state: 'working' })+ expect(run.deps.turnActivity.observe).toHaveBeenCalledWith('s1', 'text_delta', false)+ expect(String(log.mock.calls[0][0])).toMatch(/ended$/)+ })++ it('finishes a batch whose session was forgotten while it was being delivered', () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ let lookups = 0+ const run = setup('codex', {+ // Active when the batch arrives; gone from the next lookup on, as when a collaborator forgets it.+ bySession: () => lookups++ === 0 ? ({ agentId: 'a1', sessionId: 's1', engine: 'codex', active: true } as RegisteredSession) : undefined,+ })+ expect(() => run.funnel('s1', [ended(), started()])).not.toThrow()+ // Without its engine, a native turn boundary is not recognised, so the device hears the turn end.+ expect(run.calls).toContain('device ended')+ expect(String(log.mock.calls[1][0])).toContain('engine=claude')+ })++ it('ignores an empty batch and a session that is not active', () => {+ const { funnel, calls } = setup()+ funnel('s1', [])+ funnel('off', [started()])+ funnel('nobody', [started()])+ expect(calls).toEqual([])+ })++ it('works without search or a device service', () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const { funnel, calls } = setup('claude', { search: null, device: () => undefined })+ funnel('s1', [started(), ended()])+ expect(calls).toEqual([+ 'send turn_started', 'input started', 'teams started', 'deviceInput started', 'heartbeat', 'questions start', 'questions pre-turn',+ 'send turn_ended', 'deviceInput ended', 'input ended', 'questions stop',+ 'mirror',+ ])+ })+})++describe('createEventFunnel', () => {+ afterEach(() => vi.restoreAllMocks())++ it('holds events until it is armed, delivers them in order, and is the same function after', () => {+ vi.spyOn(console, 'log').mockImplementation(() => {})+ const funnel = createEventFunnel({ clients: { send: vi.fn(), sendCommander: vi.fn() }, agentIdFor: () => 'a1' })+ const emit = funnel.emit+ emit('s1', [started('first')])+ emit('s1', [])+ emit('s1', [text('second')], { replay: true })+ const { deps, calls } = setup()+ funnel.arm(deps)+ expect(calls.filter((call) => call.startsWith('send'))).toEqual(['send turn_started', 'send text_delta'])+ expect(vi.mocked(deps.mirror.ingest).mock.calls.map((call) => call[2])).toEqual([{ replay: false }, { replay: true }])+ emit('s1', [ended()])+ expect(calls.filter((call) => call.startsWith('send'))).toEqual(['send turn_started', 'send text_delta', 'send turn_ended'])+ })++ it('tells the app and, in the device\'s words, the dial when an engine aborts a turn', () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const clients = { send: vi.fn(), sendCommander: vi.fn() }+ const funnel = createEventFunnel({ clients, agentIdFor: () => 'a1' })+ funnel.announceTurnAborted('s1', 'devin', 'the model refused')+ funnel.announceTurnAborted('s1', 'commandcode', 'rate limited: retry in 60s', 'rate limited')+ expect(clients.send.mock.calls).toEqual([+ [{ type: 'error', agentId: 'a1', dbSessionId: 's1', payload: { message: 'the model refused' } }],+ [{ type: 'error', agentId: 'a1', dbSessionId: 's1', payload: { message: 'rate limited: retry in 60s' } }],+ ])+ expect(clients.sendCommander.mock.calls.map(([frame]) => frame.payload.text)).toEqual([+ deviceErrorText('the model refused', 'devin'),+ deviceErrorText('rate limited', 'commandcode'),+ ])+ expect(String(log.mock.calls[0][0])).toContain('aborted by devin error')+ })+})diff --git a/cli/src/core/turns/funnel.ts b/cli/src/core/turns/funnel.tsnew file mode 100644index 000000000..731b5ea2d--- /dev/null+++ b/cli/src/core/turns/funnel.ts@@ -0,0 +1,173 @@+/**+ * The event funnel: the one place a session's live events fan out from, to the app, search, input, the+ * teams, the device's input, the device service, the heartbeat, the question watcher and the recaps. The+ * order is exact and it matters: per event, the frame goes to the app before anything acts on it; the+ * recaps hear the whole batch after the loop; the device stream comes last and never on a replay.+ *+ * Until the core has built what the funnel feeds, events wait: a hook can register a session the instant+ * the hook server binds. `arm` installs the funnel and delivers what waited, in order. `emit` is the same+ * function before and after, so whoever holds it keeps a working funnel.+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 8: docs/design/2026-10-03-harnessd.md).+ */+import { correlateAgentEvent } from '../../lib/agentEvent.js'+import type { AutonomousDeviceInput } from '../../lib/autonomous-device/input.js'+import { isDeviceInputBoundary } from '../../lib/autonomous-device/input.js'+import type { AutonomousDeviceService } from '../../lib/autonomous-device/service.js'+import type { CommanderMirror } from '../../lib/commander.js'+import { deviceErrorText } from '../../lib/deviceErrors.js'+import { preview, sid } from '../../lib/log.js'+import type { CursorNormalizer } from '../../engines/cursor/normalizer.js'+import type { QuestionWatcher } from '../../lib/askQuestion.js'+import type { RegisteredSession } from '../../lib/registry.js'+import type { SessionInputController } from '../../lib/sessionInput.js'+import type { TurnActivity } from '../../lib/turnActivity.js'+import type { SwarmPromptScopes } from '../../teams/promptScope.js'++type Events = ReturnType<CursorNormalizer['ingest']>+type EmitOptions = { resumed?: boolean; replay?: boolean }+type Frame = { type: string; agentId?: string; dbSessionId?: string; payload: Record<string, unknown> }++export interface FunnelClients {+ /** The app. */+ send(frame: Frame): void+ /** The dial. */+ sendCommander(frame: Frame): void+}++/** What the funnel feeds, built by the time it is armed. */+export interface FunnelDeps {+ bySession: (sessionId: string) => RegisteredSession | undefined+ tokenUsage: { changed(target: RegisteredSession): void }+ agentIdFor: (sessionId: string) => string+ turnActivity: Pick<TurnActivity, 'observe' | 'snapshot'>+ isSubagentSession: (sessionId: string) => boolean+ clients: Pick<FunnelClients, 'send'>+ search: { touch(sessionId: string): void } | null | undefined+ turnStartedAt: Map<string, number>+ input: Pick<SessionInputController, 'onTurnStarted' | 'onTurnEnded'>+ teams: Pick<SwarmPromptScopes, 'started'>+ deviceInput: Pick<AutonomousDeviceInput, 'onTurnStarted' | 'onTurnEnded'>+ device: () => Pick<AutonomousDeviceService, 'turnStarted' | 'turnEnded' | 'stream'> | undefined+ startHeartbeat: (sessionId: string) => void+ questionWatcher: Pick<QuestionWatcher, 'start' | 'noteTurnStart' | 'stop'>+ mirror: Pick<CommanderMirror, 'ingest'>+}++/** The funnel itself, over what it feeds. */+export function funnelFor({+ bySession, tokenUsage, agentIdFor, turnActivity, isSubagentSession, clients, search, turnStartedAt, input, teams,+ deviceInput, device, startHeartbeat, questionWatcher, mirror,+}: FunnelDeps) {+ return (sessionId: string, events: Events, opts?: EmitOptions): void => {+ if (!events.length || !bySession(sessionId)?.active) return+ const usageSession = bySession(sessionId)+ if (usageSession?.engine === 'opencode') tokenUsage.changed(usageSession)+ for (const [eventIndex, event] of events.entries()) {+ const agentId = agentIdFor(sessionId)+ const replay = !!(opts?.resumed || opts?.replay)+ turnActivity.observe(sessionId, event.type, replay)+ const frame = correlateAgentEvent({ ...event, payload: { ...event.payload, activity: turnActivity.snapshot(sessionId) } }, sessionId, agentId)+ // A `turn_started` that is not a turn starting NOW — a turn picked back up at attach, or a prompt+ // re-read from a transcript that was already on disk — says so in the clear, beside `agentId`+ // (the payload is E2EE; the backend can only read the envelope). The backend's daily turn count+ // skips these; every other consumer ignores an unknown field. Measured before this existed: one+ // agent credited with 42 turns in a single second, all re-reads.+ if (replay) { frame.replay = true; frame.payload.replay = true }+ // The end of a turn carries the two facts an app needs to decide whether it is NEWS, in the clear+ // beside `agentId` for the same reason `replay` is — the payload is E2EE and the apps read this+ // without opening it:+ // `replay` — a turn re-read from disk, not one finishing now;+ // `subagent` — a specialist's turn nobody asked to hear about, the dial's `silent`. The dial has+ // always been told and the window never was, so an Orchestrator project of four+ // specialists put ONE row on the dial and FIVE marks in the window. Same predicate+ // for every screen now — see isSubagentSession.+ // The phone notifies on neither. Absent = false, so a client that predates these reads every end as+ // it always did.+ if (event.type === 'turn_ended') {+ if (opts?.resumed || opts?.replay) frame.replay = true+ if (isSubagentSession(sessionId)) frame.subagent = true+ }+ clients.send(frame)+ if (event.type === 'turn_started' || event.type === 'turn_ended') search?.touch(sessionId)+ if (event.type === 'turn_started') {+ turnStartedAt.set(sessionId, Date.now())+ console.log(`[turn] ${sid(sessionId)} started · engine=${bySession(sessionId)?.engine ?? 'claude'} · bytes=${Buffer.byteLength(event.payload.userMessage, 'utf8')}`)+ input.onTurnStarted(agentIdFor(sessionId), event.payload.userMessage)+ if (!opts?.resumed && !opts?.replay) teams.started(agentId, event.payload.userMessage, 'transcript', bySession(sessionId)?.engine)+ deviceInput.onTurnStarted(agentId, event.payload.userMessage)+ device()?.turnStarted(agentId)+ startHeartbeat(sessionId)+ questionWatcher.start(sessionId) // Claude opens its dialog INSIDE a turn+ // ...and anything already drawn belongs to the turn BEFORE this one — unless this is a turn the+ // daemon is picking back up at attach: a dialog on the pane then is THIS turn's, still waiting,+ // and marking it pre-turn is how a restarted daemon never announced a question Codex had open.+ if (!opts?.resumed) questionWatcher.noteTurnStart(sessionId)+ } else if (event.type === 'turn_ended') {+ const startedAt = turnStartedAt.get(sessionId)+ turnStartedAt.delete(sessionId)+ // Say when a turn was KILLED. The log previously showed an interrupt as a fresh `[turn] started+ // "[Request interrupted by user]"`, which read like a new prompt and hid the bug for weeks.+ console.log(+ `[turn] ${sid(sessionId)} ended${event.payload.aborted ? ' · aborted (interrupted)' : ''}` ++ `${startedAt ? ` · ${Date.now() - startedAt}ms` : ''}`,+ )+ // Filter only the Device receipt view; shared normalizers, mirror, and local input stay unchanged.+ if (!isDeviceInputBoundary(usageSession?.engine ?? '', events, eventIndex)) {+ device()?.turnEnded(agentId, event.payload.aborted === true)+ deviceInput.onTurnEnded(agentId)+ }+ input.onTurnEnded(agentIdFor(sessionId))+ // Command Code asks AFTER the turn: `ask_user_question` ends the turn (its Stop hook fires), the+ // dialog goes up, and the answer opens a NEW turn. Stopping the watcher here is what left the+ // terminal sitting on a question the device never showed. Its watcher runs off the session, not+ // the turn — see the attach path — so leave it alone.+ if (bySession(sessionId)?.engine !== 'commandcode') questionWatcher.stop(sessionId)+ // Do NOT stop the heartbeat here: the turn is closed but the device summarize is just starting+ // (mirror sets summarizing=true in the mirror.ingest below). The timer keeps fanning "Summarizing…"+ // to the device and self-cancels once mirror.heartbeat() reports idle (summary done).+ }+ }+ mirror.ingest(events, sessionId, { replay: !!(opts?.resumed || opts?.replay) })+ // Subscribed devices only (lib/autonomous-device/stream.ts). A transcript re-read is history, not live.+ if (!opts?.replay) device()?.stream(agentIdFor(sessionId), events)+ }+}++export function createEventFunnel({ clients, agentIdFor }: { clients: FunnelClients; agentIdFor: (sessionId: string) => string }) {+ const queuedSessionEvents: Array<{ sessionId: string; events: Events; opts?: EmitOptions }> = []+ let funnel: ((sessionId: string, events: Events, opts?: EmitOptions) => void) | null = null+ const emit = (sessionId: string, events: Events, opts?: EmitOptions): void => {+ if (funnel) funnel(sessionId, events, opts)+ else if (events.length) queuedSessionEvents.push({ sessionId, events, opts })+ }+ /** Install the funnel and deliver what waited for it, in order. */+ const arm = (deps: FunnelDeps): void => {+ funnel = funnelFor(deps)+ for (const queued of queuedSessionEvents.splice(0)) funnel(queued.sessionId, queued.events, queued.opts)+ }+ /**+ * A turn died inside the engine instead of finishing. Neither devin nor commandcode has a StopFailure+ * hook, so nothing else would tell the clients: the web would sit on the typing indicator and the+ * device tile would stay "Working…". Surface the failure to both; the CALLER closes the turn (the devin+ * reader and the commandcode normalizer each own their own turn state).+ */+ const announceTurnAborted = (+ sessionId: string,+ engine: string,+ message: string,+ deviceMessage = message,+ ): void => {+ console.log(`[turn] ${sid(sessionId)} aborted by ${engine} error · ${preview(message)}`)+ clients.send({ type: 'error', agentId: agentIdFor(sessionId), dbSessionId: sessionId, payload: { message } })+ clients.sendCommander({+ type: 'commander_event',+ agentId: agentIdFor(sessionId),+ dbSessionId: sessionId,+ payload: { kind: 'error', text: deviceErrorText(deviceMessage, engine) },+ })+ }+ return { emit, arm, announceTurnAborted }+}++export type EventFunnel = ReturnType<typeof createEventFunnel>diff --git a/cli/src/core/turns/heartbeats.spec.ts b/cli/src/core/turns/heartbeats.spec.tsnew file mode 100644index 000000000..ad8753f7e--- /dev/null+++ b/cli/src/core/turns/heartbeats.spec.ts@@ -0,0 +1,103 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { RegisteredSession } from '../../lib/registry.js'+import type { ActivityFrame } from '../../lib/turnActivity.js'+import { createHeartbeats, type HeartbeatDeps } from './heartbeats.js'++function setup(over: Partial<HeartbeatDeps> = {}) {+ let active = true+ let turnOpen = true+ let deviceBusy = false+ let activity: ActivityFrame | undefined+ const deps: HeartbeatDeps = {+ bySession: (sessionId) => sessionId === 's1' ? ({ agentId: 'a1', sessionId: 's1', active } as RegisteredSession) : undefined,+ sessionTurnOpen: () => turnOpen,+ agentIdFor: () => 'a1',+ runtimeActivity: { forget: vi.fn() },+ turnActivity: { check: vi.fn(async () => {}), snapshot: vi.fn(() => activity), forget: vi.fn() },+ mirror: { heartbeat: vi.fn(() => deviceBusy) },+ clients: { send: vi.fn() },+ ...over,+ }+ return {+ deps,+ beats: createHeartbeats(deps),+ set: (next: { active?: boolean; turnOpen?: boolean; deviceBusy?: boolean; activity?: ActivityFrame }) => {+ if (next.active !== undefined) active = next.active+ if (next.turnOpen !== undefined) turnOpen = next.turnOpen+ if (next.deviceBusy !== undefined) deviceBusy = next.deviceBusy+ if ('activity' in next) activity = next.activity+ },+ }+}++const sentTypes = (deps: HeartbeatDeps) => vi.mocked(deps.clients.send).mock.calls.map(([frame]) => (frame as { type: string }).type)++describe('turn heartbeats', () => {+ beforeEach(() => vi.useFakeTimers())+ afterEach(() => { vi.useRealTimers(); vi.restoreAllMocks() })++ it('checks an open turn every 5 s and tells the app what the agent is doing', async () => {+ const { deps, beats, set } = setup()+ set({ activity: { state: 'working' } as ActivityFrame })+ beats.startHeartbeat('s1')+ expect(beats.heartbeats.has('s1')).toBe(true)+ await vi.advanceTimersByTimeAsync(4_999)+ expect(deps.turnActivity.check).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(1)+ expect(deps.turnActivity.check).toHaveBeenCalledWith('s1')+ expect(sentTypes(deps)).toEqual(['agent_activity', 'turn_heartbeat'])+ set({ activity: { state: 'idle' } as ActivityFrame })+ await vi.advanceTimersByTimeAsync(5_000)+ expect(sentTypes(deps)).toEqual(['agent_activity', 'turn_heartbeat', 'agent_activity'])+ set({ activity: undefined })+ await vi.advanceTimersByTimeAsync(5_000)+ expect(sentTypes(deps)).toHaveLength(3)+ beats.stopHeartbeat('s1')+ })++ it('keeps beating for the dial after the turn closes, and stops once neither needs it', async () => {+ const { deps, beats, set } = setup()+ beats.startHeartbeat('s1')+ set({ turnOpen: false, deviceBusy: true })+ await vi.advanceTimersByTimeAsync(5_000)+ expect(deps.turnActivity.check).not.toHaveBeenCalled()+ expect(beats.heartbeats.has('s1')).toBe(true)+ set({ deviceBusy: false })+ await vi.advanceTimersByTimeAsync(5_000)+ expect(beats.heartbeats.has('s1')).toBe(false)+ expect(deps.runtimeActivity.forget).toHaveBeenCalledWith('s1')+ })++ it('stops for a session that is no longer active, and forgets its activity', async () => {+ const { deps, beats, set } = setup()+ beats.startHeartbeat('s1')+ set({ active: false })+ await vi.advanceTimersByTimeAsync(5_000)+ expect(beats.heartbeats.has('s1')).toBe(false)+ expect(deps.turnActivity.forget).toHaveBeenCalledWith('s1')+ expect(deps.mirror.heartbeat).not.toHaveBeenCalled()+ })++ it('says nothing when the heartbeat was stopped while the check ran', async () => {+ const run = setup()+ vi.mocked(run.deps.turnActivity.check).mockImplementation(async () => { run.beats.stopHeartbeat('s1') })+ run.set({ activity: { state: 'working' } as ActivityFrame })+ run.beats.startHeartbeat('s1')+ await vi.advanceTimersByTimeAsync(5_000)+ expect(run.deps.clients.send).not.toHaveBeenCalled()+ expect(run.deps.mirror.heartbeat).not.toHaveBeenCalled()+ })++ it('reports a probe that fails, and starting again replaces the running heartbeat', async () => {+ const { deps, beats } = setup()+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ vi.mocked(deps.turnActivity.check).mockRejectedValueOnce(new Error('pane gone'))+ beats.startHeartbeat('s1')+ beats.startHeartbeat('s1')+ await vi.advanceTimersByTimeAsync(5_000)+ expect(deps.turnActivity.check).toHaveBeenCalledTimes(1)+ expect(error).toHaveBeenCalledWith('[activity] probe failed:', 'Error: pane gone')+ beats.stopHeartbeat('s1')+ beats.stopHeartbeat('never-started')+ })+})diff --git a/cli/src/core/turns/heartbeats.ts b/cli/src/core/turns/heartbeats.tsnew file mode 100644index 000000000..0a35e2265--- /dev/null+++ b/cli/src/core/turns/heartbeats.ts@@ -0,0 +1,59 @@+/**+ * Turn heartbeats: while a turn is open, every few seconds, check what the agent is really doing, tell+ * the app (activity, and a heartbeat while working) and keep the dial's card alive; stop once the turn+ * is closed and the dial no longer needs it.+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 7: docs/design/2026-10-03-harnessd.md).+ */+import { correlateAgentEvent, turnHeartbeatFrame } from '../../lib/agentEvent.js'+import type { CommanderMirror } from '../../lib/commander.js'+import type { RegisteredSession } from '../../lib/registry.js'+import type { RuntimeActivityReader } from '../../lib/runtimeActivity.js'+import type { TurnActivity } from '../../lib/turnActivity.js'++export interface HeartbeatDeps {+ bySession: (sessionId: string) => RegisteredSession | undefined+ sessionTurnOpen: (sessionId: string) => boolean+ agentIdFor: (sessionId: string) => string+ runtimeActivity: Pick<RuntimeActivityReader, 'forget'>+ turnActivity: Pick<TurnActivity, 'check' | 'snapshot' | 'forget'>+ mirror: Pick<CommanderMirror, 'heartbeat'>+ /** The app. */+ clients: { send(frame: ReturnType<typeof correlateAgentEvent>): void }+}++export function createHeartbeats({ bySession, sessionTurnOpen, agentIdFor, runtimeActivity, turnActivity, mirror, clients }: HeartbeatDeps) {+ // A timer is an opportunity to inspect work, not proof that work is happening.+ // Keep polling unfinished transcripts even when their activity lease expires:+ // a missed file notification or a later completion must still be discovered.+ const TURN_HEARTBEAT_MS = 5000+ const heartbeats = new Map<string, NodeJS.Timeout>()+ const turnStartedAt = new Map<string, number>()+ const stopHeartbeat = (sessionId: string): void => {+ runtimeActivity.forget(sessionId)+ const timer = heartbeats.get(sessionId)+ if (timer) { clearInterval(timer); heartbeats.delete(sessionId) }+ }+ const startHeartbeat = (sessionId: string): void => {+ stopHeartbeat(sessionId)+ const beat = async () => {+ if (!bySession(sessionId)?.active) {+ stopHeartbeat(sessionId); turnActivity.forget(sessionId); return+ }+ if (sessionTurnOpen(sessionId)) await turnActivity.check(sessionId)+ if (!heartbeats.has(sessionId)) return+ const activity = turnActivity.snapshot(sessionId)+ if (activity) {+ clients.send(correlateAgentEvent({ type: 'agent_activity', payload: { activity } }, sessionId, agentIdFor(sessionId)))+ if (activity.state === 'working') clients.send(turnHeartbeatFrame(sessionId, agentIdFor(sessionId), activity))+ }+ const deviceBusy = mirror.heartbeat(sessionId)+ if (!sessionTurnOpen(sessionId) && !deviceBusy) stopHeartbeat(sessionId)+ }+ const timer = setInterval(() => { void beat().catch(error => console.error('[activity] probe failed:', String(error))) }, TURN_HEARTBEAT_MS)+ heartbeats.set(sessionId, timer)+ }+ return { heartbeats, turnStartedAt, stopHeartbeat, startHeartbeat }+}++export type Heartbeats = ReturnType<typeof createHeartbeats>diff --git a/cli/src/core/turns/recaps.spec.ts b/cli/src/core/turns/recaps.spec.tsnew file mode 100644index 000000000..916ae98f3--- /dev/null+++ b/cli/src/core/turns/recaps.spec.ts@@ -0,0 +1,124 @@+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { AgentNotifications } from '../../lib/agentNotifications.js'+import { SUBAGENT_IDLE_MS, type CommanderMirrorOpts } from '../../lib/commander.js'+import { deriveTurnSummary } from '../../lib/deviceRecap.js'+import { projectDisplayName, type RegisteredSession } from '../../lib/registry.js'+import type { ActivityFrame } from '../../lib/turnActivity.js'+import { createRecaps, type RecapDeps } from './recaps.js'++const dirs: string[] = []+const temp = () => { const dir = mkdtempSync(join(tmpdir(), 'core-recaps-')); dirs.push(dir); return dir }++function setup(over: Partial<RecapDeps> = {}) {+ const transcripts = temp()+ const transcriptPath = join(transcripts, 'main.jsonl')+ const live = { agentId: 'a1', sessionId: 's1', engine: 'claude', cwd: '/work/app', transcriptPath } as RegisteredSession+ const bare = { agentId: 'a2', sessionId: 's2', engine: 'claude', cwd: '/work/other' } as RegisteredSession+ const sessions = new Map([['s1', live], ['s2', bare]])+ const deps: RecapDeps = {+ notifications: new AgentNotifications(),+ turnActivity: { snapshot: vi.fn(() => undefined) },+ clients: { sendCommander: vi.fn(), send: vi.fn(), hasActiveCommander: vi.fn(() => false) },+ deviceIsWatching: vi.fn(() => true),+ cableWatchingLocal: vi.fn(() => false),+ bySession: (sessionId) => sessions.get(sessionId),+ resolve: (id) => id === 'a1' ? live : undefined,+ stopped: (agentId) => agentId === 'gone' ? ({ agentId: 'gone', sessionId: 'old-s' } as RegisteredSession) : null,+ orchestratorRoleOf: vi.fn(() => null),+ readLastTurn: vi.fn(async () => null),+ dataDir: temp(),+ recapForce: false,+ recapWithoutDevice: () => true,+ ...over,+ }+ const recaps = createRecaps(deps)+ const opts = (recaps.mirror as unknown as { opts: CommanderMirrorOpts }).opts+ return { deps, recaps, opts, live, transcriptPath }+}++describe('recaps', () => {+ afterEach(() => {+ vi.restoreAllMocks()+ for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true })+ })++ it('counts a specialist\'s turn, or a director\'s while specialists are out, as a sub-agent\'s', () => {+ const { deps, recaps } = setup()+ const role = vi.mocked(deps.orchestratorRoleOf)+ expect(recaps.isSubagentSession('nobody')).toBe(false)+ expect(recaps.isSubagentSession('s1')).toBe(false)+ role.mockReturnValueOnce({ role: 'worker' })+ expect(recaps.isSubagentSession('s1')).toBe(true)+ role.mockReturnValueOnce({ role: 'director', busy: true })+ expect(recaps.isSubagentSession('s1')).toBe(true)+ role.mockReturnValueOnce({ role: 'director', busy: false })+ expect(recaps.isSubagentSession('s1')).toBe(false)+ expect(role).toHaveBeenCalledWith('a1')+ })++ it('gives the mirror the clients, the device gates and an excerpt for a recap', async () => {+ const { deps, opts } = setup()+ vi.mocked(deps.turnActivity.snapshot).mockReturnValueOnce({ state: 'working' } as ActivityFrame).mockReturnValueOnce({ state: 'idle' } as ActivityFrame)+ expect(opts.verifiedWorking!('s1')).toBe(true)+ expect(opts.verifiedWorking!('s1')).toBe(false)+ const frame = { type: 'commander_event', agentId: 'a1', dbSessionId: 's1', payload: {} } as Parameters<CommanderMirrorOpts['send']>[0]+ opts.send(frame)+ opts.sendWeb({ type: 'turn_summary' })+ expect(deps.clients.sendCommander).toHaveBeenCalledWith(frame)+ expect(deps.clients.send).toHaveBeenCalledWith({ type: 'turn_summary' })+ expect(opts.hasDevice!()).toBe(true)+ expect(opts.active!()).toBe(false)+ vi.mocked(deps.cableWatchingLocal).mockReturnValueOnce(true)+ expect(opts.active!()).toBe(true)+ vi.mocked(deps.clients.hasActiveCommander).mockReturnValueOnce(true)+ expect(opts.active!()).toBe(true)+ expect(await opts.summarize!('The fix is in. Tests pass.')).toEqual(await deriveTurnSummary('The fix is in. Tests pass.'))+ expect(opts.summarizeIsLocal).toBe(true)+ expect(opts.notifyWithoutDevice).toBe(true)+ expect(opts.notifications).toBe(deps.notifications)+ expect(opts.readLastTurn).toBe(deps.readLastTurn)+ expect(opts.dataDir).toBe(deps.dataDir)+ expect(opts.recapForce).toBe(false)+ expect((opts.alwaysGenerate as () => boolean)()).toBe(true)+ })++ it('names agents and asks about sub-agents the way the rest of the core does', () => {+ const { deps, opts, live } = setup()+ expect(opts.nameFor!('s1')).toBe(projectDisplayName(live))+ expect(opts.nameFor!('nobody')).toBeUndefined()+ expect(opts.agentIdFor!('s1')).toBe('a1')+ expect(opts.agentIdFor!('nobody')).toBeUndefined()+ vi.mocked(deps.orchestratorRoleOf).mockReturnValueOnce({ role: 'worker' })+ expect(opts.isSubagent!('s1')).toBe(true)+ })++ it('counts a Claude Code sub-agent as at work while its own transcript is still growing', () => {+ const { opts, transcriptPath } = setup()+ expect(opts.subagentActive!('s2', 'x'), 'no transcript').toBe(false)+ expect(opts.subagentActive!('s1', 'x'), 'no sub-agent file').toBe(false)+ const file = join(transcriptPath.replace(/\.jsonl$/, ''), 'subagents', 'agent-x.jsonl')+ mkdirSync(join(file, '..'), { recursive: true })+ writeFileSync(file, '{}\n')+ expect(opts.subagentActive!('s1', 'x')).toBe(true)+ const old = (Date.now() - SUBAGENT_IDLE_MS - 60_000) / 1000+ utimesSync(file, old, old)+ expect(opts.subagentActive!('s1', 'x')).toBe(false)+ })++ it('looks recaps up under the engine session, asked for by agent, live or stopped', () => {+ const { recaps } = setup()+ const recent = vi.spyOn(recaps.mirror, 'recent').mockReturnValue([])+ const asks = vi.spyOn(recaps.mirror, 'recentAsks').mockReturnValue([])+ recaps.recent('a1', 3)+ recaps.recent('gone', 2)+ recaps.recent('s9', 1)+ recaps.recentAsks('a1', 5)+ recaps.recentAsks('gone')+ recaps.recentAsks('s9', 1)+ expect(recent.mock.calls).toEqual([['s1', 3], ['old-s', 2], ['s9', 1]])+ expect(asks.mock.calls).toEqual([['s1', 5], ['old-s', undefined], ['s9', 1]])+ })+})diff --git a/cli/src/core/turns/recaps.ts b/cli/src/core/turns/recaps.tsnew file mode 100644index 000000000..87b6f265f--- /dev/null+++ b/cli/src/core/turns/recaps.ts@@ -0,0 +1,110 @@+/**+ * Recaps: the dial's and the window's turn cards and the phone's notifications, through the commander+ * mirror. A recap is an excerpt of the answer, cut as the turn ends; a sub-agent's turn end is not+ * announced; recaps are stored under the engine session and asked for by agent.+ *+ * Moved verbatim out of `runForeground` (the core boundary, step 7: docs/design/2026-10-03-harnessd.md).+ */+import { statSync } from 'node:fs'+import { join } from 'node:path'+import type { AgentNotifications } from '../../lib/agentNotifications.js'+import { CommanderMirror, SUBAGENT_IDLE_MS, type CommanderMirrorOpts } from '../../lib/commander.js'+import { deriveTurnSummary } from '../../lib/deviceRecap.js'+import type { LastTurnText } from '../../lib/normalize.js'+import { projectDisplayName, type RegisteredSession } from '../../lib/registry.js'+import type { TurnActivity } from '../../lib/turnActivity.js'+import type { OrchestratorService } from '../../orchestrator/service.js'++type CommanderFrame = Parameters<CommanderMirrorOpts['send']>[0]+type WebFrame = Parameters<CommanderMirrorOpts['sendWeb']>[0]++export interface RecapDeps {+ notifications: AgentNotifications+ turnActivity: Pick<TurnActivity, 'snapshot'>+ /** The dial (`sendCommander`, `hasActiveCommander`) and the app (`send`). */+ clients: { sendCommander(frame: CommanderFrame): void; send(frame: WebFrame): void; hasActiveCommander(): boolean }+ deviceIsWatching: () => boolean+ cableWatchingLocal: () => boolean+ bySession: (sessionId: string) => RegisteredSession | undefined+ resolve: (id: string) => RegisteredSession | undefined+ /** A stopped agent's archived record (stoppedAgents.get). */+ stopped: (agentId: string) => RegisteredSession | null+ /** The orchestrator's role for an agent: a specialist, or the director. */+ orchestratorRoleOf: OrchestratorService['roleOf']+ readLastTurn: (sessionId: string) => Promise<LastTurnText | null>+ dataDir: string+ recapForce: boolean+ recapWithoutDevice: () => boolean+}++export function createRecaps({+ notifications, turnActivity, clients, deviceIsWatching, cableWatchingLocal, bySession, resolve, stopped,+ orchestratorRoleOf, readLastTurn, dataDir, recapForce, recapWithoutDevice,+}: RecapDeps) {+ // The recap is an excerpt of the answer, cut the moment the turn ends — no model in the loop. The+ // window, the phone and the dial show it beside the whole answer, so a model's rewrite (which cost+ // about 9 s of every turn) said again what the screen already showed.+ const summarizer: Pick<CommanderMirrorOpts, 'summarize' | 'summarizeIsLocal'> = {+ summarize: async (text) => deriveTurnSummary(text),+ summarizeIsLocal: true,+ }+ /**+ * A turn that belongs to a SUB-AGENT: an Orchestrator specialist, or its Director while specialists+ * are still out.+ *+ * Hoisted out of the commander's options because the dial is no longer the only screen that has to+ * know. The cable learns it as `silent` on the summary card; the window and the phone learn it as+ * `subagent` on `turn_ended` (see emitSessionEvents) — the phone notifies on neither. One rule, asked twice — the two surfaces used to disagree+ * here, and a four-specialist project put ONE row on the dial and FIVE marks in the window.+ *+ * ⚠️ The commander ORs this with its own `abandoned` state — a held turn released because a+ * sub-agent went silent — which lives inside it and is not reachable from here. That case is rare+ * (a killed or crashed sub-agent) and costs the window one extra mark, not five.+ */+ const isSubagentSession = (sessionId: string): boolean => {+ const agentId = bySession(sessionId)?.agentId+ if (!agentId) return false+ const role = orchestratorRoleOf(agentId)+ return role?.role === 'worker' || (role?.role === 'director' && role.busy)+ }+ const mirror = new CommanderMirror({+ notifications,+ notifyWithoutDevice: true,+ verifiedWorking: sessionId => turnActivity.snapshot(sessionId)?.state === 'working',+ send: (frame) => clients.sendCommander(frame),+ sendWeb: (frame) => clients.send(frame), // turn_summary_pending / turn_summary → web indicator+ hasDevice: () => deviceIsWatching(), // device-gate the LLM recap (mirror node)+ // Live cards stream to whatever is actually rendering. The dial has one screen and it is always the+ // one in front of the user, so a cable session counts as active by construction.+ active: () => clients.hasActiveCommander() || cableWatchingLocal(),+ ...summarizer,+ nameFor: (sessionId) => { const s = bySession(sessionId); return s ? projectDisplayName(s) : undefined },+ agentIdFor: (sessionId) => bySession(sessionId)?.agentId,+ // An Orchestrator specialist's turn end, or the Director's while specialists are still out, is not+ // announced: the person asked to hear from the main agent once, not from every sub-agent.+ isSubagent: (sessionId: string) => isSubagentSession(sessionId),+ // A claude sub-agent still at work is one whose transcript is still growing:+ // `<session>/subagents/agent-<id>.jsonl` beside the parent's (the same file enrichSubagentStats+ // reads). Written in the last SUBAGENT_IDLE_MS = alive; the held turn end waits for it.+ subagentActive: (sessionId, agentId) => {+ const transcriptPath = bySession(sessionId)?.transcriptPath+ if (!transcriptPath) return false+ try {+ const at = statSync(join(transcriptPath.replace(/\.jsonl$/, ''), 'subagents', `agent-${agentId}.jsonl`)).mtimeMs+ return Date.now() - at < SUBAGENT_IDLE_MS+ } catch { return false }+ },+ readLastTurn,+ dataDir,+ recapForce,+ alwaysGenerate: () => recapWithoutDevice(),+ })+ // Recaps are STORED under the engine session id — that is what lets `--resume` bring the last recap+ // back under a brand-new agent — but they are ASKED FOR by agent id, which is the only id the device+ // and the voice router know. Resolve across the two, or every tile restores empty.+ const recent = (id: string, n: number) => mirror.recent(resolve(id)?.sessionId || stopped(id)?.sessionId || id, n)+ const recentAsks = (id: string, n?: number) => mirror.recentAsks(resolve(id)?.sessionId || stopped(id)?.sessionId || id, n)+ return { mirror, isSubagentSession, recent, recentAsks }+}++export type Recaps = ReturnType<typeof createRecaps>