zcode-pro 1.7.0 → 1.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,839 @@
1
+ // 四个来源的会话扫描与解析。每个来源输出同一种结构:
2
+ // { sessionId, title, cwd, createdAt, updatedAt, model, messages }
3
+ // messages 里是 { role, time, parts },parts 支持 text / reasoning / tool / file。
4
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import { basename, join, resolve } from 'node:path';
7
+ import { zstdDecompressAll } from './zstd.mjs';
8
+ import {
9
+ dataUrlBytes, imageSize, isLocalCommandText, normalizeRoots, oneLine, outputText,
10
+ parseTime, readHead, readJsonl, readJsonlAll, readTail, stripPiInjections, textOf, toDataUrl,
11
+ walkFiles,
12
+ } from './util.mjs';
13
+
14
+ const LARGE_BYTES = 20 * 1024 * 1024;
15
+ const MAX_IMAGE_BYTES = 10 * 1024 * 1024;
16
+
17
+ let DatabaseSync;
18
+ try { ({ DatabaseSync } = await import('node:sqlite')); } catch { DatabaseSync = null; }
19
+
20
+ function fileSize(file) {
21
+ try { return statSync(file).size; } catch { return 0; }
22
+ }
23
+
24
+ function fileMtime(file) {
25
+ try { return Math.round(statSync(file).mtimeMs); } catch { return Date.now(); }
26
+ }
27
+
28
+ function sortNewest(list) {
29
+ return list.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0) || String(a.sessionId).localeCompare(String(b.sessionId)));
30
+ }
31
+
32
+ function imagePart(mime, dataUrl, filename = '') {
33
+ const url = String(dataUrl || '');
34
+ if (!url.startsWith('data:')) return null;
35
+ const sizeBytes = dataUrlBytes(url);
36
+ if (sizeBytes > MAX_IMAGE_BYTES) {
37
+ return { type: 'text', text: `[图片过大,未导入:${filename || mime || 'image'}]` };
38
+ }
39
+ const dims = imageSize(url) || {};
40
+ const metadata = {
41
+ image: { ...dims, maxDimension: 2000, resized: false, transformedSizeBytes: sizeBytes },
42
+ recoverability: 'provider_ready',
43
+ sizeBytes,
44
+ storageKind: 'inline',
45
+ };
46
+ const part = { type: 'file', mime: mime || 'image/png', url, metadata };
47
+ if (filename) part.filename = filename;
48
+ return part;
49
+ }
50
+
51
+ function toolPart(callID, name, input, start) {
52
+ return {
53
+ type: 'tool', callID: callID || `import_tool_${Math.random().toString(36).slice(2)}`,
54
+ tool: name || 'tool', input: input == null ? {} : input,
55
+ output: '', isError: false, start: start || Date.now(), end: start || Date.now(),
56
+ };
57
+ }
58
+
59
+ function attachToolResult(toolParts, callID, output, isError, end) {
60
+ const part = toolParts.get(callID);
61
+ if (!part) return;
62
+ part.output = outputText(output);
63
+ part.isError = !!isError;
64
+ part.end = end || part.end;
65
+ }
66
+
67
+ function finishMessages(messages) {
68
+ return messages.filter((m) => m.parts && m.parts.length);
69
+ }
70
+
71
+ function parseJsonInput(raw) {
72
+ if (raw && typeof raw === 'object') return raw;
73
+ if (typeof raw !== 'string') return {};
74
+ try {
75
+ const parsed = JSON.parse(raw);
76
+ return parsed && typeof parsed === 'object' ? parsed : { input: parsed };
77
+ } catch {
78
+ return { command: raw };
79
+ }
80
+ }
81
+
82
+ // ---------------------------------------------------------------------------
83
+ // Codex
84
+ // ---------------------------------------------------------------------------
85
+
86
+ function codexHome() {
87
+ return process.env.CODEX_HOME || join(homedir(), '.codex');
88
+ }
89
+
90
+ function codexStateDb() {
91
+ const home = codexHome();
92
+ try {
93
+ const names = readdirSync(home).filter((n) => /^state_\d+\.sqlite$/.test(n))
94
+ .sort((a, b) => Number(a.match(/\d+/)[0]) - Number(b.match(/\d+/)[0]));
95
+ return names.length ? join(home, names[names.length - 1]) : null;
96
+ } catch {
97
+ return null;
98
+ }
99
+ }
100
+
101
+ function codexThreads() {
102
+ const file = codexStateDb();
103
+ if (!file || !DatabaseSync) return new Map();
104
+ const out = new Map();
105
+ try {
106
+ const db = new DatabaseSync(file, { readOnly: true });
107
+ try {
108
+ for (const row of db.prepare('SELECT * FROM threads').all()) {
109
+ if (row && row.id) out.set(String(row.id), row);
110
+ }
111
+ } finally { db.close(); }
112
+ } catch { /* 旧版 Codex 没有这个库 */ }
113
+ return out;
114
+ }
115
+
116
+ function codexIndexTitles() {
117
+ const file = join(codexHome(), 'session_index.jsonl');
118
+ const out = new Map();
119
+ if (!existsSync(file)) return out;
120
+ try {
121
+ const text = readTail(file, 4 * 1024 * 1024);
122
+ for (const line of text.split(/\r?\n/)) {
123
+ if (!line.trim()) continue;
124
+ try {
125
+ const rec = JSON.parse(line);
126
+ if (rec && rec.id) out.set(String(rec.id), rec.thread_name || '');
127
+ } catch { /* 坏行 */ }
128
+ }
129
+ } catch { /* 读不到就靠文件头 */ }
130
+ return out;
131
+ }
132
+
133
+ function codexIdFromName(name) {
134
+ const m = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i.exec(name);
135
+ return m ? m[1] : '';
136
+ }
137
+
138
+ function codexMetaFromHead(file) {
139
+ const head = readHead(file, 131072);
140
+ let out = null;
141
+ let title = '';
142
+ let firstUser = '';
143
+ for (const line of head.split(/\r?\n/)) {
144
+ if (!line.trim()) continue;
145
+ let rec;
146
+ try { rec = JSON.parse(line); } catch { continue; }
147
+ const p = rec && rec.payload;
148
+ if (out === null && rec.type === 'session_meta' && p) {
149
+ out = {
150
+ id: p.id || p.session_id || '',
151
+ cwd: p.cwd || '',
152
+ time: parseTime(p.timestamp || rec.timestamp),
153
+ subagent: p.thread_source === 'subagent' || !!p.parent_thread_id || !!p.source?.subagent,
154
+ };
155
+ }
156
+ if (!title && rec.type === 'event_msg' && p?.type === 'thread_name_updated') title = String(p.thread_name || '');
157
+ if (!firstUser && rec.type === 'event_msg' && p?.type === 'user_message') firstUser = String(p.message || '');
158
+ }
159
+ return out ? { ...out, title, firstUser } : null;
160
+ }
161
+
162
+ const codexSource = {
163
+ id: 'codex',
164
+ label: 'Codex',
165
+ roots() {
166
+ return [join(codexHome(), 'sessions'), join(codexHome(), 'archived_sessions')];
167
+ },
168
+ available() {
169
+ return this.roots().some((p) => existsSync(p));
170
+ },
171
+ async list({ showAll = false } = {}) {
172
+ const threads = codexThreads();
173
+ const indexTitles = codexIndexTitles();
174
+ const files = [];
175
+ for (const dir of this.roots()) {
176
+ if (!existsSync(dir)) continue;
177
+ files.push(...walkFiles(dir, (file, name) => name.endsWith('.jsonl'), 6));
178
+ }
179
+ const byId = new Map();
180
+ for (const file of files) {
181
+ try {
182
+ const nameId = codexIdFromName(basename(file));
183
+ const meta = threads.get(nameId) || null;
184
+ const id = String(meta?.id || nameId || '');
185
+ if (!id) continue;
186
+ const headMeta = meta ? null : codexMetaFromHead(file);
187
+ const sessionId = String(meta?.id || headMeta?.id || id);
188
+ const subagent = meta ? meta.thread_source === 'subagent' : !!headMeta?.subagent;
189
+ if (subagent && !showAll) continue;
190
+ const archived = /[\\/]archived_sessions[\\/]/.test(file) || Number(meta?.archived) === 1;
191
+ const createdAt = parseTime(meta?.created_at) || headMeta?.time || fileMtime(file);
192
+ const updatedAt = parseTime(meta?.updated_at) || fileMtime(file);
193
+ const title = oneLine(meta?.title || indexTitles.get(sessionId) || meta?.first_user_message
194
+ || headMeta?.title || headMeta?.firstUser) || sessionId;
195
+ const entry = {
196
+ source: 'codex', sessionId, title, cwd: String(meta?.cwd || headMeta?.cwd || ''),
197
+ createdAt, updatedAt, sourcePath: file, archived, subagent,
198
+ model: String(meta?.model || ''), large: fileSize(file) > LARGE_BYTES,
199
+ };
200
+ const prev = byId.get(sessionId);
201
+ if (!prev || (prev.archived && !archived)) byId.set(sessionId, entry);
202
+ } catch { /* 跳过读不了的文件 */ }
203
+ }
204
+ return sortNewest([...byId.values()]);
205
+ },
206
+ async read(item) {
207
+ const file = item.sourcePath;
208
+ const meta = codexThreads().get(String(item.sessionId)) || null;
209
+ const indexTitle = codexIndexTitles().get(String(item.sessionId)) || '';
210
+ const messages = [];
211
+ const toolParts = new Map();
212
+ const execResults = new Map();
213
+ let current = null;
214
+ let lastUser = null;
215
+ let pendingImages = [];
216
+ let title = String(meta?.title || indexTitle || meta?.first_user_message || '');
217
+ let model = '';
218
+ let cwd = '';
219
+ let createdAt = 0;
220
+ let updatedAt = 0;
221
+
222
+ const flush = () => {
223
+ if (current && current.parts.length) messages.push(current);
224
+ current = null;
225
+ };
226
+ const ensureAssistant = (time) => {
227
+ if (!current) current = { role: 'assistant', time: time || Date.now(), parts: [] };
228
+ if (!current.time) current.time = time || Date.now();
229
+ return current;
230
+ };
231
+ const pushUser = (time, text, images) => {
232
+ const parts = [];
233
+ const clean = String(text || '').trim();
234
+ if (clean) parts.push({ type: 'text', text: clean });
235
+ for (const img of images || []) {
236
+ const part = imagePart(img.mime, img.dataUrl, img.filename);
237
+ if (part) parts.push(part);
238
+ }
239
+ if (!parts.length) return;
240
+ flush();
241
+ const msg = { role: 'user', time: time || Date.now(), parts };
242
+ messages.push(msg);
243
+ lastUser = msg;
244
+ };
245
+
246
+ for await (const rec of readJsonl(file)) {
247
+ const time = parseTime(rec.timestamp);
248
+ if (time) updatedAt = time;
249
+ const type = rec.type;
250
+ const payload = rec.payload || {};
251
+ if (type === 'session_meta') {
252
+ cwd = cwd || String(payload.cwd || '');
253
+ createdAt = createdAt || parseTime(payload.timestamp || rec.timestamp);
254
+ model = model || String(payload.model || payload.model_provider || '');
255
+ continue;
256
+ }
257
+ if (type === 'event_msg') {
258
+ if (payload.type === 'user_message') {
259
+ pushUser(time, payload.message, pendingImages);
260
+ pendingImages = [];
261
+ } else if (payload.type === 'agent_message') {
262
+ const text = String(payload.message || '').trim();
263
+ if (text) ensureAssistant(time).parts.push({ type: 'text', text });
264
+ } else if (payload.type === 'agent_reasoning') {
265
+ const text = String(payload.text || '').trim();
266
+ if (text) ensureAssistant(time).parts.push({ type: 'reasoning', text });
267
+ } else if (payload.type === 'thread_name_updated') {
268
+ title = String(payload.thread_name || title);
269
+ } else if (payload.type === 'exec_command_end') {
270
+ const callID = payload.call_id;
271
+ if (callID) {
272
+ const out = [payload.stdout, payload.stderr].filter(Boolean).join('\n');
273
+ execResults.set(callID, { output: out, isError: Number(payload.exit_code) !== 0, end: time });
274
+ }
275
+ } else if (payload.type === 'patch_apply_end') {
276
+ const callID = payload.call_id;
277
+ if (callID) execResults.set(callID, { output: outputText(payload.stdout || payload.changes), isError: false, end: time });
278
+ } else if (payload.type === 'mcp_tool_call_end') {
279
+ const callID = payload.call_id;
280
+ if (callID) execResults.set(callID, { output: outputText(payload.result || payload.output), isError: false, end: time });
281
+ }
282
+ continue;
283
+ }
284
+ if (type === 'response_item') {
285
+ if (payload.type === 'function_call' || payload.type === 'custom_tool_call') {
286
+ const callID = payload.call_id || payload.id || '';
287
+ const input = payload.arguments != null ? parseJsonInput(payload.arguments) : parseJsonInput(payload.input);
288
+ const part = toolPart(callID, payload.name, input, time);
289
+ ensureAssistant(time).parts.push(part);
290
+ toolParts.set(part.callID, part);
291
+ } else if (payload.type === 'function_call_output' || payload.type === 'custom_tool_call_output') {
292
+ const callID = payload.call_id || '';
293
+ attachToolResult(toolParts, callID, payload.output, payload.status === 'error' || payload.success === false, time);
294
+ } else if (payload.type === 'message' && payload.role === 'user') {
295
+ for (const block of Array.isArray(payload.content) ? payload.content : []) {
296
+ if (block && (block.type === 'input_image' || block.type === 'image')) {
297
+ const url = block.image_url || block.url || block.data || '';
298
+ if (String(url).startsWith('data:')) {
299
+ pendingImages.push({ mime: block.mime_type || block.mime || '', dataUrl: url, filename: block.filename || '' });
300
+ }
301
+ }
302
+ }
303
+ }
304
+ continue;
305
+ }
306
+ if (type === 'turn_context') {
307
+ cwd = cwd || String(payload.cwd || '');
308
+ model = model || String(payload.model || '');
309
+ }
310
+ }
311
+ flush();
312
+ for (const [callID, result] of execResults) {
313
+ const part = toolParts.get(callID);
314
+ if (part && !part.output) {
315
+ part.output = result.output;
316
+ part.isError = result.isError;
317
+ part.end = result.end || part.end;
318
+ }
319
+ }
320
+ return {
321
+ sessionId: item.sessionId, title: title || item.title, cwd: cwd || item.cwd,
322
+ createdAt: createdAt || item.createdAt, updatedAt: updatedAt || item.updatedAt,
323
+ model: model || item.model || '', messages: finishMessages(messages),
324
+ };
325
+ },
326
+ };
327
+
328
+ // ---------------------------------------------------------------------------
329
+ // Claude Code
330
+ // ---------------------------------------------------------------------------
331
+
332
+ function claudeHome() {
333
+ return process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude');
334
+ }
335
+
336
+ function claudeRecords(text) {
337
+ const out = [];
338
+ for (const line of String(text || '').split(/\r?\n/)) {
339
+ if (!line.trim()) continue;
340
+ try { out.push(JSON.parse(line)); } catch { /* 坏行 */ }
341
+ }
342
+ return out;
343
+ }
344
+
345
+ function claudeTitle(records) {
346
+ let title = '';
347
+ for (const rec of records) {
348
+ if (rec.type === 'custom-title' && rec.customTitle) title = rec.customTitle;
349
+ else if (rec.type === 'ai-title' && rec.aiTitle) title = rec.aiTitle;
350
+ else if (rec.type === 'last-prompt' && rec.lastPrompt) title = rec.lastPrompt;
351
+ }
352
+ return title;
353
+ }
354
+
355
+ function claudeFirstUserText(records) {
356
+ for (const rec of records) {
357
+ if (rec.type !== 'user' || rec.isMeta) continue;
358
+ const text = textOf(rec.message?.content ?? rec.content);
359
+ if (text && !isLocalCommandText(text)) return oneLine(text);
360
+ }
361
+ return '';
362
+ }
363
+
364
+ function claudeSubagent(records) {
365
+ return records.some((rec) => rec.isSidechain === true || rec.teamName
366
+ || /^daemon/.test(String(rec.sessionKind || ''))
367
+ || /^sdk-/.test(String(rec.entrypoint || '')));
368
+ }
369
+
370
+ const claudeSource = {
371
+ id: 'claude',
372
+ label: 'Claude Code',
373
+ roots() {
374
+ return [join(claudeHome(), 'projects')];
375
+ },
376
+ available() {
377
+ return existsSync(this.roots()[0]);
378
+ },
379
+ async list({ showAll = false } = {}) {
380
+ const dir = this.roots()[0];
381
+ if (!existsSync(dir)) return [];
382
+ const files = walkFiles(dir, (file, name) => name.endsWith('.jsonl'), 4)
383
+ .filter((file) => !/[\\/](?:worktree|worktrees)[\\/]/.test(file));
384
+ const out = [];
385
+ for (const file of files) {
386
+ try {
387
+ const head = claudeRecords(readHead(file, 262144));
388
+ const tail = claudeRecords(readTail(file, 131072));
389
+ const all = head.concat(tail);
390
+ const sessionId = basename(file, '.jsonl');
391
+ const cwd = String(all.find((r) => r.cwd)?.cwd || '');
392
+ const title = oneLine(claudeTitle(tail) || claudeTitle(head) || claudeFirstUserText(head)) || sessionId;
393
+ const hasContent = all.some((r) => r.type === 'assistant')
394
+ || (head.some((r) => r.type === 'user' && !r.isMeta && !isLocalCommandText(textOf(r.message?.content ?? r.content))));
395
+ if (!hasContent && !showAll) continue;
396
+ const subagent = claudeSubagent(all);
397
+ if (subagent && !showAll) continue;
398
+ const times = all.map((r) => parseTime(r.timestamp)).filter(Boolean).sort((a, b) => a - b);
399
+ out.push({
400
+ source: 'claude', sessionId, title, cwd,
401
+ createdAt: times[0] || fileMtime(file), updatedAt: times[times.length - 1] || fileMtime(file),
402
+ sourcePath: file, archived: false, subagent,
403
+ model: String(all.find((r) => r.type === 'assistant' && r.message?.model)?.message?.model || ''),
404
+ large: fileSize(file) > LARGE_BYTES,
405
+ });
406
+ } catch { /* 跳过读不了的文件 */ }
407
+ }
408
+ return sortNewest(out);
409
+ },
410
+ async read(item) {
411
+ const records = await readJsonlAll(item.sourcePath);
412
+ const byUuid = new Map();
413
+ let leaf = null;
414
+ for (const rec of records) {
415
+ if (rec.uuid) byUuid.set(rec.uuid, rec);
416
+ if (rec.type === 'last-prompt' && rec.leafUuid) leaf = byUuid.get(rec.leafUuid) || null;
417
+ else if (rec.uuid) leaf = rec;
418
+ }
419
+ const chain = [];
420
+ const seen = new Set();
421
+ let cursor = leaf;
422
+ while (cursor && cursor.uuid && !seen.has(cursor.uuid)) {
423
+ seen.add(cursor.uuid);
424
+ chain.push(cursor);
425
+ cursor = cursor.parentUuid ? byUuid.get(cursor.parentUuid) : null;
426
+ }
427
+ chain.reverse();
428
+ if (!chain.length) chain.push(...records.filter((r) => r.uuid));
429
+
430
+ const messages = [];
431
+ const toolParts = new Map();
432
+ let current = null;
433
+ let title = claudeTitle(records) || claudeFirstUserText(records); let model = '';
434
+ let cwd = '';
435
+ let createdAt = 0;
436
+ let updatedAt = 0;
437
+
438
+ const flush = () => {
439
+ if (current && current.parts.length) messages.push(current);
440
+ current = null;
441
+ };
442
+ const ensureAssistant = (time) => {
443
+ if (!current) current = { role: 'assistant', time: time || Date.now(), parts: [] };
444
+ return current;
445
+ };
446
+ const pushUser = (time, parts) => {
447
+ if (!parts.length) return;
448
+ flush();
449
+ messages.push({ role: 'user', time: time || Date.now(), parts });
450
+ };
451
+
452
+ for (const rec of chain) {
453
+ const time = parseTime(rec.timestamp);
454
+ if (time) { createdAt = createdAt || time; updatedAt = time; }
455
+ if (rec.cwd && !cwd) cwd = String(rec.cwd);
456
+ if (rec.message?.model) model = String(rec.message.model);
457
+ if (rec.type === 'user') {
458
+ const content = rec.message?.content ?? rec.content;
459
+ const blocks = Array.isArray(content) ? content : [{ type: 'text', text: typeof content === 'string' ? content : '' }];
460
+ const parts = [];
461
+ for (const block of blocks) {
462
+ if (!block || typeof block !== 'object') continue;
463
+ if (block.type === 'tool_result') {
464
+ attachToolResult(toolParts, block.tool_use_id, block.content, block.is_error, time);
465
+ continue;
466
+ }
467
+ if (block.type === 'text') {
468
+ if (rec.isMeta || isLocalCommandText(block.text)) continue;
469
+ if (block.text && block.text.trim()) parts.push({ type: 'text', text: block.text });
470
+ } else if (block.type === 'image') {
471
+ const src = block.source || {};
472
+ if (src.type === 'base64') {
473
+ const part = imagePart(src.media_type, toDataUrl(src.media_type, src.data));
474
+ if (part) parts.push(part);
475
+ }
476
+ }
477
+ }
478
+ pushUser(time, parts);
479
+ continue;
480
+ }
481
+ if (rec.type === 'assistant') {
482
+ const blocks = Array.isArray(rec.message?.content) ? rec.message.content : [];
483
+ for (const block of blocks) {
484
+ if (!block || typeof block !== 'object') continue;
485
+ if (block.type === 'text' && block.text && block.text.trim()) {
486
+ ensureAssistant(time).parts.push({ type: 'text', text: block.text });
487
+ } else if (block.type === 'thinking' && block.thinking) {
488
+ ensureAssistant(time).parts.push({ type: 'reasoning', text: block.thinking });
489
+ } else if (block.type === 'tool_use') {
490
+ const part = toolPart(block.id, block.name, block.input || {}, time);
491
+ ensureAssistant(time).parts.push(part);
492
+ toolParts.set(block.id, part);
493
+ }
494
+ }
495
+ }
496
+ }
497
+ flush();
498
+ return {
499
+ sessionId: item.sessionId, title: title || item.title, cwd: cwd || item.cwd,
500
+ createdAt: createdAt || item.createdAt, updatedAt: updatedAt || item.updatedAt,
501
+ model: model || item.model || '', messages: finishMessages(messages),
502
+ };
503
+ },
504
+ };
505
+
506
+ // ---------------------------------------------------------------------------
507
+ // pi
508
+ // ---------------------------------------------------------------------------
509
+
510
+ function piHome() {
511
+ return join(homedir(), '.pi', 'agent');
512
+ }
513
+
514
+ function piSessionsDir() {
515
+ const env = String(process.env.PI_CODING_AGENT_SESSION_DIR || '').trim();
516
+ if (env) return env;
517
+ try {
518
+ const settings = JSON.parse(readHead(join(piHome(), 'settings.json'), 65536) || '{}');
519
+ if (settings.sessionDir) {
520
+ const dir = String(settings.sessionDir);
521
+ return dir.startsWith('~') ? join(homedir(), dir.slice(1)) : resolve(dir);
522
+ }
523
+ } catch { /* 没有设置文件就用默认目录 */ }
524
+ return join(piHome(), 'sessions');
525
+ }
526
+
527
+ function piHeader(file) {
528
+ const head = readHead(file, 262144);
529
+ for (const line of head.split(/\r?\n/)) {
530
+ if (!line.trim()) continue;
531
+ try {
532
+ const rec = JSON.parse(line);
533
+ if (rec && rec.type === 'session') return rec;
534
+ } catch { /* 继续找 */ }
535
+ }
536
+ return null;
537
+ }
538
+
539
+ const piSource = {
540
+ id: 'pi',
541
+ label: 'pi',
542
+ roots() {
543
+ return [piSessionsDir()];
544
+ },
545
+ available() {
546
+ return existsSync(this.roots()[0]);
547
+ },
548
+ async list({ showAll = false } = {}) {
549
+ const dir = this.roots()[0];
550
+ if (!existsSync(dir)) return [];
551
+ const files = walkFiles(dir, (file, name) => name.endsWith('.jsonl') && !name.endsWith('.edit-backup'), 4);
552
+ const out = [];
553
+ for (const file of files) {
554
+ try {
555
+ const header = piHeader(file);
556
+ if (!header || !header.id) continue;
557
+ const head = readHead(file, 262144);
558
+ const tail = readTail(file, 131072);
559
+ const records = claudeRecords(head).concat(claudeRecords(tail));
560
+ const lastInfo = records.filter((r) => r.type === 'session_info' && r.name).pop();
561
+ const firstUser = records.map((r) => (r.type === 'message' && r.message?.role === 'user'
562
+ ? stripPiInjections(textOf(r.message.content)) : '')).find(Boolean);
563
+ const codexImport = records.some((r) => r.type === 'codex_import');
564
+ if (codexImport && !showAll) continue;
565
+ const subagent = header.origin === 'subagent' || Number(header.delegationDepth) > 0;
566
+ if (subagent && !showAll) continue;
567
+ const times = records.map((r) => parseTime(r.timestamp || r.message?.timestamp)).filter(Boolean).sort((a, b) => a - b);
568
+ out.push({
569
+ source: 'pi', sessionId: String(header.id),
570
+ title: oneLine(lastInfo?.name || firstUser) || String(header.id),
571
+ cwd: String(header.cwd || ''), createdAt: parseTime(header.timestamp) || fileMtime(file),
572
+ updatedAt: times[times.length - 1] || fileMtime(file), sourcePath: file,
573
+ archived: false, subagent, codexImport,
574
+ model: String(records.find((r) => r.type === 'message' && r.message?.role === 'assistant' && r.message?.model)?.message?.model || ''),
575
+ large: fileSize(file) > LARGE_BYTES,
576
+ });
577
+ } catch { /* 跳过读不了的文件 */ }
578
+ }
579
+ return sortNewest(out);
580
+ },
581
+ async read(item) {
582
+ const records = await readJsonlAll(item.sourcePath);
583
+ const header = records.find((r) => r.type === 'session') || {};
584
+ const firstUser = records.map((r) => (r.type === 'message' && r.message?.role === 'user'
585
+ ? stripPiInjections(textOf(r.message.content)) : '')).find(Boolean) || '';
586
+ let title = records.filter((r) => r.type === 'session_info' && r.name).pop()?.name || '';
587
+ const byId = new Map();
588
+ let leaf = null;
589
+ for (const rec of records) {
590
+ if (rec.id) byId.set(rec.id, rec);
591
+ if (rec.type === 'message') leaf = rec;
592
+ }
593
+ const chain = [];
594
+ const seen = new Set();
595
+ let cursor = leaf;
596
+ while (cursor && cursor.id && !seen.has(cursor.id)) {
597
+ seen.add(cursor.id);
598
+ chain.push(cursor);
599
+ cursor = cursor.parentId ? byId.get(cursor.parentId) : null;
600
+ }
601
+ chain.reverse();
602
+
603
+ const messages = [];
604
+ const toolParts = new Map();
605
+ let current = null;
606
+ let model = '';
607
+
608
+ const flush = () => {
609
+ if (current && current.parts.length) messages.push(current);
610
+ current = null;
611
+ };
612
+ const ensureAssistant = (time) => {
613
+ if (!current) current = { role: 'assistant', time: time || Date.now(), parts: [] };
614
+ return current;
615
+ };
616
+ const pushUser = (time, parts) => {
617
+ if (!parts.length) return;
618
+ flush();
619
+ messages.push({ role: 'user', time: time || Date.now(), parts });
620
+ };
621
+
622
+ for (const rec of chain) {
623
+ const time = parseTime(rec.timestamp || rec.message?.timestamp);
624
+ if (rec.type === 'session_info' && rec.name) title = String(rec.name);
625
+ if (rec.type !== 'message') continue;
626
+ const message = rec.message || {};
627
+ if (message.role === 'user') {
628
+ const parts = [];
629
+ for (const block of Array.isArray(message.content) ? message.content : []) {
630
+ if (block.type === 'text') {
631
+ const text = stripPiInjections(block.text);
632
+ if (text) parts.push({ type: 'text', text });
633
+ } else if (block.type === 'image') {
634
+ const part = imagePart(block.mimeType, toDataUrl(block.mimeType, block.data));
635
+ if (part) parts.push(part);
636
+ }
637
+ }
638
+ pushUser(time, parts);
639
+ } else if (message.role === 'assistant') {
640
+ if (message.model) model = String(message.model);
641
+ for (const block of Array.isArray(message.content) ? message.content : []) {
642
+ if (block.type === 'text' && block.text && block.text.trim()) {
643
+ ensureAssistant(time).parts.push({ type: 'text', text: block.text });
644
+ } else if (block.type === 'thinking' && block.thinking) {
645
+ ensureAssistant(time).parts.push({ type: 'reasoning', text: block.thinking });
646
+ } else if (block.type === 'toolCall') {
647
+ const part = toolPart(block.id, block.name, block.arguments || {}, time);
648
+ ensureAssistant(time).parts.push(part);
649
+ toolParts.set(block.id, part);
650
+ }
651
+ }
652
+ } else if (message.role === 'toolResult') {
653
+ attachToolResult(toolParts, message.toolCallId, message.content, message.isError, time);
654
+ }
655
+ }
656
+ flush();
657
+ return {
658
+ sessionId: item.sessionId, title: title || oneLine(firstUser) || item.title, cwd: header.cwd || item.cwd,
659
+ createdAt: parseTime(header.timestamp) || item.createdAt, updatedAt: item.updatedAt,
660
+ model: model || item.model || '', messages: finishMessages(messages),
661
+ };
662
+ },
663
+ };
664
+
665
+ // ---------------------------------------------------------------------------
666
+ // dsh
667
+ // ---------------------------------------------------------------------------
668
+
669
+ function dshHome() {
670
+ const env = String(process.env.DSH_HOME || '').trim();
671
+ return env || join(homedir(), '.dsh');
672
+ }
673
+
674
+ const dshCache = new Map();
675
+
676
+ function dshFiles() {
677
+ const dir = join(dshHome(), 'sessions');
678
+ if (!existsSync(dir)) return [];
679
+ const out = [];
680
+ for (const project of readdirSync(dir, { withFileTypes: true })) {
681
+ if (!project.isDirectory()) continue;
682
+ const projectDir = join(dir, project.name);
683
+ for (const session of readdirSync(projectDir, { withFileTypes: true })) {
684
+ if (!session.isDirectory()) continue;
685
+ const sessionDir = join(projectDir, session.name);
686
+ let names = [];
687
+ try { names = readdirSync(sessionDir); } catch { continue; }
688
+ const plain = names.find((n) => /^session\.jsonl$/.test(n));
689
+ if (plain) { out.push({ file: join(sessionDir, plain), compressed: false }); continue; }
690
+ const zst = names.filter((n) => /^session(?:\.v\d+)?\.jsonl\.zstd$/.test(n))
691
+ .sort((a, b) => Number((a.match(/\.v(\d+)\./) || [])[1] || 0) - Number((b.match(/\.v(\d+)\./) || [])[1] || 0));
692
+ if (zst.length) out.push({ file: join(sessionDir, zst[zst.length - 1]), compressed: true });
693
+ }
694
+ }
695
+ return out;
696
+ }
697
+
698
+ function dshLines(file, compressed) {
699
+ const mtime = fileMtime(file);
700
+ const cached = dshCache.get(file);
701
+ if (cached && cached.mtime === mtime) return cached.lines;
702
+ const raw = compressed ? zstdDecompressAll(readFileSync(file)) : readFileSync(file);
703
+ const lines = [];
704
+ for (const line of raw.toString('utf8').split(/\r?\n/)) {
705
+ if (!line.trim()) continue;
706
+ try { lines.push(JSON.parse(line)); } catch { /* 坏行 */ }
707
+ }
708
+ dshCache.set(file, { mtime, lines, size: raw.length });
709
+ return lines;
710
+ }
711
+
712
+ const dshSource = {
713
+ id: 'dsh',
714
+ label: 'dsh',
715
+ roots() {
716
+ return [join(dshHome(), 'sessions')];
717
+ },
718
+ available() {
719
+ return existsSync(this.roots()[0]);
720
+ },
721
+ async list({ showAll = false } = {}) {
722
+ const out = [];
723
+ for (const item of dshFiles()) {
724
+ let lines;
725
+ try { lines = dshLines(item.file, item.compressed); } catch { continue; }
726
+ const header = lines.find((r) => r.type === 'session');
727
+ if (!header || !header.id) continue;
728
+ const subagent = header.origin === 'subagent' || Number(header.delegationDepth) > 0;
729
+ if (subagent && !showAll) continue;
730
+ const titles = lines.filter((r) => r.type === 'session/title' && r.data?.title);
731
+ const firstUser = lines.map((r) => (r.type === 'user/message' && r.data?.source?.kind === 'user'
732
+ ? textOf(r.data.content) : '')).find(Boolean);
733
+ const times = lines.map((r) => parseTime(r.time)).filter(Boolean).sort((a, b) => a - b);
734
+ const size = dshCache.get(item.file)?.size || fileSize(item.file);
735
+ out.push({
736
+ source: 'dsh', sessionId: String(header.id),
737
+ title: oneLine(titles[titles.length - 1]?.data?.title || firstUser) || String(header.id),
738
+ cwd: String(header.cwd || ''), createdAt: parseTime(header.createdAt) || fileMtime(item.file),
739
+ updatedAt: times[times.length - 1] || fileMtime(item.file), sourcePath: item.file,
740
+ archived: false, subagent,
741
+ model: String(lines.find((r) => r.type === 'request/context')?.data?.model || ''),
742
+ large: size > LARGE_BYTES,
743
+ });
744
+ }
745
+ return sortNewest(out);
746
+ },
747
+ async read(item) {
748
+ const lines = dshLines(item.sourcePath, /\.zstd$/.test(item.sourcePath));
749
+ const header = lines.find((r) => r.type === 'session') || {};
750
+ const firstUser = lines.map((r) => (r.type === 'user/message' && r.data?.source?.kind === 'user'
751
+ ? textOf(r.data.content) : '')).find(Boolean) || '';
752
+ const messages = [];
753
+ const toolParts = new Map();
754
+ let current = null;
755
+ let title = '';
756
+ let model = '';
757
+
758
+ const flush = () => {
759
+ if (current && current.parts.length) messages.push(current);
760
+ current = null;
761
+ };
762
+ const ensureAssistant = (time) => {
763
+ if (!current) current = { role: 'assistant', time: time || Date.now(), parts: [] };
764
+ return current;
765
+ };
766
+ const pushUser = (time, parts) => {
767
+ if (!parts.length) return;
768
+ flush();
769
+ messages.push({ role: 'user', time: time || Date.now(), parts });
770
+ };
771
+
772
+ for (const rec of lines) {
773
+ const time = parseTime(rec.time);
774
+ if (rec.type === 'session/title' && rec.data?.title) title = String(rec.data.title);
775
+ if (rec.type === 'request/context' && rec.data?.model) model = String(rec.data.model);
776
+ if (rec.type === 'user/message') {
777
+ if (rec.data?.source?.kind !== 'user') continue;
778
+ const parts = [];
779
+ for (const block of Array.isArray(rec.data.content) ? rec.data.content : []) {
780
+ if (block.type === 'text') {
781
+ const text = String(block.text || '').trim();
782
+ if (text) parts.push({ type: 'text', text });
783
+ } else if (block.type === 'image') {
784
+ const part = imagePart(block.mimeType, toDataUrl(block.mimeType, block.data));
785
+ if (part) parts.push(part);
786
+ }
787
+ }
788
+ pushUser(time, parts);
789
+ } else if (rec.type === 'assistant/message') {
790
+ const message = rec.data?.message || {};
791
+ if (message.source?.model) model = String(message.source.model);
792
+ for (const block of Array.isArray(message.content) ? message.content : []) {
793
+ if (block.type === 'text' && block.text && block.text.trim()) {
794
+ ensureAssistant(time).parts.push({ type: 'text', text: block.text });
795
+ } else if (block.type === 'reasoning' && block.text) {
796
+ ensureAssistant(time).parts.push({ type: 'reasoning', text: block.text });
797
+ } else if (block.type === 'tool-call') {
798
+ const part = toolPart(block.id, block.name, parseJsonInput(block.arguments), time);
799
+ ensureAssistant(time).parts.push(part);
800
+ toolParts.set(block.id, part);
801
+ }
802
+ }
803
+ } else if (rec.type === 'tool/result') {
804
+ const callID = rec.data?.toolCallId || rec.data?.message?.toolCallId;
805
+ attachToolResult(toolParts, callID, rec.data?.message?.content || rec.data?.content, rec.data?.message?.isError, time);
806
+ }
807
+ }
808
+ flush();
809
+ return {
810
+ sessionId: item.sessionId, title: title || oneLine(firstUser) || item.title, cwd: header.cwd || item.cwd,
811
+ createdAt: parseTime(header.createdAt) || item.createdAt, updatedAt: item.updatedAt,
812
+ model: model || item.model || '', messages: finishMessages(messages),
813
+ };
814
+ },
815
+ };
816
+
817
+ export const SOURCES = { codex: codexSource, claude: claudeSource, pi: piSource, dsh: dshSource };
818
+
819
+ export function sourceList() {
820
+ return Object.values(SOURCES).map((s) => ({ id: s.id, label: s.label, available: s.available() }));
821
+ }
822
+
823
+ export function sourceRoots(id) {
824
+ return normalizeRoots(SOURCES[id]?.roots() || []);
825
+ }
826
+
827
+ export function sourceAvailable(id) {
828
+ return !!SOURCES[id]?.available();
829
+ }
830
+
831
+ export async function listSourceSessions(id, opts) {
832
+ if (!SOURCES[id]) throw new Error('未知来源');
833
+ return SOURCES[id].list(opts);
834
+ }
835
+
836
+ export async function readSourceSession(id, item) {
837
+ if (!SOURCES[id]) throw new Error('未知来源');
838
+ return SOURCES[id].read(item);
839
+ }