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
harnessd: session_get moves out of the socket into the core (#774)
Deeb703c70f4cf3
diff --git a/cli/src/architecture.spec.ts b/cli/src/architecture.spec.tsindex 68bc1543f..b71e55488 100644--- a/cli/src/architecture.spec.ts+++ b/cli/src/architecture.spec.ts@@ -62,7 +62,7 @@ function runForegroundLines(): number {* the code belongs in a module or a service.*/const RUN_FOREGROUND_BUDGET = 2_690-const BACKEND_SOCKET_BUDGET = 3_500+const BACKEND_SOCKET_BUDGET = 3_160/** Exceptions, each with its reason. Keep this short. */const SERVICE_MAY_IMPORT: Record<string, string> = {diff --git a/cli/src/backendSocket.cappedHistory.spec.ts b/cli/src/backendSocket.cappedHistory.spec.tsindex bb186787d..1953ce290 100644--- a/cli/src/backendSocket.cappedHistory.spec.ts+++ b/cli/src/backendSocket.cappedHistory.spec.ts@@ -28,6 +28,7 @@ vi.mock('./lib/transcriptTail.js', async (importOriginal) => {import { BackendSocket } from './backendSocket.js'import { registry } from './lib/registry.js'+import { bindHistory } from './testing/socketHistory.js'afterAll(() => rmSync(roots.base, { recursive: true, force: true }))@@ -40,6 +41,7 @@ describe('session_get past the cap, for an engine without pages', () => {beforeEach(() => {socket = new BackendSocket('fixture')+ bindHistory(socket)frames = []socket.registerLocalClient('local:capped', { sendFrame: (frame) => { frames.push(frame as never); return true }, sendBinary: () => true })vi.spyOn(console, 'warn').mockImplementation(() => {})diff --git a/cli/src/backendSocket.history.spec.ts b/cli/src/backendSocket.history.spec.tsindex 3ee8c3268..d61e4d7eb 100644--- a/cli/src/backendSocket.history.spec.ts+++ b/cli/src/backendSocket.history.spec.ts@@ -6,6 +6,7 @@ import { codexMessagesToEvents, windowCodexLines } from './engines/codex/normaliimport { messagesToEvents, subagentStatsFromRawLines, windowRawLines } from './lib/normalize.js'import { registry } from './lib/registry.js'import { tailFile } from './lib/transcriptTail.js'+import { bindHistory } from './testing/socketHistory.js'import { cl, claude, claudeScenario, codexScenario } from './testing/transcriptScenarios.js'// Transcripts are only served from the engines' own folders. Those default to this computer's real@@ -41,6 +42,7 @@ describe.each([file = join(dir, 'transcript.jsonl')writeFileSync(file, scenario().join('\n') + '\n')socket = new BackendSocket('fixture')+ bindHistory(socket)frames = []socket.registerLocalClient('local:history', { sendFrame: (frame) => { frames.push(frame as never); return true }, sendBinary: () => true })const paneId = `%${++pane}`diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.tsindex 8135cfe3e..680e89c94 100644--- a/cli/src/backendSocket.spec.ts+++ b/cli/src/backendSocket.spec.ts@@ -5,7 +5,8 @@ import { readFileSync, mkdirSync, mkdtempSync, writeFileSync, rmSync } from 'fs'import { homedir, tmpdir } from 'os'import { join } from 'path'import { fileURLToPath } from 'url'-import { AGENT_OPENED_THROTTLE_MS, BackendSocket, compactRuntimePickerModels, deviceAgentListItem, deviceAgentRow, grokHistoryPage } from './backendSocket.js'+import { AGENT_OPENED_THROTTLE_MS, BackendSocket, compactRuntimePickerModels, deviceAgentListItem, deviceAgentRow } from './backendSocket.js'+import { grokHistoryPage } from './core/transcripts/history.js'import { ServiceUnavailableError } from './core/serviceHost.js'import { AuthSessionError, type AuthSessionManager } from './lib/authSession.js'import { WS_IDLE_DEADLINE_MS as IDLE_DEADLINE_MS } from './lib/wsLiveness.js'diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex 9156072ea..c55992b95 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -26,7 +26,7 @@ import type { AutonomousDeviceService, AutonomousDeviceFrame } from './lib/autonimport { WebSocket } from 'ws'import { BACKEND_IDLE_DEADLINE_MS, watchSocketLiveness, type LivenessWatch } from './lib/wsLiveness.js'-import { stat, readdir } from 'fs/promises'+import { readdir } from 'fs/promises'import { existsSync } from 'node:fs'import { dirname, isAbsolute, join } from 'path'import { hostname, homedir } from 'os'@@ -89,37 +89,13 @@ import { DSH_ID_RE, dshSupportedEngines } from './dsh/manifest.js'import { terminalHandoffRequest } from './lib/terminalHandoff.js'import { routeVoiceTask } from './lib/voiceRouter.js'import { stoppedAgents } from './lib/stoppedAgents.js'-import { messagesToEvents, windowRawLines, SubagentStats, type SessionEvent } from './lib/normalize.js'import { TranscriptPager } from './lib/transcriptPages.js'-import { streamRecords, tailFileCapped, WHOLE_READ_CAP_BYTES } from './lib/transcriptTail.js'import { MediaPreviewError, readMediaPreviewChunk } from './lib/mediaPreview.js'import { ViewerForwarder } from './lib/viewerForwarder.js'import { InteractiveViewers } from './lib/interactiveViewer.js'import { OwnerCommands, OWNER_COMMAND_TYPES } from './lib/ownerCommands.js'import { VIEWER_DOWN_TYPES } from './lib/viewerWire.js'-import { codexMessagesToEvents } from './engines/codex/normalizer.js'-import { codexSubagentResolverFor } from './engines/codex/subagent.js'import { parseHostTheme, type HostTheme } from './lib/hostTheme.js'-import { cursorMessagesToEvents, windowCursorLines } from './engines/cursor/normalizer.js'-import { cursorConfigDir, cursorDataDir } from './engines/cursor/home.js'-import { loadCursorReplayTaskLinks } from './engines/cursor/subagent.js'-import { opencodeMessagesToEvents, windowOpencodeMessages } from './engines/opencode/normalizer.js'-import { kiloMessagesToEvents, windowKiloMessages } from './engines/kilo/normalizer.js'-import { museMessagesToEvents } from './engines/muse/normalizer.js'-import { ampMessagesToEvents } from './engines/amp/normalizer.js'-import { grokMessagesToEvents } from './engines/grok/normalizer.js'-import { agyMessagesToEvents } from './engines/agy/normalizer.js'-import { copilotMessagesToEvents } from './engines/copilot/normalizer.js'-import { ampThreadToEvents, readAmpThread } from './engines/amp/threadExport.js'-import { piMessagesToEvents, windowPiLines } from './engines/pi/normalizer.js'-import { commandcodeMessagesToEvents, windowCommandCodeLines } from './engines/commandcode/normalizer.js'-import { hermesMessagesToEvents, windowHermesMessages } from './engines/hermes/normalizer.js'-import { devinMessagesToEvents, windowDevinMessages } from './engines/devin/normalizer.js'-import { readHermesMessages } from './engines/hermes/reader.js'-import { hermesDbForSession } from './lib/hermesHome.js'-import { readDevinMessages } from './engines/devin/reader.js'-import { readOpencodeMessages } from './engines/opencode/reader.js'-import { readKiloMessages } from './engines/kilo/reader.js'import { E2eeManager, type LinkedPeer, type PairResult } from './lib/e2ee/manager.js'import { MachinePeerStore } from './lib/e2ee/machinePeers.js'import type { TerminalStreamManager } from './lib/terminalStreamManager.js'@@ -146,16 +122,6 @@ import {type TerminalP2pSignal,} from './lib/terminalP2p.js'-// OpenCode has no per-session transcript file — its history is read from this SQLite store.-const OPENCODE_DB = join(env.OPENCODE_DATA_DIR, 'opencode.db')-/** History pages and line counts for the threads clients read (lib/transcriptPages.ts). */-const transcriptPages = new TranscriptPager()-// Kilo keeps history the same way opencode does, in its own store.-const KILO_DB = join(env.KILO_DATA_DIR, 'kilo.db')-const DEVIN_DB = join(env.DEVIN_HOME, 'sessions.db')-// Hermes history likewise comes from a SQLite store, not a per-session file — one per HOME, so the-// path is the session's own (`hermesDbForSession`) rather than this machine's default.-/** Answers the device `project_recent` RPC — set by cli.ts to the CommanderMirror's `recent`. */export type RecentProvider = (sessionId: string, n: number) => Array<{ kind: string; text: string; recap?: string }>@@ -266,50 +232,6 @@ function clipDeviceAgentName(input: string): string {return `${out}${DEVICE_ELLIPSIS}`}-/**- * Amp history comes from AMP's store, not from ours.- *- * The plugin's JSONL is a record of what the plugin saw; a thread that ran before the integration existed- * — or in a pane still holding an older plugin — is simply not in it, and no local file can rebuild those- * turns. `amp threads export` returns the thread complete, including the tools Amp runs server-side.- *- * The local file stays as the FALLBACK, because an export is a network call and a pane with no history at- * all is worse than a partial one. Which source answered is logged either way: silently serving the lesser- * record is exactly how the missing tool cards went unnoticed for a day.- */-async function ampHistory(sessionId: string, lines: string[]): Promise<SessionEvent[]> {- const messages = await readAmpThread(sessionId)- if (messages) {- console.log(`[history] ${sessionId.slice(0, 12)} amp · ${messages.length} message(s) from amp's own store`)- return ampThreadToEvents(messages)- }- console.warn(`[history] ${sessionId.slice(0, 12)} amp · export unavailable — falling back to the local transcript`)- return ampMessagesToEvents(lines)-}--/** Grok has no transcript windower yet. Keep BOTH `session_get` shapes on the same real-record replay:- * web always sends a limit, while legacy callers omit it. Returning the whole small transcript for a- * page is honest (`hasMore:false`) and cannot fall through to Claude's incompatible line cursor. */-export function grokHistoryPage(lines: string[], paginated: boolean):- { events: SessionEvent[]; hasMore?: false; oldestCursor?: null } {- const events = grokMessagesToEvents(lines)- return paginated ? { events, hasMore: false, oldestCursor: null } : { events }-}--/** agy has no transcript windower either; same both-shapes replay as grok, for the same reason. */-export function agyHistoryPage(lines: string[], paginated: boolean):- { events: SessionEvent[]; hasMore?: false; oldestCursor?: null } {- const events = agyMessagesToEvents(lines)- return paginated ? { events, hasMore: false, oldestCursor: null } : { events }-}--/** Copilot has no transcript windower either; same both-shapes replay as grok and agy. */-export function copilotHistoryPage(lines: string[], paginated: boolean):- { events: SessionEvent[]; hasMore?: false; oldestCursor?: null } {- const events = copilotMessagesToEvents(lines)- return paginated ? { events, hasMore: false, oldestCursor: null } : { events }-}-export function deviceAgentListItem(raw: unknown,): { id: unknown; name?: string; engine?: ProcessEngine; selectedModel?: string | null } {@@ -390,29 +312,6 @@ export function compactRuntimePickerModels(return ordered.slice(0, DEVICE_PICKER_MAX_MODELS).map(({ id }) => ({ id }))}-/** Fill in missing sub-agent aggregates on tool_end events by reading the sub-agent's own transcript- * (`<session>/subagents/agent-<id>.jsonl`). Async/background launchers only record- * `{status:'async_launched', agentId}` in the main transcript — without this join the delegation- * card shows "0 tools · worked for 0s" forever. Best-effort per agent; missing files are skipped. */-async function enrichSubagentStats(events: SessionEvent[], transcriptPath: string): Promise<void> {- const subagentsDir = join(transcriptPath.replace(/\.jsonl$/, ''), 'subagents')- for (const e of events) {- if (e.type !== 'tool_end') continue- const sub = e.payload.subagent- if (!sub?.agentId || typeof sub.totalToolUseCount === 'number') continue- try {- // A line at a time: a long sub-agent's transcript is never held whole to count its calls.- const file = join(subagentsDir, `agent-${sub.agentId}.jsonl`)- const totals = new SubagentStats()- await streamRecords(file, 0, (await stat(file)).size, (line) => { totals.push(line) }, () => true)- const stats = totals.result()- sub.totalToolUseCount = stats.totalToolUseCount- if (sub.totalDurationMs === undefined) sub.totalDurationMs = stats.totalDurationMs- if (sub.totalTokens === undefined) sub.totalTokens = stats.totalTokens- } catch { /* subagent transcript absent (still spawning / pruned) — leave as-is */ }- }-}-/** Sections one `grid_models_list` may ask to wake — a person presses one "Show models" at a time. */const MAX_WAKES_PER_ASK = 8@@ -771,6 +670,13 @@ export class BackendSocket {recentProvider: RecentProvider | null = null/** The person's own last questions for an agent, newest first. See the `agent_recent` case. */recentAsksProvider: ((agentId: string, n: number) => string[]) | null = null+ /** Answers `session_get` with the whole reply: a conversation's history, a page at a time (cli.ts binds+ * core/transcripts/history.ts). Null answers UNSUPPORTED. */+ historyProvider: ((payload: Record<string, unknown>) => Promise<Record<string, unknown>>) | null = null+ /** History pages and line counts for the threads clients read (lib/transcriptPages.ts). `sessions_list`+ * counts lines with it here, and cli.ts hands it to the core's history for `session_get`'s pages, so a+ * transcript's line index is built once for both. */+ readonly transcriptPages = new TranscriptPager()/** Writes the structured handoff file for an agent whose engine is about to change (the* `agent_handoff_prepare` case; cli.ts wires lib/agentHandoff.ts). It resolves with where the file is,* never with text for the next engine (the desktop words that prompt itself). A `HandoffError`'s `code`@@ -2203,7 +2109,7 @@ export class BackendSocket {// lands, instead of pinning `currentSessionId` to an id no event will ever carry.if (!s || !s.sessionId) { reply(type, requestId, { sessions: [] }); return }// Counted from an index kept as the file grows (lib/transcriptPages.ts), not by reading it whole.- const messageCount = s.transcriptPath ? await transcriptPages.lineCount(s.transcriptPath) : 0+ const messageCount = s.transcriptPath ? await this.transcriptPages.lineCount(s.transcriptPath) : 0reply(type, requestId, {sessions: [{id: s.sessionId,@@ -2217,259 +2123,10 @@ export class BackendSocket {return}- case 'session_get': {- const sessionId = payload.sessionId as string | undefined- if (!sessionId) { reply(type, requestId, { error: 'MISSING_SESSION_ID' }); return }- // Only serve transcripts for a REGISTERED tmux session, read from its own trusted- // transcriptPath — never resolve an arbitrary request-supplied id to a file (that let a- // caller read any *.jsonl on the computer, incl. unshared claude history / traversal).- const s = registry.resolve(sessionId)- if (!s) { reply(type, requestId, { error: 'NOT_FOUND' }); return }- if (s.engine === 'devin') {- // Devin history comes from its SQLite store (no transcript file). Same replay/window shape.- const rawLimit = payload.limit- const limit = typeof rawLimit === 'number' && rawLimit > 0 ? Math.min(Math.floor(rawLimit), 500) : undefined- const before = typeof payload.before === 'string' ? payload.before : undefined- const messages = await readDevinMessages(DEVIN_DB, sessionId)- const timestamp = new Date(s.touchedAt).toISOString()- if (!limit) {- reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: devinMessagesToEvents(messages), timestamp, engine: s.engine })- return- }- const w = windowDevinMessages(messages, { limit, before })- if (w.staleCursor) {- reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: [], timestamp, engine: s.engine, hasMore: false, oldestCursor: null, staleCursor: true })- return- }- const events = devinMessagesToEvents(w.window)- if (before && events[events.length - 1]?.type === 'done') events.pop()- reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events, timestamp, engine: s.engine, hasMore: w.hasMore, oldestCursor: w.oldestCursor })- return- }- if (s.engine === 'hermes') {- // Hermes history lives in its SQLite store (no transcript file). Same replay/window shape.- const rawLimit = payload.limit- const limit = typeof rawLimit === 'number' && rawLimit > 0 ? Math.min(Math.floor(rawLimit), 500) : undefined- const before = typeof payload.before === 'string' ? payload.before : undefined- const messages = await readHermesMessages(await hermesDbForSession(s), sessionId)- const timestamp = new Date(s.touchedAt).toISOString()- if (!limit) {- reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: hermesMessagesToEvents(messages), timestamp, engine: s.engine })- return- }- const w = windowHermesMessages(messages, { limit, before })- if (w.staleCursor) {- reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: [], timestamp, engine: s.engine, hasMore: false, oldestCursor: null, staleCursor: true })- return- }- const events = hermesMessagesToEvents(w.window)- if (before && events[events.length - 1]?.type === 'done') events.pop()- reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events, timestamp, engine: s.engine, hasMore: w.hasMore, oldestCursor: w.oldestCursor })- return- }- if (s.engine === 'opencode') {- // OpenCode history comes from its SQLite DB (no transcript file). Same replay/window shape.- const rawLimit = payload.limit- const limit = typeof rawLimit === 'number' && rawLimit > 0 ? Math.min(Math.floor(rawLimit), 500) : undefined- const before = typeof payload.before === 'string' ? payload.before : undefined- const messages = await readOpencodeMessages(OPENCODE_DB, sessionId)- const timestamp = new Date(s.touchedAt).toISOString()- if (!limit) {- reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: opencodeMessagesToEvents(messages), timestamp, engine: s.engine })- return- }- const w = windowOpencodeMessages(messages, { limit, before })- if (w.staleCursor) {- reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: [], timestamp, engine: s.engine, hasMore: false, oldestCursor: null, staleCursor: true })- return- }- const events = opencodeMessagesToEvents(w.window)- if (before && events[events.length - 1]?.type === 'done') events.pop()- reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events, timestamp, engine: s.engine, hasMore: w.hasMore, oldestCursor: w.oldestCursor })- return- }- if (s.engine === 'kilo') {- // Kilo history likewise comes from its SQLite DB. BOTH branches below are load-bearing: the- // web client always sends a `limit`, so handling only the full-transcript one opens an empty- // pane — the exact half-dispatch this file has been caught on before. Cursors are namespaced- // `kilo:<index>` by `windowKiloMessages`, so a cursor from another engine reads as stale- // rather than silently indexing into the wrong conversation.- const rawLimit = payload.limit- const limit = typeof rawLimit === 'number' && rawLimit > 0 ? Math.min(Math.floor(rawLimit), 500) : undefined- const before = typeof payload.before === 'string' ? payload.before : undefined- const messages = await readKiloMessages(KILO_DB, sessionId)- const timestamp = new Date(s.touchedAt).toISOString()- if (!limit) {- reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: kiloMessagesToEvents(messages), timestamp, engine: s.engine })- return- }- const w = windowKiloMessages(messages, { limit, before })- if (w.staleCursor) {- reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: [], timestamp, engine: s.engine, hasMore: false, oldestCursor: null, staleCursor: true })- return- }- const events = kiloMessagesToEvents(w.window)- if (before && events[events.length - 1]?.type === 'done') events.pop()- reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events, timestamp, engine: s.engine, hasMore: w.hasMore, oldestCursor: w.oldestCursor })- return- }- if (!s.transcriptPath) {- reply(type, requestId, {- id: sessionId,- title: projectDisplayName(s),- events: [],- timestamp: new Date(s.touchedAt).toISOString(),- engine: s.engine,- hasMore: false,- oldestCursor: null,- })- return- }- // Optional pagination: `limit` = window size; `before` = uuid cursor (oldest line the- // client already holds). Absent → full transcript (legacy). Clamp limit defensively.- const rawLimit = payload.limit- const limit = typeof rawLimit === 'number' && rawLimit > 0 ? Math.min(Math.floor(rawLimit), 500) : undefined- const before = typeof payload.before === 'string' ? payload.before : undefined- if (s.engine === 'claude' || s.engine === 'codex') {- // Only the page asked for is read (lib/transcriptPages.ts): the whole history of a long session- // is more memory than the daemon has. Without a limit, the newest lines that fit a page, and- // the cursor to the rest when they do not all fit — a cursor the full-transcript reply never had.- const opts = limit ? { limit, before } : {}- const page = s.engine === 'codex'- ? await transcriptPages.codex(s.transcriptPath, opts)- : await transcriptPages.claude(s.transcriptPath, opts)- const st = await stat(s.transcriptPath).catch(() => null)- const timestamp = new Date(st?.mtimeMs ?? Date.now()).toISOString()- if (page.staleCursor) {- reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: [], timestamp, engine: s.engine, hasMore: false, oldestCursor: null, staleCursor: true })- return- }- const events = s.engine === 'codex'- ? codexMessagesToEvents(page.lines, codexSubagentResolverFor(s.codexHome))- : messagesToEvents(page.lines)- await enrichSubagentStats(events, s.transcriptPath)- // Older pages must not inject a spurious end-of-transcript marker mid-scroll.- if (limit && before && events[events.length - 1]?.type === 'done') events.pop()- reply(type, requestId, {- id: sessionId,- title: projectDisplayName(s),- events,- timestamp,- engine: s.engine,- ...(limit || page.hasMore ? { hasMore: page.hasMore, oldestCursor: page.oldestCursor } : {}),- })- return- }- // Read from the end and bounded: these engines have no pages of their own yet, and one huge- // transcript read whole would take the whole daemon down (lib/transcriptTail.ts). History past- // the cap is not shown, and the reply says so.- const { lines, truncated: capped } = await tailFileCapped(s.transcriptPath)- if (capped) console.warn(`[backend] session_get ${sid(sessionId)}: the transcript is over ${WHOLE_READ_CAP_BYTES / 1024 / 1024} MB · its oldest history is not shown`)- const truncated = capped ? { truncated: true } : {}- const st = await stat(s.transcriptPath).catch(() => null)- const timestamp = new Date(st?.mtimeMs ?? Date.now()).toISOString()-- if (!limit) {- const fullEvents = s.engine === 'cursor'- ? cursorMessagesToEvents(lines, sessionId, await loadCursorReplayTaskLinks(cursorConfigDir(), sessionId, cursorDataDir()))- : s.engine === 'muse'- ? museMessagesToEvents(lines)- : s.engine === 'amp'- ? await ampHistory(sessionId, lines)- : s.engine === 'grok'- ? grokHistoryPage(lines, false).events- : s.engine === 'agy'- ? agyHistoryPage(lines, false).events- : s.engine === 'copilot'- ? copilotHistoryPage(lines, false).events- : s.engine === 'pi'- ? piMessagesToEvents(lines)- : s.engine === 'commandcode'- ? commandcodeMessagesToEvents(lines)- : messagesToEvents(lines)- if (s.engine !== 'cursor' && s.engine !== 'pi' && s.engine !== 'commandcode' && s.engine !== 'muse' && s.engine !== 'amp' && s.engine !== 'grok' && s.engine !== 'agy' && s.engine !== 'copilot') await enrichSubagentStats(fullEvents, s.transcriptPath)- reply(type, requestId, {- id: sessionId,- title: projectDisplayName(s),- events: fullEvents,- timestamp,- engine: s.engine,- ...truncated,- })- return- }-- // Muse has no windower, so it must not fall through to the raw one: that pairs claude's- // line-uuid cursor with claude's normalizer, and a muse transcript comes back EMPTY — the web- // pane opened blank with no error anywhere. Until a muse window exists, answer the page with- // the whole transcript (`hasMore: false` ends the scroll honestly, and these sessions are- // small: a real one measured 271 lines).- // Amp is in the same position as muse and for the same reason: no windower, so falling- // through would pair claude's line-uuid cursor with claude's normalizer and return nothing.- if (s.engine === 'muse' || s.engine === 'amp' || s.engine === 'grok' || s.engine === 'agy' || s.engine === 'copilot') {- const wholePage = s.engine === 'grok'- ? grokHistoryPage(lines, true)- : s.engine === 'agy'- ? agyHistoryPage(lines, true)- : s.engine === 'copilot'- ? copilotHistoryPage(lines, true)- : null- reply(type, requestId, {- id: sessionId,- title: projectDisplayName(s),- events: s.engine === 'amp'- ? await ampHistory(sessionId, lines)- : wholePage- ? wholePage.events- : museMessagesToEvents(lines),- timestamp,- engine: s.engine,- hasMore: wholePage?.hasMore ?? false,- oldestCursor: wholePage?.oldestCursor ?? null,- ...truncated,- })- return- }- const w = s.engine === 'cursor'- ? windowCursorLines(lines, { limit, before })- : s.engine === 'pi'- ? windowPiLines(lines, { limit, before })- : s.engine === 'commandcode'- ? windowCommandCodeLines(lines, { limit, before })- : windowRawLines(lines, { limit, before })- if (w.staleCursor) {- reply(type, requestId, { id: sessionId, title: projectDisplayName(s), events: [], timestamp, engine: s.engine, hasMore: false, oldestCursor: null, staleCursor: true, ...truncated })- return- }- const events = s.engine === 'cursor'- ? cursorMessagesToEvents(- w.window,- sessionId,- await loadCursorReplayTaskLinks(cursorConfigDir(), sessionId, cursorDataDir()),- 'startIndex' in w && typeof w.startIndex === 'number' ? w.startIndex : 0,- 'initialTodos' in w && Array.isArray(w.initialTodos) ? w.initialTodos : [],- )- : s.engine === 'pi'- ? piMessagesToEvents(w.window)- : s.engine === 'commandcode'- ? commandcodeMessagesToEvents(w.window)- : messagesToEvents(w.window)- // muse and amp are answered above and never reach here, so both are absent by design.- if (s.engine !== 'cursor' && s.engine !== 'pi' && s.engine !== 'commandcode') await enrichSubagentStats(events, s.transcriptPath)- // Older pages must not inject a spurious end-of-transcript marker mid-scroll.- if (before && events[events.length - 1]?.type === 'done') events.pop()- reply(type, requestId, {- id: sessionId,- title: projectDisplayName(s),- events,- timestamp,- engine: s.engine,- hasMore: w.hasMore,- oldestCursor: w.oldestCursor,- ...truncated,- })+ // A conversation's history, a page at a time (core/transcripts/history.ts, bound by cli.ts).+ case 'session_get':+ reply(type, requestId, this.historyProvider ? await this.historyProvider(payload) : { error: 'UNSUPPORTED' })return- }case 'grid_models_list': {// Every grid this computer is signed into, in sections, the account's own first. `gridName`diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex b458c7928..640273706 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -142,6 +142,7 @@ import { createAgyBackstop } from './core/turns/agyBackstop.js'import { createIngest } from './core/transcripts/ingest.js'import { createTurnHooks } from './core/turns/turnHooks.js'import { createAttach } from './core/transcripts/attach.js'+import { createHistory } from './core/transcripts/history.js'import { createRelaunchMarks, transcriptSize } from './core/transcripts/relaunch.js'import { createForgetSession } from './core/agents/forget.js'import { createBinding } from './core/agents/bind.js'@@ -2066,6 +2067,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {const attachSession = attach.attachSessionconst neverFoldedHistory = attach.neverFoldedHistoryconst replayedFirstTurn = attach.replayedFirstTurn+ // A conversation's history, a page at a time, for a window that asks (core/transcripts/history.ts).+ backend.historyProvider = createHistory({+ resolve: (id) => registry.resolve(id),+ pages: backend.transcriptPages,+ dbs: { opencode: OPENCODE_DB, kilo: KILO_DB, devin: DEVIN_DB },+ hermesDb: (s) => hermesDbForSession(s),+ }).sessionGet// Everything the core writes into a pane, and the device's pane lock (core/input.ts).const inputs = createInput({resolve: (id) => registry.resolve(id),diff --git a/cli/src/core/transcripts/history.spec.ts b/cli/src/core/transcripts/history.spec.tsnew file mode 100644index 000000000..2d51f47af--- /dev/null+++ b/cli/src/core/transcripts/history.spec.ts@@ -0,0 +1,461 @@+import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { readAmpThread } from '../../engines/amp/threadExport.js'+import { codexMessagesToEvents } from '../../engines/codex/normalizer.js'+import { codexSubagentResolverFor } from '../../engines/codex/subagent.js'+import { cursorMessagesToEvents, windowCursorLines } from '../../engines/cursor/normalizer.js'+import { loadCursorReplayTaskLinks } from '../../engines/cursor/subagent.js'+import { devinMessagesToEvents, windowDevinMessages } from '../../engines/devin/normalizer.js'+import { readDevinMessages } from '../../engines/devin/reader.js'+import { readHermesMessages } from '../../engines/hermes/reader.js'+import { readKiloMessages } from '../../engines/kilo/reader.js'+import { readOpencodeMessages } from '../../engines/opencode/reader.js'+import { piMessagesToEvents } from '../../engines/pi/normalizer.js'+import { sid } from '../../lib/log.js'+import { messagesToEvents, windowRawLines } from '../../lib/normalize.js'+import type { RegisteredSession } from '../../lib/registry.js'+import type { HistoryPage } from '../../lib/transcriptPages.js'+import { tailFileCapped } from '../../lib/transcriptTail.js'+import { agyHistoryPage, copilotHistoryPage, createHistory, grokHistoryPage } from './history.js'++/**+ * `session_get`, answered by the core: which reader, replay and window each engine's history goes+ * through, and the reply that comes back, field for field.+ *+ * The engines' own readers, replays and windows are tested with each engine; here each is a fake that+ * says who answered. A replay names itself in every event it makes and ends with the end marker, as+ * every real replay does; a window names its engine and the record a page starts at in its cursors, and+ * reads `stale` as a cursor it cannot find. Transcript reading and sub-agent totals are the real ones.+ * The whole path through the socket, with the real engines, is in backendSocket.history.spec.ts and+ * backendSocket.cappedHistory.spec.ts.+ */+const fake = vi.hoisted(() => {+ const replay = (from: string) => (records: unknown[]) => [+ ...records.map((record) => ({ type: 'text_delta', payload: { content: `${from}: ${String(record)}` } })),+ { type: 'done', payload: { result: 'success' } },+ ]+ const windowOf = (from: string) => (records: unknown[], { limit, before }: { limit: number; before?: string }) => {+ if (before === 'stale') return { window: [], hasMore: false, oldestCursor: null, staleCursor: true }+ const end = before ? Number(before.slice(from.length + 1)) : records.length+ const start = Math.max(0, end - limit)+ return { window: records.slice(start, end), hasMore: start > 0, oldestCursor: `${from}:${start}` }+ }+ const resolver = (): null => null+ return { replay, windowOf, resolver }+})+vi.mock('../../engines/devin/reader.js', async (real) => ({ ...await real<object>(), readDevinMessages: vi.fn(async () => ['d0', 'd1', 'd2', 'd3']) }))+vi.mock('../../engines/hermes/reader.js', async (real) => ({ ...await real<object>(), readHermesMessages: vi.fn(async () => ['h0', 'h1', 'h2', 'h3']) }))+vi.mock('../../engines/opencode/reader.js', async (real) => ({ ...await real<object>(), readOpencodeMessages: vi.fn(async () => ['o0', 'o1', 'o2', 'o3']) }))+vi.mock('../../engines/kilo/reader.js', async (real) => ({ ...await real<object>(), readKiloMessages: vi.fn(async () => ['k0', 'k1', 'k2', 'k3']) }))+vi.mock('../../engines/devin/normalizer.js', async (real) => ({ ...await real<object>(), devinMessagesToEvents: vi.fn(fake.replay('devin')), windowDevinMessages: vi.fn(fake.windowOf('devin')) }))+vi.mock('../../engines/hermes/normalizer.js', async (real) => ({ ...await real<object>(), hermesMessagesToEvents: vi.fn(fake.replay('hermes')), windowHermesMessages: vi.fn(fake.windowOf('hermes')) }))+vi.mock('../../engines/opencode/normalizer.js', async (real) => ({ ...await real<object>(), opencodeMessagesToEvents: vi.fn(fake.replay('opencode')), windowOpencodeMessages: vi.fn(fake.windowOf('opencode')) }))+vi.mock('../../engines/kilo/normalizer.js', async (real) => ({ ...await real<object>(), kiloMessagesToEvents: vi.fn(fake.replay('kilo')), windowKiloMessages: vi.fn(fake.windowOf('kilo')) }))+vi.mock('../../engines/muse/normalizer.js', async (real) => ({ ...await real<object>(), museMessagesToEvents: vi.fn(fake.replay('muse')) }))+vi.mock('../../engines/amp/normalizer.js', async (real) => ({ ...await real<object>(), ampMessagesToEvents: vi.fn(fake.replay('amp')) }))+vi.mock('../../engines/amp/threadExport.js', async (real) => ({ ...await real<object>(), readAmpThread: vi.fn(async () => null), ampThreadToEvents: vi.fn(fake.replay('amp export')) }))+vi.mock('../../engines/grok/normalizer.js', async (real) => ({ ...await real<object>(), grokMessagesToEvents: vi.fn(fake.replay('grok')) }))+vi.mock('../../engines/agy/normalizer.js', async (real) => ({ ...await real<object>(), agyMessagesToEvents: vi.fn(fake.replay('agy')) }))+vi.mock('../../engines/copilot/normalizer.js', async (real) => ({ ...await real<object>(), copilotMessagesToEvents: vi.fn(fake.replay('copilot')) }))+vi.mock('../../engines/pi/normalizer.js', async (real) => ({ ...await real<object>(), piMessagesToEvents: vi.fn(fake.replay('pi')), windowPiLines: vi.fn(fake.windowOf('pi')) }))+vi.mock('../../engines/commandcode/normalizer.js', async (real) => ({ ...await real<object>(), commandcodeMessagesToEvents: vi.fn(fake.replay('commandcode')), windowCommandCodeLines: vi.fn(fake.windowOf('commandcode')) }))+vi.mock('../../engines/cursor/normalizer.js', async (real) => ({+ ...await real<object>(),+ cursorMessagesToEvents: vi.fn((lines: unknown[]) => fake.replay('cursor')(lines)),+ windowCursorLines: vi.fn((lines: unknown[], opts: { limit: number; before?: string }) => ({ ...fake.windowOf('cursor')(lines, opts), startIndex: 7, initialTodos: ['a todo carried in'] })),+}))+vi.mock('../../engines/cursor/subagent.js', async (real) => ({ ...await real<object>(), loadCursorReplayTaskLinks: vi.fn(async () => ['a task link']) }))+vi.mock('../../engines/cursor/home.js', async (real) => ({ ...await real<object>(), cursorConfigDir: vi.fn(() => '/cursor/config'), cursorDataDir: vi.fn(() => '/cursor/data') }))+vi.mock('../../engines/codex/normalizer.js', async (real) => ({ ...await real<object>(), codexMessagesToEvents: vi.fn((lines: unknown[]) => fake.replay('codex')(lines)) }))+vi.mock('../../engines/codex/subagent.js', async (real) => ({ ...await real<object>(), codexSubagentResolverFor: vi.fn(() => fake.resolver) }))+vi.mock('../../lib/normalize.js', async (real) => ({ ...await real<object>(), messagesToEvents: vi.fn(fake.replay('claude')), windowRawLines: vi.fn(fake.windowOf('raw')) }))+vi.mock('../../lib/transcriptTail.js', async (real) => {+ const actual = await real<typeof import('../../lib/transcriptTail.js')>()+ return { ...actual, tailFileCapped: vi.fn(actual.tailFileCapped) }+})++const MTIME = new Date('2026-10-04T12:00:00.000Z')+const TOUCHED = Date.parse('2026-10-05T08:30:00.000Z')+const NOW = Date.parse('2026-10-05T09:00:00.000Z')+const replayed = (from: string, records: readonly unknown[]) => fake.replay(from)([...records])+/** A page that is not the newest: what a replay made of it, without the end marker. */+const older = (from: string, records: readonly unknown[]) => replayed(from, records).slice(0, -1)+const page = (lines: string[], hasMore: boolean, oldestCursor: string | null, staleCursor?: true): HistoryPage =>+ ({ lines, hasMore, oldestCursor, clipped: false, ...(staleCursor ? { staleCursor } : {}) })++let dir: string+beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'history-')) })+afterEach(() => {+ rmSync(dir, { recursive: true, force: true })+ vi.restoreAllMocks()+ vi.resetAllMocks()+})++const session = (engine: string, over: Partial<RegisteredSession> = {}) => ({+ agentId: `agent-${engine}`, sessionId: `${engine}-session`, engine, defaultName: 'Release notes', cwd: '/work/app',+ transcriptPath: null, touchedAt: TOUCHED, codexHome: null, ...over,+}) as RegisteredSession++/** A transcript of these lines, last written at MTIME. */+function transcript(lines: string[], name = 'session.jsonl'): string {+ const file = join(dir, name)+ writeFileSync(file, lines.map((line) => `${line}\n`).join(''))+ utimesSync(file, MTIME, MTIME)+ return file+}++function setup(s?: RegisteredSession) {+ const pages = {+ claude: vi.fn(async (_path: string, _opts: { limit?: number; before?: string }) => page([], false, null)),+ codex: vi.fn(async (_path: string, _opts: { limit?: number; before?: string }) => page([], false, null)),+ }+ const deps = {+ resolve: vi.fn((id: string) => (s && (id === s.sessionId || id === s.agentId) ? s : undefined)),+ pages,+ dbs: { opencode: '/stores/opencode.db', kilo: '/stores/kilo.db', devin: '/stores/sessions.db' },+ hermesDb: vi.fn(async () => '/profiles/work/state.db'),+ }+ return { ...createHistory(deps), deps, pages }+}++/** The fields every reply about a session carries. Their order on the wire is checked on its own. */+const about = (s: RegisteredSession, timestamp: number | Date) =>+ ({ id: s.sessionId, title: 'Release notes', timestamp: new Date(timestamp).toISOString(), engine: s.engine })++describe('what cannot be served', () => {+ it('asks for a session id, and reads only a session the registry knows', async () => {+ const { sessionGet, deps } = setup()+ expect(await sessionGet({})).toStrictEqual({ error: 'MISSING_SESSION_ID' })+ expect(await sessionGet({ sessionId: '' })).toStrictEqual({ error: 'MISSING_SESSION_ID' })+ expect(deps.resolve).not.toHaveBeenCalled()+ // Never a path: an id that names no registered session names nothing to read.+ expect(await sessionGet({ sessionId: '../../outside/secret.jsonl', limit: 5 })).toStrictEqual({ error: 'NOT_FOUND' })+ expect(deps.resolve).toHaveBeenCalledWith('../../outside/secret.jsonl')+ })++ it('answers a session whose engine has written nothing yet with an empty thread, stamped when it was last touched', async () => {+ const s = session('claude')+ const { sessionGet, pages } = setup(s)+ const reply = await sessionGet({ sessionId: s.sessionId, limit: 50 })+ expect(reply).toStrictEqual({ ...about(s, TOUCHED), events: [], hasMore: false, oldestCursor: null })+ expect(Object.keys(reply)).toEqual(['id', 'title', 'events', 'timestamp', 'engine', 'hasMore', 'oldestCursor'])+ expect(pages.claude).not.toHaveBeenCalled()+ })++ it('found by agent id too, and still answers with the id it was asked for', async () => {+ const s = session('claude')+ const { sessionGet } = setup(s)+ expect(await sessionGet({ sessionId: s.agentId })).toMatchObject({ id: s.agentId, engine: 'claude' })+ })+})++describe('the engines that keep a conversation in a database', () => {+ const engines = [+ ['devin', readDevinMessages, '/stores/sessions.db', ['d0', 'd1', 'd2', 'd3']],+ ['hermes', readHermesMessages, '/profiles/work/state.db', ['h0', 'h1', 'h2', 'h3']],+ ['opencode', readOpencodeMessages, '/stores/opencode.db', ['o0', 'o1', 'o2', 'o3']],+ ['kilo', readKiloMessages, '/stores/kilo.db', ['k0', 'k1', 'k2', 'k3']],+ ] as const++ it.each(engines)('%s: the whole conversation, read from its own store and replayed', async (engine, reader, store, messages) => {+ const s = session(engine)+ const { sessionGet, deps } = setup(s)+ const reply = await sessionGet({ sessionId: s.sessionId })+ expect(reply).toStrictEqual({ ...about(s, TOUCHED), events: replayed(engine, messages) })+ expect(Object.keys(reply)).toEqual(['id', 'title', 'events', 'timestamp', 'engine'])+ expect(reader).toHaveBeenCalledWith(store, s.sessionId)+ // Hermes keeps a store per profile, and reads the one its session lives in.+ if (engine === 'hermes') expect(deps.hermesDb).toHaveBeenCalledWith(s)+ else expect(deps.hermesDb).not.toHaveBeenCalled()+ })++ it.each(engines)('%s: the newest page, the page before it, and a cursor it cannot find', async (engine, _reader, _store, messages) => {+ const s = session(engine)+ const { sessionGet } = setup(s)+ const newest = await sessionGet({ sessionId: s.sessionId, limit: 2 })+ // The newest page ends the thread, so it keeps the end marker; an older page must not carry one.+ expect(newest).toStrictEqual({ ...about(s, TOUCHED), events: replayed(engine, messages.slice(2)), hasMore: true, oldestCursor: `${engine}:2` })+ expect(Object.keys(newest)).toEqual(['id', 'title', 'events', 'timestamp', 'engine', 'hasMore', 'oldestCursor'])+ expect(await sessionGet({ sessionId: s.sessionId, limit: 2, before: `${engine}:2` }))+ .toStrictEqual({ ...about(s, TOUCHED), events: older(engine, messages.slice(0, 2)), hasMore: false, oldestCursor: `${engine}:0` })+ const stale = await sessionGet({ sessionId: s.sessionId, limit: 2, before: 'stale' })+ expect(stale).toStrictEqual({ ...about(s, TOUCHED), events: [], hasMore: false, oldestCursor: null, staleCursor: true })+ expect(Object.keys(stale)).toEqual(['id', 'title', 'events', 'timestamp', 'engine', 'hasMore', 'oldestCursor', 'staleCursor'])+ })++ it('reads a limit that makes no sense as none, the most a page may hold, or rounded down', async () => {+ const s = session('devin')+ const { sessionGet } = setup(s)+ for (const limit of [0, -5, 'ten', null]) expect(await sessionGet({ sessionId: s.sessionId, limit })).not.toHaveProperty('hasMore')+ expect(windowDevinMessages).not.toHaveBeenCalled()+ await sessionGet({ sessionId: s.sessionId, limit: 10_000 })+ expect(windowDevinMessages).toHaveBeenLastCalledWith(['d0', 'd1', 'd2', 'd3'], { limit: 500, before: undefined })+ await sessionGet({ sessionId: s.sessionId, limit: 2.7, before: 7 })+ expect(windowDevinMessages).toHaveBeenLastCalledWith(['d0', 'd1', 'd2', 'd3'], { limit: 2, before: undefined })+ })++ it('an older page drops only an end marker: a page that ends otherwise, or holds nothing, is kept as it is', async () => {+ const s = session('devin')+ const { sessionGet } = setup(s)+ const text = { type: 'text_delta', payload: { content: 'mid-turn' } }+ vi.mocked(devinMessagesToEvents).mockReturnValueOnce([text] as never).mockReturnValueOnce([])+ expect((await sessionGet({ sessionId: s.sessionId, limit: 2, before: 'devin:2' })).events).toEqual([text])+ expect((await sessionGet({ sessionId: s.sessionId, limit: 2, before: 'devin:2' })).events).toEqual([])+ })++ it('a store that cannot be read fails the request, for the socket to answer', async () => {+ const s = session('kilo')+ const { sessionGet } = setup(s)+ vi.mocked(readKiloMessages).mockRejectedValueOnce(new Error('no sqlite3'))+ await expect(sessionGet({ sessionId: s.sessionId, limit: 2 })).rejects.toThrow('no sqlite3')+ })+})++describe('Claude Code and Codex: only the page asked for is read', () => {+ it('Claude Code: a page from the pager, replayed, stamped with the transcript\'s last write', async () => {+ const file = transcript(['c1', 'c2', 'c3'])+ const s = session('claude', { transcriptPath: file })+ const { sessionGet, pages } = setup(s)+ pages.claude.mockResolvedValueOnce(page(['c2', 'c3'], true, 'uuid-2'))+ const reply = await sessionGet({ sessionId: s.sessionId, limit: 2 })+ expect(reply).toStrictEqual({ ...about(s, MTIME), events: replayed('claude', ['c2', 'c3']), hasMore: true, oldestCursor: 'uuid-2' })+ expect(Object.keys(reply)).toEqual(['id', 'title', 'events', 'timestamp', 'engine', 'hasMore', 'oldestCursor'])+ expect(pages.claude).toHaveBeenCalledWith(file, { limit: 2, before: undefined })+ expect(pages.codex).not.toHaveBeenCalled()+ })++ it('an older page drops its end marker and nothing else; a read with no limit ignores a cursor and keeps it', async () => {+ const file = transcript(['c1', 'c2', 'c3'])+ const s = session('claude', { transcriptPath: file })+ const { sessionGet, pages } = setup(s)+ pages.claude.mockResolvedValueOnce(page(['c1'], false, 'uuid-1'))+ expect(await sessionGet({ sessionId: s.sessionId, limit: 2, before: 'uuid-2' }))+ .toStrictEqual({ ...about(s, MTIME), events: older('claude', ['c1']), hasMore: false, oldestCursor: 'uuid-1' })+ expect(pages.claude).toHaveBeenLastCalledWith(file, { limit: 2, before: 'uuid-2' })+ // Without a limit, the newest lines that fit a page: a cursor means nothing then, and the reply is the+ // full-transcript one, with no cursor while every line fit.+ pages.claude.mockResolvedValueOnce(page(['c1', 'c2', 'c3'], false, 'uuid-1'))+ const whole = await sessionGet({ sessionId: s.sessionId, before: 'uuid-2' })+ expect(whole).toStrictEqual({ ...about(s, MTIME), events: replayed('claude', ['c1', 'c2', 'c3']) })+ expect(Object.keys(whole)).toEqual(['id', 'title', 'events', 'timestamp', 'engine'])+ expect(pages.claude).toHaveBeenLastCalledWith(file, {})+ // Only an end marker is dropped: an older page that ends otherwise, or holds nothing, is kept as it is.+ const text = { type: 'text_delta', payload: { content: 'mid-turn' } }+ vi.mocked(messagesToEvents).mockReturnValueOnce([text] as never).mockReturnValueOnce([])+ expect((await sessionGet({ sessionId: s.sessionId, limit: 2, before: 'uuid-1' })).events).toEqual([text])+ expect((await sessionGet({ sessionId: s.sessionId, limit: 2, before: 'uuid-1' })).events).toEqual([])+ })++ it('without a limit, a thread longer than a page holds answers with the cursor to the rest', async () => {+ const s = session('claude', { transcriptPath: transcript(['c1', 'c2', 'c3']) })+ const { sessionGet, pages } = setup(s)+ pages.claude.mockResolvedValueOnce({ ...page(['c3'], true, 'uuid-3'), clipped: true })+ expect(await sessionGet({ sessionId: s.sessionId })).toStrictEqual({ ...about(s, MTIME), events: replayed('claude', ['c3']), hasMore: true, oldestCursor: 'uuid-3' })+ })++ it('a cursor the pager cannot find is stale, so the client reloads', async () => {+ const s = session('claude', { transcriptPath: transcript(['c1']) })+ const { sessionGet, pages } = setup(s)+ pages.claude.mockResolvedValueOnce(page([], false, null, true))+ const reply = await sessionGet({ sessionId: s.sessionId, limit: 5, before: 'not-in-this-file' })+ expect(reply).toStrictEqual({ ...about(s, MTIME), events: [], hasMore: false, oldestCursor: null, staleCursor: true })+ expect(messagesToEvents).not.toHaveBeenCalled()+ })++ it('Codex: its own pager and replay, which finds sub-agents under the home the session runs in', async () => {+ const file = transcript(['x1', 'x2'])+ const s = session('codex', { transcriptPath: file, codexHome: '/homes/codex-work' })+ const { sessionGet, pages } = setup(s)+ pages.codex.mockResolvedValueOnce(page(['x1', 'x2'], false, 'codex:0'))+ expect(await sessionGet({ sessionId: s.sessionId, limit: 5 })).toStrictEqual({ ...about(s, MTIME), events: replayed('codex', ['x1', 'x2']), hasMore: false, oldestCursor: 'codex:0' })+ expect(pages.codex).toHaveBeenCalledWith(file, { limit: 5, before: undefined })+ expect(codexSubagentResolverFor).toHaveBeenCalledWith('/homes/codex-work')+ expect(codexMessagesToEvents).toHaveBeenCalledWith(['x1', 'x2'], fake.resolver)+ expect(pages.claude).not.toHaveBeenCalled()+ })++ it('a transcript that is gone is stamped now', async () => {+ vi.spyOn(Date, 'now').mockReturnValue(NOW)+ const s = session('claude', { transcriptPath: join(dir, 'gone.jsonl') })+ const { sessionGet } = setup(s)+ expect(await sessionGet({ sessionId: s.sessionId, limit: 5 })).toStrictEqual({ ...about(s, NOW), events: replayed('claude', []), hasMore: false, oldestCursor: null })+ })+})++describe('sub-agent totals, joined from their own transcripts', () => {+ // What an async sub-agent wrote: three tool calls over a minute, 22 tokens.+ const subagent = [+ JSON.stringify({ type: 'user', timestamp: '2026-10-04T10:00:00.000Z', message: { role: 'user', content: 'go' } }),+ JSON.stringify({ type: 'assistant', timestamp: '2026-10-04T10:00:05.000Z', message: { content: [{ type: 'tool_use', id: 'a' }, { type: 'tool_use', id: 'b' }], usage: { input_tokens: 10, output_tokens: 5 } } }),+ '',+ JSON.stringify({ type: 'assistant', timestamp: '2026-10-04T10:01:00.000Z', message: { content: [{ type: 'tool_use', id: 'c' }], usage: { cache_read_input_tokens: 7 } } }),+ ]+ const end = (subagentSummary?: Record<string, unknown>) =>+ ({ type: 'tool_end', payload: { id: 't', tool: 'Task', output: '', isError: false, summary: '', ...(subagentSummary ? { subagent: subagentSummary } : {}) } })+ const writeSubagent = (id: string, lines: string[]) => {+ mkdirSync(join(dir, 'session', 'subagents'), { recursive: true })+ writeFileSync(join(dir, 'session', 'subagents', `agent-${id}.jsonl`), lines.join('\r\n'))+ }++ it('fills in only what a launch left out, read a line at a time; a sub-agent with no transcript yet is left as it is', async () => {+ writeSubagent('agent7', subagent)+ // Counted already: its transcript must not be read again (this one would count one call).+ writeSubagent('agent8', [subagent[1]])+ const s = session('claude', { transcriptPath: transcript(['c1']) })+ const { sessionGet, pages } = setup(s)+ pages.claude.mockResolvedValueOnce(page(['c1'], false, null))+ vi.mocked(messagesToEvents).mockReturnValueOnce([+ { type: 'text_delta', payload: { content: 'not a tool' } },+ end(),+ end({ agentType: 'Explore' }),+ end({ agentId: 'agent7' }),+ end({ agentId: 'agent7', totalDurationMs: 5, totalTokens: 9 }),+ end({ agentId: 'agent8', totalToolUseCount: 4 }),+ end({ agentId: 'missing' }),+ ] as never)+ const { events } = await sessionGet({ sessionId: s.sessionId, limit: 50 }) as { events: Array<{ payload: { subagent?: unknown } }> }+ expect(events.map((event) => event.payload.subagent)).toEqual([+ undefined,+ undefined,+ { agentType: 'Explore' },+ { agentId: 'agent7', totalToolUseCount: 3, totalDurationMs: 60_000, totalTokens: 22 },+ { agentId: 'agent7', totalToolUseCount: 3, totalDurationMs: 5, totalTokens: 9 },+ { agentId: 'agent8', totalToolUseCount: 4 },+ { agentId: 'missing' },+ ])+ })++ it('only Claude Code\'s replay is joined: the raw replay is, and an engine with its own replay is not', async () => {+ writeSubagent('agent7', subagent)+ const lines = ['l0', 'l1']+ for (const [engine, replay, limit] of [['terminal', messagesToEvents, 5], ['terminal', messagesToEvents, undefined], ['pi', piMessagesToEvents, 5], ['pi', piMessagesToEvents, undefined]] as const) {+ const s = session(engine, { transcriptPath: transcript(lines) })+ vi.mocked(replay).mockReturnValueOnce([end({ agentId: 'agent7' })] as never)+ const { events } = await setup(s).sessionGet({ sessionId: s.sessionId, limit }) as { events: Array<{ payload: { subagent?: Record<string, unknown> } }> }+ expect(events[0].payload.subagent?.totalToolUseCount, `${engine}, limit ${limit}`).toBe(engine === 'terminal' ? 3 : undefined)+ }+ })+})++describe('the other file engines: read from the end, bounded', () => {+ const lines = ['l0', 'l1', 'l2', 'l3']++ it.each([+ ['cursor', 'cursor'], ['muse', 'muse'], ['amp', 'amp'], ['grok', 'grok'], ['agy', 'agy'], ['copilot', 'copilot'],+ ['pi', 'pi'], ['commandcode', 'commandcode'],+ // An engine with no replay of its own is read as Claude Code's lines.+ ['terminal', 'claude'],+ ])('%s: the whole transcript, through its own replay', async (engine, from) => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ const file = transcript(lines)+ const s = session(engine, { transcriptPath: file })+ const { sessionGet } = setup(s)+ const reply = await sessionGet({ sessionId: s.sessionId })+ expect(reply).toStrictEqual({ ...about(s, MTIME), events: replayed(from, lines) })+ expect(Object.keys(reply)).toEqual(['id', 'title', 'events', 'timestamp', 'engine'])+ expect(tailFileCapped).toHaveBeenCalledWith(file)+ if (engine === 'cursor') {+ expect(loadCursorReplayTaskLinks).toHaveBeenCalledWith('/cursor/config', s.sessionId, '/cursor/data')+ expect(cursorMessagesToEvents).toHaveBeenCalledWith(lines, s.sessionId, ['a task link'])+ }+ })++ it.each(['muse', 'amp', 'grok', 'agy', 'copilot'])('%s has no windower: a page is the whole transcript, and says there is no more', async (engine) => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ const s = session(engine, { transcriptPath: transcript(lines) })+ const { sessionGet } = setup(s)+ const reply = await sessionGet({ sessionId: s.sessionId, limit: 2, before: 'anything' })+ expect(reply).toStrictEqual({ ...about(s, MTIME), events: replayed(engine, lines), hasMore: false, oldestCursor: null })+ expect(Object.keys(reply)).toEqual(['id', 'title', 'events', 'timestamp', 'engine', 'hasMore', 'oldestCursor'])+ // Never the raw window: its cursor and Claude Code's replay would make nothing of these lines.+ expect(windowRawLines).not.toHaveBeenCalled()+ expect(messagesToEvents).not.toHaveBeenCalled()+ })++ it('amp: from amp\'s own store when the thread exports, else the local transcript, and the log says which', async () => {+ const log = vi.spyOn(console, 'log').mockImplementation(() => {})+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const s = session('amp', { sessionId: 'T-0123456789abcdef', transcriptPath: transcript(lines) })+ const { sessionGet } = setup(s)+ vi.mocked(readAmpThread).mockResolvedValueOnce(['e1', 'e2'] as never).mockResolvedValueOnce(['e3'] as never)+ expect((await sessionGet({ sessionId: s.sessionId })).events).toEqual(replayed('amp export', ['e1', 'e2']))+ expect((await sessionGet({ sessionId: s.sessionId, limit: 5 })).events).toEqual(replayed('amp export', ['e3']))+ expect(readAmpThread).toHaveBeenCalledWith('T-0123456789abcdef')+ expect(log).toHaveBeenCalledWith('[history] T-0123456789 amp · 2 message(s) from amp\'s own store')+ expect(log).toHaveBeenCalledWith('[history] T-0123456789 amp · 1 message(s) from amp\'s own store')+ expect((await sessionGet({ sessionId: s.sessionId, limit: 5 })).events).toEqual(replayed('amp', lines))+ expect(warn).toHaveBeenCalledWith('[history] T-0123456789 amp · export unavailable — falling back to the local transcript')+ })++ it.each([+ ['cursor', 'cursor', 'cursor'], ['pi', 'pi', 'pi'], ['commandcode', 'commandcode', 'commandcode'],+ ['terminal', 'raw', 'claude'],+ ])('%s: the newest page, the page before it, and a cursor it cannot find, through its own window', async (engine, window, from) => {+ const s = session(engine, { transcriptPath: transcript(lines) })+ const { sessionGet } = setup(s)+ const newest = await sessionGet({ sessionId: s.sessionId, limit: 2 })+ expect(newest).toStrictEqual({ ...about(s, MTIME), events: replayed(from, ['l2', 'l3']), hasMore: true, oldestCursor: `${window}:2` })+ expect(Object.keys(newest)).toEqual(['id', 'title', 'events', 'timestamp', 'engine', 'hasMore', 'oldestCursor'])+ expect(await sessionGet({ sessionId: s.sessionId, limit: 2, before: `${window}:2` }))+ .toStrictEqual({ ...about(s, MTIME), events: older(from, ['l0', 'l1']), hasMore: false, oldestCursor: `${window}:0` })+ const stale = await sessionGet({ sessionId: s.sessionId, limit: 2, before: 'stale' })+ expect(stale).toStrictEqual({ ...about(s, MTIME), events: [], hasMore: false, oldestCursor: null, staleCursor: true })+ expect(Object.keys(stale)).toEqual(['id', 'title', 'events', 'timestamp', 'engine', 'hasMore', 'oldestCursor', 'staleCursor'])+ if (engine === 'cursor') {+ // A window begins mid-conversation: its replay is told where, and which todos were open there.+ expect(cursorMessagesToEvents).toHaveBeenCalledWith(['l2', 'l3'], s.sessionId, ['a task link'], 7, ['a todo carried in'])+ }+ })++ it('cursor: a window that names no start or open todos replays as from the start', async () => {+ const s = session('cursor', { transcriptPath: transcript(lines) })+ const { sessionGet } = setup(s)+ vi.mocked(windowCursorLines).mockReturnValueOnce({ window: ['l3'], hasMore: true, oldestCursor: 'cursor:3' } as never)+ await sessionGet({ sessionId: s.sessionId, limit: 1 })+ expect(cursorMessagesToEvents).toHaveBeenCalledWith(['l3'], s.sessionId, ['a task link'], 0, [])+ })++ it('an older page drops only an end marker', async () => {+ const s = session('pi', { transcriptPath: transcript(lines) })+ const { sessionGet } = setup(s)+ const text = { type: 'text_delta', payload: { content: 'mid-turn' } }+ vi.mocked(piMessagesToEvents).mockReturnValueOnce([text] as never).mockReturnValueOnce([])+ expect((await sessionGet({ sessionId: s.sessionId, limit: 2, before: 'pi:2' })).events).toEqual([text])+ expect((await sessionGet({ sessionId: s.sessionId, limit: 2, before: 'pi:2' })).events).toEqual([])+ })++ it('past the cap: the newest history, and every reply says so, as does the log', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ vi.mocked(tailFileCapped).mockResolvedValue({ lines: ['l3'], truncated: true })+ const ask = async (engine: string, payload: Record<string, unknown>) => {+ const s = session(engine, { transcriptPath: transcript(lines) })+ return { s, reply: await setup(s).sessionGet({ sessionId: s.sessionId, ...payload }) }+ }+ const whole = await ask('muse', {})+ expect(whole.reply).toStrictEqual({ ...about(whole.s, MTIME), events: replayed('muse', ['l3']), truncated: true })+ const wholePage = await ask('grok', { limit: 5 })+ expect(wholePage.reply).toStrictEqual({ ...about(wholePage.s, MTIME), events: replayed('grok', ['l3']), hasMore: false, oldestCursor: null, truncated: true })+ const windowed = await ask('pi', { limit: 5 })+ expect(windowed.reply).toStrictEqual({ ...about(windowed.s, MTIME), events: replayed('pi', ['l3']), hasMore: false, oldestCursor: 'pi:0', truncated: true })+ const stale = await ask('commandcode', { limit: 5, before: 'stale' })+ expect(stale.reply).toStrictEqual({ ...about(stale.s, MTIME), events: [], hasMore: false, oldestCursor: null, staleCursor: true, truncated: true })+ expect(warn).toHaveBeenCalledTimes(4)+ expect(warn).toHaveBeenCalledWith(`[backend] session_get ${sid('muse-session')}: the transcript is over 64 MB · its oldest history is not shown`)+ })++ it('a transcript that is gone reads as an empty one, stamped now', async () => {+ vi.spyOn(Date, 'now').mockReturnValue(NOW)+ const s = session('muse', { transcriptPath: join(dir, 'gone.jsonl') })+ const { sessionGet } = setup(s)+ expect(await sessionGet({ sessionId: s.sessionId })).toStrictEqual({ ...about(s, NOW), events: replayed('muse', []) })+ })+})++describe('the replays with no windower answer both shapes', () => {+ it.each([['grok', grokHistoryPage], ['agy', agyHistoryPage], ['copilot', copilotHistoryPage]] as const)('%s', (engine, historyPage) => {+ expect(historyPage(['l0'], false)).toStrictEqual({ events: replayed(engine, ['l0']) })+ expect(historyPage(['l0'], true)).toStrictEqual({ events: replayed(engine, ['l0']), hasMore: false, oldestCursor: null })+ })+})diff --git a/cli/src/core/transcripts/history.ts b/cli/src/core/transcripts/history.tsnew file mode 100644index 000000000..7ff17c7ed--- /dev/null+++ b/cli/src/core/transcripts/history.ts@@ -0,0 +1,333 @@+/**+ * A conversation's history, for a window that asks for it (`session_get`): the whole thread, or the page+ * before a cursor and the cursor to the page before that. The socket hands the request here and sends+ * back what comes out, so every field of the reply is decided in this file.+ *+ * Claude Code and Codex read only the page asked for (lib/transcriptPages.ts), and the other file engines+ * at most the newest 64 MB of their transcripts (lib/transcriptTail.ts), because the whole history of one+ * long session is more memory than the daemon has (the crash of 2026-10-03). The database engines still+ * read a whole conversation from their stores and cut the page from it: bounding them is engine work+ * still to come (docs/design/2026-10-03-harnessd.md, "Next").+ *+ * Moved verbatim out of the socket's request switch (docs/design/2026-10-03-harnessd.md), but for the+ * four database engines: each had its own copy of the same windowing, and they now share one.+ */+import { stat } from 'node:fs/promises'+import { join } from 'node:path'+import { agyMessagesToEvents } from '../../engines/agy/normalizer.js'+import { ampMessagesToEvents } from '../../engines/amp/normalizer.js'+import { ampThreadToEvents, readAmpThread } from '../../engines/amp/threadExport.js'+import { codexMessagesToEvents } from '../../engines/codex/normalizer.js'+import { codexSubagentResolverFor } from '../../engines/codex/subagent.js'+import { commandcodeMessagesToEvents, windowCommandCodeLines } from '../../engines/commandcode/normalizer.js'+import { copilotMessagesToEvents } from '../../engines/copilot/normalizer.js'+import { cursorConfigDir, cursorDataDir } from '../../engines/cursor/home.js'+import { cursorMessagesToEvents, windowCursorLines } from '../../engines/cursor/normalizer.js'+import { loadCursorReplayTaskLinks } from '../../engines/cursor/subagent.js'+import { devinMessagesToEvents, windowDevinMessages } from '../../engines/devin/normalizer.js'+import { readDevinMessages } from '../../engines/devin/reader.js'+import { grokMessagesToEvents } from '../../engines/grok/normalizer.js'+import { hermesMessagesToEvents, windowHermesMessages } from '../../engines/hermes/normalizer.js'+import { readHermesMessages } from '../../engines/hermes/reader.js'+import { kiloMessagesToEvents, windowKiloMessages } from '../../engines/kilo/normalizer.js'+import { readKiloMessages } from '../../engines/kilo/reader.js'+import { museMessagesToEvents } from '../../engines/muse/normalizer.js'+import { opencodeMessagesToEvents, windowOpencodeMessages } from '../../engines/opencode/normalizer.js'+import { readOpencodeMessages } from '../../engines/opencode/reader.js'+import { piMessagesToEvents, windowPiLines } from '../../engines/pi/normalizer.js'+import { sid } from '../../lib/log.js'+import { messagesToEvents, SubagentStats, windowRawLines, type SessionEvent } from '../../lib/normalize.js'+import { projectDisplayName, type RegisteredSession } from '../../lib/registry.js'+import type { TranscriptPager } from '../../lib/transcriptPages.js'+import { streamRecords, tailFileCapped, WHOLE_READ_CAP_BYTES } from '../../lib/transcriptTail.js'++export interface HistoryDeps {+ /** The registry's lookup, by agent or session id. */+ resolve: (id: string) => RegisteredSession | undefined+ /** Claude Code's and Codex's pages. The socket's pager, so the line index it keeps for a transcript is+ * shared with the line counts `sessions_list` answers, not built twice. */+ pages: Pick<TranscriptPager, 'claude' | 'codex'>+ /** 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: (session: RegisteredSession) => Promise<string>+}++/**+ * Amp history comes from AMP's store, not from ours.+ *+ * The plugin's JSONL is a record of what the plugin saw; a thread that ran before the integration existed+ * — or in a pane still holding an older plugin — is simply not in it, and no local file can rebuild those+ * turns. `amp threads export` returns the thread complete, including the tools Amp runs server-side.+ *+ * The local file stays as the FALLBACK, because an export is a network call and a pane with no history at+ * all is worse than a partial one. Which source answered is logged either way: silently serving the lesser+ * record is exactly how the missing tool cards went unnoticed for a day.+ */+async function ampHistory(sessionId: string, lines: string[]): Promise<SessionEvent[]> {+ const messages = await readAmpThread(sessionId)+ if (messages) {+ console.log(`[history] ${sessionId.slice(0, 12)} amp · ${messages.length} message(s) from amp's own store`)+ return ampThreadToEvents(messages)+ }+ console.warn(`[history] ${sessionId.slice(0, 12)} amp · export unavailable — falling back to the local transcript`)+ return ampMessagesToEvents(lines)+}++/** Grok has no transcript windower yet. Keep BOTH `session_get` shapes on the same real-record replay:+ * web always sends a limit, while legacy callers omit it. Returning the whole small transcript for a+ * page is honest (`hasMore:false`) and cannot fall through to Claude's incompatible line cursor. */+export function grokHistoryPage(lines: string[], paginated: boolean):+ { events: SessionEvent[]; hasMore?: false; oldestCursor?: null } {+ const events = grokMessagesToEvents(lines)+ return paginated ? { events, hasMore: false, oldestCursor: null } : { events }+}++/** agy has no transcript windower either; same both-shapes replay as grok, for the same reason. */+export function agyHistoryPage(lines: string[], paginated: boolean):+ { events: SessionEvent[]; hasMore?: false; oldestCursor?: null } {+ const events = agyMessagesToEvents(lines)+ return paginated ? { events, hasMore: false, oldestCursor: null } : { events }+}++/** Copilot has no transcript windower either; same both-shapes replay as grok and agy. */+export function copilotHistoryPage(lines: string[], paginated: boolean):+ { events: SessionEvent[]; hasMore?: false; oldestCursor?: null } {+ const events = copilotMessagesToEvents(lines)+ return paginated ? { events, hasMore: false, oldestCursor: null } : { events }+}++/** Fill in missing sub-agent aggregates on tool_end events by reading the sub-agent's own transcript+ * (`<session>/subagents/agent-<id>.jsonl`). Async/background launchers only record+ * `{status:'async_launched', agentId}` in the main transcript — without this join the delegation+ * card shows "0 tools · worked for 0s" forever. Best-effort per agent; missing files are skipped. */+async function enrichSubagentStats(events: SessionEvent[], transcriptPath: string): Promise<void> {+ const subagentsDir = join(transcriptPath.replace(/\.jsonl$/, ''), 'subagents')+ for (const e of events) {+ if (e.type !== 'tool_end') continue+ const sub = e.payload.subagent+ if (!sub?.agentId || typeof sub.totalToolUseCount === 'number') continue+ try {+ // A line at a time: a long sub-agent's transcript is never held whole to count its calls.+ const file = join(subagentsDir, `agent-${sub.agentId}.jsonl`)+ const totals = new SubagentStats()+ await streamRecords(file, 0, (await stat(file)).size, (line) => { totals.push(line) }, () => true)+ const stats = totals.result()+ sub.totalToolUseCount = stats.totalToolUseCount+ if (sub.totalDurationMs === undefined) sub.totalDurationMs = stats.totalDurationMs+ if (sub.totalTokens === undefined) sub.totalTokens = stats.totalTokens+ } catch { /* subagent transcript absent (still spawning / pruned) — leave as-is */ }+ }+}++/** What a window asks for: `limit` records before the `before` cursor. No limit asks for all of them. */+interface PageAsk { limit?: number; before?: string }++/** One database engine's answer to `session_get`. */+type DatabasePage = (s: RegisteredSession, sessionId: string, ask: PageAsk) => Promise<Record<string, unknown>>++/**+ * An engine that keeps its conversations in a database, not a transcript file: the conversation read+ * from its store, then replayed whole or windowed, in the same shape as every other engine's answer.+ *+ * Both shapes are load-bearing: the web client always sends a `limit`, so answering only the whole+ * conversation opens an empty pane, the half-dispatch the socket was once caught on. Each windower+ * namespaces its cursors by engine (`kilo:<index>`), so a cursor from another engine reads as stale+ * rather than silently indexing into the wrong conversation.+ */+function databasePage<M>(+ read: (s: RegisteredSession, sessionId: string) => Promise<M[]>,+ toEvents: (messages: M[]) => SessionEvent[],+ windowOf: (messages: M[], opts: { limit: number; before?: string }) =>+ { window: M[]; hasMore: boolean; oldestCursor: string | null; staleCursor?: boolean },+): DatabasePage {+ return async (s, sessionId, { limit, before }) => {+ const messages = await read(s, sessionId)+ const timestamp = new Date(s.touchedAt).toISOString()+ if (!limit) {+ return { id: sessionId, title: projectDisplayName(s), events: toEvents(messages), timestamp, engine: s.engine }+ }+ const w = windowOf(messages, { limit, before })+ if (w.staleCursor) {+ return { id: sessionId, title: projectDisplayName(s), events: [], timestamp, engine: s.engine, hasMore: false, oldestCursor: null, staleCursor: true }+ }+ const events = toEvents(w.window)+ if (before && events[events.length - 1]?.type === 'done') events.pop()+ return { id: sessionId, title: projectDisplayName(s), events, timestamp, engine: s.engine, hasMore: w.hasMore, oldestCursor: w.oldestCursor }+ }+}++export function createHistory({ resolve, pages, dbs, hermesDb }: HistoryDeps) {+ // Devin, OpenCode and Kilo keep one store on this machine. Hermes keeps one per HOME, so its path is+ // the session's own (`hermesDb`) rather than this machine's default.+ const databases = new Map<string, DatabasePage>([+ ['devin', databasePage((_s, sessionId) => readDevinMessages(dbs.devin, sessionId), devinMessagesToEvents, windowDevinMessages)],+ ['hermes', databasePage(async (s, sessionId) => readHermesMessages(await hermesDb(s), sessionId), hermesMessagesToEvents, windowHermesMessages)],+ ['opencode', databasePage((_s, sessionId) => readOpencodeMessages(dbs.opencode, sessionId), opencodeMessagesToEvents, windowOpencodeMessages)],+ ['kilo', databasePage((_s, sessionId) => readKiloMessages(dbs.kilo, sessionId), kiloMessagesToEvents, windowKiloMessages)],+ ])++ /** The reply to a `session_get` request, for the socket to send as it is. */+ const sessionGet = async (payload: Record<string, unknown>): Promise<Record<string, unknown>> => {+ const sessionId = payload.sessionId as string | undefined+ if (!sessionId) return { error: 'MISSING_SESSION_ID' }+ // Only serve transcripts for a REGISTERED tmux session, read from its own trusted+ // transcriptPath — never resolve an arbitrary request-supplied id to a file (that let a+ // caller read any *.jsonl on the computer, incl. unshared claude history / traversal).+ const s = resolve(sessionId)+ if (!s) return { error: 'NOT_FOUND' }+ // Optional pagination: `limit` = window size; `before` = cursor (the oldest record the+ // client already holds). Absent → full transcript (legacy). Clamp limit defensively.+ const rawLimit = payload.limit+ const limit = typeof rawLimit === 'number' && rawLimit > 0 ? Math.min(Math.floor(rawLimit), 500) : undefined+ const before = typeof payload.before === 'string' ? payload.before : undefined+ const database = databases.get(s.engine)+ if (database) return database(s, sessionId, { limit, before })+ if (!s.transcriptPath) {+ return {+ id: sessionId,+ title: projectDisplayName(s),+ events: [],+ timestamp: new Date(s.touchedAt).toISOString(),+ engine: s.engine,+ hasMore: false,+ oldestCursor: null,+ }+ }+ if (s.engine === 'claude' || s.engine === 'codex') {+ // Only the page asked for is read (lib/transcriptPages.ts): the whole history of a long session+ // is more memory than the daemon has. Without a limit, the newest lines that fit a page, and+ // the cursor to the rest when they do not all fit — a cursor the full-transcript reply never had.+ const opts = limit ? { limit, before } : {}+ const page = s.engine === 'codex'+ ? await pages.codex(s.transcriptPath, opts)+ : await pages.claude(s.transcriptPath, opts)+ const st = await stat(s.transcriptPath).catch(() => null)+ const timestamp = new Date(st?.mtimeMs ?? Date.now()).toISOString()+ if (page.staleCursor) {+ return { id: sessionId, title: projectDisplayName(s), events: [], timestamp, engine: s.engine, hasMore: false, oldestCursor: null, staleCursor: true }+ }+ const events = s.engine === 'codex'+ ? codexMessagesToEvents(page.lines, codexSubagentResolverFor(s.codexHome))+ : messagesToEvents(page.lines)+ await enrichSubagentStats(events, s.transcriptPath)+ // Older pages must not inject a spurious end-of-transcript marker mid-scroll.+ if (limit && before && events[events.length - 1]?.type === 'done') events.pop()+ return {+ id: sessionId,+ title: projectDisplayName(s),+ events,+ timestamp,+ engine: s.engine,+ ...(limit || page.hasMore ? { hasMore: page.hasMore, oldestCursor: page.oldestCursor } : {}),+ }+ }+ // Read from the end and bounded: these engines have no pages of their own yet, and one huge+ // transcript read whole would take the whole daemon down (lib/transcriptTail.ts). History past+ // the cap is not shown, and the reply says so.+ const { lines, truncated: capped } = await tailFileCapped(s.transcriptPath)+ if (capped) console.warn(`[backend] session_get ${sid(sessionId)}: the transcript is over ${WHOLE_READ_CAP_BYTES / 1024 / 1024} MB · its oldest history is not shown`)+ const truncated = capped ? { truncated: true } : {}+ const st = await stat(s.transcriptPath).catch(() => null)+ const timestamp = new Date(st?.mtimeMs ?? Date.now()).toISOString()++ if (!limit) {+ const fullEvents = s.engine === 'cursor'+ ? cursorMessagesToEvents(lines, sessionId, await loadCursorReplayTaskLinks(cursorConfigDir(), sessionId, cursorDataDir()))+ : s.engine === 'muse'+ ? museMessagesToEvents(lines)+ : s.engine === 'amp'+ ? await ampHistory(sessionId, lines)+ : s.engine === 'grok'+ ? grokHistoryPage(lines, false).events+ : s.engine === 'agy'+ ? agyHistoryPage(lines, false).events+ : s.engine === 'copilot'+ ? copilotHistoryPage(lines, false).events+ : s.engine === 'pi'+ ? piMessagesToEvents(lines)+ : s.engine === 'commandcode'+ ? commandcodeMessagesToEvents(lines)+ : messagesToEvents(lines)+ if (s.engine !== 'cursor' && s.engine !== 'pi' && s.engine !== 'commandcode' && s.engine !== 'muse' && s.engine !== 'amp' && s.engine !== 'grok' && s.engine !== 'agy' && s.engine !== 'copilot') await enrichSubagentStats(fullEvents, s.transcriptPath)+ return {+ id: sessionId,+ title: projectDisplayName(s),+ events: fullEvents,+ timestamp,+ engine: s.engine,+ ...truncated,+ }+ }++ // Muse has no windower, so it must not fall through to the raw one: that pairs claude's+ // line-uuid cursor with claude's normalizer, and a muse transcript comes back EMPTY — the web+ // pane opened blank with no error anywhere. Until a muse window exists, answer the page with+ // the whole transcript (`hasMore: false` ends the scroll honestly, and these sessions are+ // small: a real one measured 271 lines).+ // Amp is in the same position as muse and for the same reason: no windower, so falling+ // through would pair claude's line-uuid cursor with claude's normalizer and return nothing.+ if (s.engine === 'muse' || s.engine === 'amp' || s.engine === 'grok' || s.engine === 'agy' || s.engine === 'copilot') {+ const wholePage = s.engine === 'grok'+ ? grokHistoryPage(lines, true)+ : s.engine === 'agy'+ ? agyHistoryPage(lines, true)+ : s.engine === 'copilot'+ ? copilotHistoryPage(lines, true)+ : null+ return {+ id: sessionId,+ title: projectDisplayName(s),+ events: s.engine === 'amp'+ ? await ampHistory(sessionId, lines)+ : wholePage+ ? wholePage.events+ : museMessagesToEvents(lines),+ timestamp,+ engine: s.engine,+ hasMore: wholePage?.hasMore ?? false,+ oldestCursor: wholePage?.oldestCursor ?? null,+ ...truncated,+ }+ }+ const w = s.engine === 'cursor'+ ? windowCursorLines(lines, { limit, before })+ : s.engine === 'pi'+ ? windowPiLines(lines, { limit, before })+ : s.engine === 'commandcode'+ ? windowCommandCodeLines(lines, { limit, before })+ : windowRawLines(lines, { limit, before })+ if (w.staleCursor) {+ return { id: sessionId, title: projectDisplayName(s), events: [], timestamp, engine: s.engine, hasMore: false, oldestCursor: null, staleCursor: true, ...truncated }+ }+ const events = s.engine === 'cursor'+ ? cursorMessagesToEvents(+ w.window,+ sessionId,+ await loadCursorReplayTaskLinks(cursorConfigDir(), sessionId, cursorDataDir()),+ 'startIndex' in w && typeof w.startIndex === 'number' ? w.startIndex : 0,+ 'initialTodos' in w && Array.isArray(w.initialTodos) ? w.initialTodos : [],+ )+ : s.engine === 'pi'+ ? piMessagesToEvents(w.window)+ : s.engine === 'commandcode'+ ? commandcodeMessagesToEvents(w.window)+ : messagesToEvents(w.window)+ // muse and amp are answered above and never reach here, so both are absent by design.+ if (s.engine !== 'cursor' && s.engine !== 'pi' && s.engine !== 'commandcode') await enrichSubagentStats(events, s.transcriptPath)+ // Older pages must not inject a spurious end-of-transcript marker mid-scroll.+ if (before && events[events.length - 1]?.type === 'done') events.pop()+ return {+ id: sessionId,+ title: projectDisplayName(s),+ events,+ timestamp,+ engine: s.engine,+ hasMore: w.hasMore,+ oldestCursor: w.oldestCursor,+ ...truncated,+ }+ }++ return { sessionGet }+}diff --git a/cli/src/engines/agy/history.spec.ts b/cli/src/engines/agy/history.spec.tsindex b6123a254..e80710394 100644--- a/cli/src/engines/agy/history.spec.ts+++ b/cli/src/engines/agy/history.spec.ts@@ -1,7 +1,7 @@import { describe, expect, it } from 'vitest'import { readFileSync } from 'node:fs'import { fileURLToPath } from 'node:url'-import { agyHistoryPage } from '../../backendSocket.js'+import { agyHistoryPage } from '../../core/transcripts/history.js'const LINES = readFileSync(fileURLToPath(new URL('../../lib/__fixtures__/agy-session.jsonl', import.meta.url)), 'utf8').split('\n').filter(Boolean)diff --git a/cli/src/testing/socketHistory.ts b/cli/src/testing/socketHistory.tsnew file mode 100644index 000000000..3e716b7a4--- /dev/null+++ b/cli/src/testing/socketHistory.ts@@ -0,0 +1,21 @@+/**+ * `session_get` answered the way the daemon answers it, for a socket a spec builds on its own. The request+ * left the socket's switch for the core (core/transcripts/history.ts), and cli.ts binds it, so a bare+ * socket answers it UNSUPPORTED. This binds it the same way: over the registry, the socket's own pager and+ * the engines' stores.+ */+import { join } from 'node:path'+import type { BackendSocket } from '../backendSocket.js'+import { env } from '../config/env.js'+import { createHistory } from '../core/transcripts/history.js'+import { hermesDbForSession } from '../lib/hermesHome.js'+import { registry } from '../lib/registry.js'++export function bindHistory(socket: BackendSocket): void {+ socket.historyProvider = createHistory({+ resolve: (id) => registry.resolve(id),+ pages: socket.transcriptPages,+ dbs: { opencode: join(env.OPENCODE_DATA_DIR, 'opencode.db'), kilo: join(env.KILO_DATA_DIR, 'kilo.db'), devin: join(env.DEVIN_HOME, 'sessions.db') },+ hermesDb: (s) => hermesDbForSession(s),+ }).sessionGet+}diff --git a/docs/design/2026-10-03-harnessd.md b/docs/design/2026-10-03-harnessd.mdindex b1d058fe2..d280d639c 100644--- a/docs/design/2026-10-03-harnessd.md+++ b/docs/design/2026-10-03-harnessd.md@@ -504,6 +504,10 @@ Done so far:- **What the daemon survives** (`e2e/robustness.e2e.ts`): hostile local clients, strangers andmalformed bodies at the hook door, a pane killed from outside, a turn that outlives a restart, aturn that ends while the daemon is down, and garbage state files at start.+- **The request switch's cases go to their owners, starting with `session_get`**+ (`cli/src/core/transcripts/history.ts`, at 100%). The socket's case is one call into the slot cli.ts+ binds, and the four database engines share one windowing path instead of a copy each. Every reply is+ unchanged, field for field. `backendSocket.ts` is down from 3,482 lines to 3,139.Next, in order: