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