@cold777/dsh-takeover 0.0.0-stage → 0.1.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.
@@ -0,0 +1,2090 @@
1
+ import { createRequire } from "node:module";
2
+ import { closeSync, existsSync, openSync, readFileSync, readSync, readdirSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { basename, dirname, join } from "node:path";
5
+ //#region node_modules/.pnpm/@agent-handoff+readers@file+vendor+@agent-handoff+readers/node_modules/@agent-handoff/readers/dist/index.mjs
6
+ /** 路径形态判断:含分隔符或盘符即按路径匹配(文件系适配器的 id 就是绝对路径)。 */
7
+ function looksLikePath(reference) {
8
+ return /[\\/]/.test(reference) || /^[A-Za-z]:/.test(reference);
9
+ }
10
+ const normPath = (p) => p.replace(/\//g, "\\").toLowerCase();
11
+ /**
12
+ * 在 refs 中解析 reference:
13
+ * - 'latest' / 空串 → 最新一条;
14
+ * - id 精确命中 → 直接返回;
15
+ * - 其余策略(id 前缀、路径、标题子串)合并候选,1 条解析、多条歧义、0 条 not-found。
16
+ */
17
+ function resolveReference(reference, refs) {
18
+ const sorted = [...refs].sort((a, b) => b.updatedAt - a.updatedAt);
19
+ const q = reference.trim();
20
+ if (q === "" || q.toLowerCase() === "latest") return sorted.length > 0 ? {
21
+ kind: "resolved",
22
+ ref: sorted[0]
23
+ } : {
24
+ kind: "not-found",
25
+ reference
26
+ };
27
+ const exact = sorted.find((r) => r.id === q);
28
+ if (exact !== void 0) return {
29
+ kind: "resolved",
30
+ ref: exact
31
+ };
32
+ const candidates = /* @__PURE__ */ new Map();
33
+ const push = (r) => {
34
+ candidates.set(r.id, r);
35
+ };
36
+ for (const r of sorted) if (r.id.startsWith(q) || r.kind === "file" && normPath(r.id).startsWith(normPath(q))) push(r);
37
+ if (looksLikePath(q)) {
38
+ const nq = normPath(q);
39
+ for (const r of sorted) {
40
+ if (r.kind !== "file") continue;
41
+ const nid = normPath(r.id);
42
+ if (nid === nq || nid.endsWith(nq)) push(r);
43
+ }
44
+ }
45
+ const lq = q.toLowerCase();
46
+ for (const r of sorted) if (r.title.toLowerCase().includes(lq)) push(r);
47
+ const list = [...candidates.values()].sort((a, b) => b.updatedAt - a.updatedAt);
48
+ if (list.length === 1) return {
49
+ kind: "resolved",
50
+ ref: list[0]
51
+ };
52
+ if (list.length > 1) return {
53
+ kind: "ambiguous",
54
+ candidates: list
55
+ };
56
+ return {
57
+ kind: "not-found",
58
+ reference
59
+ };
60
+ }
61
+ function makeTurn(partial) {
62
+ return {
63
+ cwd: "",
64
+ ts: "",
65
+ toolName: "",
66
+ toolFailed: false,
67
+ model: "",
68
+ ...partial
69
+ };
70
+ }
71
+ /** 逐行解析 transcript JSONL;非 JSON / 空行静默跳过(损坏记录不拖垮整会话) */
72
+ function* parseJsonl(text) {
73
+ for (const raw of text.split("\n")) {
74
+ const line = raw.trim();
75
+ if (!line) continue;
76
+ try {
77
+ yield JSON.parse(line);
78
+ } catch {
79
+ continue;
80
+ }
81
+ }
82
+ }
83
+ /** 把 Claude message.content(字符串或 block 数组)压平为纯文本 */
84
+ function extractTextContent(content) {
85
+ if (typeof content === "string") return content;
86
+ if (Array.isArray(content)) return content.filter((b) => b && typeof b === "object" && b.type === "text").map((b) => typeof b.text === "string" ? b.text : "").join("\n");
87
+ return "";
88
+ }
89
+ /** tool_use 的人类可读一行摘要 */
90
+ function summarizeToolCall(name, input) {
91
+ if (!input || typeof input !== "object" || Array.isArray(input)) return name;
92
+ const inp = input;
93
+ const cmd = inp.command;
94
+ if (typeof cmd === "string") {
95
+ const v = cmd.replace(/\s+/g, " ").trim();
96
+ return v.slice(0, 100) + (v.length > 100 ? "…" : "");
97
+ }
98
+ for (const key of [
99
+ "file_path",
100
+ "path",
101
+ "filePath"
102
+ ]) {
103
+ const v = inp[key];
104
+ if (typeof v === "string") return `${name}: ${v}`;
105
+ }
106
+ for (const v of Object.values(inp)) if (typeof v === "string") {
107
+ const s = v.replace(/\s+/g, " ").trim();
108
+ return `${name}: ${s.slice(0, 80)}` + (s.length > 80 ? "…" : "");
109
+ }
110
+ return name;
111
+ }
112
+ /** 把一行 Claude transcript JSON 拆成 Turn 列表 */
113
+ function entryToTurns(entry) {
114
+ const turns = [];
115
+ const etype = entry.type;
116
+ const msg = entry.message ?? {};
117
+ const cwd = typeof entry.cwd === "string" ? entry.cwd : "";
118
+ const ts = typeof entry.timestamp === "string" ? entry.timestamp : "";
119
+ const model = typeof msg.model === "string" ? msg.model : "";
120
+ const content = msg.content;
121
+ if (etype === "user" && msg.role === "user") {
122
+ if (Array.isArray(content)) {
123
+ const textParts = [];
124
+ for (const block of content) {
125
+ if (!block || typeof block !== "object") continue;
126
+ if (block.type === "tool_result") {
127
+ const rc = extractTextContent(block.content);
128
+ turns.push(makeTurn({
129
+ role: "tool",
130
+ text: rc,
131
+ cwd,
132
+ ts,
133
+ toolFailed: Boolean(block.is_error)
134
+ }));
135
+ } else if (block.type === "text") textParts.push(typeof block.text === "string" ? block.text : "");
136
+ }
137
+ const text = textParts.join("\n").trim();
138
+ if (text) turns.push(makeTurn({
139
+ role: "user",
140
+ text,
141
+ cwd,
142
+ ts
143
+ }));
144
+ } else if (typeof content === "string") {
145
+ const text = content.trim();
146
+ if (text) turns.push(makeTurn({
147
+ role: "user",
148
+ text,
149
+ cwd,
150
+ ts
151
+ }));
152
+ }
153
+ return turns;
154
+ }
155
+ if (etype === "assistant" && msg.role === "assistant") {
156
+ if (typeof content === "string") turns.push(makeTurn({
157
+ role: "assistant",
158
+ text: content,
159
+ cwd,
160
+ ts,
161
+ model
162
+ }));
163
+ else if (Array.isArray(content)) for (const block of content) {
164
+ if (!block || typeof block !== "object") continue;
165
+ const btype = block.type;
166
+ if (btype === "text" && typeof block.text === "string" && block.text.trim()) turns.push(makeTurn({
167
+ role: "assistant",
168
+ text: block.text,
169
+ cwd,
170
+ ts,
171
+ model
172
+ }));
173
+ else if (btype === "thinking" && typeof block.thinking === "string" && block.thinking.trim()) turns.push(makeTurn({
174
+ role: "assistant",
175
+ text: "[thinking] " + block.thinking,
176
+ cwd,
177
+ ts,
178
+ model
179
+ }));
180
+ else if (btype === "tool_use") {
181
+ const name = typeof block.name === "string" ? block.name : "";
182
+ turns.push(makeTurn({
183
+ role: "assistant",
184
+ cwd,
185
+ ts,
186
+ model,
187
+ text: summarizeToolCall(name, block.input),
188
+ toolName: name
189
+ }));
190
+ }
191
+ }
192
+ }
193
+ return turns;
194
+ }
195
+ /**
196
+ * Claude Code 适配器:~/.claude/projects 下递归的全部 .jsonl(引擎原生格式)。
197
+ * 移植自 dsh-hippo src/agents/claude.ts;root 可用 HANDOFF_ROOT_CLAUDE 覆盖(测试用)。
198
+ */
199
+ const ROOT$6 = process.env["HANDOFF_ROOT_CLAUDE"] ?? join(homedir(), ".claude", "projects");
200
+ function* walkJsonl$1(dir) {
201
+ let entries;
202
+ try {
203
+ entries = readdirSync(dir, { withFileTypes: true });
204
+ } catch {
205
+ return;
206
+ }
207
+ for (const e of entries) {
208
+ const p = join(dir, e.name);
209
+ if (e.isDirectory()) yield* walkJsonl$1(p);
210
+ else if (e.isFile() && e.name.endsWith(".jsonl")) yield p;
211
+ }
212
+ }
213
+ /** cwd 侦测窗口(首行一般 <8KB;超长首行的会话视为未记录而非伪造) */
214
+ const CWD_WINDOW = 8192;
215
+ /** 从转录头部窗口取真实 cwd(用户条目带 cwd 字段)。
216
+ * 目录名解码有歧义(连字符 vs 路径分隔符),拿目录名编一个「像路径的伪 cwd」比空更误导——
217
+ * 窗口内找不到(首行超长 / 字段缺失 / 读失败)一律回空串,让上层给「未记录工作区目录」警告。 */
218
+ function realCwd(file) {
219
+ try {
220
+ const fd = openSync(file, "r");
221
+ try {
222
+ const buf = Buffer.alloc(CWD_WINDOW);
223
+ const n = readSync(fd, buf, 0, CWD_WINDOW, 0);
224
+ const head = buf.toString("utf8", 0, n);
225
+ const m = /"cwd"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(head);
226
+ if (m) return JSON.parse(`"${m[1]}"`);
227
+ } finally {
228
+ closeSync(fd);
229
+ }
230
+ } catch {}
231
+ return "";
232
+ }
233
+ const claudeAdapter = {
234
+ name: "claude-code",
235
+ root: ROOT$6,
236
+ supported: true,
237
+ discover() {
238
+ const out = [];
239
+ for (const file of walkJsonl$1(ROOT$6)) {
240
+ let mtime = 0, size = 0;
241
+ try {
242
+ const st = statSync(file);
243
+ mtime = st.mtimeMs;
244
+ size = st.size;
245
+ } catch {
246
+ continue;
247
+ }
248
+ out.push({
249
+ agent: this.name,
250
+ id: file,
251
+ title: basename(file, ".jsonl"),
252
+ cwd: realCwd(file),
253
+ updatedAt: mtime,
254
+ fingerprint: `${Math.round(mtime)}:${size}`,
255
+ kind: "file"
256
+ });
257
+ }
258
+ return out.sort((a, b) => b.updatedAt - a.updatedAt);
259
+ },
260
+ parse(id) {
261
+ let text;
262
+ try {
263
+ text = readFileSync(id, "utf8");
264
+ } catch {
265
+ return [];
266
+ }
267
+ const turns = [];
268
+ for (const entry of parseJsonl(text)) turns.push(...entryToTurns(entry));
269
+ return turns;
270
+ }
271
+ };
272
+ /**
273
+ * 假 0 哨兵:存储根目录存在但 discover 为 0——上游可能已迁移存储布局。
274
+ * 出处:opencode 1.18 迁 SQLite 后旧读取器本机假报 0(casr #26 同日中招)。
275
+ * 适用于文件布局适配器(codex / cursor / grok)与 opencode 的 storage 回退路径;
276
+ * 根目录不存在(没装)不触发——那是正常静默。
277
+ */
278
+ const FAKE_ZERO_NOTE = "存储目录存在但未发现会话——上游可能已迁移存储布局(参考 opencode 1.18 迁 SQLite)";
279
+ /**
280
+ * Codex 适配器:~/.codex/sessions 下递归的 rollout-*.jsonl。
281
+ * session_meta 给 cwd;response_item 是权威消息流(event_msg 为 UI 事件,跳过避免重复)。
282
+ * 移植自 dsh-hippo src/agents/codex.ts;root 可用 HANDOFF_ROOT_CODEX 覆盖(测试用)。
283
+ */
284
+ const ROOT$5 = process.env["HANDOFF_ROOT_CODEX"] ?? join(homedir(), ".codex", "sessions");
285
+ function* walkJsonl(dir) {
286
+ let entries;
287
+ try {
288
+ entries = readdirSync(dir, { withFileTypes: true });
289
+ } catch {
290
+ return;
291
+ }
292
+ for (const e of entries) {
293
+ const p = join(dir, e.name);
294
+ if (e.isDirectory()) yield* walkJsonl(p);
295
+ else if (e.isFile() && e.name.endsWith(".jsonl")) yield p;
296
+ }
297
+ }
298
+ function parseCodexText(text) {
299
+ let cwd = "";
300
+ const turns = [];
301
+ for (const raw of text.split("\n")) {
302
+ const line = raw.trim();
303
+ if (line === "") continue;
304
+ let obj;
305
+ try {
306
+ obj = JSON.parse(line);
307
+ } catch {
308
+ continue;
309
+ }
310
+ const ts = obj.timestamp ?? "";
311
+ if (obj.type === "session_meta") {
312
+ cwd = typeof obj.payload?.cwd === "string" ? obj.payload.cwd : "";
313
+ continue;
314
+ }
315
+ if (obj.type !== "response_item" || obj.payload === void 0) continue;
316
+ const p = obj.payload;
317
+ if (p.type === "message") {
318
+ const role = p.role === "user" ? "user" : p.role === "assistant" ? "assistant" : "";
319
+ if (!role) continue;
320
+ const body = (Array.isArray(p.content) ? p.content : []).map((c) => c && typeof c === "object" && typeof c.text === "string" ? c.text : "").filter(Boolean).join("\n");
321
+ if (body) turns.push(makeTurn({
322
+ role,
323
+ text: body,
324
+ cwd,
325
+ ts,
326
+ model: typeof p.model === "string" ? p.model : ""
327
+ }));
328
+ } else if (p.type === "function_call" || p.type === "custom_tool_call" || p.type === "local_shell_call") {
329
+ const name = typeof p.name === "string" ? p.name : String(p.type);
330
+ turns.push(makeTurn({
331
+ role: "tool",
332
+ text: name,
333
+ cwd,
334
+ ts,
335
+ toolName: name
336
+ }));
337
+ } else if (p.type === "function_call_output" || p.type === "custom_tool_call_output") {
338
+ const out = typeof p.output === "string" ? p.output : JSON.stringify(p.output ?? "");
339
+ turns.push(makeTurn({
340
+ role: "tool",
341
+ text: out.slice(0, 2e3),
342
+ cwd,
343
+ ts,
344
+ toolFailed: /\berror\b/i.test(out.slice(0, 400))
345
+ }));
346
+ }
347
+ }
348
+ return turns;
349
+ }
350
+ const codexAdapter = {
351
+ name: "codex",
352
+ root: ROOT$5,
353
+ supported: true,
354
+ discover() {
355
+ const out = [];
356
+ for (const file of walkJsonl(ROOT$5)) {
357
+ let mtime = 0, size = 0;
358
+ try {
359
+ const st = statSync(file);
360
+ mtime = st.mtimeMs;
361
+ size = st.size;
362
+ } catch {
363
+ continue;
364
+ }
365
+ out.push({
366
+ agent: this.name,
367
+ id: file,
368
+ title: basename(file, ".jsonl"),
369
+ cwd: "",
370
+ updatedAt: mtime,
371
+ fingerprint: `${Math.round(mtime)}:${size}`,
372
+ kind: "file"
373
+ });
374
+ }
375
+ this.note = out.length === 0 && existsSync(ROOT$5) ? FAKE_ZERO_NOTE : void 0;
376
+ return out.sort((a, b) => b.updatedAt - a.updatedAt);
377
+ },
378
+ parse(id) {
379
+ try {
380
+ return parseCodexText(readFileSync(id, "utf8"));
381
+ } catch {
382
+ return [];
383
+ }
384
+ }
385
+ };
386
+ /**
387
+ * opencode 适配器:双布局自动探测。
388
+ * - 新版:~/.local/share/opencode/opencode.db(SQLite)——session / message / part 三表,
389
+ * message.data 与 part.data 均为 JSON 文本(role / type: text | tool)。
390
+ * - 旧版:storage/ 三层文件布局——session/<projectID>/ses_*.json → message/<ses>/msg_*.json
391
+ * → part/<msg>/prt_*.json。
392
+ * opencode.db 存在即优先走 DB(node:sqlite 只读打开,不拿写锁);node:sqlite 不可用或
393
+ * DB 不存在时回退旧版文件布局;两者皆缺返回空列表。
394
+ * 移植自 dsh-hippo src/agents/opencode.ts;root 可用 HANDOFF_ROOT_OPENCODE 覆盖
395
+ * (指向包含 opencode.db 或 storage/ 的目录,测试用)。
396
+ */
397
+ const BASE = process.env["HANDOFF_ROOT_OPENCODE"] ?? join(homedir(), ".local", "share", "opencode");
398
+ const DB_PATH$1 = join(BASE, "opencode.db");
399
+ const LEGACY_ROOT = join(BASE, "storage");
400
+ /** node:sqlite 可用性:createRequire 同步加载内建模块,失败即回退文件布局(不拖垮其他适配器)。 */
401
+ function loadSqlite$2() {
402
+ try {
403
+ return createRequire(import.meta.url)("node:sqlite").DatabaseSync;
404
+ } catch {
405
+ return null;
406
+ }
407
+ }
408
+ const DatabaseSync$2 = loadSqlite$2();
409
+ /** node:sqlite 缺席但新版 DB 在场的静态说明(走 DB 前先挂上);假 0 哨兵触发时被覆盖 */
410
+ const BASE_NOTE$1 = DatabaseSync$2 === null && existsSync(DB_PATH$1) ? "需要 Node ≥22(node:sqlite)读取新版 opencode.db" : void 0;
411
+ function openDb(dbPath = DB_PATH$1) {
412
+ if (DatabaseSync$2 === null || !existsSync(dbPath)) return null;
413
+ try {
414
+ return new DatabaseSync$2(dbPath, { readOnly: true });
415
+ } catch {
416
+ return null;
417
+ }
418
+ }
419
+ function parseJsonFile(path) {
420
+ try {
421
+ return JSON.parse(readFileSync(path, "utf8"));
422
+ } catch {
423
+ return null;
424
+ }
425
+ }
426
+ function safeJson(text) {
427
+ try {
428
+ return JSON.parse(String(text));
429
+ } catch {
430
+ return null;
431
+ }
432
+ }
433
+ /** 旧版文件布局:一个 ses_*.json 会话文件 → Turn 流 */
434
+ function parseOpenCodeSession(sessionFile, storageRoot) {
435
+ const session = parseJsonFile(sessionFile);
436
+ if (!session?.id) return [];
437
+ const cwd = session.directory ?? "";
438
+ const msgDir = join(storageRoot, "message", session.id);
439
+ let msgFiles;
440
+ try {
441
+ msgFiles = readdirSync(msgDir).filter((f) => f.endsWith(".json")).map((f) => join(msgDir, f));
442
+ } catch {
443
+ return [];
444
+ }
445
+ const msgs = msgFiles.map((f) => parseJsonFile(f)).filter((m) => m !== null && (m.role === "user" || m.role === "assistant") && typeof m.id === "string").sort((a, b) => (a.time?.created ?? 0) - (b.time?.created ?? 0));
446
+ const turns = [];
447
+ for (const m of msgs) {
448
+ const partDir = join(storageRoot, "part", m.id);
449
+ let partFiles;
450
+ try {
451
+ partFiles = readdirSync(partDir).filter((f) => f.endsWith(".json")).map((f) => join(partDir, f));
452
+ } catch {
453
+ partFiles = [];
454
+ }
455
+ const parts = partFiles.map((f) => parseJsonFile(f)).filter((p) => p !== null);
456
+ const body = parts.filter((p) => p.type === "text" && p.text).map((p) => p.text).join("\n");
457
+ const ts = m.time?.created ? new Date(m.time.created).toISOString() : "";
458
+ if (body) turns.push(makeTurn({
459
+ role: m.role === "user" ? "user" : "assistant",
460
+ text: body,
461
+ cwd,
462
+ ts
463
+ }));
464
+ for (const p of parts) {
465
+ if (p.type !== "tool") continue;
466
+ turns.push(makeTurn({
467
+ role: "tool",
468
+ text: (p.text ?? "").slice(0, 2e3),
469
+ cwd,
470
+ ts,
471
+ toolName: p.tool ?? "",
472
+ toolFailed: p.state?.status === "error"
473
+ }));
474
+ }
475
+ }
476
+ return turns;
477
+ }
478
+ /** DB 模式:按 session id 读 opencode.db。dbPath 可注入(单测用临时库)。 */
479
+ function parseOpenCodeDbSession(sessionId, dbPath = DB_PATH$1) {
480
+ const db = openDb(dbPath);
481
+ if (db === null) return [];
482
+ try {
483
+ const cwd = db.prepare("SELECT directory FROM session WHERE id = ?").all(sessionId)[0]?.directory ?? "";
484
+ const messages = db.prepare("SELECT id, data FROM message WHERE session_id = ? ORDER BY time_created, id").all(sessionId);
485
+ const turns = [];
486
+ for (const m of messages) {
487
+ const meta = safeJson(m.data);
488
+ if (!meta || meta.role !== "user" && meta.role !== "assistant") continue;
489
+ const ts = meta.time?.created ? new Date(meta.time.created).toISOString() : "";
490
+ const parts = db.prepare("SELECT data FROM part WHERE message_id = ? ORDER BY time_created, id").all(m.id);
491
+ const texts = [];
492
+ for (const row of parts) {
493
+ const part = safeJson(row.data);
494
+ if (!part) continue;
495
+ if (part.type === "text" && part.text) {
496
+ texts.push(part.text);
497
+ continue;
498
+ }
499
+ if (part.type === "tool") turns.push(makeTurn({
500
+ role: "tool",
501
+ text: (part.text ?? "").slice(0, 2e3),
502
+ cwd,
503
+ ts,
504
+ toolName: part.tool ?? "",
505
+ toolFailed: part.state?.status === "error"
506
+ }));
507
+ }
508
+ const body = texts.join("\n");
509
+ if (body) turns.push(makeTurn({
510
+ role: meta.role === "user" ? "user" : "assistant",
511
+ text: body,
512
+ cwd,
513
+ ts
514
+ }));
515
+ }
516
+ return turns;
517
+ } finally {
518
+ db.close();
519
+ }
520
+ }
521
+ const opencodeAdapter = {
522
+ name: "opencode",
523
+ root: BASE,
524
+ supported: true,
525
+ note: BASE_NOTE$1,
526
+ discover() {
527
+ const out = [];
528
+ const db = openDb();
529
+ if (db !== null) try {
530
+ const rows = db.prepare("SELECT id, title, directory, time_updated FROM session ORDER BY time_updated DESC").all();
531
+ for (const r of rows) out.push({
532
+ agent: this.name,
533
+ id: String(r.id),
534
+ title: r.title ?? "",
535
+ cwd: r.directory ?? "",
536
+ updatedAt: Number(r.time_updated ?? 0),
537
+ fingerprint: String(r.time_updated ?? 0),
538
+ kind: "sqlite"
539
+ });
540
+ return out;
541
+ } finally {
542
+ db.close();
543
+ }
544
+ const sessionRoot = join(LEGACY_ROOT, "session");
545
+ let projects = [];
546
+ try {
547
+ projects = readdirSync(sessionRoot, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => join(sessionRoot, d.name));
548
+ } catch {
549
+ if (existsSync(LEGACY_ROOT)) this.note = FAKE_ZERO_NOTE;
550
+ return out;
551
+ }
552
+ for (const projDir of projects) {
553
+ let names = [];
554
+ try {
555
+ names = readdirSync(projDir);
556
+ } catch {
557
+ continue;
558
+ }
559
+ for (const f of names) {
560
+ if (!f.endsWith(".json")) continue;
561
+ const file = join(projDir, f);
562
+ const meta = parseJsonFile(file);
563
+ let mtime = 0;
564
+ try {
565
+ mtime = statSync(file).mtimeMs;
566
+ } catch {
567
+ continue;
568
+ }
569
+ out.push({
570
+ agent: this.name,
571
+ id: file,
572
+ title: meta?.title ?? basename(f, ".json"),
573
+ cwd: meta?.directory ?? "",
574
+ updatedAt: meta?.time?.updated ?? mtime,
575
+ fingerprint: `${Math.round(mtime)}`,
576
+ kind: "file"
577
+ });
578
+ }
579
+ }
580
+ if (out.length === 0 && existsSync(LEGACY_ROOT)) this.note = FAKE_ZERO_NOTE;
581
+ else if (out.length > 0) this.note = BASE_NOTE$1;
582
+ return out.sort((a, b) => b.updatedAt - a.updatedAt);
583
+ },
584
+ parse(id) {
585
+ if (id.endsWith(".json")) return parseOpenCodeSession(id, LEGACY_ROOT);
586
+ return parseOpenCodeDbSession(id);
587
+ }
588
+ };
589
+ /**
590
+ * zcode 适配器:~/.zcode/cli/db/db.sqlite 的 session/message/part 三层表。
591
+ * 活库(当前会话在写)——一律 readonly 打开,随开随关。
592
+ * part 类型:text(正文)/ reasoning(思考,映射为 assistant 轮)/ tool(state.status=error
593
+ * 是失败信号)/ step-start(跳过)。
594
+ *
595
+ * 移植自 dsh-hippo src/agents/zcode.ts,依赖消除:better-sqlite3 → Node 内置
596
+ * node:sqlite(DatabaseSync,Node ≥22 自带;不支持则 supported=false 优雅降级,
597
+ * 不引入任何原生模块)。dbPath 可用 HANDOFF_ROOT_ZCODE 覆盖(测试用)。
598
+ */
599
+ const DB_PATH = process.env["HANDOFF_ROOT_ZCODE"] ?? join(homedir(), ".zcode", "cli", "db", "db.sqlite");
600
+ /** node:sqlite 可用性:createRequire 同步加载内建模块,失败即不支持(不拖垮其他适配器)。 */
601
+ function loadSqlite$1() {
602
+ try {
603
+ return createRequire(import.meta.url)("node:sqlite").DatabaseSync;
604
+ } catch {
605
+ return null;
606
+ }
607
+ }
608
+ const DatabaseSync$1 = loadSqlite$1();
609
+ function openReadonly(dbPath = DB_PATH) {
610
+ if (DatabaseSync$1 === null || !existsSync(dbPath)) return null;
611
+ try {
612
+ return new DatabaseSync$1(dbPath, { readOnly: true });
613
+ } catch {
614
+ return null;
615
+ }
616
+ }
617
+ /** dbPath 可注入(单测用临时库),缺省真实 ~/.zcode/cli/db/db.sqlite。 */
618
+ function parseZcodeSession(sessionId, dbPath = DB_PATH) {
619
+ const db = openReadonly(dbPath);
620
+ if (db === null) return [];
621
+ try {
622
+ const cwd = db.prepare("SELECT id, path FROM session WHERE id = ?").all(sessionId)[0]?.path ?? "";
623
+ const messages = db.prepare("SELECT id, data FROM message WHERE session_id = ? ORDER BY sequence").all(sessionId);
624
+ const turns = [];
625
+ for (const m of messages) {
626
+ let role = null;
627
+ let created = 0;
628
+ try {
629
+ const d = JSON.parse(m.data);
630
+ role = d.role === "user" ? "user" : d.role === "assistant" ? "assistant" : null;
631
+ created = d.time?.created ?? 0;
632
+ } catch {
633
+ continue;
634
+ }
635
+ if (role === null) continue;
636
+ const ts = created ? new Date(created).toISOString() : "";
637
+ const parts = db.prepare("SELECT data FROM part WHERE message_id = ? ORDER BY sequence").all(m.id);
638
+ for (const p of parts) {
639
+ let pd;
640
+ try {
641
+ pd = JSON.parse(p.data);
642
+ } catch {
643
+ continue;
644
+ }
645
+ if (pd.type === "text" && pd.text) turns.push(makeTurn({
646
+ role,
647
+ text: pd.text,
648
+ cwd,
649
+ ts
650
+ }));
651
+ else if (pd.type === "reasoning" && pd.text) turns.push(makeTurn({
652
+ role: "assistant",
653
+ text: "[thinking] " + pd.text.slice(0, 4e3),
654
+ cwd,
655
+ ts
656
+ }));
657
+ else if (pd.type === "tool") {
658
+ const failed = pd.state?.status === "error";
659
+ const input = typeof pd.state?.input === "object" && pd.state?.input !== null ? JSON.stringify(pd.state.input).slice(0, 300) : "";
660
+ const output = typeof pd.state?.output === "string" ? pd.state.output.slice(0, 2e3) : "";
661
+ turns.push(makeTurn({
662
+ role: "tool",
663
+ text: (input + "\n" + output).trim(),
664
+ cwd,
665
+ ts,
666
+ toolName: pd.tool ?? "",
667
+ toolFailed: failed
668
+ }));
669
+ }
670
+ }
671
+ }
672
+ return turns;
673
+ } finally {
674
+ db.close();
675
+ }
676
+ }
677
+ const zcodeAdapter = {
678
+ name: "zcode",
679
+ root: DB_PATH,
680
+ supported: DatabaseSync$1 !== null,
681
+ note: DatabaseSync$1 === null ? "需要 Node ≥22(node:sqlite 内建模块)" : void 0,
682
+ discover() {
683
+ const db = openReadonly();
684
+ if (db === null) return [];
685
+ try {
686
+ return db.prepare("SELECT id, path, title, time_created, time_updated FROM session").all().map((r) => ({
687
+ agent: this.name,
688
+ id: r.id,
689
+ title: r.title ?? r.id.slice(0, 18),
690
+ cwd: r.path ?? "",
691
+ updatedAt: r.time_updated ?? r.time_created ?? 0,
692
+ fingerprint: String(r.time_updated ?? r.time_created ?? 0),
693
+ kind: "sqlite"
694
+ })).sort((a, b) => b.updatedAt - a.updatedAt);
695
+ } catch {
696
+ return [];
697
+ } finally {
698
+ db.close();
699
+ }
700
+ },
701
+ parse(id) {
702
+ return parseZcodeSession(id);
703
+ }
704
+ };
705
+ /**
706
+ * pi 适配器(badlogic/pi-mono):~/.pi/agent/sessions/<路径转义>/时间戳_uuid.jsonl
707
+ * 事件流格式:type=session 给 cwd;type=message 的 message.content[] 是文本块。
708
+ * 标题取首条用户消息前 40 字(发现期限量读首 64KB,不整文件解析)。
709
+ * 移植自 dsh-hippo src/agents/pi.ts;root 可用 HANDOFF_ROOT_PI 覆盖(测试用)。
710
+ */
711
+ const ROOT$4 = process.env["HANDOFF_ROOT_PI"] ?? join(homedir(), ".pi", "agent", "sessions");
712
+ /** 限量读文件头(标题/cwd 用,避免发现期整读大会话)。 */
713
+ function readHead$1(path, bytes = 65536) {
714
+ try {
715
+ const fd = openSync(path, "r");
716
+ try {
717
+ const buf = Buffer.alloc(bytes);
718
+ const n = readSync(fd, buf, 0, bytes, 0);
719
+ return buf.toString("utf8", 0, n);
720
+ } finally {
721
+ closeSync(fd);
722
+ }
723
+ } catch {
724
+ return "";
725
+ }
726
+ }
727
+ function cwdOf(headText) {
728
+ for (const raw of headText.split("\n")) {
729
+ if (raw.trim() === "") continue;
730
+ try {
731
+ const ev = JSON.parse(raw);
732
+ if (ev.type === "session" && typeof ev.cwd === "string") return ev.cwd;
733
+ } catch {
734
+ continue;
735
+ }
736
+ }
737
+ return "";
738
+ }
739
+ function titleOf(headText) {
740
+ for (const raw of headText.split("\n")) {
741
+ if (raw.trim() === "") continue;
742
+ try {
743
+ const ev = JSON.parse(raw);
744
+ if (ev.type === "message" && ev.message?.role === "user") {
745
+ const text = (ev.message.content ?? []).map((c) => c.text ?? "").join(" ").trim();
746
+ if (text) return text.slice(0, 40);
747
+ }
748
+ } catch {
749
+ continue;
750
+ }
751
+ }
752
+ return "";
753
+ }
754
+ function parsePiText(text) {
755
+ let cwd = "";
756
+ const turns = [];
757
+ for (const raw of text.split("\n")) {
758
+ if (raw.trim() === "") continue;
759
+ let ev;
760
+ try {
761
+ ev = JSON.parse(raw);
762
+ } catch {
763
+ continue;
764
+ }
765
+ if (ev.type === "session" && typeof ev.cwd === "string") {
766
+ cwd = ev.cwd;
767
+ continue;
768
+ }
769
+ if (ev.type !== "message" || !ev.message) continue;
770
+ const role = ev.message.role === "user" ? "user" : ev.message.role === "assistant" ? "assistant" : "";
771
+ if (!role) continue;
772
+ const body = (ev.message.content ?? []).filter((c) => c.type === "text" && c.text).map((c) => c.text).join("\n");
773
+ if (body) turns.push(makeTurn({
774
+ role,
775
+ text: body,
776
+ cwd
777
+ }));
778
+ }
779
+ return turns;
780
+ }
781
+ const piAdapter = {
782
+ name: "pi",
783
+ root: ROOT$4,
784
+ supported: true,
785
+ discover() {
786
+ const out = [];
787
+ let dirs = [];
788
+ try {
789
+ dirs = readdirSync(ROOT$4, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => join(ROOT$4, d.name));
790
+ } catch {
791
+ return out;
792
+ }
793
+ for (const dir of dirs) {
794
+ let files = [];
795
+ try {
796
+ files = readdirSync(dir).filter((f) => f.endsWith(".jsonl"));
797
+ } catch {
798
+ continue;
799
+ }
800
+ for (const f of files) {
801
+ const file = join(dir, f);
802
+ let mtime = 0, size = 0;
803
+ try {
804
+ const st = statSync(file);
805
+ mtime = st.mtimeMs;
806
+ size = st.size;
807
+ } catch {
808
+ continue;
809
+ }
810
+ const head = readHead$1(file);
811
+ out.push({
812
+ agent: this.name,
813
+ id: file,
814
+ title: titleOf(head) || basename(f, ".jsonl"),
815
+ cwd: cwdOf(head),
816
+ updatedAt: mtime,
817
+ fingerprint: `${Math.round(mtime)}:${size}`,
818
+ kind: "file"
819
+ });
820
+ }
821
+ }
822
+ return out.sort((a, b) => b.updatedAt - a.updatedAt);
823
+ },
824
+ parse(id) {
825
+ try {
826
+ return parsePiText(readFileSync(id, "utf8"));
827
+ } catch {
828
+ return [];
829
+ }
830
+ }
831
+ };
832
+ /**
833
+ * WorkBuddy 适配器:~/.workbuddy/projects/<workspace-slug>/<uuid>.jsonl
834
+ * 一文件 = 一会话(单 sessionId)。记录类型(2026-09-01 实测真实会话):
835
+ *
836
+ * message(role=user|assistant) → 用户/助手轮。content 是块数组,取
837
+ * input_text/output_text 块的 text 拼接;image_blob_ref 等其他块跳过。
838
+ * reasoning → 思考行,跳过(与 function_call 交织密度高,并入会打乱轮次结构;
839
+ * 交接只要显式陈述,思考本就是过程自语)。
840
+ * function_call → 工具调用轮:toolName=name,text=name+arguments 摘要。
841
+ * function_call_result → 工具结果轮:text=output.text,status!=='completed' 即 toolFailed。
842
+ * file-history-snapshot / ai-title / resend-fork-notice → 跳过
843
+ * (ai-title 的标题在 discover 阶段取走作 SessionRef.title)。
844
+ *
845
+ * 移植自 dsh-hippo src/agents/workbuddy.ts;root 可用 HANDOFF_ROOT_WORKBUDDY 覆盖(测试用)。
846
+ */
847
+ const ROOT$3 = process.env["HANDOFF_ROOT_WORKBUDDY"] ?? join(homedir(), ".workbuddy", "projects");
848
+ /** 逐行读 JSONL(坏行跳过,与 claude 适配器同策略)。 */
849
+ function* readJsonl(file) {
850
+ for (const line of readFileSync(file, "utf8").split("\n")) {
851
+ const t = line.trim();
852
+ if (t === "") continue;
853
+ try {
854
+ yield JSON.parse(t);
855
+ } catch {}
856
+ }
857
+ }
858
+ /** content 块数组 → 纯文本(取 *_text 块,其余块跳过)。 */
859
+ function blocksToText(content) {
860
+ if (typeof content === "string") return content;
861
+ if (!Array.isArray(content)) return "";
862
+ const parts = [];
863
+ for (const b of content) if (b !== null && typeof b === "object" && typeof b.type === "string") {
864
+ const { type, text } = b;
865
+ if (type.endsWith("_text") && typeof text === "string" && text !== "") parts.push(text);
866
+ }
867
+ return parts.join("\n").trim();
868
+ }
869
+ /** function_call_result 的 output:{type:'text',text} 对象或纯字符串。 */
870
+ function resultToText(output) {
871
+ if (typeof output === "string") return output;
872
+ if (output !== null && typeof output === "object") {
873
+ const { text } = output;
874
+ if (typeof text === "string") return text;
875
+ }
876
+ return "";
877
+ }
878
+ const workbuddyAdapter = {
879
+ name: "workbuddy",
880
+ root: ROOT$3,
881
+ supported: true,
882
+ discover() {
883
+ const out = [];
884
+ let projectDirs;
885
+ try {
886
+ projectDirs = readdirSync(ROOT$3, { withFileTypes: true }).filter((e) => e.isDirectory() && !e.name.startsWith(".")).map((e) => e.name);
887
+ } catch {
888
+ return out;
889
+ }
890
+ for (const dir of projectDirs) {
891
+ let files;
892
+ try {
893
+ files = readdirSync(join(ROOT$3, dir)).filter((f) => f.endsWith(".jsonl"));
894
+ } catch {
895
+ continue;
896
+ }
897
+ for (const f of files) {
898
+ const full = join(ROOT$3, dir, f);
899
+ let mtime = 0;
900
+ let size = 0;
901
+ try {
902
+ const st = statSync(full);
903
+ mtime = st.mtimeMs;
904
+ size = st.size;
905
+ } catch {
906
+ continue;
907
+ }
908
+ let title = basename(f, ".jsonl");
909
+ let cwd = "";
910
+ try {
911
+ const fd = openSync(full, "r");
912
+ const buf = Buffer.alloc(65536);
913
+ const n = readSync(fd, buf, 0, buf.length, 0);
914
+ closeSync(fd);
915
+ const head = buf.slice(0, n).toString("utf8");
916
+ const m = head.match(/"type":\s*"ai-title",[^}]*?"aiTitle":\s*"((?:[^"\\]|\\.)*)"/);
917
+ if (m) try {
918
+ title = JSON.parse(`"${m[1]}"`);
919
+ } catch {
920
+ title = m[1];
921
+ }
922
+ const cm = head.match(/"cwd":\s*"((?:[^"\\]|\\.)*)"/);
923
+ if (cm) try {
924
+ cwd = JSON.parse(`"${cm[1]}"`);
925
+ } catch {
926
+ cwd = cm[1];
927
+ }
928
+ } catch {}
929
+ out.push({
930
+ agent: this.name,
931
+ id: full,
932
+ title,
933
+ cwd,
934
+ updatedAt: mtime,
935
+ fingerprint: `${Math.round(mtime)}:${size}`,
936
+ kind: "file"
937
+ });
938
+ }
939
+ }
940
+ return out.sort((a, b) => b.updatedAt - a.updatedAt);
941
+ },
942
+ parse(id) {
943
+ let entries;
944
+ try {
945
+ entries = [...readJsonl(id)];
946
+ } catch {
947
+ return [];
948
+ }
949
+ const turns = [];
950
+ for (const e of entries) {
951
+ const type = e.type;
952
+ const cwd = typeof e.cwd === "string" ? e.cwd : "";
953
+ const ts = typeof e.timestamp === "number" ? new Date(e.timestamp).toISOString() : "";
954
+ if (type === "message") {
955
+ const role = e.role === "user" ? "user" : e.role === "assistant" ? "assistant" : null;
956
+ if (role === null) continue;
957
+ const text = blocksToText(e.content);
958
+ if (text === "") continue;
959
+ turns.push(makeTurn({
960
+ role,
961
+ text,
962
+ cwd,
963
+ ts
964
+ }));
965
+ } else if (type === "function_call") {
966
+ const name = typeof e.name === "string" ? e.name : "";
967
+ if (name === "") continue;
968
+ const args = typeof e.arguments === "string" ? e.arguments.slice(0, 400) : "";
969
+ turns.push(makeTurn({
970
+ role: "tool",
971
+ text: args === "" ? name : `${name} ${args}`,
972
+ cwd,
973
+ ts,
974
+ toolName: name
975
+ }));
976
+ } else if (type === "function_call_result") {
977
+ const name = typeof e.name === "string" ? e.name : "";
978
+ const status = typeof e.status === "string" ? e.status : "";
979
+ const text = resultToText(e.output).slice(0, 2e3);
980
+ turns.push(makeTurn({
981
+ role: "tool",
982
+ text: text === "" ? `(${name} 无输出)` : text,
983
+ cwd,
984
+ ts,
985
+ toolName: name === "" ? "result" : name,
986
+ toolFailed: status !== "" && status !== "completed"
987
+ }));
988
+ }
989
+ }
990
+ return turns;
991
+ }
992
+ };
993
+ /**
994
+ * Cursor 适配器(自研 TS 实现;格式为公开逆向调研,
995
+ * Apache-2.0,其 NOTICE 声明该 reader 逐字节来自 xAI Grok 1.0.5 捆绑 skill——
996
+ * 此处只学存储格式,不复制其代码)。
997
+ *
998
+ * 两种本地存储形态(root 可用 HANDOFF_ROOT_CURSOR 覆盖,测试用):
999
+ *
1000
+ * 1) transcript 文件:<root>/projects/<工作区目录>/agent-transcripts/<会话id>/<会话id>.jsonl
1001
+ * 逐行 JSON,每行是一个带 role 的 value(与 store blob 同构)。
1002
+ * 2) CLI chats:<root>/chats/<md5(cwd)>/<uuid>/,内含 meta.json(标题/cwd/更新时间)
1003
+ * 与 store.db(SQLite:meta 表存元数据、blobs 表存 value,value 可能是
1004
+ * UTF-8 JSON 或十六进制编码的 JSON;二进制 / protobuf 块标不可用、不臆造)。
1005
+ *
1006
+ * value 渲染纪律:
1007
+ * - value.type 为 thinking / reasoning / redacted_thinking → 整条跳过(隐藏推理)。
1008
+ * - role 归一后不在 user / assistant / tool 内(system / developer / instruction /
1009
+ * preamble 等)→ 整条跳过(系统提示不进交接)。
1010
+ * - content 块:text / input_text / output_text 取正文;thinking / signature 跳过;
1011
+ * tool_use / tool_call 成 assistant 工具轮(只记 name+input 摘要,永不回放);
1012
+ * tool_result / tool_output 成 tool 轮(is_error → toolFailed)。
1013
+ * - 顶层 value.tool_calls(OpenAI 形态)同样只记摘要。
1014
+ * - user 正文:优先抽 <user_query>…</user_query>;以 <environment_context /
1015
+ * <user_instructions / <system_reminder / <manually_attached_skills / <timestamp
1016
+ * 等包装开头的一律丢弃;生成元文本(XML 标签开头 / [Request interrupted by user)丢弃。
1017
+ * - value 里的 messages / turns / conversation / bubbles 嵌套数组递归展开。
1018
+ *
1019
+ * 只读不写:store.db 一律 readonly 打开随开随关;不复活 Cursor、不回放存储的调用。
1020
+ */
1021
+ const ROOT$2 = process.env["HANDOFF_ROOT_CURSOR"] ?? join(homedir(), ".cursor");
1022
+ const UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
1023
+ /** 系统提示 / 前言 / 指令类 role:整条跳过 */
1024
+ const SKIPPED_ROLES = /* @__PURE__ */ new Set([
1025
+ "system",
1026
+ "developer",
1027
+ "instruction",
1028
+ "instructions",
1029
+ "preamble"
1030
+ ]);
1031
+ /** 隐藏推理块 / 签名块:跳过 */
1032
+ const SKIPPED_BLOCK_TYPES = /* @__PURE__ */ new Set([
1033
+ "thinking",
1034
+ "reasoning",
1035
+ "redacted_thinking",
1036
+ "signature"
1037
+ ]);
1038
+ /** user 正文里这些包装开头 = 环境/指令注入,不是用户原话 */
1039
+ const BLOCKED_USER_WRAPPERS = [
1040
+ "<environment_context",
1041
+ "<user_instructions",
1042
+ "<system_reminder",
1043
+ "<manually_attached_skills",
1044
+ "<timestamp"
1045
+ ];
1046
+ /** 生成元文本:XML 标签开头,或 "[Request interrupted by user" */
1047
+ const GENERATED_META_RE = /^\s*<[a-z][A-Za-z0-9_.:-]*(?:\s|\/?>)/;
1048
+ const INTERRUPTED_RE = /^\s*\[Request interrupted by user/i;
1049
+ /** node:sqlite 可用性(与 zcode 适配器同策略):缺失时 store.db 形态不可用,transcript 不受影响。 */
1050
+ function loadSqlite() {
1051
+ try {
1052
+ return createRequire(import.meta.url)("node:sqlite").DatabaseSync;
1053
+ } catch {
1054
+ return null;
1055
+ }
1056
+ }
1057
+ const DatabaseSync = loadSqlite();
1058
+ /** content 归一为块数组:字符串 → 单 text 块;对象 → 单块;数组过滤非对象。 */
1059
+ function blocksOf(content) {
1060
+ if (typeof content === "string") return [{
1061
+ type: "text",
1062
+ text: content
1063
+ }];
1064
+ if (Array.isArray(content)) return content.filter((b) => b !== null && typeof b === "object");
1065
+ if (content !== null && typeof content === "object") return [content];
1066
+ return [];
1067
+ }
1068
+ /** tool_result 块的 content → 纯文本(字符串 / 块数组 / {text} 对象)。 */
1069
+ function contentText(content) {
1070
+ if (typeof content === "string") return content;
1071
+ if (Array.isArray(content)) {
1072
+ const parts = [];
1073
+ for (const item of content) if (typeof item === "string") parts.push(item);
1074
+ else if (item !== null && typeof item === "object") {
1075
+ const t = item.text;
1076
+ if (typeof t === "string") parts.push(t);
1077
+ }
1078
+ return parts.join("\n");
1079
+ }
1080
+ if (content !== null && typeof content === "object") {
1081
+ const t = content.text;
1082
+ if (typeof t === "string") return t;
1083
+ }
1084
+ return "";
1085
+ }
1086
+ /** user 正文清洗:抽 <user_query>;包装注入丢弃;其余原样。 */
1087
+ function cursorUserText(text) {
1088
+ const matches = [...text.matchAll(/<user_query>\s*([\s\S]*?)\s*<\/user_query>/g)];
1089
+ if (matches.length > 0) {
1090
+ const joined = matches.map((m) => (m[1] ?? "").trim()).filter((s) => s !== "").join("\n");
1091
+ return joined === "" ? null : joined;
1092
+ }
1093
+ const stripped = text.trimStart();
1094
+ if (BLOCKED_USER_WRAPPERS.some((w) => stripped.startsWith(w))) return null;
1095
+ return text;
1096
+ }
1097
+ /**
1098
+ * 渲染一个 Cursor value 为 Turn 流(text 轮 + 工具调用轮 + 工具结果轮)。
1099
+ * 返回空数组 = 该 value 是系统提示 / 隐藏推理 / 空内容(调用方计数即可)。
1100
+ */
1101
+ function renderCursorValue(value) {
1102
+ if (value === null || typeof value !== "object") return [];
1103
+ const v = value;
1104
+ const vtype = typeof v.type === "string" ? v.type : "";
1105
+ if (SKIPPED_BLOCK_TYPES.has(vtype)) return [];
1106
+ const role = typeof v.role === "string" ? v.role.toLowerCase() : "";
1107
+ if (role === "" || SKIPPED_ROLES.has(role)) {
1108
+ for (const key of [
1109
+ "messages",
1110
+ "turns",
1111
+ "conversation",
1112
+ "bubbles"
1113
+ ]) {
1114
+ const nested = v[key];
1115
+ if (Array.isArray(nested)) return nested.flatMap((item) => renderCursorValue(item));
1116
+ }
1117
+ return [];
1118
+ }
1119
+ if (role !== "user" && role !== "assistant" && role !== "tool") return [];
1120
+ const ts = typeof v.timestamp === "string" ? v.timestamp : typeof v.timestamp === "number" ? new Date(v.timestamp).toISOString() : "";
1121
+ const message = v.message !== null && typeof v.message === "object" ? v.message : null;
1122
+ const content = message !== null && "content" in message ? message.content : v.content;
1123
+ const texts = [];
1124
+ const callTurns = [];
1125
+ const resultTurns = [];
1126
+ for (const block of blocksOf(content)) {
1127
+ const btype = typeof block.type === "string" ? block.type : "";
1128
+ if (SKIPPED_BLOCK_TYPES.has(btype)) continue;
1129
+ if (btype === "text" || btype === "input_text" || btype === "output_text") {
1130
+ const raw = typeof block.text === "string" ? block.text : "";
1131
+ if (raw === "") continue;
1132
+ const rendered = role === "user" ? cursorUserText(raw) : GENERATED_META_RE.test(raw) || INTERRUPTED_RE.test(raw) ? null : raw;
1133
+ if (rendered !== null && rendered.trim() !== "") texts.push(rendered);
1134
+ } else if (btype === "tool_use" || btype === "tool_call") {
1135
+ const name = typeof block.name === "string" ? block.name : "unknown";
1136
+ const input = "input" in block ? block.input : block.arguments;
1137
+ callTurns.push(makeTurn({
1138
+ role: "assistant",
1139
+ text: summarizeToolCall(name, input),
1140
+ ts,
1141
+ toolName: name
1142
+ }));
1143
+ } else if (btype === "tool_result" || btype === "tool_output") resultTurns.push(makeTurn({
1144
+ role: "tool",
1145
+ text: contentText(block.content).slice(0, 2e3),
1146
+ ts,
1147
+ toolFailed: Boolean(block.is_error)
1148
+ }));
1149
+ }
1150
+ if (Array.isArray(v.tool_calls)) for (const call of v.tool_calls) {
1151
+ if (call === null || typeof call !== "object") continue;
1152
+ const c = call;
1153
+ const fn = c.function !== null && typeof c.function === "object" ? c.function : c;
1154
+ const name = typeof fn.name === "string" ? fn.name : "unknown";
1155
+ let input = "arguments" in fn ? fn.arguments : fn.input;
1156
+ if (typeof input === "string") try {
1157
+ input = JSON.parse(input);
1158
+ } catch {}
1159
+ callTurns.push(makeTurn({
1160
+ role: "assistant",
1161
+ text: summarizeToolCall(name, input),
1162
+ ts,
1163
+ toolName: name
1164
+ }));
1165
+ }
1166
+ if (role === "tool" && resultTurns.length === 0) {
1167
+ resultTurns.push(makeTurn({
1168
+ role: "tool",
1169
+ text: contentText(content).slice(0, 2e3),
1170
+ ts,
1171
+ toolFailed: Boolean(v.is_error)
1172
+ }));
1173
+ texts.length = 0;
1174
+ }
1175
+ const turns = [];
1176
+ const text = texts.join("\n").trim();
1177
+ if (text !== "") turns.push(makeTurn({
1178
+ role: role === "tool" ? "tool" : role,
1179
+ text,
1180
+ ts
1181
+ }));
1182
+ turns.push(...callTurns, ...resultTurns);
1183
+ return turns;
1184
+ }
1185
+ /** transcript JSONL 文本 → Turn 流(坏行静默跳过)。 */
1186
+ function parseCursorTranscriptText(text) {
1187
+ const turns = [];
1188
+ for (const raw of text.split("\n")) {
1189
+ const line = raw.trim();
1190
+ if (line === "") continue;
1191
+ let value;
1192
+ try {
1193
+ value = JSON.parse(line);
1194
+ } catch {
1195
+ continue;
1196
+ }
1197
+ turns.push(...renderCursorValue(value));
1198
+ }
1199
+ return turns;
1200
+ }
1201
+ /** store blob 解码:Buffer/字符串 → JSON;偶数长度纯十六进制串先试 hex 解码;失败 = 二进制/protobuf,返回 null。 */
1202
+ function decodeCursorBlob(raw) {
1203
+ let text;
1204
+ if (raw instanceof Uint8Array) try {
1205
+ text = new TextDecoder("utf-8", { fatal: true }).decode(raw);
1206
+ } catch {
1207
+ return null;
1208
+ }
1209
+ else if (typeof raw === "string") text = raw;
1210
+ else if (raw !== null && typeof raw === "object") return raw;
1211
+ else return null;
1212
+ const stripped = text.trim();
1213
+ if (stripped === "") return null;
1214
+ if (stripped.length % 2 === 0 && /^[0-9a-fA-F]+$/.test(stripped)) try {
1215
+ return JSON.parse(Buffer.from(stripped, "hex").toString("utf-8"));
1216
+ } catch {}
1217
+ try {
1218
+ return JSON.parse(stripped);
1219
+ } catch {
1220
+ return null;
1221
+ }
1222
+ }
1223
+ /** store.db(blobs 表:id/data 或 key/value 等列名)→ Turn 流;缺库/缺 sqlite 返回 []。 */
1224
+ function parseCursorStore(dbPath) {
1225
+ if (DatabaseSync === null || !existsSync(dbPath)) return [];
1226
+ let db;
1227
+ try {
1228
+ db = new DatabaseSync(dbPath, { readOnly: true });
1229
+ } catch {
1230
+ return [];
1231
+ }
1232
+ try {
1233
+ const cols = new Set(db.prepare("PRAGMA table_info(\"blobs\")").all().map((c) => c.name));
1234
+ const keyCol = [
1235
+ "id",
1236
+ "key",
1237
+ "hash"
1238
+ ].find((c) => cols.has(c));
1239
+ const valCol = [
1240
+ "data",
1241
+ "value",
1242
+ "blob"
1243
+ ].find((c) => cols.has(c));
1244
+ if (keyCol === void 0 || valCol === void 0) return [];
1245
+ const rows = db.prepare(`SELECT "${valCol}" FROM blobs ORDER BY "${keyCol}"`).all();
1246
+ const turns = [];
1247
+ for (const row of rows) {
1248
+ const value = decodeCursorBlob(Array.isArray(row) ? row[0] : row[valCol]);
1249
+ if (value === null) continue;
1250
+ turns.push(...renderCursorValue(value));
1251
+ }
1252
+ return turns;
1253
+ } catch {
1254
+ return [];
1255
+ } finally {
1256
+ db.close();
1257
+ }
1258
+ }
1259
+ /** 限量读文件头(发现期取标题用)。 */
1260
+ function readHead(path, bytes = 65536) {
1261
+ try {
1262
+ const fd = openSync(path, "r");
1263
+ try {
1264
+ const buf = Buffer.alloc(bytes);
1265
+ const n = readSync(fd, buf, 0, bytes, 0);
1266
+ return buf.toString("utf8", 0, n);
1267
+ } finally {
1268
+ closeSync(fd);
1269
+ }
1270
+ } catch {
1271
+ return "";
1272
+ }
1273
+ }
1274
+ /** 头部文本里第一条 user 正文前 40 字作标题。 */
1275
+ function transcriptTitle(head) {
1276
+ for (const turn of parseCursorTranscriptText(head)) if (turn.role === "user" && turn.text.trim() !== "") return turn.text.trim().slice(0, 40);
1277
+ return "";
1278
+ }
1279
+ /** meta.json → 标题 / cwd / 更新时间(尽力而为,字段缺失留空)。 */
1280
+ function readMetaJson(path) {
1281
+ const meta = {
1282
+ title: "",
1283
+ cwd: "",
1284
+ updatedAt: 0
1285
+ };
1286
+ try {
1287
+ const value = JSON.parse(readFileSync(path, "utf8"));
1288
+ if (typeof value.title === "string") meta.title = value.title;
1289
+ else if (typeof value.name === "string") meta.title = value.name;
1290
+ if (typeof value.cwd === "string") meta.cwd = value.cwd;
1291
+ else if (typeof value.workspacePath === "string") meta.cwd = value.workspacePath;
1292
+ const ws = value.workspaceIdentifier;
1293
+ if (meta.cwd === "" && ws !== null && typeof ws === "object") {
1294
+ const w = ws;
1295
+ const uri = w.uri !== null && typeof w.uri === "object" ? w.uri : null;
1296
+ meta.cwd = typeof uri?.fsPath === "string" && uri.fsPath || typeof uri?.path === "string" && uri.path || typeof w.fsPath === "string" && w.fsPath || "";
1297
+ }
1298
+ for (const key of [
1299
+ "updatedAtMs",
1300
+ "lastUpdatedAt",
1301
+ "updated_at_ms"
1302
+ ]) {
1303
+ const t = value[key];
1304
+ if (typeof t === "number" && t > 0) {
1305
+ meta.updatedAt = t < 0xe8d4a51000 ? t * 1e3 : t;
1306
+ break;
1307
+ }
1308
+ }
1309
+ } catch {}
1310
+ return meta;
1311
+ }
1312
+ /** node:sqlite 缺席时的静态说明(有数据但仍缺 sqlite 时显示);假 0 哨兵触发时被覆盖,有数据后恢复 */
1313
+ const BASE_NOTE = DatabaseSync === null ? "CLI store.db 形态需要 Node ≥22(node:sqlite);transcript 形态不受影响" : void 0;
1314
+ const cursorAdapter = {
1315
+ name: "cursor",
1316
+ root: ROOT$2,
1317
+ supported: true,
1318
+ note: BASE_NOTE,
1319
+ discover() {
1320
+ const out = [];
1321
+ const seenSessions = /* @__PURE__ */ new Set();
1322
+ const projects = join(ROOT$2, "projects");
1323
+ let wsDirs = [];
1324
+ try {
1325
+ wsDirs = readdirSync(projects, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.isSymbolicLink()).map((d) => join(projects, d.name));
1326
+ } catch {
1327
+ wsDirs = [];
1328
+ }
1329
+ for (const ws of wsDirs) {
1330
+ const atDir = join(ws, "agent-transcripts");
1331
+ let sidDirs = [];
1332
+ try {
1333
+ sidDirs = readdirSync(atDir, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.isSymbolicLink()).map((d) => d.name);
1334
+ } catch {
1335
+ continue;
1336
+ }
1337
+ for (const sid of sidDirs) {
1338
+ const file = join(atDir, sid, `${sid}.jsonl`);
1339
+ let mtime = 0, size = 0;
1340
+ try {
1341
+ const st = statSync(file);
1342
+ mtime = st.mtimeMs;
1343
+ size = st.size;
1344
+ } catch {
1345
+ continue;
1346
+ }
1347
+ seenSessions.add(sid.toLowerCase());
1348
+ out.push({
1349
+ agent: this.name,
1350
+ id: file,
1351
+ title: transcriptTitle(readHead(file)) || sid,
1352
+ cwd: "",
1353
+ updatedAt: mtime,
1354
+ fingerprint: `${Math.round(mtime)}:${size}`,
1355
+ kind: "file"
1356
+ });
1357
+ }
1358
+ }
1359
+ const chats = join(ROOT$2, "chats");
1360
+ let hashDirs = [];
1361
+ try {
1362
+ hashDirs = readdirSync(chats, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.isSymbolicLink()).map((d) => join(chats, d.name));
1363
+ } catch {
1364
+ hashDirs = [];
1365
+ }
1366
+ for (const hashDir of hashDirs) {
1367
+ let sessionDirs = [];
1368
+ try {
1369
+ sessionDirs = readdirSync(hashDir, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.isSymbolicLink() && UUID_RE.test(d.name)).map((d) => d.name);
1370
+ } catch {
1371
+ continue;
1372
+ }
1373
+ for (const sid of sessionDirs) {
1374
+ if (seenSessions.has(sid.toLowerCase())) continue;
1375
+ const dir = join(hashDir, sid);
1376
+ const storePath = join(dir, "store.db");
1377
+ const metaPath = join(dir, "meta.json");
1378
+ const hasStore = existsSync(storePath);
1379
+ if (!hasStore && !existsSync(metaPath)) continue;
1380
+ const meta = readMetaJson(metaPath);
1381
+ let mtime = meta.updatedAt, size = 0;
1382
+ try {
1383
+ const st = statSync(hasStore ? storePath : metaPath);
1384
+ if (mtime === 0) mtime = st.mtimeMs;
1385
+ size = st.size;
1386
+ } catch {
1387
+ continue;
1388
+ }
1389
+ out.push({
1390
+ agent: this.name,
1391
+ id: hasStore ? storePath : metaPath,
1392
+ title: meta.title || sid,
1393
+ cwd: meta.cwd,
1394
+ updatedAt: mtime,
1395
+ fingerprint: `${Math.round(mtime)}:${size}`,
1396
+ kind: hasStore ? "sqlite" : "file"
1397
+ });
1398
+ }
1399
+ }
1400
+ this.note = out.length === 0 && existsSync(ROOT$2) ? FAKE_ZERO_NOTE : BASE_NOTE;
1401
+ return out.sort((a, b) => b.updatedAt - a.updatedAt);
1402
+ },
1403
+ parse(id) {
1404
+ try {
1405
+ if (id.endsWith(".jsonl")) return parseCursorTranscriptText(readFileSync(id, "utf8"));
1406
+ if (basename(id) === "store.db") return parseCursorStore(id);
1407
+ if (basename(id) === "meta.json") return [];
1408
+ return [];
1409
+ } catch {
1410
+ return [];
1411
+ }
1412
+ }
1413
+ };
1414
+ /**
1415
+ * Grok 适配器(自研 TS 实现;格式为公开逆向调研,
1416
+ * Apache-2.0,其 NOTICE 声明该 reader 逐字节来自 xAI Grok 1.0.5 捆绑 skill——
1417
+ * 此处只学存储格式,不复制其代码)。
1418
+ *
1419
+ * 存储形态(root 可用 HANDOFF_ROOT_GROK 覆盖,测试用;缺省 $GROK_HOME/sessions
1420
+ * 或 ~/.grok/sessions):
1421
+ *
1422
+ * <root>/<urlencode(工作区路径)>/<会话id>/
1423
+ * summary.json 会话元数据:info.id / info.cwd / generated_title /
1424
+ * session_summary / created_at / last_active_at / updated_at /
1425
+ * current_model_id / head_branch / git_root_dir
1426
+ * updates.jsonl 可见更新流(ACP 形态):每行 {params:{update:{...}}},
1427
+ * 导出流也可能直接是内层 update 对象
1428
+ * chat_history.jsonl 原始模型上下文 —— 永不读取(恢复边界)
1429
+ *
1430
+ * updates.jsonl 的 update.sessionUpdate(或 update.type)分派:
1431
+ * - user_message_chunk / agent_message_chunk → 用户/助手文本轮;
1432
+ * content 只取 type=text 块,非文本块标「内容不可用」;连续的同角色 chunk
1433
+ * 是流式分片,合并成一轮。
1434
+ * - agent_thought_chunk → 隐藏推理,丢弃。
1435
+ * - hook_execution → hook 执行记录,丢弃。
1436
+ * - tool_call / tool_call_update → status 缺省/pending 成 assistant 工具轮
1437
+ * (name 取 _meta["x.ai/tool"].name/label 或 title/kind;只记摘要,永不回放);
1438
+ * completed/failed 成 tool 结果轮(failed → toolFailed;按 toolCallId 去重)。
1439
+ * 结果正文:content 块(字符串 / {type:content,content:{type:text}} /
1440
+ * {type:text});{type:diff} 只留路径标不可用;兜底 rawOutput。
1441
+ * - plan / turn_completed / 未知类型 → 跳过。
1442
+ *
1443
+ * 只读不写、不复活 Grok 进程;损坏行静默跳过;summary.json 损坏的会话不发现。
1444
+ */
1445
+ const GROK_HOME = process.env["GROK_HOME"] ?? join(homedir(), ".grok");
1446
+ const ROOT$1 = process.env["HANDOFF_ROOT_GROK"] ?? join(GROK_HOME, "sessions");
1447
+ /** 时间戳 → ms epoch:数字(秒/毫秒自适应)或 ISO 字符串;不可解析返回 0。 */
1448
+ function toMillis$1(value) {
1449
+ if (typeof value === "number" && Number.isFinite(value)) {
1450
+ const n = Math.trunc(value);
1451
+ return Math.abs(n) < 0xe8d4a51000 ? n * 1e3 : n;
1452
+ }
1453
+ if (typeof value === "string" && value !== "") {
1454
+ const parsed = Date.parse(value);
1455
+ if (Number.isFinite(parsed)) return parsed;
1456
+ }
1457
+ return 0;
1458
+ }
1459
+ /** summary.json → 元数据;文件缺失/损坏返回 null(该会话不发现)。 */
1460
+ function readSummary(sessionDir) {
1461
+ let value;
1462
+ try {
1463
+ value = JSON.parse(readFileSync(join(sessionDir, "summary.json"), "utf8"));
1464
+ } catch {
1465
+ return null;
1466
+ }
1467
+ if (value === null || typeof value !== "object") return null;
1468
+ const info = value.info !== null && typeof value.info === "object" ? value.info : {};
1469
+ const title = typeof value.generated_title === "string" && value.generated_title !== "" ? value.generated_title : typeof value.session_summary === "string" ? value.session_summary : "";
1470
+ return {
1471
+ cwd: typeof info.cwd === "string" ? info.cwd : "",
1472
+ sessionId: typeof info.id === "string" && info.id !== "" ? info.id : basename(sessionDir),
1473
+ title,
1474
+ updatedAt: toMillis$1(value.last_active_at) || toMillis$1(value.updated_at) || toMillis$1(value.created_at),
1475
+ model: typeof value.current_model_id === "string" ? value.current_model_id : ""
1476
+ };
1477
+ }
1478
+ /** message chunk 的 content → 纯文本:只取 type=text 块,非文本块标不可用。 */
1479
+ function grokMessageText(content) {
1480
+ const blocks = typeof content === "string" ? [{
1481
+ type: "text",
1482
+ text: content
1483
+ }] : Array.isArray(content) ? content.filter((b) => b !== null && typeof b === "object") : content !== null && typeof content === "object" ? [content] : [];
1484
+ const parts = [];
1485
+ for (const block of blocks) if (block.type === "text" && typeof block.text === "string") parts.push(block.text);
1486
+ else {
1487
+ const label = typeof block.type === "string" ? block.type.replace(/_/g, " ") : "unknown";
1488
+ parts.push(`[${label} 内容不可用]`);
1489
+ }
1490
+ return parts.join("\n");
1491
+ }
1492
+ /** 连续同角色文本 chunk 是流式分片:并入上一轮;否则新开一轮。 */
1493
+ function appendTextTurn(turns, role, content, cwd, model) {
1494
+ const text = grokMessageText(content).trim();
1495
+ if (text === "") return;
1496
+ const last = turns.at(-1);
1497
+ if (last !== void 0 && last.role === role && last.toolName === "") {
1498
+ last.text = `${last.text}\n${text}`;
1499
+ return;
1500
+ }
1501
+ turns.push(makeTurn({
1502
+ role,
1503
+ text,
1504
+ cwd,
1505
+ model
1506
+ }));
1507
+ }
1508
+ /** 工具名:_meta["x.ai/tool"].name/label → title → kind → 兜底 grok_tool。 */
1509
+ function grokToolName(update) {
1510
+ const meta = update._meta !== null && typeof update._meta === "object" ? update._meta : {};
1511
+ const toolMeta = meta["x.ai/tool"] !== null && typeof meta["x.ai/tool"] === "object" ? meta["x.ai/tool"] : {};
1512
+ for (const candidate of [
1513
+ toolMeta.name,
1514
+ toolMeta.label,
1515
+ update.title,
1516
+ update.kind
1517
+ ]) if (typeof candidate === "string" && candidate !== "") return candidate;
1518
+ return "grok_tool";
1519
+ }
1520
+ /** 工具结果正文:content 块拼接;diff 只留路径;兜底 rawOutput。 */
1521
+ function grokToolOutput(update) {
1522
+ const content = update.content;
1523
+ const blocks = Array.isArray(content) ? content : content === void 0 ? [] : [content];
1524
+ const parts = [];
1525
+ for (const block of blocks) {
1526
+ if (typeof block === "string") {
1527
+ parts.push(block);
1528
+ continue;
1529
+ }
1530
+ if (block === null || typeof block !== "object") continue;
1531
+ const b = block;
1532
+ if (b.type === "content") {
1533
+ const nested = b.content;
1534
+ if (typeof nested === "string") parts.push(nested);
1535
+ else if (nested !== null && typeof nested === "object") {
1536
+ const n = nested;
1537
+ if (n.type === "text" && typeof n.text === "string") parts.push(n.text);
1538
+ }
1539
+ } else if (b.type === "text" && typeof b.text === "string") parts.push(b.text);
1540
+ else if (b.type === "diff") {
1541
+ const path = typeof b.path === "string" && b.path !== "" ? b.path : "unknown path";
1542
+ parts.push(`[diff 内容不可用:${path}]`);
1543
+ }
1544
+ }
1545
+ let output = parts.join("\n");
1546
+ if (output === "" && typeof update.rawOutput === "string") output = update.rawOutput;
1547
+ return output.slice(0, 2e3);
1548
+ }
1549
+ /**
1550
+ * updates.jsonl 文本 → Turn 流。只读可见更新流;
1551
+ * chat_history.jsonl(原始模型上下文)不在此处也永不在此处被读取。
1552
+ */
1553
+ function parseGrokUpdatesText(text, cwd = "", model = "") {
1554
+ const turns = [];
1555
+ const emittedCalls = /* @__PURE__ */ new Set();
1556
+ const emittedResults = /* @__PURE__ */ new Set();
1557
+ const callNames = /* @__PURE__ */ new Map();
1558
+ let index = 0;
1559
+ for (const raw of text.split("\n")) {
1560
+ const line = raw.trim();
1561
+ if (line === "") continue;
1562
+ let record;
1563
+ try {
1564
+ record = JSON.parse(line);
1565
+ } catch {
1566
+ continue;
1567
+ }
1568
+ index += 1;
1569
+ if (record === null || typeof record !== "object") continue;
1570
+ const params = record.params !== null && typeof record.params === "object" ? record.params : {};
1571
+ let update = params.update !== null && typeof params.update === "object" ? params.update : null;
1572
+ if (update === null && typeof record.sessionUpdate === "string") update = record;
1573
+ if (update === null) continue;
1574
+ const updateType = typeof update.sessionUpdate === "string" ? update.sessionUpdate : typeof update.type === "string" ? update.type : "";
1575
+ if (updateType === "user_message_chunk") appendTextTurn(turns, "user", update.content, cwd, model);
1576
+ else if (updateType === "agent_message_chunk") appendTextTurn(turns, "assistant", update.content, cwd, model);
1577
+ else if (updateType === "agent_thought_chunk" || updateType === "hook_execution") continue;
1578
+ else if (updateType === "tool_call" || updateType === "tool_call_update") {
1579
+ const callId = update.toolCallId !== void 0 && update.toolCallId !== null ? String(update.toolCallId) : `grok-call-${index}`;
1580
+ const status = typeof update.status === "string" ? update.status : "";
1581
+ const name = callNames.get(callId) ?? grokToolName(update);
1582
+ if (status === "completed" || status === "failed") {
1583
+ if (emittedResults.has(callId)) continue;
1584
+ emittedResults.add(callId);
1585
+ turns.push(makeTurn({
1586
+ role: "tool",
1587
+ text: grokToolOutput(update),
1588
+ cwd,
1589
+ toolName: name,
1590
+ toolFailed: status === "failed"
1591
+ }));
1592
+ } else if (!emittedCalls.has(callId)) {
1593
+ emittedCalls.add(callId);
1594
+ callNames.set(callId, name);
1595
+ const meta = update._meta !== null && typeof update._meta === "object" ? update._meta : {};
1596
+ const toolMeta = meta["x.ai/tool"] !== null && typeof meta["x.ai/tool"] === "object" ? meta["x.ai/tool"] : {};
1597
+ const rawInput = update.rawInput !== void 0 ? update.rawInput : toolMeta.input;
1598
+ turns.push(makeTurn({
1599
+ role: "assistant",
1600
+ text: summarizeToolCall(name, rawInput),
1601
+ cwd,
1602
+ toolName: name
1603
+ }));
1604
+ }
1605
+ }
1606
+ }
1607
+ return turns;
1608
+ }
1609
+ /** 解析一个会话目录(或 summary.json / updates.jsonl 路径)。 */
1610
+ function parseGrokSession(id) {
1611
+ const base = basename(id);
1612
+ const dir = base === "summary.json" || base === "updates.jsonl" ? dirname(id) : id;
1613
+ const summary = readSummary(dir);
1614
+ const cwd = summary?.cwd ?? "";
1615
+ const model = summary?.model ?? "";
1616
+ let text;
1617
+ try {
1618
+ text = readFileSync(join(dir, "updates.jsonl"), "utf8");
1619
+ } catch {
1620
+ return [];
1621
+ }
1622
+ return parseGrokUpdatesText(text, cwd, model);
1623
+ }
1624
+ const grokAdapter = {
1625
+ name: "grok",
1626
+ root: ROOT$1,
1627
+ supported: true,
1628
+ discover() {
1629
+ const out = [];
1630
+ let wsDirs = [];
1631
+ try {
1632
+ wsDirs = readdirSync(ROOT$1, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.isSymbolicLink()).map((d) => join(ROOT$1, d.name));
1633
+ } catch {
1634
+ return out;
1635
+ }
1636
+ for (const ws of wsDirs) {
1637
+ let sessionDirs = [];
1638
+ try {
1639
+ sessionDirs = readdirSync(ws, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.isSymbolicLink()).map((d) => join(ws, d.name));
1640
+ } catch {
1641
+ continue;
1642
+ }
1643
+ for (const dir of sessionDirs) {
1644
+ let updatesStat;
1645
+ try {
1646
+ updatesStat = statSync(join(dir, "updates.jsonl"));
1647
+ if (!updatesStat.isFile()) continue;
1648
+ } catch {
1649
+ continue;
1650
+ }
1651
+ const summary = readSummary(dir);
1652
+ if (summary === null) continue;
1653
+ const updatedAt = summary.updatedAt || updatesStat.mtimeMs;
1654
+ out.push({
1655
+ agent: this.name,
1656
+ id: dir,
1657
+ title: summary.title || summary.sessionId,
1658
+ cwd: summary.cwd,
1659
+ updatedAt,
1660
+ fingerprint: `${Math.round(updatedAt)}:${updatesStat.size}`,
1661
+ kind: "file"
1662
+ });
1663
+ }
1664
+ }
1665
+ this.note = out.length === 0 ? FAKE_ZERO_NOTE : void 0;
1666
+ return out.sort((a, b) => b.updatedAt - a.updatedAt);
1667
+ },
1668
+ parse(id) {
1669
+ try {
1670
+ return parseGrokSession(id);
1671
+ } catch {
1672
+ return [];
1673
+ }
1674
+ }
1675
+ };
1676
+ /**
1677
+ * Gemini CLI 适配器(自研 TS 实现;格式为公开逆向调研,2026-10 核实)。
1678
+ *
1679
+ * 存储形态(root 可用 HANDOFF_ROOT_GEMINI 覆盖,测试用;缺省 ~/.gemini/tmp):
1680
+ *
1681
+ * <root>/<项目标识>/ 项目标识 = slug 或旧版 sha256 哈希(不做格式判断,直接枚举)
1682
+ * .project_root 明文 cwd(读不到留空,调用方有空 cwd 警告兜底)
1683
+ * chats/
1684
+ * session-<timestamp>-<8位id>.jsonl 新格式(2026-10-01 起)
1685
+ * session-<timestamp>-<8位id>.json 旧格式(整块 JSON:metadata+messages 单对象)
1686
+ * <parentShortId>/session-*.jsonl 子代理会话再嵌一层(metadata.kind='subagent')
1687
+ *
1688
+ * JSONL 行法:首行 metadata(sessionId/startTime/lastUpdated/summary/directories/kind)
1689
+ * → 每行一条 MessageRecord → 穿插控制行——已知类型分派、未知行静默跳过:
1690
+ * - MessageRecord.type: user | gemini | info | error | warning;
1691
+ * - content 是字符串或 Part 数组(取 text 部分);info / error / warning 是 CLI UI
1692
+ * 消息,不计用户轮也不进 Turn;
1693
+ * - user 文本以 '/' 或 '?' 开头是斜杠命令/快捷键,跳过(首条用户消息口径对齐全包);
1694
+ * - gemini 轮带 toolCalls[{name,args,result,status,timestamp}]:每个调用出一个
1695
+ * assistant 工具轮(toolName=原生名,text=summarizeToolCall 摘要;write_file /
1696
+ * replace / read_file 是文件类、run_shell_command args.command 是命令类——与 grok
1697
+ * 适配器同口径:原生名直透 toolName,不做改名);result/status 再出一个 tool 结果
1698
+ * 轮,status==='error' 记 toolFailed。
1699
+ * - $patch / $set / $rewindTo 控制行跳过。
1700
+ *
1701
+ * 只读不写、不复活 Gemini CLI 进程;坏行/损坏文件静默跳过或返回空流。
1702
+ */
1703
+ const ROOT = process.env["HANDOFF_ROOT_GEMINI"] ?? join(homedir(), ".gemini", "tmp");
1704
+ /** ISO 时间戳 → ms epoch;不可解析返回 0。 */
1705
+ function toMillis(value) {
1706
+ if (typeof value === "number" && Number.isFinite(value)) return value;
1707
+ if (typeof value === "string" && value !== "") {
1708
+ const parsed = Date.parse(value);
1709
+ if (Number.isFinite(parsed)) return parsed;
1710
+ }
1711
+ return 0;
1712
+ }
1713
+ /** 控制行($patch / $set / $rewindTo):顶层带 $ 键,或 type 以 $ 开头。 */
1714
+ function isControlLine(record) {
1715
+ if ("$patch" in record || "$set" in record || "$rewindTo" in record) return true;
1716
+ const type = record.type;
1717
+ return typeof type === "string" && type.startsWith("$");
1718
+ }
1719
+ /** content(字符串或 Part 数组)→ 纯文本:取 text 部分,其余块跳过。 */
1720
+ function geminiContentText(content) {
1721
+ if (typeof content === "string") return content;
1722
+ if (!Array.isArray(content)) return "";
1723
+ const parts = [];
1724
+ for (const block of content) if (block !== null && typeof block === "object" && typeof block.text === "string") parts.push(block.text);
1725
+ return parts.join("\n");
1726
+ }
1727
+ /** user 文本以 '/' 或 '?' 开头 = 斜杠命令/快捷输入,不是对话内容。 */
1728
+ function isSlashCommand(text) {
1729
+ const t = text.trimStart();
1730
+ return t.startsWith("/") || t.startsWith("?");
1731
+ }
1732
+ /** toolCall 的 result:字符串直用;对象取 output/text 字符串字段;其余空。 */
1733
+ function toolResultText(result) {
1734
+ if (typeof result === "string") return result;
1735
+ if (result !== null && typeof result === "object") {
1736
+ const r = result;
1737
+ for (const key of ["output", "text"]) if (typeof r[key] === "string") return r[key];
1738
+ }
1739
+ return "";
1740
+ }
1741
+ /** 单条 MessageRecord → Turn 列表。info/error/warning 与斜杠命令不产生 Turn。 */
1742
+ function recordToTurns(record, cwd) {
1743
+ const type = typeof record.type === "string" ? record.type : "";
1744
+ const ts = typeof record.timestamp === "string" ? record.timestamp : "";
1745
+ const model = typeof record.model === "string" ? record.model : "";
1746
+ const turns = [];
1747
+ if (type === "user") {
1748
+ const text = geminiContentText(record.content).trim();
1749
+ if (text !== "" && !isSlashCommand(text)) turns.push(makeTurn({
1750
+ role: "user",
1751
+ text,
1752
+ cwd,
1753
+ ts
1754
+ }));
1755
+ return turns;
1756
+ }
1757
+ if (type === "gemini") {
1758
+ const text = geminiContentText(record.content).trim();
1759
+ if (text !== "") turns.push(makeTurn({
1760
+ role: "assistant",
1761
+ text,
1762
+ cwd,
1763
+ ts,
1764
+ model
1765
+ }));
1766
+ const toolCalls = Array.isArray(record.toolCalls) ? record.toolCalls : [];
1767
+ for (const call of toolCalls) {
1768
+ if (call === null || typeof call !== "object") continue;
1769
+ const c = call;
1770
+ const name = typeof c.name === "string" && c.name !== "" ? c.name : "gemini_tool";
1771
+ const args = c.args;
1772
+ const status = typeof c.status === "string" ? c.status : "";
1773
+ turns.push(makeTurn({
1774
+ role: "assistant",
1775
+ text: summarizeToolCall(name, args),
1776
+ cwd,
1777
+ ts,
1778
+ model,
1779
+ toolName: name
1780
+ }));
1781
+ const result = toolResultText(c.result);
1782
+ if (result !== "" || status === "error") turns.push(makeTurn({
1783
+ role: "tool",
1784
+ text: result.slice(0, 2e3),
1785
+ cwd,
1786
+ ts: typeof c.timestamp === "string" ? c.timestamp : ts,
1787
+ toolName: name,
1788
+ toolFailed: status === "error"
1789
+ }));
1790
+ }
1791
+ }
1792
+ return turns;
1793
+ }
1794
+ /** JSONL 文本 → Turn 流:已知类型分派,控制行与未知行静默跳过。 */
1795
+ function parseGeminiText(text, cwd = "") {
1796
+ const turns = [];
1797
+ for (const raw of text.split("\n")) {
1798
+ const line = raw.trim();
1799
+ if (line === "") continue;
1800
+ let record;
1801
+ try {
1802
+ record = JSON.parse(line);
1803
+ } catch {
1804
+ continue;
1805
+ }
1806
+ if (record === null || typeof record !== "object" || Array.isArray(record)) continue;
1807
+ if (isControlLine(record)) continue;
1808
+ if (typeof record.type !== "string") continue;
1809
+ turns.push(...recordToTurns(record, cwd));
1810
+ }
1811
+ return turns;
1812
+ }
1813
+ /** 旧 .json(metadata+messages 单对象)→ Turn 流。 */
1814
+ function parseGeminiJson(text, cwd = "") {
1815
+ let value;
1816
+ try {
1817
+ value = JSON.parse(text);
1818
+ } catch {
1819
+ return [];
1820
+ }
1821
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return [];
1822
+ const messages = value.messages;
1823
+ if (!Array.isArray(messages)) return [];
1824
+ const turns = [];
1825
+ for (const message of messages) {
1826
+ if (message === null || typeof message !== "object" || Array.isArray(message)) continue;
1827
+ if (isControlLine(message)) continue;
1828
+ turns.push(...recordToTurns(message, cwd));
1829
+ }
1830
+ return turns;
1831
+ }
1832
+ /**
1833
+ * cwd 反查:会话文件所在目录到 <root>/<项目标识> 沿途找 .project_root 明文文件
1834
+ * (主会话在项目目录、子代理在 chats/<parent>/ 下——子到父逐层找,都不越过项目目录)。
1835
+ * 读不到留空(调用方有空 cwd 警告兜底)。
1836
+ */
1837
+ function projectCwd(file) {
1838
+ let dir = dirname(file);
1839
+ for (let depth = 0; depth < 6; depth += 1) {
1840
+ let raw = "";
1841
+ try {
1842
+ raw = readFileSync(join(dir, ".project_root"), "utf8");
1843
+ } catch {
1844
+ raw = "";
1845
+ }
1846
+ const cwd = raw.trim();
1847
+ if (cwd !== "") return cwd;
1848
+ const parent = dirname(dir);
1849
+ if (parent === dir || basename(parent) === "tmp" || depth + 1 >= 6) return "";
1850
+ dir = parent;
1851
+ }
1852
+ return "";
1853
+ }
1854
+ /** 会话文件路径(.jsonl 新格式 / .json 旧格式)→ Turn 流。文件缺失/损坏返回 []。 */
1855
+ function parseGeminiSession(id) {
1856
+ let text;
1857
+ try {
1858
+ text = readFileSync(id, "utf8");
1859
+ } catch {
1860
+ return [];
1861
+ }
1862
+ const cwd = projectCwd(id);
1863
+ return id.toLowerCase().endsWith(".json") ? parseGeminiJson(text, cwd) : parseGeminiText(text, cwd);
1864
+ }
1865
+ /** 会话文件是否为 gemini 会话命名:session-*.jsonl / session-*.json。 */
1866
+ function isSessionFile(name) {
1867
+ return name.startsWith("session-") && (name.endsWith(".jsonl") || name.endsWith(".json"));
1868
+ }
1869
+ /** 头部 64KB 抠 metadata:summary(标题)/ lastUpdated(更新时间)——别全读大文件。 */
1870
+ function readHeadMeta(file, isJson) {
1871
+ let head = "";
1872
+ try {
1873
+ const buf = readFileSync(file);
1874
+ head = buf.subarray(0, Math.min(buf.length, 65536)).toString("utf8");
1875
+ } catch {
1876
+ return {
1877
+ summary: "",
1878
+ lastUpdated: 0
1879
+ };
1880
+ }
1881
+ let summary = "";
1882
+ let lastUpdated = 0;
1883
+ if (isJson) try {
1884
+ const meta = JSON.parse(head);
1885
+ if (typeof meta.summary === "string") summary = meta.summary;
1886
+ lastUpdated = toMillis(meta.lastUpdated);
1887
+ } catch {}
1888
+ if (summary === "") {
1889
+ const m = head.match(/"summary"\s*:\s*"((?:[^"\\]|\\.)*)"/);
1890
+ if (m) try {
1891
+ summary = JSON.parse(`"${m[1]}"`);
1892
+ } catch {
1893
+ summary = m[1];
1894
+ }
1895
+ }
1896
+ if (lastUpdated === 0) {
1897
+ const m = head.match(/"lastUpdated"\s*:\s*"([^"]*)"/);
1898
+ if (m) lastUpdated = toMillis(m[1]);
1899
+ }
1900
+ return {
1901
+ summary,
1902
+ lastUpdated
1903
+ };
1904
+ }
1905
+ function refFromFile(file) {
1906
+ let mtime = 0;
1907
+ let size = 0;
1908
+ try {
1909
+ const st = statSync(file);
1910
+ if (!st.isFile()) return null;
1911
+ mtime = st.mtimeMs;
1912
+ size = st.size;
1913
+ } catch {
1914
+ return null;
1915
+ }
1916
+ const meta = readHeadMeta(file, file.toLowerCase().endsWith(".json"));
1917
+ return {
1918
+ agent: "gemini",
1919
+ id: file,
1920
+ title: meta.summary !== "" ? meta.summary : basename(file),
1921
+ cwd: projectCwd(file),
1922
+ updatedAt: meta.lastUpdated || mtime,
1923
+ fingerprint: `${Math.round(mtime)}:${size}`,
1924
+ kind: "file"
1925
+ };
1926
+ }
1927
+ /**
1928
+ * @agent-handoff/readers:九家 agent 会话的只读读取层。
1929
+ * 移植自 dsh-hippo src/agents/,零三方运行时依赖(zcode / cursor store 用 Node 内建 node:sqlite)。
1930
+ * cursor / grok / gemini 三家为自研实现(格式为公开逆向调研)。
1931
+ *
1932
+ * 公共 API:
1933
+ * listSessions(agent?) → SessionRef[] 发现 + 按更新时间倒序
1934
+ * readSession(agent, ref) → Turn[] 解析一个会话为 Turn 流
1935
+ * resolveReference(agent, reference) 引用解析(歧义返回候选列表,不猜)
1936
+ */
1937
+ const AGENTS = [
1938
+ claudeAdapter,
1939
+ codexAdapter,
1940
+ opencodeAdapter,
1941
+ zcodeAdapter,
1942
+ piAdapter,
1943
+ workbuddyAdapter,
1944
+ cursorAdapter,
1945
+ grokAdapter,
1946
+ {
1947
+ name: "gemini",
1948
+ root: ROOT,
1949
+ supported: true,
1950
+ discover() {
1951
+ const out = [];
1952
+ let projectDirs = [];
1953
+ try {
1954
+ projectDirs = readdirSync(ROOT, { withFileTypes: true }).filter((d) => d.isDirectory() && !d.isSymbolicLink()).map((d) => join(ROOT, d.name));
1955
+ } catch {
1956
+ return out;
1957
+ }
1958
+ for (const projectDir of projectDirs) {
1959
+ let chatEntries = [];
1960
+ const chatsDir = join(projectDir, "chats");
1961
+ try {
1962
+ chatEntries = readdirSync(chatsDir, { withFileTypes: true });
1963
+ } catch {
1964
+ continue;
1965
+ }
1966
+ const files = [];
1967
+ for (const entry of chatEntries) {
1968
+ const full = join(chatsDir, entry.name);
1969
+ if (entry.isFile() && isSessionFile(entry.name)) files.push(full);
1970
+ else if (entry.isDirectory() && !entry.isSymbolicLink()) try {
1971
+ for (const name of readdirSync(full)) if (isSessionFile(name)) files.push(join(full, name));
1972
+ } catch {
1973
+ continue;
1974
+ }
1975
+ }
1976
+ for (const file of files) {
1977
+ const ref = refFromFile(file);
1978
+ if (ref !== null) out.push(ref);
1979
+ }
1980
+ }
1981
+ this.note = out.length === 0 ? FAKE_ZERO_NOTE : void 0;
1982
+ return out.sort((a, b) => b.updatedAt - a.updatedAt);
1983
+ },
1984
+ parse(id) {
1985
+ try {
1986
+ return parseGeminiSession(id);
1987
+ } catch {
1988
+ return [];
1989
+ }
1990
+ }
1991
+ }
1992
+ ];
1993
+ const byName = new Map(AGENTS.map((a) => [a.name, a]));
1994
+ /** 取适配器;未知名抛中文错(CLI 层转成用户可读信息)。 */
1995
+ function adapterFor(agent) {
1996
+ const a = byName.get(agent);
1997
+ if (a === void 0) throw new Error(`未知 agent:${agent}(支持:${AGENTS.map((x) => x.name).join(" / ")})`);
1998
+ return a;
1999
+ }
2000
+ /** 发现会话:给 agent 名只查该家;不给则查全部支持的家,单家失败不拖垮整体。 */
2001
+ function listSessions(agent) {
2002
+ if (agent !== void 0) {
2003
+ const a = adapterFor(agent);
2004
+ if (!a.supported) return [];
2005
+ return a.discover().sort((x, y) => y.updatedAt - x.updatedAt);
2006
+ }
2007
+ const out = [];
2008
+ for (const a of AGENTS) {
2009
+ if (!a.supported) continue;
2010
+ try {
2011
+ out.push(...a.discover());
2012
+ } catch {}
2013
+ }
2014
+ return out.sort((x, y) => y.updatedAt - x.updatedAt);
2015
+ }
2016
+ /** 解析一个会话为 Turn 流;ref 可以是 SessionRef 或适配器 id 字符串。
2017
+ * 同一文件(mtime+size 指纹不变)重复读取命中缓存——list 对 20 个候选逐个
2018
+ * readSession 数用户轮、show 全量解析后才分页,无缓存时每次调用都重付
2019
+ * O(总字节) 的同步 readFileSync+JSON.parse(30s 轮询场景成倍放大)。
2020
+ * 缓存有界:条目上限与累计正文上限双闸,超出按 LRU 淘汰。 */
2021
+ function readSession(agent, ref) {
2022
+ const a = adapterFor(agent);
2023
+ if (!a.supported) return [];
2024
+ const id = typeof ref === "string" ? ref : ref.id;
2025
+ const fingerprint = fileFingerprint(id);
2026
+ const cacheKey = `${a.name}\u0000${id}`;
2027
+ const hit = fingerprint === "" ? void 0 : sessionCache.get(cacheKey);
2028
+ if (hit !== void 0 && hit.fingerprint === fingerprint) {
2029
+ hit.used = ++cacheTick;
2030
+ return hit.turns;
2031
+ }
2032
+ let turns;
2033
+ try {
2034
+ turns = a.parse(id);
2035
+ } catch {
2036
+ return [];
2037
+ }
2038
+ if (fingerprint !== "" && turns.length > 0) {
2039
+ const chars = turns.reduce((n, t) => n + t.text.length, 0);
2040
+ if (chars <= CACHE_MAX_CHARS) {
2041
+ sessionCache.set(cacheKey, {
2042
+ fingerprint,
2043
+ turns,
2044
+ chars,
2045
+ used: ++cacheTick
2046
+ });
2047
+ while (sessionCache.size > CACHE_MAX_ENTRIES) evictOldest();
2048
+ trimByChars();
2049
+ }
2050
+ }
2051
+ return turns;
2052
+ }
2053
+ const sessionCache = /* @__PURE__ */ new Map();
2054
+ const CACHE_MAX_ENTRIES = 6;
2055
+ const CACHE_MAX_CHARS = 24e6;
2056
+ let cacheTick = 0;
2057
+ function evictOldest() {
2058
+ let oldestKey;
2059
+ let oldest = Number.POSITIVE_INFINITY;
2060
+ for (const [key, entry] of sessionCache) if (entry.used < oldest) {
2061
+ oldest = entry.used;
2062
+ oldestKey = key;
2063
+ }
2064
+ if (oldestKey !== void 0) sessionCache.delete(oldestKey);
2065
+ }
2066
+ function trimByChars() {
2067
+ while (cacheTotalChars() > CACHE_MAX_CHARS && sessionCache.size > 1) evictOldest();
2068
+ }
2069
+ function cacheTotalChars() {
2070
+ let n = 0;
2071
+ for (const entry of sessionCache.values()) n += entry.chars;
2072
+ return n;
2073
+ }
2074
+ /** 文件指纹(mtime:size);stat 失败回空串(不可缓存,直接现读) */
2075
+ function fileFingerprint(id) {
2076
+ try {
2077
+ const st = statSync(id);
2078
+ return st.isFile() ? `${Math.round(st.mtimeMs)}:${st.size}` : "";
2079
+ } catch {
2080
+ return "";
2081
+ }
2082
+ }
2083
+ /** 引用解析:先发现该 agent 的会话,再按 id/路径/标题规则匹配。 */
2084
+ function resolveAgentReference(agent, reference) {
2085
+ return resolveReference(reference, listSessions(agent));
2086
+ }
2087
+ //#endregion
2088
+ export { AGENTS, listSessions, readSession, resolveAgentReference };
2089
+
2090
+ //# sourceMappingURL=dist-Dk2MQOZJ.js.map