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
fix(opencode): read OpenCode 2 sessions from session_v2 and session_message, ordered by time_created + seq (#1385)
Antonio Alvino9059ba129839
diff --git a/cli/src/engines/opencode/contract.ts b/cli/src/engines/opencode/contract.tsindex 89c4d9641..7c90a444f 100644--- a/cli/src/engines/opencode/contract.ts+++ b/cli/src/engines/opencode/contract.ts@@ -21,9 +21,11 @@ export const OPENCODE_VERSION = { output: /(\d+)\.\d+\.\d+/, args: ['--version']* and writes a `user` row as a turn starts and an `idle` row as it ends — `outcome` succeeded, interrupted or* failed alike. Measured on 2.0.24's store: 550 `idle` rows since it began writing them (2026-09-28), and no* session since left with a `user` after its last `idle`.+ * Real OpenCode 2.0.29 stores show 18 row pairs that disagree with seq ordering and 40 (session_id, time_created)+ * ties. Rows are read by time_created first, seq only tying within the millisecond, the same order the readers use.*/export const OPENCODE_V2_TURN = {- sql: "SELECT type FROM session_message WHERE session_id = ? AND type IN ('user', 'idle') ORDER BY seq DESC LIMIT 1;",+ sql: "SELECT type FROM session_message WHERE session_id = ? AND type IN ('user', 'idle') ORDER BY time_created DESC, seq DESC LIMIT 1;",opens: 'user',} as constdiff --git a/cli/src/engines/opencode/normalizer.ts b/cli/src/engines/opencode/normalizer.tsindex d5a3ff8cb..82d757270 100644--- a/cli/src/engines/opencode/normalizer.ts+++ b/cli/src/engines/opencode/normalizer.ts@@ -6,7 +6,11 @@* tailer is `OpencodeReader` (polls the DB); this module holds the pure row→event mapping it shares* with the replay / recap paths (`session_get`, device recap).*- * On-disk shapes (validated against opencode 1.18.6):+ * OpenCode 2 stopped writing those tables: a conversation lives in `session_v2` and `session_message`, one row per+ * user prompt, assistant step or turn end (`ocMessageFromV2` below turns a row into the same `OcMessage` shape, so+ * everything downstream reads both versions alike).+ *+ * On-disk shapes of v1 (validated against opencode 1.18.6):* message.data = { role:'user'|'assistant', model:{providerID,modelID}, parentID?, path:{cwd,root}, tokens{…} }* part.data = discriminated by `type`:* text{text} · reasoning{text} · step-start{} · step-finish{reason:'stop',…} ·@@ -28,6 +32,8 @@ export interface OcMessage {id: stringrole: stringtimeCreated: number+ /** OpenCode 2 only: the row's `session_message.seq`, which ties a message into the same millisecond (readers order by `time_created` first, `seq` breaking the ties). */+ seq?: numberdata: Record<string, unknown>parts: OcPart[]}@@ -46,9 +52,92 @@ export function clip(value: string, limit: number): string {return value.length > limit ? `${value.slice(0, limit)}\n…[truncated]` : value}+/** A row of OpenCode 2's `session_message` table, its `data` column parsed. */+export interface OcV2Row {+ id: string+ type: string+ seq: number+ timeCreated: number+ data: Record<string, unknown>+}++/** The `session_message` types that are turns: what the user asked, what the model did, and the end of the turn. */+export const OC_V2_TURN_TYPES = ['user', 'assistant', 'idle'] as const++/**+ * One OpenCode 2 `session_message` row as the v1 message it stands for, or null for the rows that are not part+ * of the conversation (compaction, shell, synthetic, system). Shapes read off 2.0.29's own store:+ *+ * user {text, time{created}, files[], agents[]}+ * assistant {content[], finish, time{created,completed}, tokens, error?} — one row per model step, rewritten in+ * place while it streams; content items are {type:'text'|'reasoning', text} or+ * {type:'tool', id, name, state{status, input, content[{type:'text',text}|{type:'file'}], error?, metadata}, time{created,ran,completed}}+ * idle {outcome:'succeeded'|'interrupted'|'failed', time} — written when a turn ends, whatever the outcome+ *+ * Tool names are v1's, except the two v2 added that v1 has an equivalent of: `shell` is a `bash` (`TOOL_NAMES`) and+ * `subagent` a `task`, whose sub-agent session is in `metadata.sessionID`.+ *+ * A turn ends in a `step-finish` with reason `stop` in v1, which every reader already closes on, so both ways a v2+ * turn ends get one: the assistant step that finished with `stop`, and the `idle` row (the only mark of a turn that+ * was interrupted or failed). A step that finished with `tool-calls` is not an end.+ */+export function ocMessageFromV2(row: OcV2Row): OcMessage | null {+ const { id, data } = row+ const message = (role: string, parts: OcPart[]): OcMessage => ({ id, role, timeCreated: row.timeCreated, seq: row.seq, data, parts })+ const stop = (): OcPart => ({ id: `${id}:stop`, type: 'step-finish', data: { type: 'step-finish', reason: 'stop' } })+ if (row.type === 'user') {+ return message('user', [{ id: `${id}:0`, type: 'text', data: { type: 'text', text: str(data.text) } }])+ }+ if (row.type === 'idle') return message('assistant', [stop()])+ if (row.type !== 'assistant') return null+ const content = Array.isArray(data.content) ? data.content : []+ const parts: OcPart[] = []+ content.forEach((raw, index) => {+ const item = object(raw)+ if (!item) return+ const type = str(item.type)+ const partId = str(item.id) || `${id}:${index}`+ if (type === 'text' || type === 'reasoning') parts.push({ id: partId, type, data: { type, text: str(item.text) } })+ else if (type === 'tool') parts.push({ id: partId, type, data: v2ToolData(item) })+ })+ if (str(data.finish) === 'stop') parts.push(stop())+ return message('assistant', parts)+}++/** A v2 tool item in the shape of a v1 `tool` part, which `toolPartEvents` and the readers render. */+function v2ToolData(item: Record<string, unknown>): Record<string, unknown> {+ const state = object(item.state) ?? {}+ const time = object(item.time) ?? {}+ const metadata = object(state.metadata) ?? {}+ const text = (Array.isArray(state.content) ? state.content : [])+ .map((entry) => object(entry))+ .filter((entry) => entry && str(entry.type) === 'text')+ .map((entry) => str(entry!.text))+ .join('\n')+ const input = object(state.input) ?? {}+ // v2's `subagent` tool starts a child session like `task` does, with `agent` for `subagent_type`. A background+ // one is `completed` as soon as it is started (its metadata says `running`), so the card closes with the call+ // like any other: an open sub-agent row would hold the turn open.+ const subagent = str(item.name) === 'subagent'+ return {+ type: 'tool',+ tool: subagent ? 'task' : str(item.name),+ state: {+ status: str(state.status),+ input: subagent ? { ...input, subagent_type: str(input.agent) || undefined } : input,+ output: text || str(object(state.error)?.message),+ // v2 names the sub-agent's session `sessionId` on `task` and `sessionID` on `subagent`.+ metadata: { ...metadata, sessionId: str(metadata.sessionId) || str(metadata.sessionID) },+ time: { start: Number(time.ran) || Number(time.created) || 0, end: Number(time.completed) || 0 },+ },+ }+}+/** OpenCode tool ids are lowercase (`bash`, `edit`, …). Map to the Claude vocabulary the UI renders. */const TOOL_NAMES: Record<string, string> = {bash: 'Bash',+ // OpenCode 2's own shell tool: the same `command` / `workdir` / `timeout` input as `bash`.+ shell: 'Bash',edit: 'Edit',multiedit: 'Edit',patch: 'Edit',diff --git a/cli/src/engines/opencode/reader.spec.ts b/cli/src/engines/opencode/reader.spec.tsindex 56719bf73..b4e9192b8 100644--- a/cli/src/engines/opencode/reader.spec.ts+++ b/cli/src/engines/opencode/reader.spec.ts@@ -5,6 +5,7 @@ import { tmpdir } from 'os'import { join } from 'path'import { OpencodeReader, readOpencodeMessages } from './reader.js'import { opencodeV2TurnOpen } from '../launchControl.js'+import { lastOpencodeTurnText, opencodeMessagesToEvents } from './normalizer.js'import type { LiveEvent } from '../../lib/normalize.js'const hasSqlite = (() => {@@ -193,6 +194,176 @@ d('OpencodeReader (sqlite3 CLI)', () => {})})+/**+ * OpenCode 2 keeps a conversation in `session_message` (one row per prompt, assistant step and turn end) and no+ * longer writes the `message`/`part` tables. The shapes below are those of a recorded 2.0.29 store, with made-up text.+ */+d('OpencodeReader (OpenCode 2 session_message)', () => {+ let dir = ''+ let db = ''+ const CHILD = 'ses_childXYZ789'+ function v2Schema(): void {+ run(db, 'CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, type TEXT NOT NULL, seq INTEGER NOT NULL, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, data TEXT NOT NULL);')+ }+ function row(seq: number, type: string, data: Record<string, unknown>, opts: { id?: string; tc?: number; sid?: string } = {}): void {+ run(db, `INSERT INTO session_message VALUES ('${opts.id ?? `msg_${String(seq).padStart(3, '0')}`}','${opts.sid ?? SID}','${type}',${seq},${opts.tc ?? seq},${opts.tc ?? seq},'${esc(data)}');`)+ }+ const user = (seq: number, text: string, opts: { id?: string; tc?: number; sid?: string } = {}): void => row(seq, 'user', { text, time: { created: seq }, files: [], agents: [] }, opts)+ const assistant = (seq: number, content: unknown[], finish?: string, opts: { id?: string; tc?: number; sid?: string } = {}): void =>+ row(seq, 'assistant', { content, ...(finish ? { finish } : {}), time: { created: seq } }, opts)+ const idle = (seq: number, outcome: string): void => row(seq, 'idle', { outcome, time: { created: seq } })+ const tool = (id: string, name: string, status: string, input: Record<string, unknown>, text?: string, metadata: Record<string, unknown> = {}): Record<string, unknown> =>+ ({ type: 'tool', id, name, state: { status, input, content: text === undefined ? [] : [{ type: 'text', text }], metadata }, time: { created: 1, ran: 2, completed: 3 } })++ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), 'oc-reader-v2-')); db = join(dir, 'opencode.db'); schema(db); v2Schema() })+ afterEach(() => { rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }) })++ it('reads a v2 session, which has no message or part rows, as v1 messages', async () => {+ user(1, 'list the files')+ assistant(2, [+ { type: 'reasoning', text: 'I will look' },+ tool('call_1', 'bash', 'completed', { command: 'ls' }, 'a.txt\nb.txt'),+ { type: 'text', text: 'Two files.' },+ ], 'stop')+ idle(3, 'succeeded')+ row(4, 'compaction', { status: 'completed' })+ row(5, 'synthetic', { text: 'injected' })++ const messages = await readOpencodeMessages(db, SID)+ expect(messages.map((m) => [m.role, m.seq])).toEqual([['user', 1], ['assistant', 2], ['assistant', 3]])+ expect(messages[0].parts[0].data.text).toBe('list the files')+ expect(messages[1].parts.map((p) => p.type)).toEqual(['reasoning', 'tool', 'text', 'step-finish'])+ expect(messages[1].parts[1]).toMatchObject({ id: 'call_1', data: { tool: 'bash', state: { status: 'completed', input: { command: 'ls' }, output: 'a.txt\nb.txt' } } })++ const kinds = opencodeMessagesToEvents(messages).map((e) => e.type)+ expect(kinds).toEqual(['user_message', 'thinking_delta', 'tool_start', 'tool_end', 'text_delta', 'done'])+ expect(lastOpencodeTurnText(messages)).toEqual({ userMessage: 'list the files', assistantText: 'Two files.' })+ })++ it('orders by time_created, then seq — not by seq alone, which can disagree with real time in a real store', async () => {+ user(1, 'first', { id: 'msg_z', tc: 100 })+ assistant(2, [{ type: 'text', text: 'second' }], 'stop', { id: 'msg_a', tc: 100 })+ user(3, 'third', { id: 'msg_m', tc: 50 })+ const messages = await readOpencodeMessages(db, SID)+ expect(messages.map((m) => m.id)).toEqual(['msg_m', 'msg_z', 'msg_a'])+ const after = await readOpencodeMessages(db, SID, { tc: 100, id: 'msg_a', seq: 2 })+ expect(after.map((m) => m.id)).toEqual([])+ })++ it('reports a failed tool by its error and finds a sub-agent in either spelling of its session id', async () => {+ user(1, 'go')+ assistant(2, [+ { type: 'tool', id: 'call_e', name: 'read', state: { status: 'error', input: {}, content: [], error: { type: 'x', message: 'File not found' }, metadata: {} }, time: { created: 1 } },+ tool('call_t', 'task', 'completed', { description: 'Count files', subagent_type: 'general' }, '<task_result>3</task_result>', { sessionId: CHILD }),+ tool('call_s', 'subagent', 'completed', { description: 'Other' }, 'ok', { sessionID: CHILD }),+ ], 'stop')+ const parts = (await readOpencodeMessages(db, SID))[1].parts+ expect(parts[0].data.state).toMatchObject({ status: 'error', output: 'File not found' })+ expect((parts[1].data.state as { metadata: { sessionId: string } }).metadata.sessionId).toBe(CHILD)+ expect((parts[2].data.state as { metadata: { sessionId: string } }).metadata.sessionId).toBe(CHILD)+ })++ it('shows the tools v2 added as the v1 ones they stand for: shell as Bash, a sub-agent as a Task that closes with its call', async () => {+ user(1, 'go')+ assistant(2, [+ tool('call_s', 'shell', 'completed', { command: 'ls', workdir: '/work' }, 'a.txt'),+ tool('call_b', 'subagent', 'completed', { agent: 'general', description: 'Count files', prompt: 'count', background: true }, 'started', { sessionID: CHILD, status: 'running' }),+ tool('call_x', 'execute', 'completed', { code: 'return 1' }, '1'),+ ], 'stop')+ user(1, 'child prompt', { sid: CHILD, id: 'msg_c1' })+ assistant(2, [tool('c_1', 'glob', 'completed', {}, 'x')], 'stop', { sid: CHILD, id: 'msg_c2' })+ const messages = await readOpencodeMessages(db, SID)+ const events = opencodeMessagesToEvents(messages)+ const started = events.filter((e) => e.type === 'tool_start').map((e) => (e as { payload: { tool: string; input: unknown } }).payload)+ expect(started.map((p) => p.tool)).toEqual(['Bash', 'Task', 'Execute'])+ expect(started[0].input).toEqual({ command: 'ls', workdir: '/work' })+ expect(started[1].input).toEqual({ subagent_type: 'general', description: 'Count files' })+ // Even a background sub-agent, which the tool reports `running`, is closed: an open row would hold the turn open.+ expect(events.filter((e) => e.type === 'tool_end').map((e) => (e as { payload: { tool: string } }).payload.tool)).toEqual(['Bash', 'Task', 'Execute'])+ })++ it('reads a store OpenCode 2 created, which has no message or part tables', async () => {+ const fresh = join(dir, 'fresh.db')+ run(fresh, 'CREATE TABLE session_message (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, type TEXT NOT NULL, seq INTEGER NOT NULL, time_created INTEGER NOT NULL, time_updated INTEGER NOT NULL, data TEXT NOT NULL);')+ const same = db+ db = fresh+ try {+ expect(await readOpencodeMessages(db, SID)).toEqual([])+ user(1, 'hello')+ assistant(2, [{ type: 'text', text: 'hi' }], 'stop')+ expect((await readOpencodeMessages(db, SID)).map((m) => m.role)).toEqual(['user', 'assistant'])+ const events: LiveEvent[] = []+ const reader = new OpencodeReader({ dbPath: db, sessionId: SID, onEvents: (e) => events.push(...e), pollMs: 30 })+ await reader.start()+ user(3, 'again')+ await wait(150)+ reader.stop()+ expect(events).toEqual([{ type: 'turn_started', payload: { userMessage: 'again' } }])+ } finally { db = same }+ })++ it('falls back to the legacy tables when the session has no v2 rows', async () => {+ insertMessage(db, 'm1', 1, { role: 'user' }, [{ id: 'p1', tc: 1, data: { type: 'text', text: 'old v1 session' } }])+ user(1, 'a different session', { sid: 'ses_other' })+ const messages = await readOpencodeMessages(db, SID)+ expect(messages.map((m) => [m.id, m.seq])).toEqual([['m1', undefined]])+ expect(await readOpencodeMessages(db, SID, { tc: 1, id: 'm1' })).toEqual([])+ })++ it('opens the turn on attach until the assistant finishes or the turn goes idle', async () => {+ user(1, 'run the tests')+ const events: LiveEvent[] = []+ const reader = new OpencodeReader({ dbPath: db, sessionId: SID, onEvents: (e) => events.push(...e), pollMs: 600_000 })+ await reader.start(); reader.stop()+ expect(events).toEqual([{ type: 'turn_started', payload: { userMessage: 'run the tests' } }])++ assistant(2, [tool('call_1', 'bash', 'completed', { command: 'npm test' }, 'ok')], 'tool-calls')+ const mid: LiveEvent[] = []+ const midReader = new OpencodeReader({ dbPath: db, sessionId: SID, onEvents: (e) => mid.push(...e), pollMs: 600_000 })+ await midReader.start(); midReader.stop()+ expect(mid.map((e) => e.type)).toEqual(['turn_started']) // a step that ended in tool calls is not the end of the turn++ assistant(3, [{ type: 'text', text: 'passed' }], 'stop')+ const done: LiveEvent[] = []+ const doneReader = new OpencodeReader({ dbPath: db, sessionId: SID, onEvents: (e) => done.push(...e), pollMs: 600_000 })+ await doneReader.start(); doneReader.stop()+ expect(done).toEqual([])+ })++ it('streams a v2 turn live and closes it on idle, even when it was interrupted', async () => {+ user(1, 'old')+ assistant(2, [{ type: 'text', text: 'done' }], 'stop')+ idle(3, 'succeeded')+ const events: LiveEvent[] = []+ const reader = new OpencodeReader({ dbPath: db, sessionId: SID, onEvents: (e) => events.push(...e), pollMs: 30 })+ await reader.start()+ expect(events).toEqual([]) // hydrate = no replay++ user(4, 'spawn one')+ const spawn = tool('call_t', 'task', 'completed', { description: 'Count files', subagent_type: 'general' }, '<task_result>3</task_result>', { sessionId: CHILD })+ assistant(5, [spawn, { type: 'text', text: 'Hel' }])+ user(1, 'child prompt', { sid: CHILD, id: 'msg_c1' })+ assistant(2, [tool('c_1', 'glob', 'completed', {}, 'x'), tool('c_2', 'grep', 'completed', {}, 'y')], 'stop', { sid: CHILD, id: 'msg_c2' })+ await wait(200)+ run(db, `UPDATE session_message SET data='${esc({ content: [spawn, { type: 'text', text: 'Hello' }], time: { created: 5 } })}' WHERE id='msg_005';`)+ await wait(120)+ expect(reader.turnOpen).toBe(true)+ idle(6, 'interrupted') // no assistant step ever finished with `stop`+ await wait(150)+ reader.stop()++ expect(events.map((e) => e.type)).toEqual(expect.arrayContaining(['turn_started', 'tool_start', 'tool_end', 'text_delta', 'turn_ended']))+ expect(events.filter((e) => e.type === 'turn_started')).toHaveLength(1)+ expect(events.find((e) => e.type === 'turn_started')).toMatchObject({ payload: { userMessage: 'spawn one' } })+ const end = events.find((e) => e.type === 'tool_end')+ expect(end).toMatchObject({ payload: { tool: 'Task', subagent: { totalToolUseCount: 2 } } })+ const text = events.filter((e) => e.type === 'text_delta').map((e) => (e as { payload: { content: string } }).payload.content).join('')+ expect(text).toBe('Hello')+ expect(events[events.length - 1].type).toBe('turn_ended')+ expect(reader.turnOpen).toBe(false)+ })+})+d('opencodeV2TurnOpen (OpenCode 2 session_message)', () => {let dir = ''let db = ''diff --git a/cli/src/engines/opencode/reader.ts b/cli/src/engines/opencode/reader.tsindex ae95593b0..28d023d27 100644--- a/cli/src/engines/opencode/reader.ts+++ b/cli/src/engines/opencode/reader.ts@@ -8,13 +8,17 @@* engines use.** opencode 1.18.6 writes the legacy `message`/`part` tables (the newer `session_message`/`seq` tables- * exist but are empty), so those are the primary cursor.+ * exist but are empty), so those are the primary cursor. OpenCode 2 is the other way round: its conversation is+ * in `session_v2`/`session_message`, and the legacy tables only keep what v1 wrote (measured on 2.0.29: 27 recent+ * sessions with messages in `session_message` and none in `message`). A session is read from `session_message`+ * when it has rows there, else from the legacy tables, and the cursor of a v2 session is the row's `time_created`+ * with `seq` tying within the millisecond (`time_created` and `seq` disagree in real stores, so time leads).*/import type { LiveEvent } from '../../lib/normalize.js'import { sqliteReadAll } from '../../lib/sqliteRead.js'import {- MAX_OUTPUT, MAX_THINKING, clip, object, str,+ MAX_OUTPUT, MAX_THINKING, OC_V2_TURN_TYPES, clip, object, str, ocMessageFromV2,opencodeToolName, toolOutputText, toolSummary, userMessageText,isTaskPart, taskStartEvent, taskEndEvent,type OcMessage, type OcPart, type ChildStats,@@ -29,11 +33,18 @@ function parseJson(text: unknown): Record<string, unknown> {try { return object(JSON.parse(text)) ?? {} } catch { return {} }}-interface Cursor { tc: number; id: string }+/** Where a read left off. `seq` is set when the session is OpenCode 2's, ordered by `time_created` first, `seq` breaking its ties. */+interface Cursor { tc: number; id: string; seq?: number }++function cursorOf(msg: OcMessage): Cursor {+ return { tc: msg.timeCreated, id: msg.id, seq: msg.seq }+}/**- * Read messages (+ their parts) for one session from opencode.db.- * `after` restricts to messages strictly after that boundary (for incremental polling).+ * Read messages (+ their parts) for one session from opencode.db: from OpenCode 2's `session_message` when the+ * session has rows there, else from the legacy `message`/`part` tables. Either way the result is the v1 shape.+ * `after` restricts to messages strictly after that boundary (for incremental polling); a cursor with a `seq`+ * belongs to a v2 session and one without to a v1 session, so it picks the table it continues in.* Read-only, with a short busy timeout, so it never contends with opencode's writer.* Throws `OpencodeSqliteMissing` when this machine has no way to read SQLite at all.*/@@ -43,6 +54,48 @@ export async function readOpencodeMessages(after?: Cursor | null,): Promise<OcMessage[]> {if (!ID_RE.test(sessionId)) return []+ if (!after || after.seq !== undefined) {+ const afterSeq = Number.isFinite(after?.seq) ? Math.trunc(after!.seq!) : -1+ const afterTimeCreated = after?.seq !== undefined ? after.tc : undefined+ const v2 = await readV2Messages(dbPath, sessionId, afterSeq, afterTimeCreated)+ if (v2.length > 0 || after) return v2+ }+ return readLegacyMessages(dbPath, sessionId, after ?? null)+}++/** The user, assistant and idle rows of an OpenCode 2 session after `afterSeq`, in order. Empty for a v1 session. */+async function readV2Messages(dbPath: string, sessionId: string, afterSeq: number, afterTimeCreated?: number): Promise<OcMessage[]> {+ const types = OC_V2_TURN_TYPES.map((type) => `'${type}'`).join(', ')+ let sql: string+ let params: (string | number)[]+ if (afterTimeCreated !== undefined) {+ sql =+ 'SELECT m.id AS mid, m.type AS mtype, m.seq AS mseq, m.time_created AS mtc, m.data AS mdata ' ++ `FROM session_message m WHERE m.session_id = ? AND (m.time_created > ? OR (m.time_created = ? AND m.seq > ?)) AND m.type IN (${types}) ORDER BY m.time_created ASC, m.seq ASC;`+ params = [sessionId, afterTimeCreated, afterTimeCreated, afterSeq]+ } else {+ sql =+ 'SELECT m.id AS mid, m.type AS mtype, m.seq AS mseq, m.time_created AS mtc, m.data AS mdata ' ++ `FROM session_message m WHERE m.session_id = ? AND m.type IN (${types}) ORDER BY m.time_created ASC, m.seq ASC;`+ params = [sessionId]+ }+ const result = await sqliteReadAll(dbPath, sql, params, { maxBuffer: MAX_BUFFER })+ if (!result.ok) {+ if (result.reason === 'missing') throw new OpencodeSqliteMissing()+ return [] // no `session_message` table (OpenCode 1), or locked / transient — the caller falls back or retries+ }+ const messages: OcMessage[] = []+ for (const row of result.rows) {+ const message = ocMessageFromV2({+ id: str(row.mid), type: str(row.mtype), seq: Number(row.mseq) || 0, timeCreated: Number(row.mtc) || 0, data: parseJson(row.mdata),+ })+ if (message && message.id) messages.push(message)+ }+ return messages+}++/** The legacy `message`/`part` tables: OpenCode 1's conversation. */+async function readLegacyMessages(dbPath: string, sessionId: string, after: Cursor | null): Promise<OcMessage[]> {const bounded = !!after && ID_RE.test(after.id) && Number.isFinite(after.tc)const cond = bounded? 'AND (m.time_created > ? OR (m.time_created = ? AND m.id > ?)) '@@ -169,7 +222,7 @@ export class OpencodeReader {let boundary = -1for (let i = messages.length - 1; i >= 0; i--) { if (isDone(messages[i])) { boundary = i; break } }const done = boundary >= 0 ? messages[boundary] : null- this.cursor = done ? { tc: done.timeCreated, id: done.id } : null+ this.cursor = done ? cursorOf(done) : nullfor (const msg of messages) {if (msg.role === 'user') this.seenUser.add(msg.id)for (const part of msg.parts) this.seedPart(part)@@ -208,7 +261,7 @@ export class OpencodeReader {for (const msg of batch) events.push(...await this.processMessage(msg))// Advance the cursor past the trailing run of closed messages; keep an in-flight tail for re-read.for (let i = batch.length - 1; i >= 0; i--) {- if (isDone(batch[i])) { this.cursor = { tc: batch[i].timeCreated, id: batch[i].id }; break }+ if (isDone(batch[i])) { this.cursor = cursorOf(batch[i]); break }}if (events.length) this.deps.onEvents(events)} catch (err) {diff --git a/cli/src/lib/__fixtures__/usage-shapes.golden.json b/cli/src/lib/__fixtures__/usage-shapes.golden.jsonindex c9d9f40ae..e474de006 100644--- a/cli/src/lib/__fixtures__/usage-shapes.golden.json+++ b/cli/src/lib/__fixtures__/usage-shapes.golden.json@@ -195,7 +195,7 @@},"queries": [{- "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?",+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session_v2 WHERE id = ?","args": ["conversation"]@@ -213,13 +213,13 @@},"queries": [{- "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?",+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session_v2 WHERE id = ?","args": ["conversation"]},{- "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, 0 AS tokens_cache_write FROM session WHERE id = ?",+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?","args": ["conversation"]@@ -230,6 +230,12 @@"opencode/unreadable": {"value": null,"queries": [+ {+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session_v2 WHERE id = ?",+ "args": [+ "conversation"+ ]+ },{"sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?","args": [@@ -249,7 +255,7 @@"value": null,"queries": [{- "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?",+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session_v2 WHERE id = ?","args": ["conversation"]@@ -453,7 +459,7 @@},"queries": [{- "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?",+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session_v2 WHERE id = ?","args": ["conversation"]@@ -471,13 +477,13 @@},"queries": [{- "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?",+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session_v2 WHERE id = ?","args": ["conversation"]},{- "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, 0 AS tokens_cache_write FROM session WHERE id = ?",+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?","args": ["conversation"]@@ -488,6 +494,12 @@"opencode/unreadable": {"value": null,"queries": [+ {+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session_v2 WHERE id = ?",+ "args": [+ "conversation"+ ]+ },{"sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?","args": [@@ -507,7 +519,7 @@"value": null,"queries": [{- "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?",+ "sql": "SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session_v2 WHERE id = ?","args": ["conversation"]diff --git a/cli/src/lib/agentTokenUsage.spec.ts b/cli/src/lib/agentTokenUsage.spec.tsindex b65e173d2..f0e3d6ae0 100644--- a/cli/src/lib/agentTokenUsage.spec.ts+++ b/cli/src/lib/agentTokenUsage.spec.ts@@ -279,6 +279,39 @@ describe('owning-machine token cache', () => {expect(query).toHaveBeenCalledTimes(1)})+ /**+ * OpenCode 2 keeps a session in `session_v2` and no longer writes `session`: for a session v2 began the v1+ * table has no row, and a fresh store has no such table at all. v1's row is the answer for what 1.x wrote.+ */+ it('reads an OpenCode 2 session from session_v2, and falls back to the v1 row and to its older schema', async () => {+ const usage = (input: number) => ({ tokens_input: input, tokens_output: 20, tokens_reasoning: 5, tokens_cache_read: 80, tokens_cache_write: 10 })+ const ok = (rows: unknown[]) => ({ ok: true as const, via: 'builtin' as const, rows })+ const fail = { ok: false as const, reason: 'transient' as const, error: new Error('no such table') }+ const totalWith = async (answers: Record<string, unknown>) => {+ const query = vi.fn(async (_db: string, sql: string) => {+ const key = sql.includes('FROM session_v2') ? 'v2' : sql.includes('0 AS tokens_cache_write') ? 'old' : 'v1'+ return answers[key] ?? fail+ })+ store.dispose()+ store = new AgentTokenUsageCache(join(dir, `cache-${Math.random()}`), { readSqlite: query as never, now: () => now })+ target.engine = 'opencode'+ target.transcriptPath = null+ return { total: (await read())?.totalTokens ?? null, sql: query.mock.calls.map(call => call[1].match(/FROM (\w+)|0 AS/)?.[0]) }+ }++ // v2's own row, one query; it is not asked of v1.+ expect(await totalWith({ v2: ok([usage(100)]), v1: ok([usage(1)]) })).toEqual({ total: 215, sql: ['FROM session_v2'] })+ // A session 1.x wrote: v2 has no row of it.+ expect(await totalWith({ v2: ok([]), v1: ok([usage(200)]) })).toEqual({ total: 315, sql: ['FROM session_v2', 'FROM session'] })+ // A store that has no `session_v2` is OpenCode 1's.+ expect(await totalWith({ v1: ok([usage(300)]) })).toEqual({ total: 415, sql: ['FROM session_v2', 'FROM session'] })+ // 1.x before it counted cache writes, which has no such column.+ expect(await totalWith({ old: ok([{ ...usage(400), tokens_cache_write: 0 }]) })).toEqual({ total: 505, sql: ['FROM session_v2', 'FROM session', '0 AS'] })+ // v1 only holds a session when it holds it once; neither store knows it.+ expect((await totalWith({ v2: ok([]), v1: ok([]) })).total).toBeNull()+ expect((await totalWith({})).total).toBeNull()+ })+it('collects output in the same incremental pass, persists it, and does not credit inherited work', async () => {const receipt = (id: string, timestamp = at) => [{ type: 'assistant', timestamp, sessionId: 'conversation', message: { content: [{ type: 'tool_use', id, name: 'Bash', input: { command: 'gh pr create --body-file /tmp/body' } }] } },diff --git a/cli/src/lib/agentTokenUsage.ts b/cli/src/lib/agentTokenUsage.tsindex d76356810..9d16bdeb6 100644--- a/cli/src/lib/agentTokenUsage.ts+++ b/cli/src/lib/agentTokenUsage.ts@@ -305,7 +305,13 @@ export class AgentTokenUsageCache {const read = this.options.readSqlite ?? sqliteReadAllconst database = this.options.opencodeDb ?? join(env.OPENCODE_DATA_DIR, 'opencode.db')const limits = { busyTimeoutMs: 20, cliTimeoutMs: 1000, maxBuffer: 4096 }+ // OpenCode 2 keeps the session in `session_v2` and no longer writes `session`, which holds only what v1+ // wrote (and nothing of a session v2 began). Its own row is the one to read, then v1's, then v1's before+ // it counted cache writes.let result = await read(database,+ 'SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session_v2 WHERE id = ?',+ [entry.target.sessionId], limits)+ if (!result.ok || result.rows.length === 0) result = await read(database,'SELECT tokens_input, tokens_output, tokens_reasoning, tokens_cache_read, tokens_cache_write FROM session WHERE id = ?',[entry.target.sessionId], limits)if (!result.ok) result = await read(database,diff --git a/cli/src/lib/sessionRepair.spec.ts b/cli/src/lib/sessionRepair.spec.tsindex e1bed7e93..c584f14c1 100644--- a/cli/src/lib/sessionRepair.spec.ts+++ b/cli/src/lib/sessionRepair.spec.ts@@ -935,6 +935,49 @@ describe('database session repair', () => {})})+/**+ * OpenCode 2 keeps its sessions in `session_v2` (same columns) and no longer writes `session`, which stays in a+ * store 1.x made and holds only what 1.x wrote; a fresh store has no `session` at all.+ */+describe('OpenCode 2 session repair', () => {+ const t = hasSqlite ? it : it.skip+ const time = STARTED_AT + 5++ async function find(statements: string[], options: { excludedSessionId?: string } = {}) {+ const data = tempRoot()+ vi.stubEnv('XDG_DATA_HOME', data)+ mkdirSync(join(data, 'opencode'), { recursive: true })+ execFileSync('sqlite3', [join(data, 'opencode', 'opencode.db'), statements.join(';')])+ const { findLiveSession } = await load(tempRoot())+ return findLiveSession('opencode', CWD, STARTED_AT, { bornOnly: true, ...options })+ }+ const table = (name: string) => `CREATE TABLE ${name} (id TEXT, directory TEXT, parent_id TEXT, time_created INTEGER, time_updated INTEGER)`+ const row = (name: string, id: string, parent: string | null = null, updated = time) =>+ `INSERT INTO ${name} VALUES ('${id}','${CWD}',${parent ? `'${parent}'` : 'NULL'},${time},${updated})`++ t('finds the session a process started in a store that has only OpenCode 2 tables', async () => {+ await expect(find([table('session_v2'), row('session_v2', 'ses_new')])).resolves.toEqual({ sessionId: 'ses_new' })+ })++ t('reads session_v2 alone when the store has both, never the v1 rows that stopped being written', async () => {+ // The stale v1 row of a session v2 took over would be a second candidate, and a v1-only one a wrong answer.+ await expect(find([table('session'), row('session', 'ses_stale'), table('session_v2'), row('session_v2', 'ses_new')]))+ .resolves.toEqual({ sessionId: 'ses_new' })+ await expect(find([table('session'), row('session', 'ses_stale'), table('session_v2')])).resolves.toBeNull()+ })++ t('keeps the rules it has: top-level sessions only, and nothing ambiguous', async () => {+ await expect(find([table('session_v2'), row('session_v2', 'ses_parent'), row('session_v2', 'ses_child', 'ses_parent')]))+ .resolves.toEqual({ sessionId: 'ses_parent' })+ await expect(find([table('session_v2'), row('session_v2', 'ses_a'), row('session_v2', 'ses_b', null, time - 1)])).resolves.toBeNull()+ await expect(find([table('session_v2'), row('session_v2', 'ses_a')], { excludedSessionId: 'ses_a' })).resolves.toBeNull()+ })++ t('still reads OpenCode 1\'s session table in a store without session_v2', async () => {+ await expect(find([table('session'), row('session', 'ses_v1')])).resolves.toEqual({ sessionId: 'ses_v1' })+ })+})+describe('hermes repair across profile homes', () => {const t = hasSqlite ? it : it.skipconst SID_DEFAULT = '20260727_162325_e25264'diff --git a/cli/src/lib/sessionRepair.ts b/cli/src/lib/sessionRepair.tsindex a822ab21f..ee504de2a 100644--- a/cli/src/lib/sessionRepair.ts+++ b/cli/src/lib/sessionRepair.ts@@ -328,6 +328,15 @@ async function dbEngineSession(dbPath: string, sql: string, params: SqliteParam[return typeof id === 'string' && id && id !== excludedSessionId ? { sessionId: id } : null}+/**+ * Where an OpenCode store keeps its sessions: OpenCode 2's `session_v2`, which has the same columns, when the+ * store has it, else OpenCode 1's `session`. A v2 store still holds the v1 table, only what v1 wrote.+ */+async function opencodeSessionTable(dbPath: string): Promise<'session_v2' | 'session'> {+ const found = await sqliteReadAll(dbPath, "SELECT name FROM sqlite_master WHERE type='table' AND name='session_v2'", [], { maxBuffer: 4096 })+ return found.ok && found.rows.length > 0 ? 'session_v2' : 'session'+}+/** One `?` per directory, for an `IN (…)` over both spellings of the cwd. */function placeholders(count: number): string {return Array.from({ length: count }, () => '?').join(', ')@@ -474,16 +483,18 @@ export async function findLiveSession(if (!isAbsolute(root)) throw new IdentityReadUnavailable('the session working directory is invalid')return root ? { cwd: root, sessionId: basename(sessionDir) } : null}, opts)- case 'opencode':+ case 'opencode': {// time_created is epoch MILLISECONDS here.+ const database = join(env.OPENCODE_DATA_DIR, 'opencode.db')return dbEngineSession(- join(env.OPENCODE_DATA_DIR, 'opencode.db'),- `SELECT id FROM session WHERE directory IN (${dirList}) AND parent_id IS NULL`+ database,+ `SELECT id FROM ${await opencodeSessionTable(database)} WHERE directory IN (${dirList}) AND parent_id IS NULL`+ ' AND (time_created >= ? OR time_updated >= ?)'+ ' ORDER BY time_updated DESC LIMIT 2;',[...dirs, Math.trunc(sinceMs), Math.trunc(sinceMs)],opts?.excludedSessionId,)+ }case 'kilo':// Same store shape as opencode (measured: `session` is byte-identical between the two DBs), and// time_created is epoch MILLISECONDS here too — the real row on this machine reads 1786091927554.diff --git a/cli/src/lib/sessionSearch/externals/opencode.spec.ts b/cli/src/lib/sessionSearch/externals/opencode.spec.tsindex e6392f094..b581c437e 100644--- a/cli/src/lib/sessionSearch/externals/opencode.spec.ts+++ b/cli/src/lib/sessionSearch/externals/opencode.spec.ts@@ -13,7 +13,7 @@ import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitestimport { builtinSqlite, closeSqliteHandles, overrideBuiltinSqlite } from '../../sqliteBuiltin.js'import {- LIST_LIMIT, ancestry, argvSubcommand, engineProcess, opencodeListSql, opencodeProvider, opencodeTurnOpen,+ LIST_LIMIT, ancestry, argvSubcommand, engineProcess, opencodeListSql, opencodeProvider, opencodeTurnOpen, opencodeV2TurnOpen,ownerRecord, parseOwnerRecord, readSql, rowsOf, splitCounts, storeStamp, tableColumns, tally, type SqlRead,} from './opencode.js'import { scanMemo } from './support.js'@@ -68,6 +68,31 @@ CREATE INDEX \`session_project_idx\` ON \`session\` (\`project_id\`);CREATE INDEX \`session_parent_idx\` ON \`session\` (\`parent_id\`);`+/**+ * opencode 2.0.29's own DDL for the tables that replaced them (`.schema`, read-only, this machine). A store it+ * created has these and none of the above; one it took over from 1.x has both, the v1 tables no longer written.+ */+const V2_SCHEMA = `+CREATE TABLE \`session_v2\` (+ \`id\` text PRIMARY KEY, \`project_id\` text NOT NULL, \`workspace_id\` text, \`parent_id\` text, \`fork_session_id\` text,+ \`fork_boundary\` text, \`slug\` text NOT NULL, \`directory\` text NOT NULL, \`path\` text, \`title\` text, \`version\` text NOT NULL,+ \`share_url\` text, \`summary_additions\` integer, \`summary_deletions\` integer, \`summary_files\` integer, \`summary_diffs\` text,+ \`metadata\` text, \`cost\` real DEFAULT 0 NOT NULL, \`tokens_input\` integer DEFAULT 0 NOT NULL,+ \`tokens_output\` integer DEFAULT 0 NOT NULL, \`tokens_reasoning\` integer DEFAULT 0 NOT NULL,+ \`tokens_cache_read\` integer DEFAULT 0 NOT NULL, \`tokens_cache_write\` integer DEFAULT 0 NOT NULL, \`revert\` text,+ \`permission\` text, \`agent\` text, \`model\` text, \`time_created\` integer NOT NULL, \`time_updated\` integer NOT NULL,+ \`time_compacting\` integer, \`time_archived\` integer, \`time_suspended\` integer, \`resume_attempts\` integer DEFAULT 0 NOT NULL,+ \`time_idle\` integer, \`time_viewed\` integer, \`idle_outcome\` text+);+CREATE TABLE \`session_message\` (+ \`id\` text PRIMARY KEY, \`session_id\` text NOT NULL, \`type\` text NOT NULL, \`seq\` integer NOT NULL,+ \`time_created\` integer NOT NULL, \`time_updated\` integer NOT NULL, \`data\` text NOT NULL,+ CONSTRAINT \`fk_session_message_session_id_session_v2_id_fk\` FOREIGN KEY (\`session_id\`) REFERENCES \`session_v2\`(\`id\`) ON DELETE CASCADE+);+CREATE UNIQUE INDEX \`session_message_session_seq_idx\` ON \`session_message\` (\`session_id\`,\`seq\`);+CREATE INDEX \`session_message_session_type_seq_idx\` ON \`session_message\` (\`session_id\`,\`type\`,\`seq\`);+`+/** What `opencode run` writes (measured, 1.18.32): no one is there to answer a question. */const RUN_PERMISSION = JSON.stringify([{ permission: 'question', pattern: '*', action: 'deny' },@@ -93,7 +118,7 @@ class Store {this.db = new Database(path, { readOnly: false })this.db.exec('PRAGMA journal_mode = WAL')this.db.exec(schema)- if (schema === SCHEMA) {+ if (schema.includes('CREATE TABLE `project`')) {this.db.prepare("INSERT INTO project (id, worktree, time_created, time_updated, sandboxes) VALUES ('p', '/', 0, 0, '[]')").all()}}@@ -118,6 +143,35 @@ class Store {return id}+ private readonly v2seq = new Map<string, number>()++ /** A session row of OpenCode 2's `session_v2`, which has the columns of the v1 `session`. */+ v2Session(id: string, row: SessionRow = {}): this {+ this.db.prepare(+ 'INSERT INTO session_v2 (id, project_id, parent_id, slug, directory, title, version, permission, time_created, time_updated, time_archived)'+ + " VALUES (?, 'p', ?, 'slug', ?, ?, '2.0.29', ?, ?, ?, ?)",+ ).all(id, row.parent ?? null, row.directory ?? `/work/${id}`, row.title ?? 'A title', row.permission ?? null,+ T0, row.updated ?? T0, row.archived ?? null)+ return this+ }++ /** A `session_message` row: what a prompt, an assistant step and the end of a turn are made of. */+ v2Message(sessionId: string, type: string, data: Record<string, unknown>, at = T0): this {+ const seq = this.v2seq.get(sessionId) ?? 0+ this.v2seq.set(sessionId, seq + 1)+ this.db.prepare('INSERT INTO session_message (id, session_id, type, seq, time_created, time_updated, data) VALUES (?, ?, ?, ?, ?, ?, ?)')+ .all(`msg_${sessionId}_${seq}`, sessionId, type, seq, at, at, JSON.stringify(data))+ return this+ }++ /** A person's ask, a finished answer and the end of the turn, as OpenCode 2 writes them. */+ v2Turn(sessionId: string, at = T0): this {+ return this+ .v2Message(sessionId, 'user', { text: 'please fix the build', time: { created: at }, files: [], agents: [] }, at)+ .v2Message(sessionId, 'assistant', { content: [{ type: 'text', text: 'Done.' }], finish: 'stop', time: { created: at + 1, completed: at + 2 } }, at + 1)+ .v2Message(sessionId, 'idle', { outcome: 'succeeded', time: { created: at + 3 } }, at + 3)+ }+/** A person's ask and a finished answer. */turn(sessionId: string, at = T0): this {this.message(sessionId, { role: 'user', time: { created: at } }, at, [{ type: 'text', text: 'please fix the build' }])@@ -258,6 +312,115 @@ describe.each(READERS)('OpenCode discovery read through %s', (_name, reader) =>expect(existsSync(`${store.path}-shm`)).toBe(false)})+ it('lists OpenCode 2 from session_v2, whose sessions the v1 tables no longer hold', async () => {+ const store = new Store(join(tempDir(), 'opencode.db'), SCHEMA + V2_SCHEMA)+ // A session v2 took over from 1.x: in both, its headless mark only on the v1 row (v2 leaves `permission` empty).+ store.session('ses_oldrun', { permission: RUN_PERMISSION }).turn('ses_oldrun')+ store.v2Session('ses_oldrun').v2Turn('ses_oldrun')+ store.session('ses_old', { title: 'Old title', updated: T0 }).turn('ses_old')+ store.v2Session('ses_old', { title: 'Old title', updated: T0 }).v2Turn('ses_old', T0 + 1000) // answered again in v2+ // A session v2 began: no v1 row, a later message than its time_updated.+ store.v2Session('ses_new', { directory: '/work/app', title: 'Add search', updated: T0 + 10 }).v2Turn('ses_new', T0 + 50)+ store.v2Session('ses_child', { parent: 'ses_new' }).v2Turn('ses_child')+ // Compactions, shell runs and turn ends are not something said.+ store.v2Session('ses_unused').v2Message('ses_unused', 'compaction', { status: 'completed' })+ // A v1 row the store has no v2 row of is not OpenCode 2's.+ store.session('ses_stale').turn('ses_stale')++ const provider = opencodeProvider({ engine: 'opencode', dbPath: store.path })+ const found = await provider.scan(context().ctx)+ // The last prompt or answer (a turn end is not one), or time_updated when that is later.+ expect(Object.fromEntries(found.map((s) => [s.sessionId, s.mtime]))).toEqual({ ses_old: T0 + 1001, ses_new: T0 + 51 })+ expect(provider.lastScan()).toEqual({ found: 2, child: 1, headless: 1, empty: 1 })+ const session = found.find((s) => s.sessionId === 'ses_new')!+ expect(session).toMatchObject({ engine: 'opencode', cwd: '/work/app', title: 'Add search', origin: 'terminal' })+ expect((await session.readHistory!()).map((e) => e.type)).toEqual(['user_message', 'text_delta', 'done'])+ store.close()+ })++ it('lists a fresh OpenCode 2 store, which has no v1 tables at all', async () => {+ const store = new Store(join(tempDir(), 'opencode.db'), V2_SCHEMA)+ store.v2Session('ses_only', { title: 'Only v2' }).v2Turn('ses_only')+ store.v2Session('ses_none')+ const provider = opencodeProvider({ engine: 'opencode', dbPath: store.path })+ expect(await provider.scan(context().ctx)).toMatchObject([{ sessionId: 'ses_only', title: 'Only v2' }])+ expect(provider.lastScan()).toEqual({ found: 1, empty: 1 })+ store.close()+ })++ it('says from the newest turn row of an OpenCode 2 session whether a turn is running', async () => {+ const store = new Store(join(tempDir(), 'opencode.db'), V2_SCHEMA)+ const provider = opencodeProvider({ engine: 'opencode', dbPath: store.path })+ const busy = (id: string) => provider.busy!({ pid: 1, record: ownerRecord(store.path, id) })+ const step = (id: string, data: Record<string, unknown>) => store.v2Session(id).v2Message(id, 'user', { text: 'go' }).v2Message(id, 'assistant', data)+ const done = { created: T0, completed: T0 + 1 }+ const tool = (status: string) => ({ type: 'tool', id: 'call_1', name: 'bash', state: { status, input: {}, content: [], metadata: {} } })++ // No row of this session in a store that only has v2 tables: nothing was said.+ expect(await busy('ses_missing')).toBe(false)+ expect(await busy('ses_new')).toBe(false)++ store.v2Session('ses_asked').v2Message('ses_asked', 'user', { text: 'go' })+ expect(await busy('ses_asked')).toBe(true)+ step('ses_streaming', { content: [{ type: 'text', text: '...' }], time: { created: T0 } })+ expect(await busy('ses_streaming')).toBe(true)+ step('ses_stopped', { content: [{ type: 'text', text: 'Done' }], finish: 'stop', time: done })+ expect(await busy('ses_stopped')).toBe(false)+ step('ses_toolcalls', { content: [tool('completed')], finish: 'tool-calls', time: done })+ expect(await busy('ses_toolcalls')).toBe(true)+ for (const status of ['running', 'pending']) {+ step(`ses_tool${status}`, { content: [tool(status)], time: done })+ expect(await busy(`ses_tool${status}`)).toBe(true)+ }+ step('ses_failed', { content: [], finish: 'error', error: { type: 'api', message: 'x' }, time: done })+ expect(await busy('ses_failed')).toBe(false)+ step('ses_nullerror', { content: [], error: null, time: { created: T0 } })+ expect(await busy('ses_nullerror')).toBe(true)+ // The turn's end is its own row, whatever the outcome; rows that are not turns do not move it.+ store.v2Session('ses_idle').v2Turn('ses_idle').v2Message('ses_idle', 'compaction', { status: 'running' })+ expect(await busy('ses_idle')).toBe(false)+ store.v2Session('ses_interrupted').v2Message('ses_interrupted', 'user', { text: 'go' }).v2Message('ses_interrupted', 'idle', { outcome: 'interrupted' })+ expect(await busy('ses_interrupted')).toBe(false)++ expect(await provider.busy!({ pid: 1, record: ownerRecord(join(tempDir(), 'gone.db'), 'ses_x') })).toBeNull()+ store.close()+ })++ it('reads the newest v2 turn row by time_created, seq only tying the same millisecond', async () => {+ const store = new Store(join(tempDir(), 'opencode.db'), V2_SCHEMA)+ const provider = opencodeProvider({ engine: 'opencode', dbPath: store.path })+ const busy = (id: string) => provider.busy!({ pid: 1, record: ownerRecord(store.path, id) })++ // A tie (40 measured in a 2.0.29 store): the same millisecond, `seq` says which came second, the still-open step.+ store.v2Session('ses_tie')+ store.v2Message('ses_tie', 'user', { text: 'go' }, T0)+ store.v2Message('ses_tie', 'assistant', { content: [{ type: 'text', text: '…' }], time: { created: T0 } }, T0)+ expect(await busy('ses_tie')).toBe(true)++ // A pair the two orders disagree on (18 measured): the turn's `idle` end holds a lower `seq` than the step it+ // answers, and a later `time_created`. By `seq` alone the stale step would hold the session open.+ store.v2Session('ses_swapped')+ store.v2Message('ses_swapped', 'idle', { outcome: 'interrupted' }, T0 + 100)+ store.v2Message('ses_swapped', 'assistant', { content: [{ type: 'text', text: '…' }], time: { created: T0 } }, T0)+ expect(await busy('ses_swapped')).toBe(false)+ store.close()+ })++ it('asks the v1 tables about a session OpenCode 2 has no row of, and reads v2 first when a store has both', async () => {+ const store = new Store(join(tempDir(), 'opencode.db'), SCHEMA + V2_SCHEMA)+ const provider = opencodeProvider({ engine: 'opencode', dbPath: store.path })+ const busy = (id: string) => provider.busy!({ pid: 1, record: ownerRecord(store.path, id) })+ store.session('ses_v1asked').message('ses_v1asked', { role: 'user' })+ expect(await busy('ses_v1asked')).toBe(true)+ store.session('ses_v1done').turn('ses_v1done')+ expect(await busy('ses_v1done')).toBe(false)+ // Taken over from 1.x, then answered in v2: the stale v1 prompt does not make it busy.+ store.session('ses_both').message('ses_both', { role: 'user' })+ store.v2Session('ses_both').v2Turn('ses_both')+ expect(await busy('ses_both')).toBe(false)+ store.close()+ })+it('lists the newest 500 and counts the rest as older', async () => {const store = new Store(join(tempDir(), 'opencode.db'))store.db.exec('BEGIN')@@ -528,4 +691,18 @@ describe('the shared helpers', () => {expect(opencodeTurnOpen([])).toBe(false)expect(opencodeTurnOpen([{ role: 'tool' }])).toBeNull()})++ it('reads an OpenCode 2 tail: a prompt is open, a turn end closed, a step by its completion, tools and error', () => {+ expect(opencodeV2TurnOpen({ type: 'user' })).toBe(true)+ expect(opencodeV2TurnOpen({ type: 'idle' })).toBe(false)+ expect(opencodeV2TurnOpen({ type: 'compaction' })).toBeNull()+ const step = { type: 'assistant', completed: 1, failed: null, pending: 0, finish: 'stop' }+ expect(opencodeV2TurnOpen(step)).toBe(false)+ expect(opencodeV2TurnOpen({ ...step, completed: null })).toBe(true)+ expect(opencodeV2TurnOpen({ ...step, pending: 1 })).toBe(true)+ expect(opencodeV2TurnOpen({ ...step, finish: 'tool-calls' })).toBe(true)+ expect(opencodeV2TurnOpen({ ...step, finish: null })).toBe(false)+ expect(opencodeV2TurnOpen({ ...step, finish: 'tool-calls', failed: 'object' })).toBe(false)+ expect(opencodeV2TurnOpen({ ...step, completed: null, failed: 'null' })).toBe(true)+ })})diff --git a/cli/src/lib/sessionSearch/externals/opencode.ts b/cli/src/lib/sessionSearch/externals/opencode.tsindex 655eee5d9..1a286f929 100644--- a/cli/src/lib/sessionSearch/externals/opencode.ts+++ b/cli/src/lib/sessionSearch/externals/opencode.ts@@ -9,6 +9,12 @@ import { externalReadFailed } from '../evidence.js'* (measured in the 1.18.32 binary; the TUI leaves it NULL). A session with no message was never used.* Times are epoch milliseconds.*+ * OpenCode 2 keeps its sessions in `session_v2` and their messages in `session_message` (same session columns,+ * one row per prompt, assistant step or turn end) and no longer writes the v1 tables, which stay in the file with+ * what v1 wrote (a fresh OpenCode 2 store has none of them): a store that has `session_v2` is listed from it alone.+ * Kilo's has no such table. v2 leaves `permission` empty even for `opencode run` (measured, 2.0.29), so a headless+ * session is told by the `permission` of its v1 row, which the sessions v2 took over still have.+ ** Neither engine leaves a per-session lock or pid file: the only owner evidence is the id in a* process's arguments (`-s/--session`, never with `--fork`, which writes a NEW session), and it names* the session the process started on, not necessarily the one it has now (`fromArgs`). Whether it is@@ -50,7 +56,7 @@ const SESSION_ID = /^ses_[A-Za-z0-9]{1,64}$/const PLACEHOLDER_TITLE = /^(New session - |Child session - )\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$//** A headless `run` (and the GitHub agent) denies the `question` tool: nobody is there to answer. */-const HEADLESS = "EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(s.permission) THEN s.permission ELSE '[]' END) r"+const headless = (permission: string) => `EXISTS (SELECT 1 FROM json_each(CASE WHEN json_valid(${permission}) THEN ${permission} ELSE '[]' END) r`+ " WHERE CASE WHEN r.type = 'object' THEN json_extract(r.value, '$.permission') END = 'question'"+ " AND CASE WHEN r.type = 'object' THEN json_extract(r.value, '$.action') END = 'deny')"@@ -60,31 +66,45 @@ const VALUE_FLAGS = new Set(['-s', '--session', '-m', '--model', '--agent', '--pinterface Listed { rows: SqliteRow[]; counts: Tally }+export interface V2Store {+ /** The columns of the v1 `session` table the file still holds; none when it holds no such table. */+ legacy: ReadonlySet<string>+}+/*** One statement: the newest sessions a person can resume, and how many rows each rule kept out (a* row with a null id is a count). Columns come from the store's own schema, since versions differ.+ * With `v2` the sessions are those of an OpenCode 2 store, `session_v2` and `session_message`.*/-export function opencodeListSql(session: ReadonlySet<string>, message: ReadonlySet<string>): string | null {+export function opencodeListSql(session: ReadonlySet<string>, message: ReadonlySet<string>, v2?: V2Store): string | null {if (!session.has('id') || !session.has('directory') || !session.has('time_updated')) return null+ // v2's message table also holds compactions, shell runs and turn ends: only what was said counts as use.const lastMessage = message.has('session_id') && message.has('time_created')- ? '(SELECT max(m.time_created) FROM message m WHERE m.session_id = s.id)'+ ? `(SELECT max(m.time_created) FROM ${v2 ? "session_message m WHERE m.type IN ('user', 'assistant') AND" : 'message m WHERE'} m.session_id = s.id)`: 'NULL'+ const permission = session.has('permission')+ ? v2 && v2.legacy.has('id') && v2.legacy.has('permission')+ ? 'coalesce(s.permission, (SELECT old.permission FROM session old WHERE old.id = s.id))'+ : 's.permission'+ : nullconst skip = `CASE${session.has('parent_id') ? " WHEN s.parent_id IS NOT NULL THEN 'child'" : ''}`+ `${session.has('time_archived') ? " WHEN s.time_archived IS NOT NULL THEN 'archived'" : ''}`- + `${session.has('permission') ? ` WHEN ${HEADLESS} THEN 'headless'` : ''}`+ + `${permission ? ` WHEN ${headless(permission)} THEN 'headless'` : ''}`+ ` WHEN ${lastMessage} IS NULL THEN 'empty' ELSE '' END`const title = session.has('title') ? 's.title' : "''"return 'SELECT * FROM (SELECT s.id AS id, s.directory AS directory, '+ `${title} AS title, s.time_updated AS updated, ${lastMessage} AS last_msg, '' AS skip, NULL AS n `- + `FROM session s WHERE ${skip} = '' `+ + `FROM ${v2 ? 'session_v2' : 'session'} s WHERE ${skip} = '' `+ `ORDER BY max(coalesce(s.time_updated, 0), coalesce(${lastMessage}, 0)) DESC LIMIT ${LIST_LIMIT}) `- + `UNION ALL SELECT NULL, NULL, NULL, NULL, NULL, ${skip} AS skip, count(*) AS n FROM session s GROUP BY skip`+ + `UNION ALL SELECT NULL, NULL, NULL, NULL, NULL, ${skip} AS skip, count(*) AS n FROM ${v2 ? 'session_v2' : 'session'} s GROUP BY skip`}async function listSessions(read: SqlRead, dbPath: string): Promise<Listed | null> {- const columns = await tableColumns(read, dbPath, ['session', 'message'])+ const columns = await tableColumns(read, dbPath, ['session', 'message', 'session_v2', 'session_message'])if (!columns) return null- const sql = opencodeListSql(columns.get('session') ?? new Set(), columns.get('message') ?? new Set())+ const sql = columns.has('session_v2')+ ? opencodeListSql(columns.get('session_v2') ?? new Set(), columns.get('session_message') ?? new Set(), { legacy: columns.get('session') ?? new Set() })+ : opencodeListSql(columns.get('session') ?? new Set(), columns.get('message') ?? new Set())if (!sql) return { rows: [], counts: {} }const rows = await rowsOf(read, dbPath, sql)return rows && splitCounts(rows)@@ -103,6 +123,29 @@ const TAIL_SQL = "SELECT json_extract(m.data, '$.role') AS role, json_extract(m.+ ' FROM (SELECT id, data FROM message WHERE session_id = ? ORDER BY time_created DESC, id DESC LIMIT 1) m'+ ' LEFT JOIN part p ON p.message_id = m.id'+/**+ * The same question of an OpenCode 2 session, from the newest row that says where the turn is: a prompt (open),+ * a turn end (`idle`, closed) or an assistant step. A step is open until it completes, while a tool is still+ * pending or running, and when it stopped to call tools; an error ends it. Rows are read in `time_created`+ * order, `seq` only tying that millisecond: 2.0.29 stores hold ties on it and pairs `seq` lays the other way+ * round from time (same order the readers use).+ */+const V2_TAIL_SQL = "SELECT m.type AS type, json_extract(m.data, '$.finish') AS finish,"+ + " json_extract(m.data, '$.time.completed') AS completed, json_type(m.data, '$.error') AS failed,"+ + " EXISTS (SELECT 1 FROM json_each(m.data, '$.content') c WHERE json_extract(c.value, '$.type') = 'tool'"+ + " AND json_extract(c.value, '$.state.status') IN ('pending', 'running')) AS pending"+ + " FROM session_message m WHERE m.session_id = ? AND m.type IN ('user', 'assistant', 'idle')"+ + " ORDER BY m.time_created DESC, m.seq DESC LIMIT 1"++export function opencodeV2TurnOpen(row: SqliteRow): boolean | null {+ if (row.type === 'user') return true+ if (row.type === 'idle') return false+ if (row.type !== 'assistant') return null+ if (typeof row.failed === 'string' && row.failed !== 'null') return false+ if (!row.completed || Number(row.pending) === 1) return true+ return row.finish === 'tool-calls'+}+export function opencodeTurnOpen(rows: readonly SqliteRow[]): boolean | null {const head = rows[0]if (!head) return false@@ -122,7 +165,8 @@ export function opencodeTurnOpen(rows: readonly SqliteRow[]): boolean | null {export function opencodeProvider(options: OpencodeOptions): ExternalProvider & Counting {const { engine, dbPath } = options- const read = checkedSql(options.read ?? readSql)+ const rawRead = options.read ?? readSql+ const read = checkedSql(rawRead)const available = options.available ?? hasSqliteReaderlet counts: Tally = {}const history = (sessionId: string) => engine === 'kilo'@@ -181,8 +225,21 @@ export function opencodeProvider(options: OpencodeOptions): ExternalProvider & Casync busy(owner): Promise<boolean | null> {const at = parseOwnerRecord(owner.record)if (!at) return null- const result = await read(at.dbPath, TAIL_SQL, [at.sessionId])- return result.ok ? opencodeTurnOpen(result.rows) : null+ if (engine !== 'opencode') {+ const result = await read(at.dbPath, TAIL_SQL, [at.sessionId])+ return result.ok ? opencodeTurnOpen(result.rows) : null+ }+ // OpenCode 2's own record first, then the v1 tables of a session it has no row of. Neither table is a+ // failure to read: a store has only the one its version wrote.+ const noTable = (result: SqliteReadResult) => !result.ok && /no such table/i.test(result.error?.message ?? '')+ const unreadable = (): null => { externalReadFailed(new Error('SQLite read failed'), 'conversation store'); return null }+ const v2 = await rawRead(at.dbPath, V2_TAIL_SQL, [at.sessionId])+ if (v2.ok && v2.rows.length > 0) return opencodeV2TurnOpen(v2.rows[0])+ if (!v2.ok && !noTable(v2)) return unreadable()+ const v1 = await rawRead(at.dbPath, TAIL_SQL, [at.sessionId])+ if (v1.ok) return opencodeTurnOpen(v1.rows)+ if (!noTable(v1)) return unreadable()+ return v2.ok ? false : null // v2 only, and it has said nothing in this session; or not OpenCode's store},}}diff --git a/cli/src/services/handoffProcess.spec.ts b/cli/src/services/handoffProcess.spec.tsindex 29e884104..61430afba 100644--- a/cli/src/services/handoffProcess.spec.ts+++ b/cli/src/services/handoffProcess.spec.ts@@ -14,6 +14,8 @@ import { runServiceProcess, type ServiceProcessOptions } from './process.js'vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))// The SQLite binding, faked: an OpenCode store with one turn in it, and a count of the times it was loaded.+// `ses_handoff1` is an OpenCode 1 conversation (message and part rows, nothing in session_message) and+// `ses_handoff2` an OpenCode 2 one (session_message rows only).const binding = vi.hoisted(() => ({ loads: 0, reads: [] as Array<{ path: string; sql: string; params: unknown[] }> }))vi.mock('../lib/sqliteBuiltin.js', () => {binding.loads++@@ -22,6 +24,14 @@ vi.mock('../lib/sqliteBuiltin.js', () => {builtinSqlite: () => class {},readBuiltin: (_database: unknown, path: string, sql: string, params: unknown[]) => {binding.reads.push({ path, sql, params })+ if (sql.includes('FROM session_message')) {+ const v2 = (id: string, type: string, seq: number, data: Record<string, unknown>) => ({ mid: id, mtype: type, mseq: seq, mtc: seq, mdata: JSON.stringify(data) })+ return { ok: true, via: 'builtin', rows: params[0] === 'ses_handoff2' ? [+ v2('msg_1', 'user', 0, { text: 'add a search box' }),+ v2('msg_2', 'assistant', 1, { content: [{ type: 'text', text: 'Added the search box.' }], finish: 'stop' }),+ v2('msg_3', 'idle', 2, { outcome: 'succeeded' }),+ ] : [] }+ }return { ok: true, via: 'builtin', rows: [{ mid: 'msg_1', mtc: 1, mdata: JSON.stringify({ role: 'user' }), pid: 'prt_1', pdata: part('text', 'add a login page') },{ mid: 'msg_2', mtc: 2, mdata: JSON.stringify({ role: 'assistant' }), pid: 'prt_2', pdata: part('text', 'Added the login page.') },@@ -120,6 +130,7 @@ describe('the handoff in the edge host', () => {const agents: Record<string, Record<string, unknown>> = {claude: { agentId: 'claude-1', sessionId: 's1', engine: 'claude', cwd: ws, transcriptPath: null, registeredAt: Date.now() - 60_000 },opencode: { agentId: 'opencode-1', sessionId: 'ses_handoff1', engine: 'opencode', cwd: ws, transcriptPath: null, registeredAt: Date.now() - 60_000 },+ opencode2: { agentId: 'opencode-2', sessionId: 'ses_handoff2', engine: 'opencode', cwd: ws, transcriptPath: null, registeredAt: Date.now() - 60_000 },}const publicationErrors: unknown[] = []const commit = createHandoffPublisher({ directory: join(ws, 'daemon-data'),@@ -140,13 +151,24 @@ describe('the handoff in the edge host', () => {await prepare({ agentId: 'claude-1', changeId: 'c'.repeat(32), targetEngine: 'codex' }, asker)expect(binding.loads).toBe(1)expect(binding.reads).toEqual([])- // OpenCode reads through the same binding and hands over the turn the store holds.+ // OpenCode reads through the same binding and hands over the turn the store holds: OpenCode 2's+ // session_message first, and for an OpenCode 1 conversation, which has no rows there, its message rows.+ const database = join(env.OPENCODE_DATA_DIR, 'opencode.db')const handed = await prepare({ agentId: 'opencode-1', changeId: 'a'.repeat(32), targetEngine: 'claude' }, asker) as { file: string | null }expect(binding.loads).toBe(1)- expect(binding.reads).toEqual([{ path: join(env.OPENCODE_DATA_DIR, 'opencode.db'), sql: expect.stringContaining('FROM message m'), params: ['ses_handoff1'] }])+ expect(binding.reads).toEqual([+ { path: database, sql: expect.stringContaining('FROM session_message m'), params: ['ses_handoff1'] },+ { path: database, sql: expect.stringContaining('FROM message m'), params: ['ses_handoff1'] },+ ])expect(publicationErrors).toEqual([])expect(handed).toMatchObject({ file: expect.any(String) })expect(readFileSync(join(ws, handed.file!), 'utf8')).toContain('add a login page')+ // An OpenCode 2 conversation is handed over from session_message alone.+ binding.reads.length = 0+ const handed2 = await prepare({ agentId: 'opencode-2', changeId: 'b'.repeat(32), targetEngine: 'claude' }, asker) as { file: string | null }+ expect(binding.reads).toEqual([{ path: database, sql: expect.stringContaining('FROM session_message m'), params: ['ses_handoff2'] }])+ expect(publicationErrors).toEqual([])+ expect(readFileSync(join(ws, handed2.file!), 'utf8')).toContain('add a search box')} finally { rmSync(ws, { recursive: true, force: true }) }})})