@wwwfz/dsh-agent-bridge 0.0.0-stage → 0.8.2

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.
@@ -0,0 +1,980 @@
1
+ import { createReadStream } from 'node:fs';
2
+ import { open, readdir, realpath, stat } from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import zlib from 'node:zlib';
6
+
7
+ const maxSessions = 8_000;
8
+ const maxMessages = 36;
9
+ const maxMessageLength = 4_000;
10
+ const maxTranscriptBytes = 12 * 1024 * 1024;
11
+ const maxTranscriptRowBytes = 256 * 1024;
12
+ const tailBufferBytes = maxTranscriptBytes + 1;
13
+ const transcriptHeaderBytes = 96 * 1024;
14
+ const codexLocations = ['sessions', 'archived_sessions'];
15
+ const jsonlFile = /\.jsonl$/i;
16
+ const compressedCodexFile = /\.jsonl\.zst$/i;
17
+ const hasZstd = typeof zlib.createZstdDecompress === 'function';
18
+ const conversationLimits = { messages: 600, characters: 160_000, messageLength: 24_000 };
19
+
20
+ const agentLabels = {
21
+ codex: 'Codex', claude: 'Claude Code', opencode: 'OpenCode', workbuddy: 'WorkBuddy',
22
+ qoder: 'Qoder', trae: 'TRAE', antigravity: 'Antigravity', gemini: 'Gemini CLI',
23
+ copilot: 'GitHub Copilot', qwen: 'Qwen Code',
24
+ };
25
+
26
+ function configuredRoots(config, agent) {
27
+ const aliases = {
28
+ antigravity: ['antigravity-cli'], claude: ['claude-code'], codex: ['codex-cli'],
29
+ copilot: ['vscode', 'vscode-copilot', 'vscode-insiders', 'vscodium', 'code-oss'],
30
+ gemini: ['gemini-cli'], opencode: ['open-code'], qoder: ['qoder-cn'],
31
+ qwen: ['qwen-code'], trae: ['trae-cn', 'trae-solo'],
32
+ };
33
+ const roots = config.agentRoots ?? {};
34
+ const keys = [agent, ...(aliases[agent] ?? [])];
35
+ if (keys.some(key => Object.hasOwn(roots, key))) return keys.flatMap(key => roots[key] ?? []);
36
+ if (!config.home) return [];
37
+ const defaults = {
38
+ codex: ['.codex'], claude: ['.claude'], opencode: ['.local/share/opencode'],
39
+ qoder: ['.qoder-cn', '.qoder'], workbuddy: ['.workbuddy'],
40
+ trae: ['.trae-cn'],
41
+ antigravity: ['.gemini/antigravity', '.gemini/antigravity-cli'], gemini: ['.gemini'],
42
+ qwen: ['.qwen'],
43
+ };
44
+ return (defaults[agent] ?? []).map(root => path.join(config.home, root));
45
+ }
46
+
47
+ function pathKey(file) {
48
+ const normalized = path.normalize(file).replace(/^\\\\\?\\/, '');
49
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
50
+ }
51
+
52
+ async function physicalPath(file) {
53
+ return realpath(file).catch(() => undefined);
54
+ }
55
+
56
+ function inside(root, file) {
57
+ const relative = path.relative(pathKey(root), pathKey(file));
58
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
59
+ }
60
+
61
+ async function scopedFile(file, root) {
62
+ const [actual, base] = await Promise.all([physicalPath(file), physicalPath(root)]);
63
+ return actual && base && inside(base, actual) ? actual : undefined;
64
+ }
65
+
66
+ async function prefix(file, bytes) {
67
+ const handle = await open(file, 'r');
68
+ try {
69
+ const info = await handle.stat();
70
+ if (!info.isFile()) return { text: '', truncated: false };
71
+ const buffer = Buffer.alloc(Math.min(info.size, bytes));
72
+ const result = await handle.read(buffer, 0, buffer.length, 0);
73
+ return { text: buffer.toString('utf8', 0, result.bytesRead), truncated: info.size > result.bytesRead, modified: info.mtimeMs };
74
+ } finally {
75
+ await handle.close();
76
+ }
77
+ }
78
+
79
+ function json(text) {
80
+ try { return JSON.parse(text); } catch { return undefined; }
81
+ }
82
+
83
+ function rowsFrom(text, truncated) {
84
+ const value = text.replace(/^\uFEFF/, '');
85
+ const end = truncated ? value.lastIndexOf('\n') + 1 : value.length;
86
+ return value.slice(0, end).split(/\r?\n/).map(json).filter(Boolean);
87
+ }
88
+
89
+ async function directories(root) {
90
+ return readdir(root, { withFileTypes: true });
91
+ }
92
+
93
+ function missingStore() {
94
+ return Object.assign(new Error('未发现可读取的本地数据目录'), { code: 'ENOENT' });
95
+ }
96
+
97
+ async function dataDirectories(root, relatives) {
98
+ const candidates = await Promise.all(relatives.map(relative => scopedFile(path.join(root, relative), root)));
99
+ const found = await Promise.all(candidates.filter(Boolean).map(async candidate => (await stat(candidate)).isDirectory() ? candidate : undefined));
100
+ return [...new Set(found.filter(Boolean))];
101
+ }
102
+
103
+ function yamlScalar(value) {
104
+ const text = value.trim();
105
+ if (text.startsWith('"')) return json(text) ?? '';
106
+ if (text.startsWith("'") && text.endsWith("'")) return text.slice(1, -1).replaceAll("''", "'");
107
+ return text.replace(/\s+#.*$/, '');
108
+ }
109
+
110
+ // WorkspaceHub emits a fixed, flat schema for project metadata and its root list.
111
+ function projectRecord(text) {
112
+ const record = { roots: [], agentIDs: [] };
113
+ let section;
114
+ for (const line of text.replace(/^\uFEFF/, '').split(/\r?\n/)) {
115
+ const top = /^([A-Za-z][\w]*):\s*(.*)$/.exec(line);
116
+ if (top) {
117
+ section = top[1];
118
+ if (['id', 'name', 'canonicalPath', 'entryKind'].includes(section)) record[section] = yamlScalar(top[2]);
119
+ if (section === 'agentIDs' && top[2].startsWith('[') && top[2].endsWith(']')) {
120
+ record.agentIDs = top[2].slice(1, -1).split(',').map(yamlScalar).filter(Boolean);
121
+ }
122
+ continue;
123
+ }
124
+ if (section === 'agentIDs') {
125
+ const entry = /^\s*-\s+(.+)$/.exec(line);
126
+ if (entry) record.agentIDs.push(yamlScalar(entry[1]));
127
+ }
128
+ if (section === 'roots') {
129
+ const entry = /^\s*-\s+id:\s*(.*)$/.exec(line);
130
+ if (entry) record.roots.push({ id: yamlScalar(entry[1]) });
131
+ const field = /^\s+(role|path):\s*(.*)$/.exec(line);
132
+ if (field && record.roots.length) record.roots.at(-1)[field[1]] = yamlScalar(field[2]);
133
+ }
134
+ }
135
+ return record;
136
+ }
137
+
138
+ async function workspaceProjects(root) {
139
+ const result = [];
140
+ const records = path.basename(root) === '项目档案' ? root : path.join(root, '项目档案');
141
+ for (const entry of await directories(records)) {
142
+ if (!entry.isDirectory() || !/^P\d{3,}$/.test(entry.name)) continue;
143
+ const file = await scopedFile(path.join(records, entry.name, 'project.yaml'), records);
144
+ if (!file) continue;
145
+ const { text, truncated } = await prefix(file, 256 * 1024);
146
+ if (truncated) continue;
147
+ const record = projectRecord(text);
148
+ if (record.id !== entry.name || typeof record.canonicalPath !== 'string' || !path.isAbsolute(record.canonicalPath)) continue;
149
+ const locations = [record.canonicalPath, ...record.roots.filter(item => item.role === 'auxiliary').map(item => item.path)];
150
+ for (const location of locations) {
151
+ if (!location || !path.isAbsolute(location)) continue;
152
+ // A file project opens its containing directory, the nearest valid DSH cwd.
153
+ const info = await stat(location).catch(() => undefined);
154
+ const cwd = info?.isFile() ? path.dirname(location) : location;
155
+ for (const agent of record.agentIDs.length ? record.agentIDs : ['workspacehub']) {
156
+ result.push({ cwd, agent, name: record.name, projectId: record.id, projectRoot: root });
157
+ }
158
+ }
159
+ }
160
+ return result;
161
+ }
162
+
163
+ async function withDatabase(file, callback) {
164
+ const { DatabaseSync } = await import('node:sqlite');
165
+ const db = new DatabaseSync(file, { readOnly: true });
166
+ try {
167
+ db.exec('PRAGMA trusted_schema = OFF');
168
+ return callback(db);
169
+ } finally {
170
+ db.close();
171
+ }
172
+ }
173
+
174
+ function columns(db, table) {
175
+ return new Set(db.prepare('SELECT name FROM pragma_table_info(?)').all(table).map(row => row.name));
176
+ }
177
+
178
+ async function archivedProjects(file) {
179
+ return withDatabase(file, db => {
180
+ const fields = columns(db, 'sessions');
181
+ if (!['id', 'cwd', 'agent'].every(field => fields.has(field))) throw new Error('未识别 AgentsView 会话表');
182
+ const sort = fields.has('ended_at') ? 'ended_at' : 'id';
183
+ const deleted = fields.has('deleted_at') ? ' AND deleted_at IS NULL' : '';
184
+ const machine = fields.has('machine') ? " AND machine IN ('', 'local')" : '';
185
+ const title = fields.has('title') ? 'substr(title, 1, 200)' : 'NULL';
186
+ return db.prepare(`SELECT id, cwd, agent, ${sort} AS date, ${title} AS title FROM sessions WHERE cwd <> ''${deleted}${machine} ORDER BY ${sort} DESC LIMIT ?`)
187
+ .all(maxSessions).map(({ id, cwd, agent, date, title }) => ({ cwd, agent, archive: { kind: 'agentsview', agent, file, id, date, title } }));
188
+ });
189
+ }
190
+
191
+ async function codexProjects(root) {
192
+ const entries = await directories(root);
193
+ const states = entries.filter(entry => entry.isFile() && /^state_\d+\.sqlite$/.test(entry.name));
194
+ states.sort((a, b) => Number(b.name.match(/\d+/)[0]) - Number(a.name.match(/\d+/)[0]));
195
+ let indexed;
196
+ let indexError;
197
+ for (const entry of states) {
198
+ const file = await scopedFile(path.join(root, entry.name), root);
199
+ if (!file) continue;
200
+ try {
201
+ indexed = await withDatabase(file, db => {
202
+ const fields = columns(db, 'threads');
203
+ if (!['cwd', 'rollout_path', 'id'].every(field => fields.has(field))) return undefined;
204
+ const sort = fields.has('updated_at') ? 'updated_at' : 'id';
205
+ const title = fields.has('title') ? 'substr(title, 1, 200)' : 'NULL';
206
+ 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);
207
+ });
208
+ if (indexed) break;
209
+ } catch (error) {
210
+ indexError = error;
211
+ }
212
+ }
213
+ const bases = await transcriptDirectories(root, codexLocations);
214
+ if (!bases.length) throw indexError ?? missingStore();
215
+ const byFile = new Map();
216
+ for (let offset = 0; offset < (indexed?.length ?? 0); offset += 32) {
217
+ const batch = await Promise.all(indexed.slice(offset, offset + 32).map(async ({ id, cwd, rollout_path, date, title }) => {
218
+ const file = await resolveCodexTranscript(rollout_path, bases);
219
+ return file ? { cwd, agent: 'codex', archive: { kind: 'codex', file, root, id, date, title } } : undefined;
220
+ }));
221
+ for (const project of batch.filter(Boolean)) {
222
+ const key = pathKey(project.archive.file);
223
+ if (!byFile.has(key)) byFile.set(key, project);
224
+ }
225
+ }
226
+ // Files may be compressed or moved before SQLite catches up. Keep SQLite's
227
+ // titles when its path resolves, and discover compressed files independently.
228
+ const byId = new Set([...byFile.values()].map(project => project.archive.id).filter(Boolean));
229
+ const include = file => !byFile.has(pathKey(file))
230
+ && ((!indexed?.length && jsonlFile.test(file)) || (hasZstd && compressedCodexFile.test(file)));
231
+ const fallback = await scanJsonlProjects(root, 'codex', bases, 4, include, maxSessions - byFile.size);
232
+ for (const project of fallback) {
233
+ const { file, id } = project.archive;
234
+ if (id && byId.has(id)) continue;
235
+ if (id) byId.add(id);
236
+ byFile.set(pathKey(file), project);
237
+ }
238
+ return [...byFile.values()];
239
+ }
240
+
241
+ async function resolveCodexTranscript(file, bases) {
242
+ if (typeof file !== 'string' || !path.isAbsolute(file)) return undefined;
243
+ const candidates = compressedCodexFile.test(file) ? [file, file.slice(0, -4)]
244
+ : jsonlFile.test(file) ? [file, file + '.zst'] : [];
245
+ for (const candidate of candidates) {
246
+ const actual = await physicalPath(candidate);
247
+ if (!actual || !bases.some(base => inside(base, actual))
248
+ || !(jsonlFile.test(actual) || hasZstd && compressedCodexFile.test(actual))) continue;
249
+ if ((await stat(actual).catch(() => undefined))?.isFile()) return actual;
250
+ }
251
+ }
252
+
253
+ function opencodeTables(db) {
254
+ return ['session_v2', 'session'].filter(table => {
255
+ const fields = columns(db, table);
256
+ return ['id', 'directory', 'time_updated'].every(field => fields.has(field));
257
+ });
258
+ }
259
+
260
+ async function opencodeProjects(root) {
261
+ const file = await opencodeDatabase(root);
262
+ if (!file) throw missingStore();
263
+ return withDatabase(file, db => {
264
+ const tables = opencodeTables(db);
265
+ if (!tables.length) throw new Error('未识别 OpenCode 会话表');
266
+ const projects = tables.flatMap(table => {
267
+ const title = columns(db, table).has('title') ? 'substr(title, 1, 200)' : 'NULL';
268
+ 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 ?`)
269
+ .all(maxSessions).map(({ id, cwd, date, title }) => ({ cwd, agent: 'opencode', archive: { kind: 'opencode', file, id, table, date, title } }));
270
+ });
271
+ const fields = columns(db, 'project');
272
+ if (fields.has('worktree')) {
273
+ const name = fields.has('name') ? 'name' : 'NULL';
274
+ projects.push(...db.prepare(`SELECT worktree AS cwd, ${name} AS name FROM project WHERE worktree <> '' LIMIT ?`).all(maxSessions)
275
+ .map(row => ({ ...row, agent: 'opencode' })));
276
+ }
277
+ return projects;
278
+ });
279
+ }
280
+
281
+ async function opencodeDatabase(root) {
282
+ const info = await stat(root).catch(() => undefined);
283
+ if (info?.isFile()) return physicalPath(root);
284
+ if (!info?.isDirectory()) return undefined;
285
+ for (const relative of ['opencode.db', 'opencode/opencode.db']) {
286
+ const candidate = await scopedFile(path.join(root, relative), root);
287
+ if (candidate && (await stat(candidate)).isFile()) return candidate;
288
+ }
289
+ return undefined;
290
+ }
291
+
292
+ async function transcriptFiles(root, depth, limit, predicate) {
293
+ const files = [];
294
+ const stack = [{ root, depth }];
295
+ while (stack.length && files.length < limit) {
296
+ const current = stack.pop();
297
+ const entries = await directories(current.root).catch(() => []);
298
+ for (const entry of entries) {
299
+ const file = path.join(current.root, entry.name);
300
+ if (entry.isFile() && predicate(entry.name, file)) files.push(file);
301
+ if (files.length >= limit) break;
302
+ if (entry.isDirectory() && current.depth > 0 && entry.name !== 'subagents') {
303
+ stack.push({ root: file, depth: current.depth - 1 });
304
+ }
305
+ }
306
+ }
307
+ return files;
308
+ }
309
+
310
+ async function nativeCwd(file, agent, rows) {
311
+ if (agent === 'codex') return rows.find(row => row.type === 'session_meta')?.payload?.cwd;
312
+ const cwd = rows.find(row => typeof row.cwd === 'string' && path.isAbsolute(row.cwd))?.cwd;
313
+ if (cwd || agent !== 'qoder') return cwd;
314
+ const sidecar = await scopedFile(file.replace(/\.jsonl$/i, '-session.json'), path.dirname(file));
315
+ if (!sidecar) return undefined;
316
+ const { text, truncated } = await prefix(sidecar, 128 * 1024);
317
+ const metadata = truncated ? undefined : json(text);
318
+ return metadata?.working_dir ?? metadata?.workingDir ?? metadata?.cwd;
319
+ }
320
+
321
+ async function jsonlProjects(root, agent, children = ['projects'], depth = 1) {
322
+ const roots = await transcriptDirectories(root, children);
323
+ if (!roots.length) throw missingStore();
324
+ return scanJsonlProjects(root, agent, roots, depth, file => jsonlFile.test(file));
325
+ }
326
+
327
+ async function scanJsonlProjects(root, agent, roots, depth, include, limit = maxSessions) {
328
+ const files = [];
329
+ for (const target of roots) {
330
+ files.push(...await transcriptFiles(target, depth, limit - files.length, (_name, file) => include(file)));
331
+ }
332
+ const result = [];
333
+ for (let offset = 0; offset < files.length; offset += 32) {
334
+ const batch = await Promise.all(files.slice(offset, offset + 32).map(async file => {
335
+ try {
336
+ const compressed = agent === 'codex' && compressedCodexFile.test(file);
337
+ const { text, truncated, modified } = compressed ? await compressedPrefix(file) : await prefix(file, transcriptHeaderBytes);
338
+ const rows = rowsFrom(text, truncated);
339
+ const cwd = await nativeCwd(file, agent, rows);
340
+ const id = agent === 'codex' ? rows.find(row => row.type === 'session_meta')?.payload?.id : undefined;
341
+ const title = rows.findLast(row => row.type === 'custom-title' && typeof row.customTitle === 'string')?.customTitle
342
+ ?? rows.findLast(row => row.type === 'summary' && typeof row.summary === 'string')?.summary
343
+ ?? firstQuestion(rows, agent);
344
+ return cwd ? { cwd, agent, archive: { kind: agent, file, root, id, date: modified, title: title?.slice(0, 200) } } : undefined;
345
+ } catch { return undefined; }
346
+ }));
347
+ result.push(...batch.filter(Boolean));
348
+ }
349
+ return result;
350
+ }
351
+
352
+ function transcriptDirectories(root, children) {
353
+ return dataDirectories(root, children.includes(path.basename(root).toLowerCase()) ? [''] : children);
354
+ }
355
+
356
+ function editorStores(root) {
357
+ const relatives = path.basename(root).toLowerCase() === 'workspacestorage'
358
+ ? [''] : ['workspaceStorage', 'User/workspaceStorage'];
359
+ return dataDirectories(root, relatives);
360
+ }
361
+
362
+ async function editorProjects(root, agent) {
363
+ const stores = await editorStores(root);
364
+ if (!stores.length) throw missingStore();
365
+ const files = [];
366
+ for (const store of stores) {
367
+ files.push(...await transcriptFiles(store, 1, maxSessions - files.length, name => name === 'workspace.json'));
368
+ }
369
+ const result = [];
370
+ for (const file of files) {
371
+ try {
372
+ const { text } = await prefix(file, 32 * 1024);
373
+ const value = json(text);
374
+ const cwd = localDirectory(value?.folder);
375
+ if (!cwd) continue;
376
+ result.push({ cwd, agent });
377
+ if (agent !== 'copilot') continue;
378
+ const sessions = await transcriptFiles(path.join(path.dirname(file), 'chatSessions'), 0, maxSessions, name => /\.jsonl?$/i.test(name));
379
+ for (const session of sessions) {
380
+ const info = await stat(session).catch(() => undefined);
381
+ if (info) result.push({ cwd, agent, archive: { kind: 'copilot', file: session, root, date: info.mtimeMs } });
382
+ }
383
+ } catch { continue; }
384
+ }
385
+ return result;
386
+ }
387
+
388
+ async function geminiProjects(root) {
389
+ const [base] = await transcriptDirectories(root, ['tmp']);
390
+ if (!base) throw missingStore();
391
+ const files = await transcriptFiles(base, 1, maxSessions, name => name === '.project_root');
392
+ const result = [];
393
+ for (const file of files) {
394
+ const { text } = await prefix(file, 32 * 1024);
395
+ const cwd = text.trim();
396
+ result.push({ cwd, agent: 'gemini' });
397
+ const sessions = await transcriptFiles(path.join(path.dirname(file), 'chats'), 0, maxSessions, name => /^session-.+\.jsonl?$/i.test(name));
398
+ for (const session of sessions) {
399
+ const info = await stat(session).catch(() => undefined);
400
+ if (info) result.push({ cwd, agent: 'gemini', archive: { kind: 'gemini', file: session, root, date: info.mtimeMs } });
401
+ }
402
+ }
403
+ return result;
404
+ }
405
+
406
+ function localDirectory(value) {
407
+ if (typeof value !== 'string') return undefined;
408
+ if (path.isAbsolute(value)) return value;
409
+ if (!value.startsWith('file:')) return undefined;
410
+ try { return fileURLToPath(value); } catch { return undefined; }
411
+ }
412
+
413
+ async function antigravityProjects(root) {
414
+ await directories(root);
415
+ const projects = [];
416
+ const database = await scopedFile(path.join(root, 'conversation_summaries.db'), root);
417
+ const file = await scopedFile(path.join(root, 'history.jsonl'), root);
418
+ if (!database && !file) throw missingStore();
419
+ if (database) {
420
+ const rows = await withDatabase(database, db => {
421
+ const fields = columns(db, 'conversation_summaries');
422
+ if (!fields.has('workspace_uris')) return [];
423
+ return db.prepare("SELECT workspace_uris FROM conversation_summaries WHERE workspace_uris NOT IN ('', '[]') LIMIT ?").all(maxSessions);
424
+ });
425
+ for (const row of rows) {
426
+ const uris = json(row.workspace_uris);
427
+ if (!Array.isArray(uris)) continue;
428
+ for (const uri of uris) {
429
+ const cwd = localDirectory(uri);
430
+ if (cwd) projects.push({ cwd, agent: 'antigravity' });
431
+ }
432
+ }
433
+ }
434
+ if (file) {
435
+ const { text, truncated } = await prefix(file, maxTranscriptBytes);
436
+ for (const row of rowsFrom(text, truncated)) {
437
+ const cwd = localDirectory(row.workspace);
438
+ if (cwd && typeof row.conversationId === 'string') {
439
+ projects.push({ cwd, agent: 'antigravity', archive: { kind: 'antigravity', file, root, id: row.conversationId, date: row.timestamp } });
440
+ }
441
+ }
442
+ }
443
+ return projects;
444
+ }
445
+
446
+ export async function scanProjects(config) {
447
+ const projects = [];
448
+ const sources = [];
449
+ const discovered = new Map();
450
+ async function scan(id, label, paths, load, partial) {
451
+ let errors = 0;
452
+ const checks = await Promise.all(paths.map(async value => {
453
+ try { return await realpath(value); } catch (error) {
454
+ if (error.code !== 'ENOENT' && error.code !== 'ENOTDIR') errors++;
455
+ return undefined;
456
+ }
457
+ }));
458
+ const candidates = [...new Set(checks.filter(Boolean))];
459
+ let succeeded = 0;
460
+ let found = 0;
461
+ for (const file of candidates) {
462
+ try {
463
+ const rows = await load(file);
464
+ projects.push(...rows);
465
+ found += rows.length;
466
+ succeeded++;
467
+ } catch (error) {
468
+ if (error.code !== 'ENOENT') errors++;
469
+ }
470
+ }
471
+ const status = succeeded ? (errors || partial ? 'partial' : 'ready') : errors ? 'error' : candidates.length ? 'partial' : 'unavailable';
472
+ const detail = succeeded ? `${found} 条项目来源记录${partial ? ` · ${partial}` : ''}${errors ? ' · 部分来源读取失败' : ''}`
473
+ : errors ? '本地来源无法读取或格式无法识别' : candidates.length ? '已找到数据目录,尚无可读取的项目来源' : undefined;
474
+ sources.push({ id, label, status, detail });
475
+ }
476
+
477
+ await Promise.all([
478
+ scan('workspacehub', 'Agent Workspace Manager', config.workspaceHubRoots ?? [], workspaceProjects),
479
+ scan('agentsview', 'AgentsView 会话归档', config.archiveFiles ?? [], archivedProjects),
480
+ ...Object.entries({
481
+ codex: codexProjects, claude: root => jsonlProjects(root, 'claude'),
482
+ opencode: opencodeProjects, workbuddy: root => jsonlProjects(root, 'workbuddy'),
483
+ qoder: root => jsonlProjects(root, 'qoder'), qwen: root => jsonlProjects(root, 'qwen', ['projects'], 2),
484
+ trae: root => editorProjects(root, 'trae'), copilot: root => editorProjects(root, 'copilot'),
485
+ gemini: geminiProjects,
486
+ antigravity: antigravityProjects,
487
+ }).map(([agent, load]) => scan(agent, agentLabels[agent], configuredRoots(config, agent), load, {
488
+ trae: '支持工作区元数据;会话可从 AgentsView 读取已归档部分',
489
+ copilot: '支持 VS Code 工作区会话;其他版本可从 AgentsView 读取已归档部分',
490
+ antigravity: '支持工作区元数据和 CLI 提示记录;完整会话可从 AgentsView 读取已归档部分',
491
+ }[agent])),
492
+ ]);
493
+
494
+ for (const cwd of config.projectRoots ?? []) projects.push({ cwd, agent: 'manual' });
495
+ const canonical = new Map();
496
+ for (const project of projects) {
497
+ if (typeof project.cwd !== 'string' || !path.isAbsolute(project.cwd) || project.cwd === path.parse(project.cwd).root) continue;
498
+ const key = pathKey(project.cwd);
499
+ if (!canonical.has(key)) canonical.set(key, await physicalPath(project.cwd) ?? path.normalize(project.cwd));
500
+ project.cwd = canonical.get(key);
501
+ const timestamp = dateMillis(project.archive?.date);
502
+ if (timestamp > 0 && timestamp < 8_640_000_000_000_000) project.updatedAt = new Date(timestamp).toISOString();
503
+ const identity = JSON.stringify([pathKey(project.cwd), project.agent, project.projectId, project.archive?.kind, project.archive?.file, project.archive?.id]);
504
+ const previous = discovered.get(identity);
505
+ if (!previous || compareDate(project.archive?.date, previous.archive?.date) > 0) discovered.set(identity, project);
506
+ }
507
+ return { projects: [...discovered.values()], sources: sources.sort((a, b) => a.id.localeCompare(b.id)) };
508
+ }
509
+
510
+ export function dateMillis(value) {
511
+ if (typeof value === 'string') return Date.parse(value) || 0;
512
+ if (!Number.isFinite(value) || value <= 0 || value > 8_640_000_000_000_000) return 0;
513
+ return Math.trunc(value < 10_000_000_000 ? value * 1_000 : value);
514
+ }
515
+
516
+ function compareDate(a, b) {
517
+ return dateMillis(a) - dateMillis(b);
518
+ }
519
+
520
+ async function sameDirectory(cwd, expected) {
521
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return false;
522
+ const actual = await physicalPath(cwd);
523
+ return pathKey(actual ?? cwd) === pathKey(expected);
524
+ }
525
+
526
+ function stripRuntimeWrapper(text) {
527
+ let value = text.trimStart();
528
+ let stripped = false;
529
+ while (value.startsWith('<') || value.startsWith('#')) {
530
+ const wrapper = /^<(environment_context|permissions instructions|collaboration_mode|system-reminder|developer_instructions|user_instructions|app-context|subagent_notification)(?=[>\s])[^>]*(?:>|$)/i.exec(value);
531
+ const instructions = wrapper ? undefined : /^# AGENTS\.md instructions for [\s\S]*?\n<INSTRUCTIONS>/i.exec(value);
532
+ if (!wrapper && !instructions) break;
533
+ const closing = `</${wrapper?.[1].toLowerCase() ?? 'instructions'}>`;
534
+ const end = value.toLowerCase().indexOf(closing, (wrapper ?? instructions)[0].length);
535
+ if (end === -1) return '';
536
+ value = value.slice(end + closing.length).trimStart();
537
+ stripped = true;
538
+ }
539
+ return stripped ? value : text;
540
+ }
541
+
542
+ function messageText(text) {
543
+ return typeof text === 'string' ? stripRuntimeWrapper(text).trim() : '';
544
+ }
545
+
546
+ function appendMessage(result, role, text, timestamp) {
547
+ if (role !== 'user' && role !== 'assistant') return;
548
+ const value = messageText(text);
549
+ if (!value) return;
550
+ for (const match of value.matchAll(/<skill>\s*<name>([^<]+)<\/name>/gi)) addSkill(result, match[1]);
551
+ if (value.startsWith('<skill>')) return;
552
+ const { limits } = result;
553
+ if (limits) {
554
+ const bounded = value.slice(0, limits.messageLength).replace(/[\uD800-\uDBFF]$/, '');
555
+ result.messages.push({ role, text: bounded, agent: result.agent, time: dateMillis(timestamp) });
556
+ result.characters += bounded.length;
557
+ if (value.length > bounded.length) result.truncated = true;
558
+ while (result.messages.length > limits.messages || result.characters > limits.characters) {
559
+ const first = result.messages.shift();
560
+ if (first.role === 'user') result.removedQuestion = first;
561
+ result.characters -= first.text.length;
562
+ result.truncated = true;
563
+ }
564
+ } else {
565
+ result.messages.push({ role, text: value.slice(0, maxMessageLength), agent: result.agent });
566
+ if (result.messages.length > maxMessages) result.messages.shift();
567
+ }
568
+ }
569
+
570
+ function addSkill(result, name) {
571
+ if (typeof name === 'string' && /^[\p{L}\p{N}_:.\/-]{1,140}$/u.test(name.trim())) result.usedSkills.add(name.trim());
572
+ }
573
+
574
+ function skillPaths(result, value) {
575
+ if (typeof value !== 'string') return;
576
+ for (const match of value.replace(/[\\/]+/g, '/').matchAll(/(?:^|\/)([\p{L}\p{N}_:.-]+)\/SKILL\.md\b/giu)) addSkill(result, match[1]);
577
+ }
578
+
579
+ function readTool(result, name, input) {
580
+ const data = typeof input === 'string' ? json(input) : input;
581
+ if (typeof name !== 'string') return;
582
+ if (name === 'exec' && typeof input === 'string' && /(?:\bGet-Content\b|\breadFile\b|\bcat\s+)/i.test(input)) skillPaths(result, input);
583
+ if (!data) return;
584
+ if (/^(?:skill|activate_skill)$/i.test(name)) addSkill(result, data.skill ?? data.name ?? data.skill_name);
585
+ if (/^(?:read|exec_command|bash|shell)$/i.test(name)) {
586
+ for (const value of [data.file_path, data.filePath, data.path, data.cmd, data.command]) skillPaths(result, value);
587
+ }
588
+ }
589
+
590
+ function textBlocks(content, result) {
591
+ if (typeof content === 'string') return content;
592
+ if (!Array.isArray(content)) return '';
593
+ const texts = [];
594
+ for (const block of content) {
595
+ if (typeof block === 'string') texts.push(block);
596
+ if (['text', 'input_text', 'output_text'].includes(block?.type) && typeof block.text === 'string') texts.push(block.text);
597
+ if (result && block?.type === 'tool_use') readTool(result, block.name, block.input);
598
+ if (result && block?.type === 'tool') readTool(result, block.tool ?? block.name, block.state?.input ?? block.input ?? block.args);
599
+ }
600
+ // A Codex user message can contain several independent input_text blocks.
601
+ // Filter each one so an internal block never hides a neighboring prompt.
602
+ return texts.map(stripRuntimeWrapper).filter(value => value.trim()).join('\n');
603
+ }
604
+
605
+ function firstQuestion(rows, agent) {
606
+ for (const row of rows) {
607
+ if (row.isSidechain || row.isMeta || row.isCompactSummary) continue;
608
+ let body;
609
+ if (agent === 'codex') {
610
+ if (row.type === 'response_item' && row.payload?.type === 'message' && row.payload.role === 'user') {
611
+ body = textBlocks(row.payload.content);
612
+ }
613
+ } else if (agent === 'workbuddy') {
614
+ if (row.type === 'message' && ['user', 'human'].includes(row.role)) body = textBlocks(row.content);
615
+ } else if (row.type === 'user') {
616
+ body = agent === 'qwen' && Array.isArray(row.message?.parts)
617
+ ? row.message.parts.filter(part => !part?.thought).map(part => part?.text ?? '').join('\n')
618
+ : textBlocks(row.message?.content);
619
+ }
620
+ const title = messageText(body);
621
+ if (title && !title.startsWith('<skill>')) return title;
622
+ }
623
+ }
624
+
625
+ async function readGeminiHistory(descriptor, cwd, config, result) {
626
+ for (const root of configuredRoots(config, 'gemini')) {
627
+ const [base] = await transcriptDirectories(root, ['tmp']);
628
+ if (!base) continue;
629
+ const file = await scopedFile(descriptor.file, base);
630
+ if (!file || path.basename(path.dirname(file)) !== 'chats' || !/^session-.+\.jsonl?$/i.test(path.basename(file))) continue;
631
+ const marker = await scopedFile(path.resolve(path.dirname(file), '..', '.project_root'), base);
632
+ if (!marker || !await sameDirectory((await prefix(marker, 32 * 1024)).text.trim(), cwd)) continue;
633
+ const { text, truncated } = await prefix(file, maxTranscriptBytes);
634
+ if (truncated) result.truncated = true;
635
+ const messages = json(text)?.messages ?? rowsFrom(text, truncated);
636
+ if (!Array.isArray(messages)) continue;
637
+ for (const row of messages) {
638
+ const message = row.message ?? row;
639
+ if (!['user', 'gemini', 'assistant'].includes(message.type)) continue;
640
+ const content = Array.isArray(message.content) ? message.content.map(block => block?.text ?? '').join('\n') : message.content;
641
+ appendMessage(result, message.type === 'gemini' ? 'assistant' : message.type, content, message.timestamp);
642
+ for (const tool of Array.isArray(message.toolCalls) ? message.toolCalls : []) readTool(result, tool.name, tool.args);
643
+ }
644
+ return;
645
+ }
646
+ }
647
+
648
+ async function readAntigravityHistory(descriptor, cwd, config, result) {
649
+ for (const root of configuredRoots(config, 'antigravity')) {
650
+ const file = await scopedFile(path.join(root, 'history.jsonl'), root);
651
+ if (!file || pathKey(descriptor.file) !== pathKey(file)) continue;
652
+ const { text, truncated } = await prefix(file, maxTranscriptBytes);
653
+ for (const row of rowsFrom(text, truncated)) {
654
+ if (row.conversationId === descriptor.id && await sameDirectory(localDirectory(row.workspace), cwd)) {
655
+ appendMessage(result, 'user', row.display);
656
+ }
657
+ }
658
+ return;
659
+ }
660
+ }
661
+
662
+ function copilotRequests(text, truncated) {
663
+ const snapshot = json(text);
664
+ if (Array.isArray(snapshot?.requests)) return snapshot.requests;
665
+ let state;
666
+ for (const op of rowsFrom(text, truncated)) {
667
+ if (op.kind === 0) {
668
+ state = op.v;
669
+ continue;
670
+ }
671
+ if (!Array.isArray(op.k) || op.k[0] !== 'requests' || op.k.length > 8) continue;
672
+ const keys = op.k.map(String);
673
+ if (keys.some(key => ['__proto__', 'prototype', 'constructor'].includes(key))) continue;
674
+ const key = keys.pop();
675
+ let target = state;
676
+ for (const part of keys) target = target && Object.hasOwn(target, part) ? target[part] : undefined;
677
+ if (!target || typeof target !== 'object') continue;
678
+ if (Array.isArray(target) && (!/^\d+$/.test(key) || Number(key) >= target.length)) continue;
679
+ if (op.kind === 1) target[key] = op.v;
680
+ if (op.kind === 2 && Array.isArray(target[key]) && Array.isArray(op.v)) {
681
+ const current = target[key];
682
+ const index = Number.isInteger(op.i) ? Math.max(0, Math.min(op.i, current.length)) : current.length;
683
+ target[key] = current.slice(0, index).concat(op.v, current.slice(index + op.v.length));
684
+ }
685
+ if (op.kind === 3 && !Array.isArray(target)) delete target[key];
686
+ }
687
+ return Array.isArray(state?.requests) ? state.requests : [];
688
+ }
689
+
690
+ async function readCopilotHistory(descriptor, cwd, config, result) {
691
+ const stores = await Promise.all(configuredRoots(config, 'copilot').map(editorStores));
692
+ for (const base of stores.flat()) {
693
+ const file = await scopedFile(descriptor.file, base);
694
+ if (!file || path.basename(path.dirname(file)) !== 'chatSessions' || !/\.jsonl?$/i.test(file)) continue;
695
+ const workspace = await scopedFile(path.resolve(path.dirname(file), '..', 'workspace.json'), base);
696
+ if (!workspace) continue;
697
+ const marker = json((await prefix(workspace, 32 * 1024)).text);
698
+ if (!await sameDirectory(localDirectory(marker?.folder), cwd)) continue;
699
+ const { text, truncated } = await prefix(file, maxTranscriptBytes);
700
+ if (truncated) result.truncated = true;
701
+ const requests = copilotRequests(text, truncated);
702
+ for (const request of result.limits ? requests : requests.slice(-maxMessages)) {
703
+ appendMessage(result, 'user', request?.message?.text, request?.timestamp);
704
+ const response = Array.isArray(request?.response) ? request.response : [];
705
+ appendMessage(result, 'assistant', response.filter(item => !item?.kind || item.kind === 'markdownContent')
706
+ .map(item => item?.value?.value ?? item?.value ?? '').filter(value => typeof value === 'string').join(''), request?.timestamp);
707
+ for (const item of response) {
708
+ if (item?.kind === 'toolInvocationSerialized') readTool(result, item.toolId, item.parameters);
709
+ }
710
+ }
711
+ return;
712
+ }
713
+ }
714
+
715
+ async function* zstdChunks(file) {
716
+ const decoder = zlib.createZstdDecompress();
717
+ const input = createReadStream(file);
718
+ input.on('error', error => decoder.destroy(error));
719
+ try {
720
+ yield* input.pipe(decoder);
721
+ } finally {
722
+ // Discovery stops after the header. Close both ends without reading the rest.
723
+ input.destroy();
724
+ decoder.destroy();
725
+ }
726
+ }
727
+
728
+ async function compressedPrefix(file) {
729
+ const { mtimeMs: modified } = await stat(file);
730
+ const chunks = [];
731
+ let bytes = 0;
732
+ for await (const chunk of zstdChunks(file)) {
733
+ const part = chunk.subarray(0, transcriptHeaderBytes - bytes);
734
+ if (part.length) chunks.push(part);
735
+ bytes += part.length;
736
+ if (part.length < chunk.length) {
737
+ return { text: Buffer.concat(chunks, bytes).toString('utf8'), truncated: true, modified };
738
+ }
739
+ }
740
+ return { text: Buffer.concat(chunks, bytes).toString('utf8'), truncated: false, modified };
741
+ }
742
+
743
+ async function* compressedRows(file) {
744
+ // Keep at most one bounded JSONL record. Large tool outputs commonly sit
745
+ // between the last question and answer and must not compete with them.
746
+ let parts = [];
747
+ let bytes = 0;
748
+ for await (const chunk of zstdChunks(file)) {
749
+ let offset = 0;
750
+ while (offset < chunk.length) {
751
+ const newline = chunk.indexOf(10, offset);
752
+ const end = newline === -1 ? chunk.length : newline;
753
+ const length = end - offset;
754
+ if (bytes <= maxTranscriptRowBytes && length) {
755
+ bytes += length;
756
+ if (bytes <= maxTranscriptRowBytes) parts.push(chunk.subarray(offset, end));
757
+ else parts = [];
758
+ }
759
+ if (newline === -1) break;
760
+ if (bytes > maxTranscriptRowBytes) yield null;
761
+ else if (bytes) {
762
+ const row = json(Buffer.concat(parts, bytes).toString('utf8').replace(/^\uFEFF/, ''));
763
+ if (row) yield row;
764
+ }
765
+ offset = newline + 1;
766
+ bytes = 0;
767
+ parts = [];
768
+ }
769
+ }
770
+ if (bytes > maxTranscriptRowBytes) yield null;
771
+ else if (bytes) {
772
+ const row = json(Buffer.concat(parts, bytes).toString('utf8').replace(/^\uFEFF/, ''));
773
+ if (row) yield row;
774
+ }
775
+ }
776
+
777
+ function readCodexRow(result, row) {
778
+ if (row === null || row.type === 'compacted' || row.isCompactSummary) {
779
+ if (result.limits) result.truncated = true;
780
+ return;
781
+ }
782
+ if (row.isSidechain || row.isMeta || row.type !== 'response_item') return;
783
+ const payload = row.payload;
784
+ if (payload?.type === 'message') appendMessage(result, payload.role, textBlocks(payload.content, result), row.timestamp);
785
+ if (payload?.type === 'function_call') readTool(result, payload.name, payload.arguments);
786
+ if (payload?.type === 'custom_tool_call') readTool(result, payload.name, payload.input);
787
+ }
788
+
789
+ async function readCompressedCodex(file, cwd, result) {
790
+ // Use a separate accumulator so a damaged file never contributes an
791
+ // incomplete history or discards previously read project context.
792
+ const local = { messages: [], usedSkills: new Set(), limits: result.limits,
793
+ characters: 0, truncated: false, agent: result.agent };
794
+ let validated = false;
795
+ for await (const row of compressedRows(file)) {
796
+ if (!validated) {
797
+ if (row?.type !== 'session_meta') return;
798
+ if (!await sameDirectory(row.payload?.cwd, cwd)) return;
799
+ validated = true;
800
+ continue;
801
+ }
802
+ readCodexRow(local, row);
803
+ }
804
+ if (result.limits) {
805
+ Object.assign(result, local);
806
+ } else {
807
+ result.messages.push(...local.messages);
808
+ if (result.messages.length > maxMessages) result.messages.splice(0, result.messages.length - maxMessages);
809
+ for (const skill of local.usedSkills) result.usedSkills.add(skill);
810
+ }
811
+ }
812
+
813
+ async function transcriptTail(file) {
814
+ const handle = await open(file, 'r');
815
+ try {
816
+ const { size } = await handle.stat();
817
+ const buffer = Buffer.alloc(Math.min(size, tailBufferBytes));
818
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, size - buffer.length);
819
+ return parseTail(buffer.subarray(0, bytesRead));
820
+ } finally {
821
+ await handle.close();
822
+ }
823
+ }
824
+
825
+ function parseTail(buffer) {
826
+ const truncated = buffer.length > maxTranscriptBytes;
827
+ // Inspect one byte before the window so a complete first line isn't dropped.
828
+ const newline = truncated ? buffer.indexOf(10, buffer.length - tailBufferBytes) : -1;
829
+ return {
830
+ history: truncated && newline === -1 ? [] : rowsFrom(buffer.toString('utf8', newline + 1), false),
831
+ truncated,
832
+ };
833
+ }
834
+
835
+ async function readJsonlHistory(descriptor, cwd, config, result) {
836
+ const codex = descriptor.kind === 'codex';
837
+ const locations = codex ? codexLocations : ['projects'];
838
+ const bases = (await Promise.all(configuredRoots(config, descriptor.kind)
839
+ .map(root => transcriptDirectories(root, locations)))).flat();
840
+ let file;
841
+ if (codex) file = await resolveCodexTranscript(descriptor.file, bases);
842
+ else {
843
+ for (const base of bases) {
844
+ file = await scopedFile(descriptor.file, base);
845
+ if (file) break;
846
+ }
847
+ }
848
+ if (!file) return;
849
+ if (codex && compressedCodexFile.test(file)) return readCompressedCodex(file, cwd, result);
850
+ if (!jsonlFile.test(file)) return;
851
+ // Validate the embedded working directory before returning messages from this source.
852
+ const { text, truncated } = await prefix(file, transcriptHeaderBytes);
853
+ if (!await sameDirectory(await nativeCwd(file, descriptor.kind, rowsFrom(text, truncated)), cwd)) return;
854
+ const transcript = await transcriptTail(file);
855
+
856
+ // Active transcripts may have a torn last row. Large transcripts keep the latest bounded tail.
857
+ const { history } = transcript;
858
+ if (transcript.truncated) result.truncated = true;
859
+ for (const row of history) {
860
+ if (result.limits && row.isCompactSummary) result.truncated = true;
861
+ if (row.isSidechain || row.isMeta || row.isCompactSummary) continue;
862
+ if (descriptor.kind === 'codex') {
863
+ readCodexRow(result, row);
864
+ } else if (descriptor.kind === 'workbuddy') {
865
+ if (row.type === 'message') appendMessage(result, row.role === 'human' ? 'user' : row.role, textBlocks(row.content, result), row.timestamp);
866
+ if (row.type === 'function_call') readTool(result, row.name, row.arguments);
867
+ } else if (descriptor.kind === 'qwen' && (row.type === 'user' || row.type === 'assistant')) {
868
+ const parts = Array.isArray(row.message?.parts) ? row.message.parts : [];
869
+ appendMessage(result, row.type, parts.filter(part => !part?.thought && typeof part?.text === 'string').map(part => part.text).join('\n'), row.timestamp);
870
+ for (const part of parts) readTool(result, part?.functionCall?.name, part?.functionCall?.args);
871
+ } else if (row.type === 'user' || row.type === 'assistant') {
872
+ appendMessage(result, row.type, textBlocks(row.message?.content, result), row.timestamp);
873
+ }
874
+ }
875
+ }
876
+
877
+ async function allowedArchive(descriptor, config) {
878
+ const candidates = descriptor.kind === 'agentsview' ? config.archiveFiles ?? []
879
+ : (await Promise.all(configuredRoots(config, 'opencode').map(opencodeDatabase))).filter(Boolean);
880
+ const actual = await physicalPath(descriptor.file);
881
+ if (!actual) return undefined;
882
+ for (const candidate of candidates) {
883
+ const allowed = await physicalPath(candidate);
884
+ if (allowed && pathKey(allowed) === pathKey(actual)) return actual;
885
+ }
886
+ return undefined;
887
+ }
888
+
889
+ async function readDatabaseHistory(descriptor, cwd, config, result) {
890
+ const file = await allowedArchive(descriptor, config);
891
+ if (!file) return;
892
+ const snapshot = await withDatabase(file, db => {
893
+ if (descriptor.kind === 'agentsview') {
894
+ const sessionFields = columns(db, 'sessions');
895
+ const deleted = sessionFields.has('deleted_at') ? ' AND deleted_at IS NULL' : '';
896
+ const machine = sessionFields.has('machine') ? " AND machine IN ('', 'local')" : '';
897
+ const project = db.prepare('SELECT cwd, agent FROM sessions WHERE id = ?' + deleted + machine).get(descriptor.id);
898
+ const fields = columns(db, 'messages');
899
+ const content = fields.has('dialogue_text') ? "COALESCE(dialogue_text, '')" : 'content';
900
+ const system = fields.has('is_system') ? ' AND is_system = 0' : '';
901
+ const time = fields.has('timestamp') ? 'timestamp' : 'NULL';
902
+ const messages = db.prepare(`SELECT role, substr(${content}, 1, ?) AS text, ${time} AS time FROM messages WHERE session_id = ? AND role IN ('user', 'assistant')${system} ORDER BY ordinal DESC LIMIT ?`)
903
+ .all(result.limits ? result.limits.messageLength + 1 : maxMessageLength, descriptor.id,
904
+ result.limits ? result.limits.messages + 1 : maxMessages).reverse();
905
+ const skills = columns(db, 'tool_calls').has('skill_name') ? db.prepare('SELECT DISTINCT skill_name FROM tool_calls WHERE session_id = ? AND skill_name IS NOT NULL LIMIT 200').all(descriptor.id) : [];
906
+ return { cwd: project?.cwd, agent: project?.agent, messages, skills };
907
+ }
908
+ if (!opencodeTables(db).includes(descriptor.table)) return undefined;
909
+ const project = db.prepare(`SELECT directory FROM ${descriptor.table} WHERE id = ?`).get(descriptor.id);
910
+ const fields = columns(db, 'session_message');
911
+ if (['type', 'session_id', 'data'].every(field => fields.has(field))) {
912
+ const order = fields.has('seq') ? 'seq' : 'time_created';
913
+ const time = fields.has('time_created') ? 'time_created' : 'NULL';
914
+ const messages = db.prepare(`SELECT type, data, ${time} AS time FROM session_message WHERE session_id = ? AND type IN ('user','assistant','skill') ORDER BY ${order} DESC LIMIT ?`)
915
+ .all(descriptor.id, result.limits ? result.limits.messages + 1 : 100).reverse();
916
+ if (messages.length) return { cwd: project?.directory, projection: messages };
917
+ }
918
+ if (!columns(db, 'message').has('data') || !columns(db, 'part').has('data')) return { cwd: project?.directory };
919
+ const messages = db.prepare('SELECT id, data, time_created FROM message WHERE session_id = ? ORDER BY time_created DESC LIMIT ?')
920
+ .all(descriptor.id, result.limits ? result.limits.messages + 1 : maxMessages).reverse();
921
+ const parts = db.prepare('SELECT data FROM part WHERE session_id = ? AND message_id = ? ORDER BY time_created LIMIT 100');
922
+ return { cwd: project?.directory, legacy: messages.map(row => ({ role: json(row.data)?.role, time: row.time_created, parts: parts.all(descriptor.id, row.id).map(part => json(part.data)) })) };
923
+ });
924
+ if (!snapshot || !await sameDirectory(snapshot.cwd, cwd)) return;
925
+ if (snapshot.agent) result.agent = snapshot.agent;
926
+ for (const row of snapshot.messages ?? []) appendMessage(result, row.role, row.text, row.time);
927
+ for (const row of snapshot.skills ?? []) addSkill(result, row.skill_name);
928
+ for (const row of snapshot.projection ?? []) {
929
+ const data = json(row.data);
930
+ if (row.type === 'skill') addSkill(result, data?.name ?? data?.skill);
931
+ else appendMessage(result, row.type, data?.text ?? textBlocks(data?.content, result), row.time);
932
+ }
933
+ for (const row of snapshot.legacy ?? []) appendMessage(result, row.role, textBlocks(row.parts, result), row.time);
934
+ if (result.limits && (snapshot.messages ?? snapshot.projection ?? snapshot.legacy ?? []).length > result.limits.messages) {
935
+ result.truncated = true;
936
+ }
937
+ }
938
+
939
+ async function readHistory(archive, cwd, config, result) {
940
+ result.agent = archive.agent ?? archive.kind;
941
+ if (archive.kind === 'agentsview' || archive.kind === 'opencode') await readDatabaseHistory(archive, cwd, config, result);
942
+ if (['codex', 'claude', 'qoder', 'qwen', 'workbuddy'].includes(archive.kind)) await readJsonlHistory(archive, cwd, config, result);
943
+ if (archive.kind === 'gemini') await readGeminiHistory(archive, cwd, config, result);
944
+ if (archive.kind === 'antigravity') await readAntigravityHistory(archive, cwd, config, result);
945
+ if (archive.kind === 'copilot') await readCopilotHistory(archive, cwd, config, result);
946
+ }
947
+
948
+ export async function readConversationHistory(archive, cwd, config) {
949
+ const result = { messages: [], usedSkills: new Set(), limits: conversationLimits, characters: 0, truncated: false };
950
+ await readHistory(archive, cwd, config, result);
951
+ if (result.messages[0]?.role === 'assistant' && result.removedQuestion) {
952
+ // The latest retained replies may belong to a long turn whose question
953
+ // fell out of the sliding budget. Keep that real question with its replies.
954
+ const question = result.removedQuestion;
955
+ while (result.messages.length >= result.limits.messages || result.characters + question.text.length > result.limits.characters) {
956
+ result.characters -= result.messages.shift().text.length;
957
+ }
958
+ result.messages.unshift(question);
959
+ }
960
+ const start = result.messages.findIndex(message => message.role === 'user');
961
+ return { messages: start < 0 ? [] : result.messages.slice(start), truncated: result.truncated || start > 0 };
962
+ }
963
+
964
+ export async function readProjectHistory(project, config) {
965
+ const result = { messages: [], usedSkills: new Set() };
966
+ const archives = project.archives ?? (project.archive ? [project.archive] : []);
967
+ const ordered = [...archives].filter(item => typeof item?.file === 'string').sort((a, b) => compareDate(b.date, a.date));
968
+ for (const archive of ordered.slice(0, 12).reverse()) {
969
+ try { await readHistory(archive, project.cwd, config, result); }
970
+ catch { continue; }
971
+ }
972
+ const seen = new Set();
973
+ const messages = result.messages.filter(({ role, text, agent }) => {
974
+ const key = `${agent}\0${role}\0${text}`;
975
+ if (seen.has(key)) return false;
976
+ seen.add(key);
977
+ return true;
978
+ });
979
+ return { messages, usedSkills: [...result.usedSkills].sort() };
980
+ }