@wwwfz/dsh-agent-bridge 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/projects.js CHANGED
@@ -4,8 +4,8 @@ import { open, readdir, realpath, stat } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import zlib from 'node:zlib';
7
+ import { sourceJson, sourceJsonl, sourceValueLimit } from './conversation-readers.js';
7
8
 
8
- const maxSessions = 8_000;
9
9
  const maxMessages = 36;
10
10
  const maxMessageLength = 4_000;
11
11
  const maxTranscriptBytes = 12 * 1024 * 1024;
@@ -186,8 +186,9 @@ async function archivedProjects(file) {
186
186
  const deleted = fields.has('deleted_at') ? ' AND deleted_at IS NULL' : '';
187
187
  const machine = fields.has('machine') ? " AND machine IN ('', 'local')" : '';
188
188
  const title = fields.has('title') ? 'substr(title, 1, 200)' : 'NULL';
189
- return db.prepare(`SELECT id, cwd, agent, ${sort} AS date, ${title} AS title FROM sessions WHERE cwd <> ''${deleted}${machine} ORDER BY ${sort} DESC LIMIT ?`)
190
- .all(maxSessions).map(({ id, cwd, agent, date, title }) => ({ cwd, agent, archive: { kind: 'agentsview', agent, file, id, date, title } }));
189
+ const rows = db.prepare(`SELECT id, cwd, agent, ${sort} AS date, ${title} AS title FROM sessions WHERE cwd <> ''${deleted}${machine} ORDER BY ${sort} DESC`)
190
+ .iterate();
191
+ return Array.from(rows, ({ id, cwd, agent, date, title }) => ({ cwd, agent, archive: { kind: 'agentsview', agent, file, id, date, title } }));
191
192
  });
192
193
  }
193
194
 
@@ -206,7 +207,7 @@ async function codexProjects(root) {
206
207
  if (!['cwd', 'rollout_path', 'id'].every(field => fields.has(field))) return undefined;
207
208
  const sort = fields.has('updated_at') ? 'updated_at' : 'id';
208
209
  const title = fields.has('title') ? 'substr(title, 1, 200)' : 'NULL';
209
- return db.prepare(`SELECT id, cwd, rollout_path, ${sort} AS date, ${title} AS title FROM threads WHERE cwd <> '' ORDER BY ${sort} DESC LIMIT ?`).all(maxSessions);
210
+ return db.prepare(`SELECT id, cwd, rollout_path, ${sort} AS date, ${title} AS title FROM threads WHERE cwd <> '' ORDER BY ${sort} DESC`).all();
210
211
  });
211
212
  if (indexed) break;
212
213
  } catch (error) {
@@ -226,12 +227,12 @@ async function codexProjects(root) {
226
227
  if (!byFile.has(key)) byFile.set(key, project);
227
228
  }
228
229
  }
229
- // Files may be compressed or moved before SQLite catches up. Keep SQLite's
230
- // titles when its path resolves, and discover compressed files independently.
230
+ // SQLite can lag an active or archived transcript. Keep its titles for
231
+ // resolved files and discover any additional plain or compressed transcripts.
231
232
  const byId = new Set([...byFile.values()].map(project => project.archive.id).filter(Boolean));
232
233
  const include = file => !byFile.has(pathKey(file))
233
- && ((!indexed?.length && jsonlFile.test(file)) || (hasZstd && compressedCodexFile.test(file)));
234
- const fallback = await scanJsonlProjects(root, 'codex', bases, 4, include, maxSessions - byFile.size);
234
+ && (jsonlFile.test(file) || (hasZstd && compressedCodexFile.test(file)));
235
+ const fallback = await scanJsonlProjects(root, 'codex', bases, 4, include);
235
236
  for (const project of fallback) {
236
237
  const { file, id } = project.archive;
237
238
  if (id && byId.has(id)) continue;
@@ -268,14 +269,15 @@ async function opencodeProjects(root) {
268
269
  if (!tables.length) throw new Error('未识别 OpenCode 会话表');
269
270
  const projects = tables.flatMap(table => {
270
271
  const title = columns(db, table).has('title') ? 'substr(title, 1, 200)' : 'NULL';
271
- return db.prepare(`SELECT id, directory AS cwd, time_updated AS date, ${title} AS title FROM ${table} WHERE directory <> '' ORDER BY time_updated DESC LIMIT ?`)
272
- .all(maxSessions).map(({ id, cwd, date, title }) => ({ cwd, agent: 'opencode', archive: { kind: 'opencode', file, id, table, date, title } }));
272
+ const rows = db.prepare(`SELECT id, directory AS cwd, time_updated AS date, ${title} AS title FROM ${table} WHERE directory <> '' ORDER BY time_updated DESC`).iterate();
273
+ return Array.from(rows, ({ id, cwd, date, title }) => ({ cwd, agent: 'opencode', archive: { kind: 'opencode', file, id, table, date, title } }));
273
274
  });
274
275
  const fields = columns(db, 'project');
275
276
  if (fields.has('worktree')) {
276
277
  const name = fields.has('name') ? 'name' : 'NULL';
277
- projects.push(...db.prepare(`SELECT worktree AS cwd, ${name} AS name FROM project WHERE worktree <> '' LIMIT ?`).all(maxSessions)
278
- .map(row => ({ ...row, agent: 'opencode' })));
278
+ for (const row of db.prepare(`SELECT worktree AS cwd, ${name} AS name FROM project WHERE worktree <> ''`).iterate()) {
279
+ projects.push({ ...row, agent: 'opencode' });
280
+ }
279
281
  }
280
282
  return projects;
281
283
  });
@@ -292,22 +294,19 @@ async function opencodeDatabase(root) {
292
294
  return undefined;
293
295
  }
294
296
 
295
- async function transcriptFiles(root, depth, limit, predicate) {
296
- const files = [];
297
+ async function* transcriptFiles(root, depth, predicate) {
297
298
  const stack = [{ root, depth }];
298
- while (stack.length && files.length < limit) {
299
+ while (stack.length) {
299
300
  const current = stack.pop();
300
301
  const entries = await directories(current.root).catch(() => []);
301
302
  for (const entry of entries) {
302
303
  const file = path.join(current.root, entry.name);
303
- if (entry.isFile() && predicate(entry.name, file)) files.push(file);
304
- if (files.length >= limit) break;
304
+ if (entry.isFile() && predicate(entry.name, file)) yield file;
305
305
  if (entry.isDirectory() && current.depth > 0 && entry.name !== 'subagents') {
306
306
  stack.push({ root: file, depth: current.depth - 1 });
307
307
  }
308
308
  }
309
309
  }
310
- return files;
311
310
  }
312
311
 
313
312
  async function nativeCwd(file, agent, rows) {
@@ -327,14 +326,11 @@ async function jsonlProjects(root, agent, children = ['projects'], depth = 1) {
327
326
  return scanJsonlProjects(root, agent, roots, depth, file => jsonlFile.test(file));
328
327
  }
329
328
 
330
- async function scanJsonlProjects(root, agent, roots, depth, include, limit = maxSessions) {
331
- const files = [];
332
- for (const target of roots) {
333
- files.push(...await transcriptFiles(target, depth, limit - files.length, (_name, file) => include(file)));
334
- }
329
+ async function scanJsonlProjects(root, agent, roots, depth, include) {
335
330
  const result = [];
336
- for (let offset = 0; offset < files.length; offset += 32) {
337
- const batch = await Promise.all(files.slice(offset, offset + 32).map(async file => {
331
+ const batch = [];
332
+ async function flush() {
333
+ const rows = await Promise.all(batch.splice(0).map(async file => {
338
334
  try {
339
335
  const compressed = agent === 'codex' && compressedCodexFile.test(file);
340
336
  const { text, truncated, modified } = compressed ? await compressedPrefix(file) : await prefix(file, transcriptHeaderBytes);
@@ -347,8 +343,15 @@ async function scanJsonlProjects(root, agent, roots, depth, include, limit = max
347
343
  return cwd ? { cwd, agent, archive: { kind: agent, file, root, id, date: modified, title: title?.slice(0, 200) } } : undefined;
348
344
  } catch { return undefined; }
349
345
  }));
350
- result.push(...batch.filter(Boolean));
346
+ result.push(...rows.filter(Boolean));
351
347
  }
348
+ for (const target of roots) {
349
+ for await (const file of transcriptFiles(target, depth, (_name, candidate) => include(candidate))) {
350
+ batch.push(file);
351
+ if (batch.length === 32) await flush();
352
+ }
353
+ }
354
+ if (batch.length) await flush();
352
355
  return result;
353
356
  }
354
357
 
@@ -362,28 +365,66 @@ function editorStores(root) {
362
365
  return dataDirectories(root, relatives);
363
366
  }
364
367
 
368
+ async function copilotDatabase(root) {
369
+ const actual = await physicalPath(root);
370
+ if (!actual) return undefined;
371
+ if (path.basename(actual).toLowerCase() === 'session-store.db' && (await stat(actual)).isFile()) return actual;
372
+ for (const prefix of ['', 'User']) {
373
+ const file = await scopedFile(path.join(actual, prefix, 'globalStorage', 'github.copilot-chat', 'session-store.db'), actual);
374
+ if (file && (await stat(file)).isFile()) return file;
375
+ }
376
+ }
377
+
378
+ function copilotTables(db) {
379
+ const sessions = columns(db, 'sessions');
380
+ const turns = columns(db, 'turns');
381
+ return ['id', 'cwd'].every(field => sessions.has(field))
382
+ && ['id', 'session_id', 'turn_index', 'user_message', 'assistant_response', 'timestamp'].every(field => turns.has(field));
383
+ }
384
+
385
+ function copilotHostFilter(fields) {
386
+ return fields.has('host_type') ? " AND host_type = 'vscode'" : '';
387
+ }
388
+
389
+ async function copilotDbProjects(file, root) {
390
+ return withDatabase(file, db => {
391
+ if (!copilotTables(db)) throw new Error('Unrecognized Copilot session store');
392
+ const fields = columns(db, 'sessions');
393
+ const title = fields.has('summary') ? 'substr(summary, 1, 200)' : 'NULL';
394
+ const date = fields.has('updated_at') ? 'updated_at' : 'NULL';
395
+ const rows = db.prepare(`SELECT id, cwd, ${title} AS title, ${date} AS date FROM sessions WHERE cwd <> ''${copilotHostFilter(fields)} ORDER BY date DESC, id`)
396
+ .iterate();
397
+ return Array.from(rows, row => ({
398
+ cwd: localDirectory(row.cwd), agent: 'copilot',
399
+ archive: { kind: 'copilot', storage: 'sqlite', file, root, id: row.id, title: row.title, date: row.date },
400
+ }));
401
+ });
402
+ }
403
+
365
404
  async function editorProjects(root, agent) {
366
405
  const stores = await editorStores(root);
367
- if (!stores.length) throw missingStore();
368
- const files = [];
406
+ const database = agent === 'copilot' ? await copilotDatabase(root) : undefined;
407
+ if (!stores.length && !database) throw missingStore();
408
+ const result = [];
369
409
  for (const store of stores) {
370
- files.push(...await transcriptFiles(store, 1, maxSessions - files.length, name => name === 'workspace.json'));
410
+ for await (const file of transcriptFiles(store, 1, name => name === 'workspace.json')) {
411
+ try {
412
+ const { text } = await prefix(file, 32 * 1024);
413
+ const value = json(text);
414
+ const cwd = localDirectory(value?.folder);
415
+ if (!cwd) continue;
416
+ result.push({ cwd, agent });
417
+ if (agent !== 'copilot') continue;
418
+ for await (const session of transcriptFiles(path.join(path.dirname(file), 'chatSessions'), 0, name => /\.jsonl?$/i.test(name))) {
419
+ const info = await stat(session).catch(() => undefined);
420
+ if (info) result.push({ cwd, agent, archive: { kind: 'copilot', file: session, root, date: info.mtimeMs } });
421
+ }
422
+ } catch { continue; }
423
+ }
371
424
  }
372
- const result = [];
373
- for (const file of files) {
374
- try {
375
- const { text } = await prefix(file, 32 * 1024);
376
- const value = json(text);
377
- const cwd = localDirectory(value?.folder);
378
- if (!cwd) continue;
379
- result.push({ cwd, agent });
380
- if (agent !== 'copilot') continue;
381
- const sessions = await transcriptFiles(path.join(path.dirname(file), 'chatSessions'), 0, maxSessions, name => /\.jsonl?$/i.test(name));
382
- for (const session of sessions) {
383
- const info = await stat(session).catch(() => undefined);
384
- if (info) result.push({ cwd, agent, archive: { kind: 'copilot', file: session, root, date: info.mtimeMs } });
385
- }
386
- } catch { continue; }
425
+ if (database) {
426
+ try { for (const project of await copilotDbProjects(database, root)) result.push(project); }
427
+ catch (error) { if (!result.length) throw error; }
387
428
  }
388
429
  return result;
389
430
  }
@@ -391,14 +432,12 @@ async function editorProjects(root, agent) {
391
432
  async function geminiProjects(root) {
392
433
  const [base] = await transcriptDirectories(root, ['tmp']);
393
434
  if (!base) throw missingStore();
394
- const files = await transcriptFiles(base, 1, maxSessions, name => name === '.project_root');
395
435
  const result = [];
396
- for (const file of files) {
436
+ for await (const file of transcriptFiles(base, 1, name => name === '.project_root')) {
397
437
  const { text } = await prefix(file, 32 * 1024);
398
438
  const cwd = text.trim();
399
439
  result.push({ cwd, agent: 'gemini' });
400
- const sessions = await transcriptFiles(path.join(path.dirname(file), 'chats'), 0, maxSessions, name => /^session-.+\.jsonl?$/i.test(name));
401
- for (const session of sessions) {
440
+ for await (const session of transcriptFiles(path.join(path.dirname(file), 'chats'), 0, name => /^session-.+\.jsonl?$/i.test(name))) {
402
441
  const info = await stat(session).catch(() => undefined);
403
442
  if (info) result.push({ cwd, agent: 'gemini', archive: { kind: 'gemini', file: session, root, date: info.mtimeMs } });
404
443
  }
@@ -423,7 +462,7 @@ async function antigravityProjects(root) {
423
462
  const rows = await withDatabase(database, db => {
424
463
  const fields = columns(db, 'conversation_summaries');
425
464
  if (!fields.has('workspace_uris')) return [];
426
- return db.prepare("SELECT workspace_uris FROM conversation_summaries WHERE workspace_uris NOT IN ('', '[]') LIMIT ?").all(maxSessions);
465
+ return db.prepare("SELECT workspace_uris FROM conversation_summaries WHERE workspace_uris NOT IN ('', '[]')").all();
427
466
  });
428
467
  for (const row of rows) {
429
468
  const uris = json(row.workspace_uris);
@@ -464,7 +503,7 @@ export async function scanProjects(config) {
464
503
  for (const file of candidates) {
465
504
  try {
466
505
  const rows = await load(file);
467
- projects.push(...rows);
506
+ for (const row of rows) projects.push(row);
468
507
  found += rows.length;
469
508
  succeeded++;
470
509
  } catch (error) {
@@ -489,7 +528,7 @@ export async function scanProjects(config) {
489
528
  antigravity: antigravityProjects,
490
529
  }).map(([agent, load]) => scan(agent, agentLabels[agent], configuredRoots(config, agent), load, {
491
530
  trae: '支持工作区元数据;会话可从 AgentsView 读取已归档部分',
492
- copilot: '支持 VS Code 工作区会话;其他版本可从 AgentsView 读取已归档部分',
531
+ copilot: '支持 VS Code 工作区会话及本机会话库;其他版本可从 AgentsView 读取已归档部分',
493
532
  antigravity: '支持工作区元数据和 CLI 提示记录;完整会话可从 AgentsView 读取已归档部分',
494
533
  }[agent])),
495
534
  ]);
@@ -546,7 +585,8 @@ function messageText(text) {
546
585
  return typeof text === 'string' ? stripRuntimeWrapper(text).trim() : '';
547
586
  }
548
587
 
549
- function markSourcePartial(result) {
588
+ function markSourcePartial(result, reason = 'source-compacted') {
589
+ result.events?.push({ kind: 'gap', reason });
550
590
  result.sourcePartial = true;
551
591
  result.truncated = true;
552
592
  }
@@ -557,6 +597,17 @@ function appendMessage(result, role, text, timestamp, { estimatedTime = false }
557
597
  if (!value) return false;
558
598
  for (const match of value.matchAll(/<skill>\s*<name>([^<]+)<\/name>/gi)) addSkill(result, match[1]);
559
599
  if (value.startsWith('<skill>')) return false;
600
+ if (result.events) {
601
+ if (role === 'user') result.turn++;
602
+ const time = dateMillis(timestamp);
603
+ result.events.push({
604
+ kind: 'message', role, text: stripRuntimeWrapper(text), turn: result.turn,
605
+ ...(time > 0 && !estimatedTime ? { time } : {}),
606
+ ...(result.sourceId ? { sourceId: result.sourceId } : {}),
607
+ ...(result.parentId ? { parentId: result.parentId } : {}),
608
+ });
609
+ return true;
610
+ }
560
611
  const { limits } = result;
561
612
  if (limits) {
562
613
  const bounded = value.slice(0, limits.messageLength).replace(/[\uD800-\uDBFF]$/, '');
@@ -610,6 +661,15 @@ function cleanTraceText(value) {
610
661
  }
611
662
 
612
663
  function addTrace(result, item) {
664
+ if (result.events) {
665
+ const { id, text, ...details } = item;
666
+ result.events.push({
667
+ ...details, text: traceValue(text).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, ' '),
668
+ ...(id ? { sourceId: id } : {}),
669
+ ...(item.kind !== 'tool_result' ? { turn: result.turn } : {}),
670
+ });
671
+ return undefined;
672
+ }
613
673
  if (!result.trace) return undefined;
614
674
  const text = cleanTraceText(item.text);
615
675
  const bounded = text.slice(0, traceTextLimit).replace(/[\uD800-\uDBFF]$/, '');
@@ -648,8 +708,8 @@ function traceCallId(value) {
648
708
  }
649
709
 
650
710
  function addSummary(result, text, time, id) {
651
- const value = cleanTraceText(text);
652
- if (!value) return;
711
+ const value = result.events ? traceValue(text) : cleanTraceText(text);
712
+ if (!value.trim()) return;
653
713
  addTrace(result, { kind: 'summary', text: value, status: 'ok', time: dateMillis(time), id });
654
714
  }
655
715
 
@@ -658,15 +718,17 @@ function addToolCall(result, name, callId, input, time) {
658
718
  addTrace(result, {
659
719
  kind: 'tool_call', name: name.trim().slice(0, 120),
660
720
  callId: traceCallId(callId),
661
- text: cleanTraceText(input), status: 'pending', time: dateMillis(time),
721
+ text: result.events ? traceValue(input) : cleanTraceText(input), status: 'pending', time: dateMillis(time),
662
722
  });
663
723
  }
664
724
 
665
- function addToolResult(result, callId, output, failed) {
666
- if (!result.trace || typeof callId !== 'string' || !callId) return;
725
+ function addToolResult(result, callId, output, failed, time) {
726
+ if (!result.events && (!result.trace || typeof callId !== 'string' || !callId)) return;
667
727
  addTrace(result, {
668
- kind: 'tool_result', callId: traceCallId(callId), text: cleanTraceText(output),
669
- status: failed === true ? 'error' : 'ok',
728
+ kind: 'tool_result', callId: traceCallId(callId),
729
+ text: result.events ? traceValue(output) : cleanTraceText(output),
730
+ status: failed === 'incomplete' ? 'incomplete' : failed === true ? 'error' : 'ok',
731
+ ...(time === undefined ? {} : { time: dateMillis(time) }),
670
732
  });
671
733
  }
672
734
 
@@ -698,19 +760,23 @@ function textBlocks(content, result) {
698
760
  addToolCall(result, block.name, block.id, block.input);
699
761
  }
700
762
  if (result && block?.type === 'tool_result') {
701
- const value = Array.isArray(block.content)
702
- ? block.content.filter(part => part?.type === 'text' && typeof part.text === 'string').map(part => part.text).join('\n')
703
- : block.content;
763
+ const value = result.events ? sourceToolOutput(result, block.content, block.tool_use_id)
764
+ : (Array.isArray(block.content)
765
+ ? block.content.filter(part => part?.type === 'text' && typeof part.text === 'string').map(part => part.text).join('\n')
766
+ : block.content);
704
767
  addToolResult(result, block.tool_use_id, value, block.is_error === true);
705
768
  }
706
769
  if (result && block?.type === 'tool') {
707
770
  const input = block.state?.input ?? block.input ?? block.args;
708
771
  readTool(result, block.tool ?? block.name, input);
709
772
  const callId = block.callID ?? block.callId ?? block.id;
710
- addToolCall(result, block.tool ?? block.name, callId, input);
773
+ addToolCall(result, block.tool ?? block.name, callId, input, block.time?.created);
711
774
  const state = block.state ?? {};
712
775
  if (state.status === 'completed' || state.status === 'error') {
713
- addToolResult(result, callId, state.output ?? state.result ?? state.error, state.status === 'error');
776
+ const output = state.output ?? state.result ?? state.content ?? state.error?.message ?? state.error;
777
+ const time = result.events ? block.time?.completed : undefined;
778
+ addToolResult(result, callId, result.events ? sourceToolOutput(result, output, callId) : output, state.status === 'error', time);
779
+ if (result.events && state.metadata?.truncated === true) markSourcePartial(result, 'source-tool-output-truncated');
714
780
  }
715
781
  }
716
782
  }
@@ -719,6 +785,99 @@ function textBlocks(content, result) {
719
785
  return texts.map(stripRuntimeWrapper).filter(value => value.trim()).join('\n');
720
786
  }
721
787
 
788
+ function sourceAttachment(block) {
789
+ const type = block?.type;
790
+ if (!['input_image', 'image', 'file', 'input_file', 'document'].includes(type) && !block?.inlineData && !block?.fileData) return;
791
+ const source = block.source ?? block.inlineData ?? block.fileData ?? block;
792
+ const url = block.image_url?.url ?? block.image_url ?? block.url ?? source.fileUri ?? source.url;
793
+ const embedded = typeof url === 'string' ? /^data:([a-z\d.+-]+\/[a-z\d.+-]+);base64,([a-z\d+/=]+)$/i.exec(url) : undefined;
794
+ const encoded = embedded?.[2] ?? source.data ?? block.file_data;
795
+ const sourceType = embedded?.[1] ?? source.media_type ?? source.mimeType ?? source.mime ?? block.mime;
796
+ const mediaType = typeof sourceType === 'string' ? sourceType : undefined;
797
+ const originalName = block.filename ?? block.name ?? block.title;
798
+ const name = typeof originalName === 'string' && path.win32.basename(originalName)
799
+ || ((typeof type === 'string' && type.includes('image')) || mediaType?.startsWith('image/') ? '图片' : '附件');
800
+ const file = localDirectory(block.path ?? url);
801
+ if (typeof encoded === 'string' && /^[\da-z+/]+={0,2}$/i.test(encoded)) {
802
+ return { name, mediaType, data: Buffer.from(encoded, 'base64') };
803
+ }
804
+ if (file) return { name, mediaType, path: file };
805
+ return { name, mediaType, status: typeof url === 'string' ? 'remote-reference' : 'name-only' };
806
+ }
807
+
808
+ function sourceToolOutput(result, value, callId) {
809
+ if (!Array.isArray(value)) return value;
810
+ for (const attachment of value.map(sourceAttachment).filter(Boolean)) {
811
+ result.events.push({
812
+ kind: 'attachment', role: 'assistant', turn: result.turn, sourceId: result.sourceId,
813
+ callId: traceCallId(callId), ...attachment,
814
+ });
815
+ }
816
+ return textBlocks(value);
817
+ }
818
+
819
+ function sourceBlockText(block, functionParts) {
820
+ if (typeof block === 'string') return block;
821
+ if (block?.thought || typeof block?.text !== 'string') return undefined;
822
+ if (['text', 'input_text', 'output_text'].includes(block.type) || (functionParts && block.type === undefined)) return block.text;
823
+ }
824
+
825
+ function sourceReasoning(block) {
826
+ if (block?.type === 'thinking') return block.thinking;
827
+ if (block?.type === 'reasoning' || block?.thought === true) return block.text;
828
+ }
829
+
830
+ function readAssistantBlocks(result, blocks, timestamp, hints) {
831
+ let foundText = false;
832
+ let text = [];
833
+ const flush = () => {
834
+ if (text.length) foundText = appendMessage(result, 'assistant', text.join('\n'), timestamp, hints) || foundText;
835
+ text = [];
836
+ };
837
+ for (const block of blocks) {
838
+ const body = sourceBlockText(block, hints.functionParts);
839
+ if (body !== undefined) {
840
+ text.push(stripRuntimeWrapper(body));
841
+ continue;
842
+ }
843
+ const thought = sourceReasoning(block);
844
+ const attachment = sourceAttachment(block);
845
+ const tool = ['tool', 'tool_use', 'tool_result'].includes(block?.type)
846
+ || (hints.functionParts && (block?.functionCall || block?.functionResponse));
847
+ if (!thought && !tool && !attachment) continue;
848
+ flush();
849
+ if (typeof thought === 'string') addSummary(result, thought, timestamp, result.sourceId);
850
+ if (attachment) {
851
+ result.events.push({ kind: 'attachment', role: 'assistant', turn: result.turn, sourceId: result.sourceId, ...attachment });
852
+ }
853
+ if (tool) {
854
+ textBlocks([block], result);
855
+ if (hints.functionParts) readFunctionParts(result, [block], timestamp);
856
+ }
857
+ }
858
+ flush();
859
+ if (!foundText) appendMessage(result, 'assistant', hints.text, timestamp, hints);
860
+ }
861
+
862
+ function readSourceBlocks(result, role, content, timestamp, hints = {}) {
863
+ const blocks = Array.isArray(content) ? content : [];
864
+ if (role === 'assistant' && blocks.length) {
865
+ readAssistantBlocks(result, blocks, timestamp, hints);
866
+ return;
867
+ }
868
+ const attachments = blocks.map(sourceAttachment).filter(Boolean);
869
+ const added = appendMessage(result, role, hints.text ?? textBlocks(content), timestamp, hints);
870
+ const standalone = role === 'user' && attachments.length > 0 && !added;
871
+ if (standalone) result.turn++;
872
+ for (const [index, attachment] of attachments.entries()) {
873
+ result.events.push({
874
+ kind: 'attachment', role, turn: result.turn, sourceId: result.sourceId, ...attachment,
875
+ ...(standalone && index === 0 ? { standalone: true } : {}),
876
+ });
877
+ }
878
+ textBlocks(blocks, result);
879
+ }
880
+
722
881
  function firstQuestion(rows, agent) {
723
882
  for (const row of rows) {
724
883
  if (row.isSidechain || row.isMeta || row.isCompactSummary) continue;
@@ -739,7 +898,7 @@ function firstQuestion(rows, agent) {
739
898
  }
740
899
  }
741
900
 
742
- async function readGeminiHistory(descriptor, cwd, config, result) {
901
+ async function allowedGemini(descriptor, cwd, config) {
743
902
  for (const root of configuredRoots(config, 'gemini')) {
744
903
  const [base] = await transcriptDirectories(root, ['tmp']);
745
904
  if (!base) continue;
@@ -747,18 +906,23 @@ async function readGeminiHistory(descriptor, cwd, config, result) {
747
906
  if (!file || path.basename(path.dirname(file)) !== 'chats' || !/^session-.+\.jsonl?$/i.test(path.basename(file))) continue;
748
907
  const marker = await scopedFile(path.resolve(path.dirname(file), '..', '.project_root'), base);
749
908
  if (!marker || !await sameDirectory((await prefix(marker, 32 * 1024)).text.trim(), cwd)) continue;
750
- const { text, truncated } = await prefix(file, maxTranscriptBytes);
751
- if (truncated) markSourcePartial(result);
752
- const messages = json(text)?.messages ?? rowsFrom(text, truncated);
753
- if (!Array.isArray(messages)) continue;
754
- for (const row of messages) {
755
- const message = row.message ?? row;
756
- if (!['user', 'gemini', 'assistant'].includes(message.type)) continue;
757
- const content = Array.isArray(message.content) ? message.content.map(block => block?.text ?? '').join('\n') : message.content;
758
- appendMessage(result, message.type === 'gemini' ? 'assistant' : message.type, content, message.timestamp);
759
- for (const tool of Array.isArray(message.toolCalls) ? message.toolCalls : []) readTool(result, tool.name, tool.args);
760
- }
761
- return;
909
+ return file;
910
+ }
911
+ }
912
+
913
+ async function readGeminiHistory(descriptor, cwd, config, result) {
914
+ const file = await allowedGemini(descriptor, cwd, config);
915
+ if (!file) return;
916
+ const { text, truncated } = await prefix(file, maxTranscriptBytes);
917
+ if (truncated) markSourcePartial(result);
918
+ const messages = json(text)?.messages ?? rowsFrom(text, truncated);
919
+ if (!Array.isArray(messages)) return;
920
+ for (const row of messages) {
921
+ const message = row.message ?? row;
922
+ if (!['user', 'gemini', 'assistant'].includes(message.type)) continue;
923
+ const content = Array.isArray(message.content) ? message.content.map(block => block?.text ?? '').join('\n') : message.content;
924
+ appendMessage(result, message.type === 'gemini' ? 'assistant' : message.type, content, message.timestamp);
925
+ for (const tool of Array.isArray(message.toolCalls) ? message.toolCalls : []) readTool(result, tool.name, tool.args);
762
926
  }
763
927
  }
764
928
 
@@ -781,30 +945,40 @@ function copilotRequests(text, truncated) {
781
945
  if (Array.isArray(snapshot?.requests)) return snapshot.requests;
782
946
  let state;
783
947
  for (const op of rowsFrom(text, truncated)) {
784
- if (op.kind === 0) {
785
- state = op.v;
786
- continue;
787
- }
788
- if (!Array.isArray(op.k) || op.k[0] !== 'requests' || op.k.length > 8) continue;
789
- const keys = op.k.map(String);
790
- if (keys.some(key => ['__proto__', 'prototype', 'constructor'].includes(key))) continue;
791
- const key = keys.pop();
792
- let target = state;
793
- for (const part of keys) target = target && Object.hasOwn(target, part) ? target[part] : undefined;
794
- if (!target || typeof target !== 'object') continue;
795
- if (Array.isArray(target) && (!/^\d+$/.test(key) || Number(key) >= target.length)) continue;
796
- if (op.kind === 1) target[key] = op.v;
797
- if (op.kind === 2 && Array.isArray(target[key]) && Array.isArray(op.v)) {
798
- const current = target[key];
799
- const index = Number.isInteger(op.i) ? Math.max(0, Math.min(op.i, current.length)) : current.length;
800
- target[key] = current.slice(0, index).concat(op.v, current.slice(index + op.v.length));
801
- }
802
- if (op.kind === 3 && !Array.isArray(target)) delete target[key];
948
+ if (op.kind === 0) state = op.v;
949
+ else applyCopilotOp(state, op);
803
950
  }
804
951
  return Array.isArray(state?.requests) ? state.requests : [];
805
952
  }
806
953
 
807
- async function readCopilotHistory(descriptor, cwd, config, result) {
954
+ function applyCopilotOp(state, op) {
955
+ if (!Array.isArray(op.k) || op.k[0] !== 'requests') return true;
956
+ if (op.k.length > 8) return false;
957
+ const keys = op.k.map(String);
958
+ if (keys.some(key => ['__proto__', 'prototype', 'constructor'].includes(key))) return false;
959
+ const key = keys.pop();
960
+ let target = state;
961
+ for (const part of keys) target = target && Object.hasOwn(target, part) ? target[part] : undefined;
962
+ if (!target || typeof target !== 'object') return false;
963
+ if (Array.isArray(target) && (!/^\d+$/.test(key) || Number(key) >= target.length)) return false;
964
+ if (op.kind === 1) {
965
+ target[key] = op.v;
966
+ return true;
967
+ }
968
+ if (op.kind === 2 && Array.isArray(target[key]) && Array.isArray(op.v)) {
969
+ const current = target[key];
970
+ const index = Number.isInteger(op.i) ? Math.max(0, Math.min(op.i, current.length)) : current.length;
971
+ target[key] = current.slice(0, index).concat(op.v, current.slice(index + op.v.length));
972
+ return true;
973
+ }
974
+ if (op.kind === 3 && !Array.isArray(target)) {
975
+ delete target[key];
976
+ return true;
977
+ }
978
+ return false;
979
+ }
980
+
981
+ async function allowedEditorChat(descriptor, cwd, config) {
808
982
  const stores = await Promise.all(configuredRoots(config, 'copilot').map(editorStores));
809
983
  for (const base of stores.flat()) {
810
984
  const file = await scopedFile(descriptor.file, base);
@@ -813,21 +987,34 @@ async function readCopilotHistory(descriptor, cwd, config, result) {
813
987
  if (!workspace) continue;
814
988
  const marker = json((await prefix(workspace, 32 * 1024)).text);
815
989
  if (!await sameDirectory(localDirectory(marker?.folder), cwd)) continue;
816
- const { text, truncated } = await prefix(file, maxTranscriptBytes);
817
- if (truncated) markSourcePartial(result);
818
- const requests = copilotRequests(text, truncated);
819
- for (const request of result.limits ? requests : requests.slice(-maxMessages)) {
820
- appendMessage(result, 'user', request?.message?.text, request?.timestamp);
821
- const response = Array.isArray(request?.response) ? request.response : [];
822
- const answer = response.filter(item => !item?.kind || item.kind === 'markdownContent')
823
- .map(item => item?.value?.value ?? item?.value ?? '').filter(value => typeof value === 'string').join('');
824
- // Copilot stores the request time. Use it for transcript order only.
825
- appendMessage(result, 'assistant', answer, request?.timestamp, { estimatedTime: true });
826
- for (const item of response) {
827
- if (item?.kind === 'toolInvocationSerialized') readTool(result, item.toolId, item.parameters);
828
- }
990
+ return file;
991
+ }
992
+ }
993
+
994
+ function copilotText(item) {
995
+ if (item?.kind && item.kind !== 'markdownContent') return '';
996
+ const value = item?.value?.value ?? item?.value;
997
+ return typeof value === 'string' ? value : '';
998
+ }
999
+
1000
+ function copilotAnswer(response) {
1001
+ return response.map(copilotText).join('');
1002
+ }
1003
+
1004
+ async function readCopilotHistory(descriptor, cwd, config, result) {
1005
+ const file = await allowedEditorChat(descriptor, cwd, config);
1006
+ if (!file) return;
1007
+ const { text, truncated } = await prefix(file, maxTranscriptBytes);
1008
+ if (truncated) markSourcePartial(result);
1009
+ const requests = copilotRequests(text, truncated);
1010
+ for (const request of result.limits ? requests : requests.slice(-maxMessages)) {
1011
+ appendMessage(result, 'user', request?.message?.text, request?.timestamp);
1012
+ const response = Array.isArray(request?.response) ? request.response : [];
1013
+ // Copilot stores the request time. Use it for transcript order only.
1014
+ appendMessage(result, 'assistant', copilotAnswer(response), request?.timestamp, { estimatedTime: true });
1015
+ for (const item of response) {
1016
+ if (item?.kind === 'toolInvocationSerialized') readTool(result, item.toolId, item.parameters);
829
1017
  }
830
- return;
831
1018
  }
832
1019
  }
833
1020
 
@@ -895,11 +1082,24 @@ async function* compressedRows(file) {
895
1082
 
896
1083
  function readCodexRow(result, row) {
897
1084
  if (row === null || row.type === 'compacted' || row.isCompactSummary) {
898
- if (result.limits) markSourcePartial(result);
1085
+ if (result.limits || result.events) markSourcePartial(result);
899
1086
  return;
900
1087
  }
901
- if (row.isSidechain || row.isMeta) return;
1088
+ if (row.isSidechain) {
1089
+ if (result.events) markSourcePartial(result, 'unresolved-branch');
1090
+ return;
1091
+ }
1092
+ if (row.isMeta) return;
902
1093
  const payload = row.payload;
1094
+ if (row.type === 'event_msg' && result.events) {
1095
+ if (payload?.type === 'task_started') result.sourceTurn = payload.turn_id;
1096
+ if (['turn_aborted', 'task_complete'].includes(payload?.type)) {
1097
+ const turn = payload.turn_id ? result.sourceTurns.get(payload.turn_id) : result.turn;
1098
+ if (turn) result.events.push({
1099
+ kind: 'turn_end', turn, status: payload.type === 'turn_aborted' ? 'interrupted' : 'completed',
1100
+ });
1101
+ }
1102
+ }
903
1103
  if (row.type === 'event_msg' && payload?.type === 'token_count' && result.readStats) {
904
1104
  // Codex repeats cumulative snapshots. The latest recorded total already
905
1105
  // includes earlier turns, and may be available even when only a tail was read.
@@ -916,7 +1116,15 @@ function readCodexRow(result, row) {
916
1116
  }
917
1117
  if (row.type !== 'response_item') return;
918
1118
  if (payload?.type === 'message') {
919
- appendMessage(result, payload.role, textBlocks(payload.content, result), row.timestamp);
1119
+ if (result.events && ['user', 'assistant'].includes(payload.role)) {
1120
+ const previousTurn = result.turn;
1121
+ readSourceBlocks(result, payload.role, payload.content, row.timestamp);
1122
+ if (result.turn !== previousTurn && typeof result.sourceTurn === 'string') {
1123
+ result.sourceTurns.set(result.sourceTurn, result.turn);
1124
+ }
1125
+ } else {
1126
+ appendMessage(result, payload.role, textBlocks(payload.content, result), row.timestamp);
1127
+ }
920
1128
  return;
921
1129
  }
922
1130
  if (payload?.type === 'reasoning') {
@@ -934,12 +1142,13 @@ function readCodexRow(result, row) {
934
1142
  }
935
1143
  if (payload?.type === 'function_call_output' || payload?.type === 'custom_tool_call_output') {
936
1144
  const output = payload.output ?? payload.content;
937
- const text = Array.isArray(output)
938
- ? output.filter(item => item?.type === 'input_text' && typeof item.text === 'string').map(item => item.text).join('\n')
939
- : output;
1145
+ const text = result.events ? traceValue(sourceToolOutput(result, output, payload.call_id))
1146
+ : (Array.isArray(output)
1147
+ ? output.filter(item => item?.type === 'input_text' && typeof item.text === 'string').map(item => item.text).join('\n')
1148
+ : output);
940
1149
  const value = typeof text === 'string' ? text : '';
941
1150
  addToolResult(result, payload.call_id, value, payload.status === 'failed'
942
- || /^(?:exit code: [1-9]|process exited with code [1-9])/im.test(value));
1151
+ || /^(?:exit code: [1-9]|process exited with code [1-9])/im.test(value), ...(result.events ? [row.timestamp] : []));
943
1152
  }
944
1153
  }
945
1154
 
@@ -994,7 +1203,7 @@ function parseTail(buffer) {
994
1203
  };
995
1204
  }
996
1205
 
997
- async function readJsonlHistory(descriptor, cwd, config, result) {
1206
+ async function allowedJsonl(descriptor, config) {
998
1207
  const codex = descriptor.kind === 'codex';
999
1208
  const locations = codex ? codexLocations : ['projects'];
1000
1209
  const bases = (await Promise.all(configuredRoots(config, descriptor.kind)
@@ -1007,6 +1216,12 @@ async function readJsonlHistory(descriptor, cwd, config, result) {
1007
1216
  if (file) break;
1008
1217
  }
1009
1218
  }
1219
+ return file;
1220
+ }
1221
+
1222
+ async function readJsonlHistory(descriptor, cwd, config, result) {
1223
+ const codex = descriptor.kind === 'codex';
1224
+ const file = await allowedJsonl(descriptor, config);
1010
1225
  if (!file) return;
1011
1226
  if (codex && compressedCodexFile.test(file)) return readCompressedCodex(file, cwd, result);
1012
1227
  if (!jsonlFile.test(file)) return;
@@ -1038,7 +1253,8 @@ async function readJsonlHistory(descriptor, cwd, config, result) {
1038
1253
 
1039
1254
  async function allowedArchive(descriptor, config) {
1040
1255
  const candidates = descriptor.kind === 'agentsview' ? config.archiveFiles ?? []
1041
- : (await Promise.all(configuredRoots(config, 'opencode').map(opencodeDatabase))).filter(Boolean);
1256
+ : (await Promise.all(configuredRoots(config, descriptor.kind)
1257
+ .map(descriptor.kind === 'copilot' ? copilotDatabase : opencodeDatabase))).filter(Boolean);
1042
1258
  const actual = await physicalPath(descriptor.file);
1043
1259
  if (!actual) return undefined;
1044
1260
  for (const candidate of candidates) {
@@ -1104,7 +1320,439 @@ async function readHistory(archive, cwd, config, result) {
1104
1320
  if (['codex', 'claude', 'qoder', 'qwen', 'workbuddy'].includes(archive.kind)) await readJsonlHistory(archive, cwd, config, result);
1105
1321
  if (archive.kind === 'gemini') await readGeminiHistory(archive, cwd, config, result);
1106
1322
  if (archive.kind === 'antigravity') await readAntigravityHistory(archive, cwd, config, result);
1107
- if (archive.kind === 'copilot') await readCopilotHistory(archive, cwd, config, result);
1323
+ if (archive.kind === 'copilot' && archive.storage === 'sqlite') {
1324
+ for await (const event of readSourceEvents(archive, { config, sourceCwd: cwd })) {
1325
+ if (event.kind === 'message') appendMessage(result, event.role, event.text, event.time);
1326
+ if (event.kind === 'gap' && result.limits) markSourcePartial(result, event.reason);
1327
+ }
1328
+ } else if (archive.kind === 'copilot') await readCopilotHistory(archive, cwd, config, result);
1329
+ }
1330
+
1331
+ function readSourceMessageRow(result, kind, row) {
1332
+ if (kind === 'codex') {
1333
+ readCodexRow(result, row);
1334
+ } else if (row.isCompactSummary || (row.type === 'system' && row.subtype === 'compact_boundary')) {
1335
+ markSourcePartial(result);
1336
+ } else if (row.isSidechain) {
1337
+ markSourcePartial(result, 'unresolved-branch');
1338
+ } else if (!row.isMeta) {
1339
+ if (kind === 'workbuddy') {
1340
+ if (row.type === 'message') readSourceBlocks(result, row.role === 'human' ? 'user' : row.role, row.content, row.timestamp);
1341
+ if (row.type === 'reasoning') {
1342
+ const text = blocks => Array.isArray(blocks) ? blocks
1343
+ .filter(block => block?.type === 'reasoning_text' && typeof block.text === 'string')
1344
+ .map(block => block.text).join('\n\n') : '';
1345
+ addSummary(result, text(row.content) || text(row.rawContent), row.timestamp, result.sourceId);
1346
+ }
1347
+ if (row.type === 'function_call') {
1348
+ readTool(result, row.name, row.arguments);
1349
+ addToolCall(result, row.name, row.callId ?? row.call_id ?? row.id, row.arguments, row.timestamp);
1350
+ }
1351
+ if (['function_call_output', 'function_call_result'].includes(row.type)) {
1352
+ const blocks = Array.isArray(row.output) ? row.output : [row.output];
1353
+ const output = blocks.length && blocks.every(block => block?.type === 'text' && typeof block.text === 'string')
1354
+ ? blocks.map(block => block.text).join('\n') : row.output;
1355
+ const status = row.status === 'incomplete' ? 'incomplete' : ['error', 'failed'].includes(row.status);
1356
+ addToolResult(result, row.callId ?? row.call_id, output, status, row.timestamp);
1357
+ }
1358
+ } else if (kind === 'qwen' && Array.isArray(row.message?.parts)) {
1359
+ const parts = row.message.parts;
1360
+ if (row.type === 'user' || row.type === 'assistant') {
1361
+ readSourceBlocks(result, row.type, parts, row.timestamp, {
1362
+ functionParts: true,
1363
+ text: parts.map(part => sourceBlockText(part, true)).filter(Boolean).join('\n'),
1364
+ });
1365
+ }
1366
+ if (['user', 'tool_result'].includes(row.type)) readFunctionParts(result, parts, row.timestamp);
1367
+ } else if (row.type === 'user' || row.type === 'assistant') {
1368
+ readSourceBlocks(result, row.type, row.message?.content, row.timestamp);
1369
+ }
1370
+ }
1371
+ }
1372
+
1373
+ function readFunctionParts(result, parts, time) {
1374
+ for (const part of parts) {
1375
+ if (part?.functionCall) {
1376
+ const { name, id, args } = part.functionCall;
1377
+ readTool(result, name, args);
1378
+ addToolCall(result, name, id, args, time);
1379
+ }
1380
+ if (part?.functionResponse) {
1381
+ const { id, response } = part.functionResponse;
1382
+ const error = Boolean(response?.error);
1383
+ const output = response && typeof response === 'object' && Object.keys(response).length === 1
1384
+ ? response.error ?? response.output ?? response : response;
1385
+ addToolResult(result, id, output, error, time);
1386
+ }
1387
+ }
1388
+ }
1389
+
1390
+ function sourceIdentity(result, row, ordinal) {
1391
+ result.sourceId = row.uuid ?? row.message?.id ?? row.payload?.id ?? row.id ?? `row:${ordinal}`;
1392
+ result.parentId = row.parentUuid ?? row.message?.parentId;
1393
+ }
1394
+
1395
+ async function* jsonlSourceEvents(archive, options, result) {
1396
+ const { config, sourceCwd, signal } = options;
1397
+ const file = await allowedJsonl(archive, config);
1398
+ if (!file) {
1399
+ yield { kind: 'gap', reason: compressedCodexFile.test(archive.file) && !hasZstd ? 'unsupported-compression' : 'source-unavailable' };
1400
+ return;
1401
+ }
1402
+ let validated = false;
1403
+ let ordinal = 0;
1404
+ let pendingBytes = 0;
1405
+ let pending = [];
1406
+ for await (const { row, bytes, gap } of sourceJsonl(file, { compressed: compressedCodexFile.test(file), signal })) {
1407
+ if (gap) {
1408
+ yield { kind: 'gap', reason: gap };
1409
+ continue;
1410
+ }
1411
+ ordinal++;
1412
+ if (!validated) {
1413
+ // Codex authenticates the session before any content can leave the reader.
1414
+ const cwd = await nativeCwd(file, archive.kind, [row]);
1415
+ if (!cwd) {
1416
+ pendingBytes += bytes;
1417
+ if (archive.kind === 'codex' || pendingBytes > sourceValueLimit || pending.length >= 65_536) {
1418
+ yield { kind: 'gap', reason: 'source-metadata-missing' };
1419
+ return;
1420
+ }
1421
+ pending.push([row, ordinal]);
1422
+ continue;
1423
+ }
1424
+ if (!await sameDirectory(cwd, sourceCwd)
1425
+ || (archive.kind === 'codex' && archive.id && row.payload?.id && row.payload.id !== archive.id)) {
1426
+ yield { kind: 'gap', reason: 'source-mismatch' };
1427
+ return;
1428
+ }
1429
+ validated = true;
1430
+ for (const [earlier, sequence] of pending) {
1431
+ sourceIdentity(result, earlier, sequence);
1432
+ readSourceMessageRow(result, archive.kind, earlier);
1433
+ yield* result.events.splice(0);
1434
+ }
1435
+ pending = [];
1436
+ }
1437
+ sourceIdentity(result, row, ordinal);
1438
+ readSourceMessageRow(result, archive.kind, row);
1439
+ yield* result.events.splice(0);
1440
+ }
1441
+ if (!validated && ordinal) yield { kind: 'gap', reason: 'source-metadata-missing' };
1442
+ }
1443
+
1444
+ function* agentsViewEvents(db, id, result) {
1445
+ const fields = columns(db, 'messages');
1446
+ if (!['ordinal', 'role', 'session_id'].every(field => fields.has(field))
1447
+ || (!fields.has('dialogue_text') && !fields.has('content'))) {
1448
+ markSourcePartial(result, 'unsupported-source-schema');
1449
+ return;
1450
+ }
1451
+ const content = fields.has('dialogue_text') ? 'dialogue_text' : 'content';
1452
+ const system = fields.has('is_system') ? ' AND is_system = 0' : '';
1453
+ const time = fields.has('timestamp') ? 'timestamp' : 'NULL';
1454
+ for (const row of db.prepare(`SELECT ordinal, role, ${content} AS text, ${time} AS time FROM messages
1455
+ WHERE session_id = ? AND role IN ('user','assistant')${system} ORDER BY ordinal`).iterate(id)) {
1456
+ result.sourceId = `message:${row.ordinal}`;
1457
+ appendMessage(result, row.role, row.text, row.time);
1458
+ yield* result.events.splice(0);
1459
+ }
1460
+ const toolFields = columns(db, 'tool_calls');
1461
+ if (!toolFields.has('session_id')) return;
1462
+ if (toolFields.has('skill_name')) {
1463
+ for (const row of db.prepare('SELECT DISTINCT skill_name FROM tool_calls WHERE session_id = ?').iterate(id)) {
1464
+ addSkill(result, row.skill_name);
1465
+ }
1466
+ }
1467
+ if (db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? LIMIT 1').get(id)) {
1468
+ markSourcePartial(result, 'archive-tool-details-unavailable');
1469
+ }
1470
+ }
1471
+
1472
+ function mergeOpenCodeParts(content, rows, result) {
1473
+ for (const row of rows) {
1474
+ const data = json(row.data);
1475
+ if (!data) {
1476
+ markSourcePartial(result, 'malformed-record');
1477
+ continue;
1478
+ }
1479
+ const part = { ...data, type: row.type, ...(row.call_id ? { callID: row.call_id } : {}) };
1480
+ const current = content[row.ordinal];
1481
+ if (!current || current.type !== part.type) {
1482
+ content.push(part);
1483
+ continue;
1484
+ }
1485
+ const sameText = part.text === undefined || current.text === undefined || part.text === current.text;
1486
+ const sameCall = !part.callID || !current.callID || current.callID === part.callID;
1487
+ if (!sameText || !sameCall) {
1488
+ markSourcePartial(result, 'unresolved-source-projection');
1489
+ continue;
1490
+ }
1491
+ content[row.ordinal] = { ...current, ...part, ...(part.state ? { state: { ...current.state, ...part.state } } : {}) };
1492
+ }
1493
+ return content;
1494
+ }
1495
+
1496
+ function* openCodeEvents(db, id, result) {
1497
+ const projection = columns(db, 'session_message');
1498
+ const messages = columns(db, 'message');
1499
+ const parts = columns(db, 'part');
1500
+ // The normalized part table carries text and tool statuses directly. If
1501
+ // both layouts exist and contain this session, never replay the projection
1502
+ // as a second copy.
1503
+ if (['id', 'session_id', 'data', 'time_created'].every(field => messages.has(field))
1504
+ && ['session_id', 'message_id', 'data', 'time_created'].every(field => parts.has(field))
1505
+ && db.prepare('SELECT 1 FROM message WHERE session_id = ? LIMIT 1').get(id)) {
1506
+ const order = parts.has('id') ? 'time_created, id' : 'time_created';
1507
+ const readParts = db.prepare(`SELECT data FROM part WHERE session_id = ? AND message_id = ? ORDER BY ${order}`);
1508
+ for (const row of db.prepare('SELECT id, data, time_created AS time FROM message WHERE session_id = ? ORDER BY time, id').iterate(id)) {
1509
+ const data = json(row.data);
1510
+ result.sourceId = row.id;
1511
+ result.parentId = data?.parentID;
1512
+ const content = [];
1513
+ for (const part of readParts.iterate(id, row.id)) {
1514
+ const block = json(part.data);
1515
+ if (block) content.push(block);
1516
+ else markSourcePartial(result, 'malformed-record');
1517
+ }
1518
+ if (['user', 'assistant'].includes(data?.role)) readSourceBlocks(result, data.role, content, row.time);
1519
+ else if (!data) markSourcePartial(result, 'malformed-record');
1520
+ yield* result.events.splice(0);
1521
+ }
1522
+ if (['type', 'session_id'].every(field => projection.has(field))) {
1523
+ const messageCount = db.prepare('SELECT count(*) AS count FROM message WHERE session_id = ?').get(id).count;
1524
+ const projectionCount = db.prepare("SELECT count(*) AS count FROM session_message WHERE session_id = ? AND type IN ('user','assistant')").get(id).count;
1525
+ if (projectionCount > messageCount) markSourcePartial(result, 'unresolved-source-projection');
1526
+ }
1527
+ return;
1528
+ }
1529
+ if (['type', 'session_id', 'data'].every(field => projection.has(field))) {
1530
+ const seq = projection.has('seq') ? 'seq' : projection.has('time_created') ? 'time_created' : 'rowid';
1531
+ const time = projection.has('time_created') ? 'time_created' : 'NULL';
1532
+ const messageId = projection.has('id') ? 'id' : 'NULL';
1533
+ const projectedParts = columns(db, 'session_part');
1534
+ const readParts = projection.has('id') && ['session_id', 'message_id', 'ordinal', 'type', 'data'].every(field => projectedParts.has(field))
1535
+ ? db.prepare(`SELECT ordinal, type, data, ${projectedParts.has('call_id') ? 'call_id' : 'NULL'} AS call_id FROM session_part
1536
+ WHERE session_id = ? AND message_id = ? ORDER BY ordinal`) : undefined;
1537
+ for (const row of db.prepare(`SELECT ${messageId} AS id, type, data, ${seq} AS seq, ${time} AS time FROM session_message
1538
+ WHERE session_id = ? AND type IN ('user','assistant','skill','idle') ORDER BY seq, id`).iterate(id)) {
1539
+ const data = json(row.data);
1540
+ if (!data) markSourcePartial(result, 'malformed-record');
1541
+ else if (row.type === 'skill') addSkill(result, data.name ?? data.skill);
1542
+ else if (row.type === 'idle') {
1543
+ const status = data.outcome === 'succeeded' ? 'completed'
1544
+ : ['aborted', 'cancelled', 'failed', 'interrupted'].includes(data.outcome) ? 'interrupted' : undefined;
1545
+ if (status && result.turn) result.events.push({ kind: 'turn_end', status, turn: result.turn });
1546
+ }
1547
+ else {
1548
+ result.sourceId = row.id ?? data.id ?? `message:${row.seq}`;
1549
+ const content = Array.isArray(data.content) ? [...data.content] : [];
1550
+ if (readParts) mergeOpenCodeParts(content, readParts.iterate(id, row.id), result);
1551
+ if (Array.isArray(data.files)) {
1552
+ content.push(...data.files.filter(file => file && typeof file === 'object').map(file => ({ type: 'file', ...file })));
1553
+ }
1554
+ readSourceBlocks(result, row.type, content, row.time, {
1555
+ text: data.text ?? (typeof data.content === 'string' ? data.content : undefined),
1556
+ });
1557
+ }
1558
+ yield* result.events.splice(0);
1559
+ }
1560
+ return;
1561
+ }
1562
+ if (!messages.size || !parts.size) markSourcePartial(result, 'unsupported-source-schema');
1563
+ }
1564
+
1565
+ function* copilotSqliteEvents(db, id, result) {
1566
+ for (const row of db.prepare('SELECT id, user_message, assistant_response, timestamp FROM turns WHERE session_id = ? ORDER BY turn_index, id').iterate(id)) {
1567
+ result.sourceId = `request:${row.id}`;
1568
+ appendMessage(result, 'user', row.user_message, row.timestamp);
1569
+ result.sourceId = `response:${row.id}`;
1570
+ appendMessage(result, 'assistant', row.assistant_response, row.timestamp, { estimatedTime: true });
1571
+ yield* result.events.splice(0);
1572
+ }
1573
+ markSourcePartial(result, 'source-dialogue-only');
1574
+ }
1575
+
1576
+ async function* databaseSourceEvents(archive, options, result) {
1577
+ const { sourceCwd, config, signal } = options;
1578
+ const file = await allowedArchive(archive, config);
1579
+ if (!file) {
1580
+ yield { kind: 'gap', reason: 'source-unavailable' };
1581
+ return;
1582
+ }
1583
+ const { DatabaseSync } = await import('node:sqlite');
1584
+ const db = new DatabaseSync(file, { readOnly: true });
1585
+ try {
1586
+ db.exec('PRAGMA trusted_schema = OFF; PRAGMA busy_timeout = 1000; BEGIN');
1587
+ let cwd;
1588
+ let events;
1589
+ if (archive.kind === 'agentsview') {
1590
+ const fields = columns(db, 'sessions');
1591
+ const deleted = fields.has('deleted_at') ? ' AND deleted_at IS NULL' : '';
1592
+ const machine = fields.has('machine') ? " AND machine IN ('', 'local')" : '';
1593
+ cwd = db.prepare('SELECT cwd FROM sessions WHERE id = ?' + deleted + machine).get(archive.id)?.cwd;
1594
+ events = agentsViewEvents;
1595
+ } else if (archive.kind === 'copilot' && copilotTables(db)) {
1596
+ const host = copilotHostFilter(columns(db, 'sessions'));
1597
+ cwd = localDirectory(db.prepare('SELECT cwd FROM sessions WHERE id = ?' + host).get(archive.id)?.cwd);
1598
+ events = copilotSqliteEvents;
1599
+ } else if (archive.kind === 'opencode' && opencodeTables(db).includes(archive.table)) {
1600
+ cwd = db.prepare(`SELECT directory FROM ${archive.table} WHERE id = ?`).get(archive.id)?.directory;
1601
+ events = openCodeEvents;
1602
+ }
1603
+ if (!events) {
1604
+ yield { kind: 'gap', reason: 'unsupported-source-schema' };
1605
+ } else if (!await sameDirectory(cwd, sourceCwd)) {
1606
+ yield { kind: 'gap', reason: 'source-mismatch' };
1607
+ } else {
1608
+ for (const event of events(db, archive.id, result)) {
1609
+ signal?.throwIfAborted();
1610
+ yield event;
1611
+ }
1612
+ yield* result.events.splice(0);
1613
+ }
1614
+ } finally {
1615
+ db.close();
1616
+ }
1617
+ }
1618
+
1619
+ function geminiEvent(result, row, index) {
1620
+ const message = row?.message ?? row;
1621
+ if (!['user', 'gemini', 'assistant'].includes(message?.type)) return;
1622
+ sourceIdentity(result, row, index);
1623
+ const role = message.type === 'gemini' ? 'assistant' : message.type;
1624
+ const blocks = Array.isArray(message.content) ? message.content : [];
1625
+ readSourceBlocks(result, role, message.content, message.timestamp ?? row.timestamp, {
1626
+ functionParts: true,
1627
+ text: blocks.length ? blocks.map(block => sourceBlockText(block, true)).filter(Boolean).join('\n') : undefined,
1628
+ });
1629
+ if (role === 'user') readFunctionParts(result, blocks, message.timestamp);
1630
+ for (const tool of Array.isArray(message.toolCalls) ? message.toolCalls : []) {
1631
+ readTool(result, tool.name, tool.args);
1632
+ addToolCall(result, tool.name, tool.id, tool.args, tool.timestamp ?? message.timestamp);
1633
+ if (tool.result !== undefined || tool.error !== undefined) {
1634
+ addToolResult(result, tool.id, tool.result ?? tool.error, tool.status === 'error' || Boolean(tool.error), tool.timestamp);
1635
+ }
1636
+ }
1637
+ }
1638
+
1639
+ function* copilotEvent(result, requests) {
1640
+ let index = 0;
1641
+ for (const request of requests) {
1642
+ index++;
1643
+ result.sourceId = request?.requestId ?? request?.id ?? `request:${index}`;
1644
+ const requestId = result.sourceId;
1645
+ appendMessage(result, 'user', request?.message?.text, request?.timestamp);
1646
+ const response = Array.isArray(request?.response) ? request.response : [];
1647
+ result.sourceId = `${requestId}:response`;
1648
+ let text = '';
1649
+ const flush = () => {
1650
+ appendMessage(result, 'assistant', text, request?.timestamp, { estimatedTime: true });
1651
+ text = '';
1652
+ };
1653
+ for (const item of response) {
1654
+ if (item?.kind === 'thinking') {
1655
+ const value = item.value?.value ?? item.value;
1656
+ if (typeof value === 'string' && value.trim()) {
1657
+ flush();
1658
+ addSummary(result, value, undefined);
1659
+ }
1660
+ continue;
1661
+ }
1662
+ if (item?.kind !== 'toolInvocationSerialized') {
1663
+ text += copilotText(item);
1664
+ continue;
1665
+ }
1666
+ flush();
1667
+ const callId = item.toolCallId ?? item.invocationId;
1668
+ readTool(result, item.toolId, item.parameters);
1669
+ addToolCall(result, item.toolId ?? item.name, callId, item.parameters, request.timestamp);
1670
+ if (item.resultDetails !== undefined || item.result !== undefined || item.error !== undefined) {
1671
+ addToolResult(result, callId, item.resultDetails ?? item.result ?? item.error, Boolean(item.error));
1672
+ }
1673
+ }
1674
+ flush();
1675
+ yield* result.events.splice(0);
1676
+ }
1677
+ }
1678
+
1679
+ async function* editorSourceEvents(archive, { sourceCwd, config, signal }, result) {
1680
+ const copilot = archive.kind === 'copilot';
1681
+ const file = await (copilot ? allowedEditorChat : allowedGemini)(archive, sourceCwd, config);
1682
+ if (!file) {
1683
+ yield { kind: 'gap', reason: 'source-unavailable' };
1684
+ return;
1685
+ }
1686
+ const jsonl = /\.jsonl$/i.test(file);
1687
+ if (!jsonl) {
1688
+ const { row, gap } = await sourceJson(file, signal);
1689
+ if (gap) {
1690
+ yield { kind: 'gap', reason: gap };
1691
+ } else if (copilot && Array.isArray(row?.requests)) {
1692
+ yield* copilotEvent(result, row.requests);
1693
+ } else if (Array.isArray(row?.messages)) {
1694
+ for (const [index, message] of row.messages.entries()) {
1695
+ signal?.throwIfAborted();
1696
+ geminiEvent(result, message, index + 1);
1697
+ yield* result.events.splice(0);
1698
+ }
1699
+ } else {
1700
+ yield { kind: 'gap', reason: 'unsupported-source-schema' };
1701
+ }
1702
+ return;
1703
+ }
1704
+ let state;
1705
+ let index = 0;
1706
+ let uncertain = false;
1707
+ for await (const { row, gap } of sourceJsonl(file, { signal })) {
1708
+ if (gap) {
1709
+ yield { kind: 'gap', reason: gap };
1710
+ } else if (copilot) {
1711
+ if (row.kind === 0) state = row.v;
1712
+ else if (!applyCopilotOp(state, row)) uncertain = true;
1713
+ } else {
1714
+ geminiEvent(result, row, ++index);
1715
+ yield* result.events.splice(0);
1716
+ }
1717
+ }
1718
+ if (copilot) {
1719
+ if (uncertain) yield { kind: 'gap', reason: 'unsupported-incremental-edit' };
1720
+ if (Array.isArray(state?.requests)) yield* copilotEvent(result, state.requests);
1721
+ else yield { kind: 'gap', reason: 'unsupported-source-schema' };
1722
+ }
1723
+ }
1724
+
1725
+ export async function* readSourceEvents(archive, options) {
1726
+ const { signal } = options;
1727
+ const result = { events: [], usedSkills: new Set(), readStats: {}, turn: 0, sourceTurns: new Map() };
1728
+ try {
1729
+ signal?.throwIfAborted();
1730
+ if (['codex', 'claude', 'qoder', 'qwen', 'workbuddy'].includes(archive?.kind)) {
1731
+ yield* jsonlSourceEvents(archive, options, result);
1732
+ } else if (['opencode', 'agentsview'].includes(archive?.kind) || archive?.kind === 'copilot' && archive.storage === 'sqlite') {
1733
+ yield* databaseSourceEvents(archive, options, result);
1734
+ } else if (['copilot', 'gemini'].includes(archive?.kind)) {
1735
+ yield* editorSourceEvents(archive, options, result);
1736
+ } else {
1737
+ yield { kind: 'gap', reason: 'unsupported-source' };
1738
+ }
1739
+ } catch (error) {
1740
+ signal?.throwIfAborted();
1741
+ yield { kind: 'gap', reason: error.sourceReason ?? 'source-unreadable' };
1742
+ }
1743
+ const { tokens } = result.readStats;
1744
+ if (result.usedSkills.size || tokens) {
1745
+ yield { kind: 'metadata', usedSkills: [...result.usedSkills].sort(), ...(tokens ? { sourceStats: { tokens } } : {}) };
1746
+ }
1747
+ }
1748
+
1749
+ export async function probeConversation(archive, options) {
1750
+ let reason;
1751
+ for await (const event of readSourceEvents(archive, options)) {
1752
+ if (event.role === 'user' && ['message', 'attachment'].includes(event.kind)) return { state: 'ready' };
1753
+ if (event.kind === 'gap') reason ??= event.reason;
1754
+ }
1755
+ return reason ? { state: 'unknown', reason } : { state: 'empty' };
1108
1756
  }
1109
1757
 
1110
1758
  export async function readConversationHistory(archive, cwd, config) {