@wwwfz/dsh-agent-bridge 0.9.0 → 0.11.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/README.md +61 -99
- package/THIRD_PARTY_NOTICES.md +5 -63
- package/package.json +2 -1
- package/src/assets.js +32 -19
- package/src/catalog.js +1139 -906
- package/src/client.js +1218 -623
- package/src/conversation-readers.js +198 -0
- package/src/conversation-search.js +55 -0
- package/src/conversation-store.js +747 -0
- package/src/export.js +35 -2
- package/src/handoff.js +149 -0
- package/src/history-attachment.js +41 -0
- package/src/index.js +153 -7
- package/src/native-transcript.js +217 -0
- package/src/project-archive.js +50 -0
- package/src/projects.js +877 -149
- package/src/session-import.js +65 -19
- package/src/session-trace.js +1 -1
- package/src/skill-cli.js +287 -0
- package/src/skill-history.js +129 -0
- package/src/skill-output.js +19 -0
- package/src/skill-package.js +303 -321
- package/src/skill-provider.js +155 -193
- package/src/watch.js +11 -1
- package/web/inline-process.css +22 -0
- package/web/panel.css +547 -607
- package/web/panel.html +298 -277
- package/web/panel.js +3339 -2334
- package/web/reader.css +311 -0
- package/web/relay-categories.js +3 -0
- package/web/share-redaction.js +136 -0
- package/web/share-review.js +204 -0
package/src/projects.js
CHANGED
|
@@ -4,8 +4,10 @@ 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';
|
|
8
|
+
import { conversationId, keyFor, pathKey as projectPathKey } from './handoff.js';
|
|
9
|
+
import { readCodexAliases } from './project-archive.js';
|
|
7
10
|
|
|
8
|
-
const maxSessions = 8_000;
|
|
9
11
|
const maxMessages = 36;
|
|
10
12
|
const maxMessageLength = 4_000;
|
|
11
13
|
const maxTranscriptBytes = 12 * 1024 * 1024;
|
|
@@ -16,6 +18,7 @@ const codexLocations = ['sessions', 'archived_sessions'];
|
|
|
16
18
|
const jsonlFile = /\.jsonl$/i;
|
|
17
19
|
const compressedCodexFile = /\.jsonl\.zst$/i;
|
|
18
20
|
const hasZstd = typeof zlib.createZstdDecompress === 'function';
|
|
21
|
+
const indexedCodexHeaders = new Map();
|
|
19
22
|
const conversationLimits = { messages: 600, characters: 160_000, messageLength: 24_000 };
|
|
20
23
|
const traceItemLimit = 600;
|
|
21
24
|
const traceTextLimit = 8_000;
|
|
@@ -186,12 +189,41 @@ async function archivedProjects(file) {
|
|
|
186
189
|
const deleted = fields.has('deleted_at') ? ' AND deleted_at IS NULL' : '';
|
|
187
190
|
const machine = fields.has('machine') ? " AND machine IN ('', 'local')" : '';
|
|
188
191
|
const title = fields.has('title') ? 'substr(title, 1, 200)' : 'NULL';
|
|
189
|
-
|
|
190
|
-
.
|
|
192
|
+
const rows = db.prepare(`SELECT id, cwd, agent, ${sort} AS date, ${title} AS title FROM sessions WHERE cwd <> ''${deleted}${machine} ORDER BY ${sort} DESC`)
|
|
193
|
+
.iterate();
|
|
194
|
+
return Array.from(rows, ({ id, cwd, agent, date, title }) => ({ cwd, agent, archive: { kind: 'agentsview', agent, file, id, date, title } }));
|
|
191
195
|
});
|
|
192
196
|
}
|
|
193
197
|
|
|
194
|
-
async function
|
|
198
|
+
async function indexedCodexMetadata(file, info) {
|
|
199
|
+
const stamp = [info.dev, info.ino, info.size, info.mtimeNs, info.ctimeNs].join(':');
|
|
200
|
+
const cached = indexedCodexHeaders.get(file);
|
|
201
|
+
if (cached?.stamp === stamp) return cached.meta;
|
|
202
|
+
const input = compressedCodexFile.test(file) ? zstdChunks(file) : createReadStream(file, { highWaterMark: 8 * 1024 });
|
|
203
|
+
const chunks = [];
|
|
204
|
+
let bytes = 0;
|
|
205
|
+
for await (const chunk of input) {
|
|
206
|
+
const newline = chunk.indexOf(10);
|
|
207
|
+
const line = newline < 0 ? chunk : chunk.subarray(0, newline);
|
|
208
|
+
bytes += line.length;
|
|
209
|
+
if (bytes > transcriptHeaderBytes) break;
|
|
210
|
+
chunks.push(line);
|
|
211
|
+
if (newline >= 0) break;
|
|
212
|
+
}
|
|
213
|
+
const row = bytes <= transcriptHeaderBytes && json(Buffer.concat(chunks).toString('utf8').replace(/^\uFEFF/, ''));
|
|
214
|
+
const payload = row?.type === 'session_meta' && row.payload;
|
|
215
|
+
const meta = payload ? {
|
|
216
|
+
id: typeof payload.id === 'string' ? payload.id : undefined,
|
|
217
|
+
cwd: typeof payload.cwd === 'string' ? payload.cwd : undefined,
|
|
218
|
+
} : undefined;
|
|
219
|
+
// Keep only identity fields, never conversation text. Unchanged indexed rolls
|
|
220
|
+
// already require a stat for containment/type checking and need no second read.
|
|
221
|
+
if (!cached && indexedCodexHeaders.size >= 16_384) indexedCodexHeaders.delete(indexedCodexHeaders.keys().next().value);
|
|
222
|
+
indexedCodexHeaders.set(file, { stamp, meta });
|
|
223
|
+
return meta;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function codexProjects(root, configured) {
|
|
195
227
|
const entries = await directories(root);
|
|
196
228
|
const states = entries.filter(entry => entry.isFile() && /^state_\d+\.sqlite$/.test(entry.name));
|
|
197
229
|
states.sort((a, b) => Number(b.name.match(/\d+/)[0]) - Number(a.name.match(/\d+/)[0]));
|
|
@@ -206,7 +238,7 @@ async function codexProjects(root) {
|
|
|
206
238
|
if (!['cwd', 'rollout_path', 'id'].every(field => fields.has(field))) return undefined;
|
|
207
239
|
const sort = fields.has('updated_at') ? 'updated_at' : 'id';
|
|
208
240
|
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
|
|
241
|
+
return db.prepare(`SELECT id, cwd, rollout_path, ${sort} AS date, ${title} AS title FROM threads WHERE cwd <> '' ORDER BY ${sort} DESC`).all();
|
|
210
242
|
});
|
|
211
243
|
if (indexed) break;
|
|
212
244
|
} catch (error) {
|
|
@@ -215,29 +247,63 @@ async function codexProjects(root) {
|
|
|
215
247
|
}
|
|
216
248
|
const bases = await transcriptDirectories(root, codexLocations);
|
|
217
249
|
if (!bases.length) throw indexError ?? missingStore();
|
|
250
|
+
const profile = codexLocations.includes(path.basename(root).toLowerCase()) ? path.dirname(root) : root;
|
|
251
|
+
const rolloutRoots = configured.some(dir => pathKey(dir) === pathKey(profile))
|
|
252
|
+
? codexLocations.map(name => path.join(profile, name))
|
|
253
|
+
: configured.filter(dir => pathKey(path.dirname(dir)) === pathKey(profile) && codexLocations.includes(path.basename(dir).toLowerCase()));
|
|
254
|
+
const threadKey = (cwd, id) => typeof cwd === 'string' && typeof id === 'string' && id.trim()
|
|
255
|
+
? JSON.stringify([pathKey(cwd), id]) : undefined;
|
|
256
|
+
const observed = new Map();
|
|
257
|
+
function remember(key, file) {
|
|
258
|
+
if (!key || typeof file !== 'string' || !path.isAbsolute(file)) return;
|
|
259
|
+
// Windows index rows sometimes store a namespaced path; realpath(), which
|
|
260
|
+
// supplied the old bridge IDs, returned the ordinary absolute path.
|
|
261
|
+
const clean = path.normalize(process.platform === 'win32'
|
|
262
|
+
? file.replace(/^\\\\\?\\UNC\\/i, '\\\\').replace(/^\\\\\?\\/, '') : file);
|
|
263
|
+
if (!(jsonlFile.test(clean) || compressedCodexFile.test(clean)) || !rolloutRoots.some(base => inside(base, clean))) return;
|
|
264
|
+
if (!observed.has(key)) observed.set(key, new Set());
|
|
265
|
+
observed.get(key).add(clean);
|
|
266
|
+
}
|
|
218
267
|
const byFile = new Map();
|
|
219
268
|
for (let offset = 0; offset < (indexed?.length ?? 0); offset += 32) {
|
|
220
269
|
const batch = await Promise.all(indexed.slice(offset, offset + 32).map(async ({ id, cwd, rollout_path, date, title }) => {
|
|
221
|
-
|
|
222
|
-
|
|
270
|
+
if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return;
|
|
271
|
+
remember(threadKey(cwd, id), rollout_path);
|
|
272
|
+
const found = await resolveCodexTranscript(rollout_path, bases);
|
|
273
|
+
if (!found) return;
|
|
274
|
+
const { file, info } = found;
|
|
275
|
+
const meta = await indexedCodexMetadata(file, info).catch(() => undefined);
|
|
276
|
+
if ((meta?.id && id && meta.id !== id)
|
|
277
|
+
|| (meta && (!meta.cwd || !path.isAbsolute(meta.cwd) || (pathKey(meta.cwd) !== pathKey(cwd) && !await sameDirectory(meta.cwd, cwd))))) return;
|
|
278
|
+
return { cwd, agent: 'codex', archive: { kind: 'codex', file, root, id: meta?.id || id, date, title } };
|
|
223
279
|
}));
|
|
224
280
|
for (const project of batch.filter(Boolean)) {
|
|
225
281
|
const key = pathKey(project.archive.file);
|
|
226
282
|
if (!byFile.has(key)) byFile.set(key, project);
|
|
227
283
|
}
|
|
228
284
|
}
|
|
229
|
-
//
|
|
230
|
-
//
|
|
231
|
-
const byId = new Set([...byFile.values()].map(project => project.archive.id).filter(Boolean));
|
|
285
|
+
// SQLite can lag an active or archived transcript. Keep its titles for
|
|
286
|
+
// resolved files and discover any additional plain or compressed transcripts.
|
|
287
|
+
const byId = new Set([...byFile.values()].map(project => threadKey(project.cwd, project.archive.id)).filter(Boolean));
|
|
232
288
|
const include = file => !byFile.has(pathKey(file))
|
|
233
|
-
&& (
|
|
234
|
-
const fallback = await scanJsonlProjects(root, 'codex', bases, 4, include
|
|
289
|
+
&& (jsonlFile.test(file) || (hasZstd && compressedCodexFile.test(file)));
|
|
290
|
+
const fallback = await scanJsonlProjects(root, 'codex', bases, 4, include);
|
|
235
291
|
for (const project of fallback) {
|
|
236
292
|
const { file, id } = project.archive;
|
|
237
|
-
|
|
238
|
-
|
|
293
|
+
const key = threadKey(project.cwd, id);
|
|
294
|
+
remember(key, file);
|
|
295
|
+
if (key && byId.has(key)) continue;
|
|
296
|
+
if (key) byId.add(key);
|
|
239
297
|
byFile.set(pathKey(file), project);
|
|
240
298
|
}
|
|
299
|
+
for (const { cwd, archive } of byFile.values()) {
|
|
300
|
+
const key = threadKey(cwd, archive.id);
|
|
301
|
+
if (!key) continue;
|
|
302
|
+
archive.profile = profile;
|
|
303
|
+
archive.rolloutRoots = rolloutRoots;
|
|
304
|
+
const previousFiles = [...observed.get(key) ?? []].filter(file => file !== archive.file);
|
|
305
|
+
if (previousFiles.length) archive.previousFiles = previousFiles;
|
|
306
|
+
}
|
|
241
307
|
return [...byFile.values()];
|
|
242
308
|
}
|
|
243
309
|
|
|
@@ -249,7 +315,8 @@ async function resolveCodexTranscript(file, bases) {
|
|
|
249
315
|
const actual = await physicalPath(candidate);
|
|
250
316
|
if (!actual || !bases.some(base => inside(base, actual))
|
|
251
317
|
|| !(jsonlFile.test(actual) || hasZstd && compressedCodexFile.test(actual))) continue;
|
|
252
|
-
|
|
318
|
+
const info = await stat(actual, { bigint: true }).catch(() => undefined);
|
|
319
|
+
if (info?.isFile()) return { file: actual, info };
|
|
253
320
|
}
|
|
254
321
|
}
|
|
255
322
|
|
|
@@ -268,14 +335,15 @@ async function opencodeProjects(root) {
|
|
|
268
335
|
if (!tables.length) throw new Error('未识别 OpenCode 会话表');
|
|
269
336
|
const projects = tables.flatMap(table => {
|
|
270
337
|
const title = columns(db, table).has('title') ? 'substr(title, 1, 200)' : 'NULL';
|
|
271
|
-
|
|
272
|
-
|
|
338
|
+
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();
|
|
339
|
+
return Array.from(rows, ({ id, cwd, date, title }) => ({ cwd, agent: 'opencode', archive: { kind: 'opencode', file, id, table, date, title } }));
|
|
273
340
|
});
|
|
274
341
|
const fields = columns(db, 'project');
|
|
275
342
|
if (fields.has('worktree')) {
|
|
276
343
|
const name = fields.has('name') ? 'name' : 'NULL';
|
|
277
|
-
|
|
278
|
-
.
|
|
344
|
+
for (const row of db.prepare(`SELECT worktree AS cwd, ${name} AS name FROM project WHERE worktree <> ''`).iterate()) {
|
|
345
|
+
projects.push({ ...row, agent: 'opencode' });
|
|
346
|
+
}
|
|
279
347
|
}
|
|
280
348
|
return projects;
|
|
281
349
|
});
|
|
@@ -292,22 +360,19 @@ async function opencodeDatabase(root) {
|
|
|
292
360
|
return undefined;
|
|
293
361
|
}
|
|
294
362
|
|
|
295
|
-
async function transcriptFiles(root, depth,
|
|
296
|
-
const files = [];
|
|
363
|
+
async function* transcriptFiles(root, depth, predicate) {
|
|
297
364
|
const stack = [{ root, depth }];
|
|
298
|
-
while (stack.length
|
|
365
|
+
while (stack.length) {
|
|
299
366
|
const current = stack.pop();
|
|
300
367
|
const entries = await directories(current.root).catch(() => []);
|
|
301
368
|
for (const entry of entries) {
|
|
302
369
|
const file = path.join(current.root, entry.name);
|
|
303
|
-
if (entry.isFile() && predicate(entry.name, file))
|
|
304
|
-
if (files.length >= limit) break;
|
|
370
|
+
if (entry.isFile() && predicate(entry.name, file)) yield file;
|
|
305
371
|
if (entry.isDirectory() && current.depth > 0 && entry.name !== 'subagents') {
|
|
306
372
|
stack.push({ root: file, depth: current.depth - 1 });
|
|
307
373
|
}
|
|
308
374
|
}
|
|
309
375
|
}
|
|
310
|
-
return files;
|
|
311
376
|
}
|
|
312
377
|
|
|
313
378
|
async function nativeCwd(file, agent, rows) {
|
|
@@ -327,14 +392,11 @@ async function jsonlProjects(root, agent, children = ['projects'], depth = 1) {
|
|
|
327
392
|
return scanJsonlProjects(root, agent, roots, depth, file => jsonlFile.test(file));
|
|
328
393
|
}
|
|
329
394
|
|
|
330
|
-
async function scanJsonlProjects(root, agent, roots, depth, include
|
|
331
|
-
const files = [];
|
|
332
|
-
for (const target of roots) {
|
|
333
|
-
files.push(...await transcriptFiles(target, depth, limit - files.length, (_name, file) => include(file)));
|
|
334
|
-
}
|
|
395
|
+
async function scanJsonlProjects(root, agent, roots, depth, include) {
|
|
335
396
|
const result = [];
|
|
336
|
-
|
|
337
|
-
|
|
397
|
+
const batch = [];
|
|
398
|
+
async function flush() {
|
|
399
|
+
const rows = await Promise.all(batch.splice(0).map(async file => {
|
|
338
400
|
try {
|
|
339
401
|
const compressed = agent === 'codex' && compressedCodexFile.test(file);
|
|
340
402
|
const { text, truncated, modified } = compressed ? await compressedPrefix(file) : await prefix(file, transcriptHeaderBytes);
|
|
@@ -347,8 +409,15 @@ async function scanJsonlProjects(root, agent, roots, depth, include, limit = max
|
|
|
347
409
|
return cwd ? { cwd, agent, archive: { kind: agent, file, root, id, date: modified, title: title?.slice(0, 200) } } : undefined;
|
|
348
410
|
} catch { return undefined; }
|
|
349
411
|
}));
|
|
350
|
-
result.push(...
|
|
412
|
+
result.push(...rows.filter(Boolean));
|
|
413
|
+
}
|
|
414
|
+
for (const target of roots) {
|
|
415
|
+
for await (const file of transcriptFiles(target, depth, (_name, candidate) => include(candidate))) {
|
|
416
|
+
batch.push(file);
|
|
417
|
+
if (batch.length === 32) await flush();
|
|
418
|
+
}
|
|
351
419
|
}
|
|
420
|
+
if (batch.length) await flush();
|
|
352
421
|
return result;
|
|
353
422
|
}
|
|
354
423
|
|
|
@@ -362,28 +431,66 @@ function editorStores(root) {
|
|
|
362
431
|
return dataDirectories(root, relatives);
|
|
363
432
|
}
|
|
364
433
|
|
|
434
|
+
async function copilotDatabase(root) {
|
|
435
|
+
const actual = await physicalPath(root);
|
|
436
|
+
if (!actual) return undefined;
|
|
437
|
+
if (path.basename(actual).toLowerCase() === 'session-store.db' && (await stat(actual)).isFile()) return actual;
|
|
438
|
+
for (const prefix of ['', 'User']) {
|
|
439
|
+
const file = await scopedFile(path.join(actual, prefix, 'globalStorage', 'github.copilot-chat', 'session-store.db'), actual);
|
|
440
|
+
if (file && (await stat(file)).isFile()) return file;
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function copilotTables(db) {
|
|
445
|
+
const sessions = columns(db, 'sessions');
|
|
446
|
+
const turns = columns(db, 'turns');
|
|
447
|
+
return ['id', 'cwd'].every(field => sessions.has(field))
|
|
448
|
+
&& ['id', 'session_id', 'turn_index', 'user_message', 'assistant_response', 'timestamp'].every(field => turns.has(field));
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
function copilotHostFilter(fields) {
|
|
452
|
+
return fields.has('host_type') ? " AND host_type = 'vscode'" : '';
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
async function copilotDbProjects(file, root) {
|
|
456
|
+
return withDatabase(file, db => {
|
|
457
|
+
if (!copilotTables(db)) throw new Error('Unrecognized Copilot session store');
|
|
458
|
+
const fields = columns(db, 'sessions');
|
|
459
|
+
const title = fields.has('summary') ? 'substr(summary, 1, 200)' : 'NULL';
|
|
460
|
+
const date = fields.has('updated_at') ? 'updated_at' : 'NULL';
|
|
461
|
+
const rows = db.prepare(`SELECT id, cwd, ${title} AS title, ${date} AS date FROM sessions WHERE cwd <> ''${copilotHostFilter(fields)} ORDER BY date DESC, id`)
|
|
462
|
+
.iterate();
|
|
463
|
+
return Array.from(rows, row => ({
|
|
464
|
+
cwd: localDirectory(row.cwd), agent: 'copilot',
|
|
465
|
+
archive: { kind: 'copilot', storage: 'sqlite', file, root, id: row.id, title: row.title, date: row.date },
|
|
466
|
+
}));
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
|
|
365
470
|
async function editorProjects(root, agent) {
|
|
366
471
|
const stores = await editorStores(root);
|
|
367
|
-
|
|
368
|
-
|
|
472
|
+
const database = agent === 'copilot' ? await copilotDatabase(root) : undefined;
|
|
473
|
+
if (!stores.length && !database) throw missingStore();
|
|
474
|
+
const result = [];
|
|
369
475
|
for (const store of stores) {
|
|
370
|
-
|
|
476
|
+
for await (const file of transcriptFiles(store, 1, name => name === 'workspace.json')) {
|
|
477
|
+
try {
|
|
478
|
+
const { text } = await prefix(file, 32 * 1024);
|
|
479
|
+
const value = json(text);
|
|
480
|
+
const cwd = localDirectory(value?.folder);
|
|
481
|
+
if (!cwd) continue;
|
|
482
|
+
result.push({ cwd, agent });
|
|
483
|
+
if (agent !== 'copilot') continue;
|
|
484
|
+
for await (const session of transcriptFiles(path.join(path.dirname(file), 'chatSessions'), 0, name => /\.jsonl?$/i.test(name))) {
|
|
485
|
+
const info = await stat(session).catch(() => undefined);
|
|
486
|
+
if (info) result.push({ cwd, agent, archive: { kind: 'copilot', file: session, root, date: info.mtimeMs } });
|
|
487
|
+
}
|
|
488
|
+
} catch { continue; }
|
|
489
|
+
}
|
|
371
490
|
}
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
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; }
|
|
491
|
+
if (database) {
|
|
492
|
+
try { for (const project of await copilotDbProjects(database, root)) result.push(project); }
|
|
493
|
+
catch (error) { if (!result.length) throw error; }
|
|
387
494
|
}
|
|
388
495
|
return result;
|
|
389
496
|
}
|
|
@@ -391,14 +498,12 @@ async function editorProjects(root, agent) {
|
|
|
391
498
|
async function geminiProjects(root) {
|
|
392
499
|
const [base] = await transcriptDirectories(root, ['tmp']);
|
|
393
500
|
if (!base) throw missingStore();
|
|
394
|
-
const files = await transcriptFiles(base, 1, maxSessions, name => name === '.project_root');
|
|
395
501
|
const result = [];
|
|
396
|
-
for (const file of
|
|
502
|
+
for await (const file of transcriptFiles(base, 1, name => name === '.project_root')) {
|
|
397
503
|
const { text } = await prefix(file, 32 * 1024);
|
|
398
504
|
const cwd = text.trim();
|
|
399
505
|
result.push({ cwd, agent: 'gemini' });
|
|
400
|
-
const
|
|
401
|
-
for (const session of sessions) {
|
|
506
|
+
for await (const session of transcriptFiles(path.join(path.dirname(file), 'chats'), 0, name => /^session-.+\.jsonl?$/i.test(name))) {
|
|
402
507
|
const info = await stat(session).catch(() => undefined);
|
|
403
508
|
if (info) result.push({ cwd, agent: 'gemini', archive: { kind: 'gemini', file: session, root, date: info.mtimeMs } });
|
|
404
509
|
}
|
|
@@ -423,7 +528,7 @@ async function antigravityProjects(root) {
|
|
|
423
528
|
const rows = await withDatabase(database, db => {
|
|
424
529
|
const fields = columns(db, 'conversation_summaries');
|
|
425
530
|
if (!fields.has('workspace_uris')) return [];
|
|
426
|
-
return db.prepare("SELECT workspace_uris FROM conversation_summaries WHERE workspace_uris NOT IN ('', '[]')
|
|
531
|
+
return db.prepare("SELECT workspace_uris FROM conversation_summaries WHERE workspace_uris NOT IN ('', '[]')").all();
|
|
427
532
|
});
|
|
428
533
|
for (const row of rows) {
|
|
429
534
|
const uris = json(row.workspace_uris);
|
|
@@ -446,7 +551,7 @@ async function antigravityProjects(root) {
|
|
|
446
551
|
return projects;
|
|
447
552
|
}
|
|
448
553
|
|
|
449
|
-
export async function scanProjects(config) {
|
|
554
|
+
export async function scanProjects(config, { includeTranscripts = true } = {}) {
|
|
450
555
|
const projects = [];
|
|
451
556
|
const sources = [];
|
|
452
557
|
const discovered = new Map();
|
|
@@ -463,8 +568,8 @@ export async function scanProjects(config) {
|
|
|
463
568
|
let found = 0;
|
|
464
569
|
for (const file of candidates) {
|
|
465
570
|
try {
|
|
466
|
-
const rows = await load(file);
|
|
467
|
-
projects.push(
|
|
571
|
+
const rows = await load(file, candidates);
|
|
572
|
+
for (const row of rows) projects.push(row);
|
|
468
573
|
found += rows.length;
|
|
469
574
|
succeeded++;
|
|
470
575
|
} catch (error) {
|
|
@@ -479,19 +584,21 @@ export async function scanProjects(config) {
|
|
|
479
584
|
|
|
480
585
|
await Promise.all([
|
|
481
586
|
scan('workspacehub', 'Agent Workspace Manager', config.workspaceHubRoots ?? [], workspaceProjects),
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
587
|
+
...(includeTranscripts ? [
|
|
588
|
+
scan('agentsview', 'AgentsView 会话归档', config.archiveFiles ?? [], archivedProjects),
|
|
589
|
+
...Object.entries({
|
|
590
|
+
codex: codexProjects, claude: root => jsonlProjects(root, 'claude'),
|
|
591
|
+
opencode: opencodeProjects, workbuddy: root => jsonlProjects(root, 'workbuddy'),
|
|
592
|
+
qoder: root => jsonlProjects(root, 'qoder'), qwen: root => jsonlProjects(root, 'qwen', ['projects'], 2),
|
|
593
|
+
trae: root => editorProjects(root, 'trae'), copilot: root => editorProjects(root, 'copilot'),
|
|
594
|
+
gemini: geminiProjects,
|
|
595
|
+
antigravity: antigravityProjects,
|
|
596
|
+
}).map(([agent, load]) => scan(agent, agentLabels[agent], configuredRoots(config, agent), load, {
|
|
597
|
+
trae: '支持工作区元数据;会话可从 AgentsView 读取已归档部分',
|
|
598
|
+
copilot: '支持 VS Code 工作区会话及本机会话库;其他版本可从 AgentsView 读取已归档部分',
|
|
599
|
+
antigravity: '支持工作区元数据和 CLI 提示记录;完整会话可从 AgentsView 读取已归档部分',
|
|
600
|
+
}[agent])),
|
|
601
|
+
] : []),
|
|
495
602
|
]);
|
|
496
603
|
|
|
497
604
|
for (const cwd of config.projectRoots ?? []) projects.push({ cwd, agent: 'manual' });
|
|
@@ -501,12 +608,21 @@ export async function scanProjects(config) {
|
|
|
501
608
|
const key = pathKey(project.cwd);
|
|
502
609
|
if (!canonical.has(key)) canonical.set(key, await physicalPath(project.cwd) ?? path.normalize(project.cwd));
|
|
503
610
|
project.cwd = canonical.get(key);
|
|
611
|
+
if (project.archive?.profile) project.archive.sourceCwd = project.cwd;
|
|
504
612
|
const timestamp = dateMillis(project.archive?.date);
|
|
505
613
|
if (timestamp > 0 && timestamp < 8_640_000_000_000_000) project.updatedAt = new Date(timestamp).toISOString();
|
|
506
614
|
const identity = JSON.stringify([pathKey(project.cwd), project.agent, project.projectId, project.archive?.kind, project.archive?.file, project.archive?.id]);
|
|
507
615
|
const previous = discovered.get(identity);
|
|
508
616
|
if (!previous || compareDate(project.archive?.date, previous.archive?.date) > 0) discovered.set(identity, project);
|
|
509
617
|
}
|
|
618
|
+
const sourcesWithThreads = [...discovered.values()].filter(item => item.archive?.profile);
|
|
619
|
+
if (sourcesWithThreads.length && config.configFile) {
|
|
620
|
+
const aliases = await readCodexAliases(config).catch(() => new Map());
|
|
621
|
+
for (const { cwd, archive } of sourcesWithThreads) {
|
|
622
|
+
const known = aliases.get(keyFor(projectPathKey(cwd)))?.get(conversationId(archive));
|
|
623
|
+
if (known) archive.savedIds = known;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
510
626
|
return { projects: [...discovered.values()], sources: sources.sort((a, b) => a.id.localeCompare(b.id)) };
|
|
511
627
|
}
|
|
512
628
|
|
|
@@ -546,7 +662,8 @@ function messageText(text) {
|
|
|
546
662
|
return typeof text === 'string' ? stripRuntimeWrapper(text).trim() : '';
|
|
547
663
|
}
|
|
548
664
|
|
|
549
|
-
function markSourcePartial(result) {
|
|
665
|
+
function markSourcePartial(result, reason = 'source-compacted') {
|
|
666
|
+
result.events?.push({ kind: 'gap', reason });
|
|
550
667
|
result.sourcePartial = true;
|
|
551
668
|
result.truncated = true;
|
|
552
669
|
}
|
|
@@ -557,6 +674,17 @@ function appendMessage(result, role, text, timestamp, { estimatedTime = false }
|
|
|
557
674
|
if (!value) return false;
|
|
558
675
|
for (const match of value.matchAll(/<skill>\s*<name>([^<]+)<\/name>/gi)) addSkill(result, match[1]);
|
|
559
676
|
if (value.startsWith('<skill>')) return false;
|
|
677
|
+
if (result.events) {
|
|
678
|
+
if (role === 'user') result.turn++;
|
|
679
|
+
const time = dateMillis(timestamp);
|
|
680
|
+
result.events.push({
|
|
681
|
+
kind: 'message', role, text: stripRuntimeWrapper(text), turn: result.turn,
|
|
682
|
+
...(time > 0 && !estimatedTime ? { time } : {}),
|
|
683
|
+
...(result.sourceId ? { sourceId: result.sourceId } : {}),
|
|
684
|
+
...(result.parentId ? { parentId: result.parentId } : {}),
|
|
685
|
+
});
|
|
686
|
+
return true;
|
|
687
|
+
}
|
|
560
688
|
const { limits } = result;
|
|
561
689
|
if (limits) {
|
|
562
690
|
const bounded = value.slice(0, limits.messageLength).replace(/[\uD800-\uDBFF]$/, '');
|
|
@@ -610,6 +738,15 @@ function cleanTraceText(value) {
|
|
|
610
738
|
}
|
|
611
739
|
|
|
612
740
|
function addTrace(result, item) {
|
|
741
|
+
if (result.events) {
|
|
742
|
+
const { id, text, ...details } = item;
|
|
743
|
+
result.events.push({
|
|
744
|
+
...details, text: traceValue(text).replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f]/g, ' '),
|
|
745
|
+
...(id ? { sourceId: id } : {}),
|
|
746
|
+
...(item.kind !== 'tool_result' ? { turn: result.turn } : {}),
|
|
747
|
+
});
|
|
748
|
+
return undefined;
|
|
749
|
+
}
|
|
613
750
|
if (!result.trace) return undefined;
|
|
614
751
|
const text = cleanTraceText(item.text);
|
|
615
752
|
const bounded = text.slice(0, traceTextLimit).replace(/[\uD800-\uDBFF]$/, '');
|
|
@@ -648,25 +785,28 @@ function traceCallId(value) {
|
|
|
648
785
|
}
|
|
649
786
|
|
|
650
787
|
function addSummary(result, text, time, id) {
|
|
651
|
-
|
|
652
|
-
|
|
788
|
+
if (!result.events && !result.trace) return;
|
|
789
|
+
const value = result.events ? traceValue(text) : cleanTraceText(text);
|
|
790
|
+
if (!value.trim()) return;
|
|
653
791
|
addTrace(result, { kind: 'summary', text: value, status: 'ok', time: dateMillis(time), id });
|
|
654
792
|
}
|
|
655
793
|
|
|
656
794
|
function addToolCall(result, name, callId, input, time) {
|
|
657
|
-
if (typeof name !== 'string' || !name.trim()) return;
|
|
795
|
+
if ((!result.events && !result.trace) || typeof name !== 'string' || !name.trim()) return;
|
|
658
796
|
addTrace(result, {
|
|
659
797
|
kind: 'tool_call', name: name.trim().slice(0, 120),
|
|
660
798
|
callId: traceCallId(callId),
|
|
661
|
-
text: cleanTraceText(input), status: 'pending', time: dateMillis(time),
|
|
799
|
+
text: result.events ? traceValue(input) : cleanTraceText(input), status: 'pending', time: dateMillis(time),
|
|
662
800
|
});
|
|
663
801
|
}
|
|
664
802
|
|
|
665
|
-
function addToolResult(result, callId, output, failed) {
|
|
666
|
-
if (!result.trace || typeof callId !== 'string' || !callId) return;
|
|
803
|
+
function addToolResult(result, callId, output, failed, time) {
|
|
804
|
+
if (!result.events && (!result.trace || typeof callId !== 'string' || !callId)) return;
|
|
667
805
|
addTrace(result, {
|
|
668
|
-
kind: 'tool_result', callId: traceCallId(callId),
|
|
669
|
-
|
|
806
|
+
kind: 'tool_result', callId: traceCallId(callId),
|
|
807
|
+
text: result.events ? traceValue(output) : cleanTraceText(output),
|
|
808
|
+
status: failed === 'incomplete' ? 'incomplete' : failed === true ? 'error' : 'ok',
|
|
809
|
+
...(time === undefined ? {} : { time: dateMillis(time) }),
|
|
670
810
|
});
|
|
671
811
|
}
|
|
672
812
|
|
|
@@ -698,19 +838,23 @@ function textBlocks(content, result) {
|
|
|
698
838
|
addToolCall(result, block.name, block.id, block.input);
|
|
699
839
|
}
|
|
700
840
|
if (result && block?.type === 'tool_result') {
|
|
701
|
-
const value =
|
|
702
|
-
|
|
703
|
-
|
|
841
|
+
const value = result.events ? sourceToolOutput(result, block.content, block.tool_use_id)
|
|
842
|
+
: (Array.isArray(block.content)
|
|
843
|
+
? block.content.filter(part => part?.type === 'text' && typeof part.text === 'string').map(part => part.text).join('\n')
|
|
844
|
+
: block.content);
|
|
704
845
|
addToolResult(result, block.tool_use_id, value, block.is_error === true);
|
|
705
846
|
}
|
|
706
847
|
if (result && block?.type === 'tool') {
|
|
707
848
|
const input = block.state?.input ?? block.input ?? block.args;
|
|
708
849
|
readTool(result, block.tool ?? block.name, input);
|
|
709
850
|
const callId = block.callID ?? block.callId ?? block.id;
|
|
710
|
-
addToolCall(result, block.tool ?? block.name, callId, input);
|
|
851
|
+
addToolCall(result, block.tool ?? block.name, callId, input, block.time?.created);
|
|
711
852
|
const state = block.state ?? {};
|
|
712
853
|
if (state.status === 'completed' || state.status === 'error') {
|
|
713
|
-
|
|
854
|
+
const output = state.output ?? state.result ?? state.content ?? state.error?.message ?? state.error;
|
|
855
|
+
const time = result.events ? block.time?.completed : undefined;
|
|
856
|
+
addToolResult(result, callId, result.events ? sourceToolOutput(result, output, callId) : output, state.status === 'error', time);
|
|
857
|
+
if (result.events && state.metadata?.truncated === true) markSourcePartial(result, 'source-tool-output-truncated');
|
|
714
858
|
}
|
|
715
859
|
}
|
|
716
860
|
}
|
|
@@ -719,6 +863,99 @@ function textBlocks(content, result) {
|
|
|
719
863
|
return texts.map(stripRuntimeWrapper).filter(value => value.trim()).join('\n');
|
|
720
864
|
}
|
|
721
865
|
|
|
866
|
+
function sourceAttachment(block) {
|
|
867
|
+
const type = block?.type;
|
|
868
|
+
if (!['input_image', 'image', 'file', 'input_file', 'document'].includes(type) && !block?.inlineData && !block?.fileData) return;
|
|
869
|
+
const source = block.source ?? block.inlineData ?? block.fileData ?? block;
|
|
870
|
+
const url = block.image_url?.url ?? block.image_url ?? block.url ?? source.fileUri ?? source.url;
|
|
871
|
+
const embedded = typeof url === 'string' ? /^data:([a-z\d.+-]+\/[a-z\d.+-]+);base64,([a-z\d+/=]+)$/i.exec(url) : undefined;
|
|
872
|
+
const encoded = embedded?.[2] ?? source.data ?? block.file_data;
|
|
873
|
+
const sourceType = embedded?.[1] ?? source.media_type ?? source.mimeType ?? source.mime ?? block.mime;
|
|
874
|
+
const mediaType = typeof sourceType === 'string' ? sourceType : undefined;
|
|
875
|
+
const originalName = block.filename ?? block.name ?? block.title;
|
|
876
|
+
const name = typeof originalName === 'string' && path.win32.basename(originalName)
|
|
877
|
+
|| ((typeof type === 'string' && type.includes('image')) || mediaType?.startsWith('image/') ? '图片' : '附件');
|
|
878
|
+
const file = localDirectory(block.path ?? url);
|
|
879
|
+
if (typeof encoded === 'string' && /^[\da-z+/]+={0,2}$/i.test(encoded)) {
|
|
880
|
+
return { name, mediaType, data: Buffer.from(encoded, 'base64') };
|
|
881
|
+
}
|
|
882
|
+
if (file) return { name, mediaType, path: file };
|
|
883
|
+
return { name, mediaType, status: typeof url === 'string' ? 'remote-reference' : 'name-only' };
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
function sourceToolOutput(result, value, callId) {
|
|
887
|
+
if (!Array.isArray(value)) return value;
|
|
888
|
+
for (const attachment of value.map(sourceAttachment).filter(Boolean)) {
|
|
889
|
+
result.events.push({
|
|
890
|
+
kind: 'attachment', role: 'assistant', turn: result.turn, sourceId: result.sourceId,
|
|
891
|
+
callId: traceCallId(callId), ...attachment,
|
|
892
|
+
});
|
|
893
|
+
}
|
|
894
|
+
return textBlocks(value);
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
function sourceBlockText(block, functionParts) {
|
|
898
|
+
if (typeof block === 'string') return block;
|
|
899
|
+
if (block?.thought || typeof block?.text !== 'string') return undefined;
|
|
900
|
+
if (['text', 'input_text', 'output_text'].includes(block.type) || (functionParts && block.type === undefined)) return block.text;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
function sourceReasoning(block) {
|
|
904
|
+
if (block?.type === 'thinking') return block.thinking;
|
|
905
|
+
if (block?.type === 'reasoning' || block?.thought === true) return block.text;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
function readAssistantBlocks(result, blocks, timestamp, hints) {
|
|
909
|
+
let foundText = false;
|
|
910
|
+
let text = [];
|
|
911
|
+
const flush = () => {
|
|
912
|
+
if (text.length) foundText = appendMessage(result, 'assistant', text.join('\n'), timestamp, hints) || foundText;
|
|
913
|
+
text = [];
|
|
914
|
+
};
|
|
915
|
+
for (const block of blocks) {
|
|
916
|
+
const body = sourceBlockText(block, hints.functionParts);
|
|
917
|
+
if (body !== undefined) {
|
|
918
|
+
text.push(stripRuntimeWrapper(body));
|
|
919
|
+
continue;
|
|
920
|
+
}
|
|
921
|
+
const thought = sourceReasoning(block);
|
|
922
|
+
const attachment = sourceAttachment(block);
|
|
923
|
+
const tool = ['tool', 'tool_use', 'tool_result'].includes(block?.type)
|
|
924
|
+
|| (hints.functionParts && (block?.functionCall || block?.functionResponse));
|
|
925
|
+
if (!thought && !tool && !attachment) continue;
|
|
926
|
+
flush();
|
|
927
|
+
if (typeof thought === 'string') addSummary(result, thought, timestamp, result.sourceId);
|
|
928
|
+
if (attachment) {
|
|
929
|
+
result.events.push({ kind: 'attachment', role: 'assistant', turn: result.turn, sourceId: result.sourceId, ...attachment });
|
|
930
|
+
}
|
|
931
|
+
if (tool) {
|
|
932
|
+
textBlocks([block], result);
|
|
933
|
+
if (hints.functionParts) readFunctionParts(result, [block], timestamp);
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
flush();
|
|
937
|
+
if (!foundText) appendMessage(result, 'assistant', hints.text, timestamp, hints);
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
function readSourceBlocks(result, role, content, timestamp, hints = {}) {
|
|
941
|
+
const blocks = Array.isArray(content) ? content : [];
|
|
942
|
+
if (role === 'assistant' && blocks.length) {
|
|
943
|
+
readAssistantBlocks(result, blocks, timestamp, hints);
|
|
944
|
+
return;
|
|
945
|
+
}
|
|
946
|
+
const attachments = blocks.map(sourceAttachment).filter(Boolean);
|
|
947
|
+
const added = appendMessage(result, role, hints.text ?? textBlocks(content), timestamp, hints);
|
|
948
|
+
const standalone = role === 'user' && attachments.length > 0 && !added;
|
|
949
|
+
if (standalone) result.turn++;
|
|
950
|
+
for (const [index, attachment] of attachments.entries()) {
|
|
951
|
+
result.events.push({
|
|
952
|
+
kind: 'attachment', role, turn: result.turn, sourceId: result.sourceId, ...attachment,
|
|
953
|
+
...(standalone && index === 0 ? { standalone: true } : {}),
|
|
954
|
+
});
|
|
955
|
+
}
|
|
956
|
+
textBlocks(blocks, result);
|
|
957
|
+
}
|
|
958
|
+
|
|
722
959
|
function firstQuestion(rows, agent) {
|
|
723
960
|
for (const row of rows) {
|
|
724
961
|
if (row.isSidechain || row.isMeta || row.isCompactSummary) continue;
|
|
@@ -739,7 +976,7 @@ function firstQuestion(rows, agent) {
|
|
|
739
976
|
}
|
|
740
977
|
}
|
|
741
978
|
|
|
742
|
-
async function
|
|
979
|
+
async function allowedGemini(descriptor, cwd, config) {
|
|
743
980
|
for (const root of configuredRoots(config, 'gemini')) {
|
|
744
981
|
const [base] = await transcriptDirectories(root, ['tmp']);
|
|
745
982
|
if (!base) continue;
|
|
@@ -747,18 +984,23 @@ async function readGeminiHistory(descriptor, cwd, config, result) {
|
|
|
747
984
|
if (!file || path.basename(path.dirname(file)) !== 'chats' || !/^session-.+\.jsonl?$/i.test(path.basename(file))) continue;
|
|
748
985
|
const marker = await scopedFile(path.resolve(path.dirname(file), '..', '.project_root'), base);
|
|
749
986
|
if (!marker || !await sameDirectory((await prefix(marker, 32 * 1024)).text.trim(), cwd)) continue;
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
987
|
+
return file;
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
async function readGeminiHistory(descriptor, cwd, config, result) {
|
|
992
|
+
const file = await allowedGemini(descriptor, cwd, config);
|
|
993
|
+
if (!file) return;
|
|
994
|
+
const { text, truncated } = await prefix(file, maxTranscriptBytes);
|
|
995
|
+
if (truncated) markSourcePartial(result);
|
|
996
|
+
const messages = json(text)?.messages ?? rowsFrom(text, truncated);
|
|
997
|
+
if (!Array.isArray(messages)) return;
|
|
998
|
+
for (const row of messages) {
|
|
999
|
+
const message = row.message ?? row;
|
|
1000
|
+
if (!['user', 'gemini', 'assistant'].includes(message.type)) continue;
|
|
1001
|
+
const content = Array.isArray(message.content) ? message.content.map(block => block?.text ?? '').join('\n') : message.content;
|
|
1002
|
+
appendMessage(result, message.type === 'gemini' ? 'assistant' : message.type, content, message.timestamp);
|
|
1003
|
+
for (const tool of Array.isArray(message.toolCalls) ? message.toolCalls : []) readTool(result, tool.name, tool.args);
|
|
762
1004
|
}
|
|
763
1005
|
}
|
|
764
1006
|
|
|
@@ -781,30 +1023,40 @@ function copilotRequests(text, truncated) {
|
|
|
781
1023
|
if (Array.isArray(snapshot?.requests)) return snapshot.requests;
|
|
782
1024
|
let state;
|
|
783
1025
|
for (const op of rowsFrom(text, truncated)) {
|
|
784
|
-
if (op.kind === 0)
|
|
785
|
-
|
|
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];
|
|
1026
|
+
if (op.kind === 0) state = op.v;
|
|
1027
|
+
else applyCopilotOp(state, op);
|
|
803
1028
|
}
|
|
804
1029
|
return Array.isArray(state?.requests) ? state.requests : [];
|
|
805
1030
|
}
|
|
806
1031
|
|
|
807
|
-
|
|
1032
|
+
function applyCopilotOp(state, op) {
|
|
1033
|
+
if (!Array.isArray(op.k) || op.k[0] !== 'requests') return true;
|
|
1034
|
+
if (op.k.length > 8) return false;
|
|
1035
|
+
const keys = op.k.map(String);
|
|
1036
|
+
if (keys.some(key => ['__proto__', 'prototype', 'constructor'].includes(key))) return false;
|
|
1037
|
+
const key = keys.pop();
|
|
1038
|
+
let target = state;
|
|
1039
|
+
for (const part of keys) target = target && Object.hasOwn(target, part) ? target[part] : undefined;
|
|
1040
|
+
if (!target || typeof target !== 'object') return false;
|
|
1041
|
+
if (Array.isArray(target) && (!/^\d+$/.test(key) || Number(key) >= target.length)) return false;
|
|
1042
|
+
if (op.kind === 1) {
|
|
1043
|
+
target[key] = op.v;
|
|
1044
|
+
return true;
|
|
1045
|
+
}
|
|
1046
|
+
if (op.kind === 2 && Array.isArray(target[key]) && Array.isArray(op.v)) {
|
|
1047
|
+
const current = target[key];
|
|
1048
|
+
const index = Number.isInteger(op.i) ? Math.max(0, Math.min(op.i, current.length)) : current.length;
|
|
1049
|
+
target[key] = current.slice(0, index).concat(op.v, current.slice(index + op.v.length));
|
|
1050
|
+
return true;
|
|
1051
|
+
}
|
|
1052
|
+
if (op.kind === 3 && !Array.isArray(target)) {
|
|
1053
|
+
delete target[key];
|
|
1054
|
+
return true;
|
|
1055
|
+
}
|
|
1056
|
+
return false;
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
async function allowedEditorChat(descriptor, cwd, config) {
|
|
808
1060
|
const stores = await Promise.all(configuredRoots(config, 'copilot').map(editorStores));
|
|
809
1061
|
for (const base of stores.flat()) {
|
|
810
1062
|
const file = await scopedFile(descriptor.file, base);
|
|
@@ -813,21 +1065,34 @@ async function readCopilotHistory(descriptor, cwd, config, result) {
|
|
|
813
1065
|
if (!workspace) continue;
|
|
814
1066
|
const marker = json((await prefix(workspace, 32 * 1024)).text);
|
|
815
1067
|
if (!await sameDirectory(localDirectory(marker?.folder), cwd)) continue;
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
1068
|
+
return file;
|
|
1069
|
+
}
|
|
1070
|
+
}
|
|
1071
|
+
|
|
1072
|
+
function copilotText(item) {
|
|
1073
|
+
if (item?.kind && item.kind !== 'markdownContent') return '';
|
|
1074
|
+
const value = item?.value?.value ?? item?.value;
|
|
1075
|
+
return typeof value === 'string' ? value : '';
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
function copilotAnswer(response) {
|
|
1079
|
+
return response.map(copilotText).join('');
|
|
1080
|
+
}
|
|
1081
|
+
|
|
1082
|
+
async function readCopilotHistory(descriptor, cwd, config, result) {
|
|
1083
|
+
const file = await allowedEditorChat(descriptor, cwd, config);
|
|
1084
|
+
if (!file) return;
|
|
1085
|
+
const { text, truncated } = await prefix(file, maxTranscriptBytes);
|
|
1086
|
+
if (truncated) markSourcePartial(result);
|
|
1087
|
+
const requests = copilotRequests(text, truncated);
|
|
1088
|
+
for (const request of result.limits ? requests : requests.slice(-maxMessages)) {
|
|
1089
|
+
appendMessage(result, 'user', request?.message?.text, request?.timestamp);
|
|
1090
|
+
const response = Array.isArray(request?.response) ? request.response : [];
|
|
1091
|
+
// Copilot stores the request time. Use it for transcript order only.
|
|
1092
|
+
appendMessage(result, 'assistant', copilotAnswer(response), request?.timestamp, { estimatedTime: true });
|
|
1093
|
+
for (const item of response) {
|
|
1094
|
+
if (item?.kind === 'toolInvocationSerialized') readTool(result, item.toolId, item.parameters);
|
|
829
1095
|
}
|
|
830
|
-
return;
|
|
831
1096
|
}
|
|
832
1097
|
}
|
|
833
1098
|
|
|
@@ -895,11 +1160,24 @@ async function* compressedRows(file) {
|
|
|
895
1160
|
|
|
896
1161
|
function readCodexRow(result, row) {
|
|
897
1162
|
if (row === null || row.type === 'compacted' || row.isCompactSummary) {
|
|
898
|
-
if (result.limits) markSourcePartial(result);
|
|
1163
|
+
if (result.limits || result.events) markSourcePartial(result);
|
|
1164
|
+
return;
|
|
1165
|
+
}
|
|
1166
|
+
if (row.isSidechain) {
|
|
1167
|
+
if (result.events) markSourcePartial(result, 'unresolved-branch');
|
|
899
1168
|
return;
|
|
900
1169
|
}
|
|
901
|
-
if (row.
|
|
1170
|
+
if (row.isMeta) return;
|
|
902
1171
|
const payload = row.payload;
|
|
1172
|
+
if (row.type === 'event_msg' && result.events) {
|
|
1173
|
+
if (payload?.type === 'task_started') result.sourceTurn = payload.turn_id;
|
|
1174
|
+
if (['turn_aborted', 'task_complete'].includes(payload?.type)) {
|
|
1175
|
+
const turn = payload.turn_id ? result.sourceTurns.get(payload.turn_id) : result.turn;
|
|
1176
|
+
if (turn) result.events.push({
|
|
1177
|
+
kind: 'turn_end', turn, status: payload.type === 'turn_aborted' ? 'interrupted' : 'completed',
|
|
1178
|
+
});
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
903
1181
|
if (row.type === 'event_msg' && payload?.type === 'token_count' && result.readStats) {
|
|
904
1182
|
// Codex repeats cumulative snapshots. The latest recorded total already
|
|
905
1183
|
// includes earlier turns, and may be available even when only a tail was read.
|
|
@@ -916,10 +1194,19 @@ function readCodexRow(result, row) {
|
|
|
916
1194
|
}
|
|
917
1195
|
if (row.type !== 'response_item') return;
|
|
918
1196
|
if (payload?.type === 'message') {
|
|
919
|
-
|
|
1197
|
+
if (result.events && ['user', 'assistant'].includes(payload.role)) {
|
|
1198
|
+
const previousTurn = result.turn;
|
|
1199
|
+
readSourceBlocks(result, payload.role, payload.content, row.timestamp);
|
|
1200
|
+
if (result.turn !== previousTurn && typeof result.sourceTurn === 'string') {
|
|
1201
|
+
result.sourceTurns.set(result.sourceTurn, result.turn);
|
|
1202
|
+
}
|
|
1203
|
+
} else {
|
|
1204
|
+
appendMessage(result, payload.role, textBlocks(payload.content, result), row.timestamp);
|
|
1205
|
+
}
|
|
920
1206
|
return;
|
|
921
1207
|
}
|
|
922
1208
|
if (payload?.type === 'reasoning') {
|
|
1209
|
+
if (!result.events && !result.trace) return;
|
|
923
1210
|
// Only the visible summary is retained; encrypted reasoning has no text.
|
|
924
1211
|
const summary = Array.isArray(payload.summary) ? payload.summary : [];
|
|
925
1212
|
const text = summary.filter(item => item?.type === 'summary_text' && typeof item.text === 'string')
|
|
@@ -933,13 +1220,15 @@ function readCodexRow(result, row) {
|
|
|
933
1220
|
return;
|
|
934
1221
|
}
|
|
935
1222
|
if (payload?.type === 'function_call_output' || payload?.type === 'custom_tool_call_output') {
|
|
1223
|
+
if (!result.events && !result.trace) return;
|
|
936
1224
|
const output = payload.output ?? payload.content;
|
|
937
|
-
const text =
|
|
938
|
-
|
|
939
|
-
|
|
1225
|
+
const text = result.events ? traceValue(sourceToolOutput(result, output, payload.call_id))
|
|
1226
|
+
: (Array.isArray(output)
|
|
1227
|
+
? output.filter(item => item?.type === 'input_text' && typeof item.text === 'string').map(item => item.text).join('\n')
|
|
1228
|
+
: output);
|
|
940
1229
|
const value = typeof text === 'string' ? text : '';
|
|
941
1230
|
addToolResult(result, payload.call_id, value, payload.status === 'failed'
|
|
942
|
-
|| /^(?:exit code: [1-9]|process exited with code [1-9])/im.test(value));
|
|
1231
|
+
|| /^(?:exit code: [1-9]|process exited with code [1-9])/im.test(value), ...(result.events ? [row.timestamp] : []));
|
|
943
1232
|
}
|
|
944
1233
|
}
|
|
945
1234
|
|
|
@@ -994,19 +1283,25 @@ function parseTail(buffer) {
|
|
|
994
1283
|
};
|
|
995
1284
|
}
|
|
996
1285
|
|
|
997
|
-
async function
|
|
1286
|
+
async function allowedJsonl(descriptor, config) {
|
|
998
1287
|
const codex = descriptor.kind === 'codex';
|
|
999
1288
|
const locations = codex ? codexLocations : ['projects'];
|
|
1000
1289
|
const bases = (await Promise.all(configuredRoots(config, descriptor.kind)
|
|
1001
1290
|
.map(root => transcriptDirectories(root, locations)))).flat();
|
|
1002
1291
|
let file;
|
|
1003
|
-
if (codex) file = await resolveCodexTranscript(descriptor.file, bases);
|
|
1292
|
+
if (codex) file = (await resolveCodexTranscript(descriptor.file, bases))?.file;
|
|
1004
1293
|
else {
|
|
1005
1294
|
for (const base of bases) {
|
|
1006
1295
|
file = await scopedFile(descriptor.file, base);
|
|
1007
1296
|
if (file) break;
|
|
1008
1297
|
}
|
|
1009
1298
|
}
|
|
1299
|
+
return file;
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
async function readJsonlHistory(descriptor, cwd, config, result) {
|
|
1303
|
+
const codex = descriptor.kind === 'codex';
|
|
1304
|
+
const file = await allowedJsonl(descriptor, config);
|
|
1010
1305
|
if (!file) return;
|
|
1011
1306
|
if (codex && compressedCodexFile.test(file)) return readCompressedCodex(file, cwd, result);
|
|
1012
1307
|
if (!jsonlFile.test(file)) return;
|
|
@@ -1038,7 +1333,8 @@ async function readJsonlHistory(descriptor, cwd, config, result) {
|
|
|
1038
1333
|
|
|
1039
1334
|
async function allowedArchive(descriptor, config) {
|
|
1040
1335
|
const candidates = descriptor.kind === 'agentsview' ? config.archiveFiles ?? []
|
|
1041
|
-
: (await Promise.all(configuredRoots(config,
|
|
1336
|
+
: (await Promise.all(configuredRoots(config, descriptor.kind)
|
|
1337
|
+
.map(descriptor.kind === 'copilot' ? copilotDatabase : opencodeDatabase))).filter(Boolean);
|
|
1042
1338
|
const actual = await physicalPath(descriptor.file);
|
|
1043
1339
|
if (!actual) return undefined;
|
|
1044
1340
|
for (const candidate of candidates) {
|
|
@@ -1104,23 +1400,455 @@ async function readHistory(archive, cwd, config, result) {
|
|
|
1104
1400
|
if (['codex', 'claude', 'qoder', 'qwen', 'workbuddy'].includes(archive.kind)) await readJsonlHistory(archive, cwd, config, result);
|
|
1105
1401
|
if (archive.kind === 'gemini') await readGeminiHistory(archive, cwd, config, result);
|
|
1106
1402
|
if (archive.kind === 'antigravity') await readAntigravityHistory(archive, cwd, config, result);
|
|
1107
|
-
if (archive.kind === 'copilot'
|
|
1403
|
+
if (archive.kind === 'copilot' && archive.storage === 'sqlite') {
|
|
1404
|
+
for await (const event of readSourceEvents(archive, { config, sourceCwd: cwd })) {
|
|
1405
|
+
if (event.kind === 'message') appendMessage(result, event.role, event.text, event.time);
|
|
1406
|
+
if (event.kind === 'gap' && result.limits) markSourcePartial(result, event.reason);
|
|
1407
|
+
}
|
|
1408
|
+
} else if (archive.kind === 'copilot') await readCopilotHistory(archive, cwd, config, result);
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
function readSourceMessageRow(result, kind, row) {
|
|
1412
|
+
if (kind === 'codex') {
|
|
1413
|
+
readCodexRow(result, row);
|
|
1414
|
+
} else if (row.isCompactSummary || (row.type === 'system' && row.subtype === 'compact_boundary')) {
|
|
1415
|
+
markSourcePartial(result);
|
|
1416
|
+
} else if (row.isSidechain) {
|
|
1417
|
+
markSourcePartial(result, 'unresolved-branch');
|
|
1418
|
+
} else if (!row.isMeta) {
|
|
1419
|
+
if (kind === 'workbuddy') {
|
|
1420
|
+
if (row.type === 'message') readSourceBlocks(result, row.role === 'human' ? 'user' : row.role, row.content, row.timestamp);
|
|
1421
|
+
if (row.type === 'reasoning') {
|
|
1422
|
+
const text = blocks => Array.isArray(blocks) ? blocks
|
|
1423
|
+
.filter(block => block?.type === 'reasoning_text' && typeof block.text === 'string')
|
|
1424
|
+
.map(block => block.text).join('\n\n') : '';
|
|
1425
|
+
addSummary(result, text(row.content) || text(row.rawContent), row.timestamp, result.sourceId);
|
|
1426
|
+
}
|
|
1427
|
+
if (row.type === 'function_call') {
|
|
1428
|
+
readTool(result, row.name, row.arguments);
|
|
1429
|
+
addToolCall(result, row.name, row.callId ?? row.call_id ?? row.id, row.arguments, row.timestamp);
|
|
1430
|
+
}
|
|
1431
|
+
if (['function_call_output', 'function_call_result'].includes(row.type)) {
|
|
1432
|
+
const blocks = Array.isArray(row.output) ? row.output : [row.output];
|
|
1433
|
+
const output = blocks.length && blocks.every(block => block?.type === 'text' && typeof block.text === 'string')
|
|
1434
|
+
? blocks.map(block => block.text).join('\n') : row.output;
|
|
1435
|
+
const status = row.status === 'incomplete' ? 'incomplete' : ['error', 'failed'].includes(row.status);
|
|
1436
|
+
addToolResult(result, row.callId ?? row.call_id, output, status, row.timestamp);
|
|
1437
|
+
}
|
|
1438
|
+
} else if (kind === 'qwen' && Array.isArray(row.message?.parts)) {
|
|
1439
|
+
const parts = row.message.parts;
|
|
1440
|
+
if (row.type === 'user' || row.type === 'assistant') {
|
|
1441
|
+
readSourceBlocks(result, row.type, parts, row.timestamp, {
|
|
1442
|
+
functionParts: true,
|
|
1443
|
+
text: parts.map(part => sourceBlockText(part, true)).filter(Boolean).join('\n'),
|
|
1444
|
+
});
|
|
1445
|
+
}
|
|
1446
|
+
if (['user', 'tool_result'].includes(row.type)) readFunctionParts(result, parts, row.timestamp);
|
|
1447
|
+
} else if (row.type === 'user' || row.type === 'assistant') {
|
|
1448
|
+
readSourceBlocks(result, row.type, row.message?.content, row.timestamp);
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
function readFunctionParts(result, parts, time) {
|
|
1454
|
+
for (const part of parts) {
|
|
1455
|
+
if (part?.functionCall) {
|
|
1456
|
+
const { name, id, args } = part.functionCall;
|
|
1457
|
+
readTool(result, name, args);
|
|
1458
|
+
addToolCall(result, name, id, args, time);
|
|
1459
|
+
}
|
|
1460
|
+
if (part?.functionResponse) {
|
|
1461
|
+
const { id, response } = part.functionResponse;
|
|
1462
|
+
const error = Boolean(response?.error);
|
|
1463
|
+
const output = response && typeof response === 'object' && Object.keys(response).length === 1
|
|
1464
|
+
? response.error ?? response.output ?? response : response;
|
|
1465
|
+
addToolResult(result, id, output, error, time);
|
|
1466
|
+
}
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
function sourceIdentity(result, row, ordinal) {
|
|
1471
|
+
result.sourceId = row.uuid ?? row.message?.id ?? row.payload?.id ?? row.id ?? `row:${ordinal}`;
|
|
1472
|
+
result.parentId = row.parentUuid ?? row.message?.parentId;
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1475
|
+
async function* jsonlSourceEvents(archive, options, result) {
|
|
1476
|
+
const { config, sourceCwd, signal } = options;
|
|
1477
|
+
const file = await allowedJsonl(archive, config);
|
|
1478
|
+
if (!file) {
|
|
1479
|
+
yield { kind: 'gap', reason: compressedCodexFile.test(archive.file) && !hasZstd ? 'unsupported-compression' : 'source-unavailable' };
|
|
1480
|
+
return;
|
|
1481
|
+
}
|
|
1482
|
+
let validated = false;
|
|
1483
|
+
let ordinal = 0;
|
|
1484
|
+
let pendingBytes = 0;
|
|
1485
|
+
let pending = [];
|
|
1486
|
+
for await (const { row, bytes, gap } of sourceJsonl(file, { compressed: compressedCodexFile.test(file), signal })) {
|
|
1487
|
+
if (gap) {
|
|
1488
|
+
yield { kind: 'gap', reason: gap };
|
|
1489
|
+
continue;
|
|
1490
|
+
}
|
|
1491
|
+
ordinal++;
|
|
1492
|
+
if (!validated) {
|
|
1493
|
+
// Codex authenticates the session before any content can leave the reader.
|
|
1494
|
+
const cwd = await nativeCwd(file, archive.kind, [row]);
|
|
1495
|
+
if (!cwd) {
|
|
1496
|
+
pendingBytes += bytes;
|
|
1497
|
+
if (archive.kind === 'codex' || pendingBytes > sourceValueLimit || pending.length >= 65_536) {
|
|
1498
|
+
yield { kind: 'gap', reason: 'source-metadata-missing' };
|
|
1499
|
+
return;
|
|
1500
|
+
}
|
|
1501
|
+
pending.push([row, ordinal]);
|
|
1502
|
+
continue;
|
|
1503
|
+
}
|
|
1504
|
+
if (!await sameDirectory(cwd, sourceCwd)
|
|
1505
|
+
|| (archive.kind === 'codex' && archive.id && row.payload?.id && row.payload.id !== archive.id)) {
|
|
1506
|
+
yield { kind: 'gap', reason: 'source-mismatch' };
|
|
1507
|
+
return;
|
|
1508
|
+
}
|
|
1509
|
+
validated = true;
|
|
1510
|
+
for (const [earlier, sequence] of pending) {
|
|
1511
|
+
sourceIdentity(result, earlier, sequence);
|
|
1512
|
+
readSourceMessageRow(result, archive.kind, earlier);
|
|
1513
|
+
yield* result.events.splice(0);
|
|
1514
|
+
}
|
|
1515
|
+
pending = [];
|
|
1516
|
+
}
|
|
1517
|
+
sourceIdentity(result, row, ordinal);
|
|
1518
|
+
readSourceMessageRow(result, archive.kind, row);
|
|
1519
|
+
yield* result.events.splice(0);
|
|
1520
|
+
}
|
|
1521
|
+
if (!validated && ordinal) yield { kind: 'gap', reason: 'source-metadata-missing' };
|
|
1522
|
+
}
|
|
1523
|
+
|
|
1524
|
+
function* agentsViewEvents(db, id, result) {
|
|
1525
|
+
const fields = columns(db, 'messages');
|
|
1526
|
+
if (!['ordinal', 'role', 'session_id'].every(field => fields.has(field))
|
|
1527
|
+
|| (!fields.has('dialogue_text') && !fields.has('content'))) {
|
|
1528
|
+
markSourcePartial(result, 'unsupported-source-schema');
|
|
1529
|
+
return;
|
|
1530
|
+
}
|
|
1531
|
+
const content = fields.has('dialogue_text') ? 'dialogue_text' : 'content';
|
|
1532
|
+
const system = fields.has('is_system') ? ' AND is_system = 0' : '';
|
|
1533
|
+
const time = fields.has('timestamp') ? 'timestamp' : 'NULL';
|
|
1534
|
+
for (const row of db.prepare(`SELECT ordinal, role, ${content} AS text, ${time} AS time FROM messages
|
|
1535
|
+
WHERE session_id = ? AND role IN ('user','assistant')${system} ORDER BY ordinal`).iterate(id)) {
|
|
1536
|
+
result.sourceId = `message:${row.ordinal}`;
|
|
1537
|
+
appendMessage(result, row.role, row.text, row.time);
|
|
1538
|
+
yield* result.events.splice(0);
|
|
1539
|
+
}
|
|
1540
|
+
const toolFields = columns(db, 'tool_calls');
|
|
1541
|
+
if (!toolFields.has('session_id')) return;
|
|
1542
|
+
if (toolFields.has('skill_name')) {
|
|
1543
|
+
for (const row of db.prepare('SELECT DISTINCT skill_name FROM tool_calls WHERE session_id = ?').iterate(id)) {
|
|
1544
|
+
addSkill(result, row.skill_name);
|
|
1545
|
+
}
|
|
1546
|
+
}
|
|
1547
|
+
if (db.prepare('SELECT 1 FROM tool_calls WHERE session_id = ? LIMIT 1').get(id)) {
|
|
1548
|
+
markSourcePartial(result, 'archive-tool-details-unavailable');
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
function mergeOpenCodeParts(content, rows, result) {
|
|
1553
|
+
for (const row of rows) {
|
|
1554
|
+
const data = json(row.data);
|
|
1555
|
+
if (!data) {
|
|
1556
|
+
markSourcePartial(result, 'malformed-record');
|
|
1557
|
+
continue;
|
|
1558
|
+
}
|
|
1559
|
+
const part = { ...data, type: row.type, ...(row.call_id ? { callID: row.call_id } : {}) };
|
|
1560
|
+
const current = content[row.ordinal];
|
|
1561
|
+
if (!current || current.type !== part.type) {
|
|
1562
|
+
content.push(part);
|
|
1563
|
+
continue;
|
|
1564
|
+
}
|
|
1565
|
+
const sameText = part.text === undefined || current.text === undefined || part.text === current.text;
|
|
1566
|
+
const sameCall = !part.callID || !current.callID || current.callID === part.callID;
|
|
1567
|
+
if (!sameText || !sameCall) {
|
|
1568
|
+
markSourcePartial(result, 'unresolved-source-projection');
|
|
1569
|
+
continue;
|
|
1570
|
+
}
|
|
1571
|
+
content[row.ordinal] = { ...current, ...part, ...(part.state ? { state: { ...current.state, ...part.state } } : {}) };
|
|
1572
|
+
}
|
|
1573
|
+
return content;
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
function* openCodeEvents(db, id, result) {
|
|
1577
|
+
const projection = columns(db, 'session_message');
|
|
1578
|
+
const messages = columns(db, 'message');
|
|
1579
|
+
const parts = columns(db, 'part');
|
|
1580
|
+
// The normalized part table carries text and tool statuses directly. If
|
|
1581
|
+
// both layouts exist and contain this session, never replay the projection
|
|
1582
|
+
// as a second copy.
|
|
1583
|
+
if (['id', 'session_id', 'data', 'time_created'].every(field => messages.has(field))
|
|
1584
|
+
&& ['session_id', 'message_id', 'data', 'time_created'].every(field => parts.has(field))
|
|
1585
|
+
&& db.prepare('SELECT 1 FROM message WHERE session_id = ? LIMIT 1').get(id)) {
|
|
1586
|
+
const order = parts.has('id') ? 'time_created, id' : 'time_created';
|
|
1587
|
+
const readParts = db.prepare(`SELECT data FROM part WHERE session_id = ? AND message_id = ? ORDER BY ${order}`);
|
|
1588
|
+
for (const row of db.prepare('SELECT id, data, time_created AS time FROM message WHERE session_id = ? ORDER BY time, id').iterate(id)) {
|
|
1589
|
+
const data = json(row.data);
|
|
1590
|
+
result.sourceId = row.id;
|
|
1591
|
+
result.parentId = data?.parentID;
|
|
1592
|
+
const content = [];
|
|
1593
|
+
for (const part of readParts.iterate(id, row.id)) {
|
|
1594
|
+
const block = json(part.data);
|
|
1595
|
+
if (block) content.push(block);
|
|
1596
|
+
else markSourcePartial(result, 'malformed-record');
|
|
1597
|
+
}
|
|
1598
|
+
if (['user', 'assistant'].includes(data?.role)) readSourceBlocks(result, data.role, content, row.time);
|
|
1599
|
+
else if (!data) markSourcePartial(result, 'malformed-record');
|
|
1600
|
+
yield* result.events.splice(0);
|
|
1601
|
+
}
|
|
1602
|
+
if (['type', 'session_id'].every(field => projection.has(field))) {
|
|
1603
|
+
const messageCount = db.prepare('SELECT count(*) AS count FROM message WHERE session_id = ?').get(id).count;
|
|
1604
|
+
const projectionCount = db.prepare("SELECT count(*) AS count FROM session_message WHERE session_id = ? AND type IN ('user','assistant')").get(id).count;
|
|
1605
|
+
if (projectionCount > messageCount) markSourcePartial(result, 'unresolved-source-projection');
|
|
1606
|
+
}
|
|
1607
|
+
return;
|
|
1608
|
+
}
|
|
1609
|
+
if (['type', 'session_id', 'data'].every(field => projection.has(field))) {
|
|
1610
|
+
const seq = projection.has('seq') ? 'seq' : projection.has('time_created') ? 'time_created' : 'rowid';
|
|
1611
|
+
const time = projection.has('time_created') ? 'time_created' : 'NULL';
|
|
1612
|
+
const messageId = projection.has('id') ? 'id' : 'NULL';
|
|
1613
|
+
const projectedParts = columns(db, 'session_part');
|
|
1614
|
+
const readParts = projection.has('id') && ['session_id', 'message_id', 'ordinal', 'type', 'data'].every(field => projectedParts.has(field))
|
|
1615
|
+
? db.prepare(`SELECT ordinal, type, data, ${projectedParts.has('call_id') ? 'call_id' : 'NULL'} AS call_id FROM session_part
|
|
1616
|
+
WHERE session_id = ? AND message_id = ? ORDER BY ordinal`) : undefined;
|
|
1617
|
+
for (const row of db.prepare(`SELECT ${messageId} AS id, type, data, ${seq} AS seq, ${time} AS time FROM session_message
|
|
1618
|
+
WHERE session_id = ? AND type IN ('user','assistant','skill','idle') ORDER BY seq, id`).iterate(id)) {
|
|
1619
|
+
const data = json(row.data);
|
|
1620
|
+
if (!data) markSourcePartial(result, 'malformed-record');
|
|
1621
|
+
else if (row.type === 'skill') addSkill(result, data.name ?? data.skill);
|
|
1622
|
+
else if (row.type === 'idle') {
|
|
1623
|
+
const status = data.outcome === 'succeeded' ? 'completed'
|
|
1624
|
+
: ['aborted', 'cancelled', 'failed', 'interrupted'].includes(data.outcome) ? 'interrupted' : undefined;
|
|
1625
|
+
if (status && result.turn) result.events.push({ kind: 'turn_end', status, turn: result.turn });
|
|
1626
|
+
}
|
|
1627
|
+
else {
|
|
1628
|
+
result.sourceId = row.id ?? data.id ?? `message:${row.seq}`;
|
|
1629
|
+
const content = Array.isArray(data.content) ? [...data.content] : [];
|
|
1630
|
+
if (readParts) mergeOpenCodeParts(content, readParts.iterate(id, row.id), result);
|
|
1631
|
+
if (Array.isArray(data.files)) {
|
|
1632
|
+
content.push(...data.files.filter(file => file && typeof file === 'object').map(file => ({ type: 'file', ...file })));
|
|
1633
|
+
}
|
|
1634
|
+
readSourceBlocks(result, row.type, content, row.time, {
|
|
1635
|
+
text: data.text ?? (typeof data.content === 'string' ? data.content : undefined),
|
|
1636
|
+
});
|
|
1637
|
+
}
|
|
1638
|
+
yield* result.events.splice(0);
|
|
1639
|
+
}
|
|
1640
|
+
return;
|
|
1641
|
+
}
|
|
1642
|
+
if (!messages.size || !parts.size) markSourcePartial(result, 'unsupported-source-schema');
|
|
1643
|
+
}
|
|
1644
|
+
|
|
1645
|
+
function* copilotSqliteEvents(db, id, result) {
|
|
1646
|
+
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)) {
|
|
1647
|
+
result.sourceId = `request:${row.id}`;
|
|
1648
|
+
appendMessage(result, 'user', row.user_message, row.timestamp);
|
|
1649
|
+
result.sourceId = `response:${row.id}`;
|
|
1650
|
+
appendMessage(result, 'assistant', row.assistant_response, row.timestamp, { estimatedTime: true });
|
|
1651
|
+
yield* result.events.splice(0);
|
|
1652
|
+
}
|
|
1653
|
+
markSourcePartial(result, 'source-dialogue-only');
|
|
1654
|
+
}
|
|
1655
|
+
|
|
1656
|
+
async function* databaseSourceEvents(archive, options, result) {
|
|
1657
|
+
const { sourceCwd, config, signal } = options;
|
|
1658
|
+
const file = await allowedArchive(archive, config);
|
|
1659
|
+
if (!file) {
|
|
1660
|
+
yield { kind: 'gap', reason: 'source-unavailable' };
|
|
1661
|
+
return;
|
|
1662
|
+
}
|
|
1663
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
1664
|
+
const db = new DatabaseSync(file, { readOnly: true });
|
|
1665
|
+
try {
|
|
1666
|
+
db.exec('PRAGMA trusted_schema = OFF; PRAGMA busy_timeout = 1000; BEGIN');
|
|
1667
|
+
let cwd;
|
|
1668
|
+
let events;
|
|
1669
|
+
if (archive.kind === 'agentsview') {
|
|
1670
|
+
const fields = columns(db, 'sessions');
|
|
1671
|
+
const deleted = fields.has('deleted_at') ? ' AND deleted_at IS NULL' : '';
|
|
1672
|
+
const machine = fields.has('machine') ? " AND machine IN ('', 'local')" : '';
|
|
1673
|
+
cwd = db.prepare('SELECT cwd FROM sessions WHERE id = ?' + deleted + machine).get(archive.id)?.cwd;
|
|
1674
|
+
events = agentsViewEvents;
|
|
1675
|
+
} else if (archive.kind === 'copilot' && copilotTables(db)) {
|
|
1676
|
+
const host = copilotHostFilter(columns(db, 'sessions'));
|
|
1677
|
+
cwd = localDirectory(db.prepare('SELECT cwd FROM sessions WHERE id = ?' + host).get(archive.id)?.cwd);
|
|
1678
|
+
events = copilotSqliteEvents;
|
|
1679
|
+
} else if (archive.kind === 'opencode' && opencodeTables(db).includes(archive.table)) {
|
|
1680
|
+
cwd = db.prepare(`SELECT directory FROM ${archive.table} WHERE id = ?`).get(archive.id)?.directory;
|
|
1681
|
+
events = openCodeEvents;
|
|
1682
|
+
}
|
|
1683
|
+
if (!events) {
|
|
1684
|
+
yield { kind: 'gap', reason: 'unsupported-source-schema' };
|
|
1685
|
+
} else if (!await sameDirectory(cwd, sourceCwd)) {
|
|
1686
|
+
yield { kind: 'gap', reason: 'source-mismatch' };
|
|
1687
|
+
} else {
|
|
1688
|
+
for (const event of events(db, archive.id, result)) {
|
|
1689
|
+
signal?.throwIfAborted();
|
|
1690
|
+
yield event;
|
|
1691
|
+
}
|
|
1692
|
+
yield* result.events.splice(0);
|
|
1693
|
+
}
|
|
1694
|
+
} finally {
|
|
1695
|
+
db.close();
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
|
|
1699
|
+
function geminiEvent(result, row, index) {
|
|
1700
|
+
const message = row?.message ?? row;
|
|
1701
|
+
if (!['user', 'gemini', 'assistant'].includes(message?.type)) return;
|
|
1702
|
+
sourceIdentity(result, row, index);
|
|
1703
|
+
const role = message.type === 'gemini' ? 'assistant' : message.type;
|
|
1704
|
+
const blocks = Array.isArray(message.content) ? message.content : [];
|
|
1705
|
+
readSourceBlocks(result, role, message.content, message.timestamp ?? row.timestamp, {
|
|
1706
|
+
functionParts: true,
|
|
1707
|
+
text: blocks.length ? blocks.map(block => sourceBlockText(block, true)).filter(Boolean).join('\n') : undefined,
|
|
1708
|
+
});
|
|
1709
|
+
if (role === 'user') readFunctionParts(result, blocks, message.timestamp);
|
|
1710
|
+
for (const tool of Array.isArray(message.toolCalls) ? message.toolCalls : []) {
|
|
1711
|
+
readTool(result, tool.name, tool.args);
|
|
1712
|
+
addToolCall(result, tool.name, tool.id, tool.args, tool.timestamp ?? message.timestamp);
|
|
1713
|
+
if (tool.result !== undefined || tool.error !== undefined) {
|
|
1714
|
+
addToolResult(result, tool.id, tool.result ?? tool.error, tool.status === 'error' || Boolean(tool.error), tool.timestamp);
|
|
1715
|
+
}
|
|
1716
|
+
}
|
|
1717
|
+
}
|
|
1718
|
+
|
|
1719
|
+
function* copilotEvent(result, requests) {
|
|
1720
|
+
let index = 0;
|
|
1721
|
+
for (const request of requests) {
|
|
1722
|
+
index++;
|
|
1723
|
+
result.sourceId = request?.requestId ?? request?.id ?? `request:${index}`;
|
|
1724
|
+
const requestId = result.sourceId;
|
|
1725
|
+
appendMessage(result, 'user', request?.message?.text, request?.timestamp);
|
|
1726
|
+
const response = Array.isArray(request?.response) ? request.response : [];
|
|
1727
|
+
result.sourceId = `${requestId}:response`;
|
|
1728
|
+
let text = '';
|
|
1729
|
+
const flush = () => {
|
|
1730
|
+
appendMessage(result, 'assistant', text, request?.timestamp, { estimatedTime: true });
|
|
1731
|
+
text = '';
|
|
1732
|
+
};
|
|
1733
|
+
for (const item of response) {
|
|
1734
|
+
if (item?.kind === 'thinking') {
|
|
1735
|
+
const value = item.value?.value ?? item.value;
|
|
1736
|
+
if (typeof value === 'string' && value.trim()) {
|
|
1737
|
+
flush();
|
|
1738
|
+
addSummary(result, value, undefined);
|
|
1739
|
+
}
|
|
1740
|
+
continue;
|
|
1741
|
+
}
|
|
1742
|
+
if (item?.kind !== 'toolInvocationSerialized') {
|
|
1743
|
+
text += copilotText(item);
|
|
1744
|
+
continue;
|
|
1745
|
+
}
|
|
1746
|
+
flush();
|
|
1747
|
+
const callId = item.toolCallId ?? item.invocationId;
|
|
1748
|
+
readTool(result, item.toolId, item.parameters);
|
|
1749
|
+
addToolCall(result, item.toolId ?? item.name, callId, item.parameters, request.timestamp);
|
|
1750
|
+
if (item.resultDetails !== undefined || item.result !== undefined || item.error !== undefined) {
|
|
1751
|
+
addToolResult(result, callId, item.resultDetails ?? item.result ?? item.error, Boolean(item.error));
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
flush();
|
|
1755
|
+
yield* result.events.splice(0);
|
|
1756
|
+
}
|
|
1757
|
+
}
|
|
1758
|
+
|
|
1759
|
+
async function* editorSourceEvents(archive, { sourceCwd, config, signal }, result) {
|
|
1760
|
+
const copilot = archive.kind === 'copilot';
|
|
1761
|
+
const file = await (copilot ? allowedEditorChat : allowedGemini)(archive, sourceCwd, config);
|
|
1762
|
+
if (!file) {
|
|
1763
|
+
yield { kind: 'gap', reason: 'source-unavailable' };
|
|
1764
|
+
return;
|
|
1765
|
+
}
|
|
1766
|
+
const jsonl = /\.jsonl$/i.test(file);
|
|
1767
|
+
if (!jsonl) {
|
|
1768
|
+
const { row, gap } = await sourceJson(file, signal);
|
|
1769
|
+
if (gap) {
|
|
1770
|
+
yield { kind: 'gap', reason: gap };
|
|
1771
|
+
} else if (copilot && Array.isArray(row?.requests)) {
|
|
1772
|
+
yield* copilotEvent(result, row.requests);
|
|
1773
|
+
} else if (Array.isArray(row?.messages)) {
|
|
1774
|
+
for (const [index, message] of row.messages.entries()) {
|
|
1775
|
+
signal?.throwIfAborted();
|
|
1776
|
+
geminiEvent(result, message, index + 1);
|
|
1777
|
+
yield* result.events.splice(0);
|
|
1778
|
+
}
|
|
1779
|
+
} else {
|
|
1780
|
+
yield { kind: 'gap', reason: 'unsupported-source-schema' };
|
|
1781
|
+
}
|
|
1782
|
+
return;
|
|
1783
|
+
}
|
|
1784
|
+
let state;
|
|
1785
|
+
let index = 0;
|
|
1786
|
+
let uncertain = false;
|
|
1787
|
+
for await (const { row, gap } of sourceJsonl(file, { signal })) {
|
|
1788
|
+
if (gap) {
|
|
1789
|
+
yield { kind: 'gap', reason: gap };
|
|
1790
|
+
} else if (copilot) {
|
|
1791
|
+
if (row.kind === 0) state = row.v;
|
|
1792
|
+
else if (!applyCopilotOp(state, row)) uncertain = true;
|
|
1793
|
+
} else {
|
|
1794
|
+
geminiEvent(result, row, ++index);
|
|
1795
|
+
yield* result.events.splice(0);
|
|
1796
|
+
}
|
|
1797
|
+
}
|
|
1798
|
+
if (copilot) {
|
|
1799
|
+
if (uncertain) yield { kind: 'gap', reason: 'unsupported-incremental-edit' };
|
|
1800
|
+
if (Array.isArray(state?.requests)) yield* copilotEvent(result, state.requests);
|
|
1801
|
+
else yield { kind: 'gap', reason: 'unsupported-source-schema' };
|
|
1802
|
+
}
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
export async function* readSourceEvents(archive, options) {
|
|
1806
|
+
const { signal } = options;
|
|
1807
|
+
const result = { events: [], usedSkills: new Set(), readStats: {}, turn: 0, sourceTurns: new Map() };
|
|
1808
|
+
try {
|
|
1809
|
+
signal?.throwIfAborted();
|
|
1810
|
+
if (['codex', 'claude', 'qoder', 'qwen', 'workbuddy'].includes(archive?.kind)) {
|
|
1811
|
+
yield* jsonlSourceEvents(archive, options, result);
|
|
1812
|
+
} else if (['opencode', 'agentsview'].includes(archive?.kind) || archive?.kind === 'copilot' && archive.storage === 'sqlite') {
|
|
1813
|
+
yield* databaseSourceEvents(archive, options, result);
|
|
1814
|
+
} else if (['copilot', 'gemini'].includes(archive?.kind)) {
|
|
1815
|
+
yield* editorSourceEvents(archive, options, result);
|
|
1816
|
+
} else {
|
|
1817
|
+
yield { kind: 'gap', reason: 'unsupported-source' };
|
|
1818
|
+
}
|
|
1819
|
+
} catch (error) {
|
|
1820
|
+
signal?.throwIfAborted();
|
|
1821
|
+
yield { kind: 'gap', reason: error.sourceReason ?? 'source-unreadable' };
|
|
1822
|
+
}
|
|
1823
|
+
const { tokens } = result.readStats;
|
|
1824
|
+
if (result.usedSkills.size || tokens) {
|
|
1825
|
+
yield { kind: 'metadata', usedSkills: [...result.usedSkills].sort(), ...(tokens ? { sourceStats: { tokens } } : {}) };
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
|
|
1829
|
+
export async function probeConversation(archive, options) {
|
|
1830
|
+
let reason;
|
|
1831
|
+
for await (const event of readSourceEvents(archive, options)) {
|
|
1832
|
+
if (event.role === 'user' && ['message', 'attachment'].includes(event.kind)) return { state: 'ready' };
|
|
1833
|
+
if (event.kind === 'gap') reason ??= event.reason;
|
|
1834
|
+
}
|
|
1835
|
+
return reason ? { state: 'unknown', reason } : { state: 'empty' };
|
|
1108
1836
|
}
|
|
1109
1837
|
|
|
1110
|
-
export async function readConversationHistory(archive, cwd, config) {
|
|
1838
|
+
export async function readConversationHistory(archive, cwd, config, { includeTrace = true } = {}) {
|
|
1111
1839
|
const result = {
|
|
1112
1840
|
messages: [], usedSkills: new Set(), limits: conversationLimits, characters: 0, truncated: false,
|
|
1113
|
-
trace: [], traceKeys: new Set(), traceOrder: 0, messageSeq: 0, turn: 0, turnRef: undefined,
|
|
1841
|
+
...(includeTrace ? { trace: [], traceKeys: new Set(), traceOrder: 0, messageSeq: 0, turn: 0, turnRef: undefined } : {}),
|
|
1114
1842
|
readStats: { userMessages: 0, assistantMessages: 0, timedMessages: 0 },
|
|
1115
1843
|
};
|
|
1116
1844
|
await readHistory(archive, cwd, config, result);
|
|
1117
1845
|
const calls = new Map();
|
|
1118
|
-
for (const item of result.trace) {
|
|
1846
|
+
for (const item of result.trace ?? []) {
|
|
1119
1847
|
if (item.kind !== 'tool_call') continue;
|
|
1120
1848
|
item.status = 'missing';
|
|
1121
1849
|
if (item.callId) calls.set(item.callId, item);
|
|
1122
1850
|
}
|
|
1123
|
-
for (const item of result.trace) {
|
|
1851
|
+
for (const item of result.trace ?? []) {
|
|
1124
1852
|
if (item.kind !== 'tool_result') continue;
|
|
1125
1853
|
const call = calls.get(item.callId);
|
|
1126
1854
|
item.turnRef = call?.turnRef;
|
|
@@ -1146,7 +1874,7 @@ export async function readConversationHistory(archive, cwd, config) {
|
|
|
1146
1874
|
// The last displayed reply in each source turn is its disclosure anchor.
|
|
1147
1875
|
// A turn without a reply is anchored to its own user message.
|
|
1148
1876
|
const indexOf = new Map(retained.map((message, index) => [message.turnRef, index]));
|
|
1149
|
-
const trace = result.trace
|
|
1877
|
+
const trace = (result.trace ?? [])
|
|
1150
1878
|
.filter(item => item.turnRef !== undefined && indexOf.has(item.turnRef))
|
|
1151
1879
|
.map(({ turnRef, ...item }) => ({ ...item, messageIndex: indexOf.get(turnRef) }))
|
|
1152
1880
|
.sort((a, b) => a.turn - b.turn || a.order - b.order);
|