@aiti-ai/ext-shared 0.0.0-stage → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +36 -2
  3. package/agent-accounts.test.mjs +227 -0
  4. package/agent-accounts.ts +324 -0
  5. package/agent-capability-contract.test.mjs +129 -0
  6. package/agent-interaction.test.mjs +194 -0
  7. package/agent-interaction.ts +340 -0
  8. package/agent-launch.test.mjs +262 -0
  9. package/agent-spawn-env.test.mjs +169 -0
  10. package/agent-spawn-env.ts +548 -0
  11. package/aiti-editor-inject.mjs +49 -0
  12. package/backend-queue.test.mjs +336 -0
  13. package/backend-queue.ts +469 -0
  14. package/blob-save-route.ts +128 -0
  15. package/cbc-model-catalog.ts +86 -0
  16. package/check-client.mjs +273 -0
  17. package/check-ext-globals.mjs +144 -0
  18. package/controlled-login-dialog.mjs +270 -0
  19. package/controlled-login.mjs +398 -0
  20. package/controlled-login.test.mjs +466 -0
  21. package/convert-saveas.test.mjs +39 -0
  22. package/convert-saveas.ts +170 -0
  23. package/copy-client-bundle.mjs +39 -0
  24. package/cursor-cli-store.ts +377 -0
  25. package/dedupe-fetch.test.mjs +71 -0
  26. package/dedupe-fetch.ts +58 -0
  27. package/deploy-commit.mjs +52 -0
  28. package/dev-pack.mjs +246 -0
  29. package/dock-icons.ts +127 -0
  30. package/esbuild-bin.test.mjs +53 -0
  31. package/esbuild-bin.ts +66 -0
  32. package/exec-async.test.mjs +86 -0
  33. package/exec-async.ts +179 -0
  34. package/ext-display-names.ts +91 -0
  35. package/ext-entry-contracts.test.mjs +131 -0
  36. package/ext-float-dock-core.test.mjs +348 -0
  37. package/ext-float-dock-core.ts +783 -0
  38. package/ext-float-dock-lite.ts +52 -0
  39. package/ext-float-dock.test.mjs +286 -0
  40. package/ext-float-dock.ts +740 -0
  41. package/ext-icons-deploy.mjs +24 -0
  42. package/ext-lazy.test.mjs +186 -0
  43. package/ext-lazy.tsx +183 -0
  44. package/ext-model-state.test.mjs +272 -0
  45. package/ext-model-state.ts +324 -0
  46. package/ext-protocol.mjs +113 -0
  47. package/ext-protocol.test.mjs +88 -0
  48. package/ext-session-usage.test.mjs +219 -0
  49. package/ext-session-usage.ts +507 -0
  50. package/external-cli-governance.ts +153 -0
  51. package/git-ops-client/api.mjs +56 -0
  52. package/git-ops-client/branch-panel.tsx +987 -0
  53. package/git-ops-client/i18n.mjs +328 -0
  54. package/host-tools-allow.test.mjs +46 -0
  55. package/host-tools-allow.ts +84 -0
  56. package/icons/alert.svg +1 -0
  57. package/icons/bookmark.svg +1 -0
  58. package/icons/bot.svg +1 -0
  59. package/icons/chart-column.svg +1 -0
  60. package/icons/check-circle.svg +1 -0
  61. package/icons/clipboard-list.svg +1 -0
  62. package/icons/clock.svg +1 -0
  63. package/icons/coffee.svg +1 -0
  64. package/icons/edit.svg +1 -0
  65. package/icons/eye.svg +1 -0
  66. package/icons/git-branch.svg +1 -0
  67. package/icons/git-commit-horizontal.svg +1 -0
  68. package/icons/globe.svg +1 -0
  69. package/icons/history.svg +1 -0
  70. package/icons/import.svg +1 -0
  71. package/icons/inbox.svg +1 -0
  72. package/icons/key-round.svg +1 -0
  73. package/icons/layout-grid.svg +1 -0
  74. package/icons/mail.svg +1 -0
  75. package/icons/message-circle.svg +1 -0
  76. package/icons/message-square.svg +1 -0
  77. package/icons/meter-vertical.svg +1 -0
  78. package/icons/mic.svg +1 -0
  79. package/icons/monitor.svg +1 -0
  80. package/icons/pen-line.svg +1 -0
  81. package/icons/plug.svg +1 -0
  82. package/icons/radio-dot.svg +1 -0
  83. package/icons/radio.svg +1 -0
  84. package/icons/refresh.svg +1 -0
  85. package/icons/rocket.svg +1 -0
  86. package/icons/search.svg +1 -0
  87. package/icons/shield.svg +1 -0
  88. package/icons/sparkles.svg +1 -0
  89. package/icons/square-kanban.svg +1 -0
  90. package/icons/terminal.svg +1 -0
  91. package/icons/users.svg +1 -0
  92. package/icons/volume-2.svg +1 -0
  93. package/icons/wand.svg +1 -0
  94. package/icons/wrench.svg +1 -0
  95. package/icons/x-circle.svg +1 -0
  96. package/icons/x.svg +1 -0
  97. package/ignore-semantics.ts +76 -0
  98. package/lazy-loading-metrics.mjs +61 -0
  99. package/new-session-cwd.test.mjs +389 -0
  100. package/new-session-cwd.ts +253 -0
  101. package/open-viewer-window.ts +65 -0
  102. package/overlay-back-client.test.mjs +123 -0
  103. package/overlay-back-client.ts +87 -0
  104. package/package.json +65 -4
  105. package/pi-fork-rpc/README.md +12 -0
  106. package/pi-fork-rpc/cli-resolve.test.mjs +42 -0
  107. package/pi-fork-rpc/cli-resolve.ts +79 -0
  108. package/pi-fork-rpc/remote-queue.test.mjs +100 -0
  109. package/pi-fork-rpc/remote-queue.ts +140 -0
  110. package/pi-fork-rpc/spec.ts +106 -0
  111. package/pi-fork-rpc/wire.test.mjs +260 -0
  112. package/pi-fork-rpc/wire.ts +367 -0
  113. package/popup-anchor.ts +45 -0
  114. package/provider-priority-contract.test.mjs +55 -0
  115. package/reconcile-deps.mjs +41 -0
  116. package/reload-instances.mjs +60 -0
  117. package/seed-tool.test.mjs +95 -0
  118. package/seed-tool.ts +88 -0
  119. package/session-recycle.ts +109 -0
  120. package/shared-copy-sync.test.mjs +115 -0
  121. package/soffice-locate.ts +171 -0
  122. package/soffice-panel.ts +239 -0
  123. package/sync-dir.mjs +91 -0
  124. package/sync-dir.test.mjs +101 -0
  125. package/sync-gate.test.mjs +93 -0
  126. package/sync-mirror.test.mjs +85 -0
  127. package/task-list.test.mjs +91 -0
  128. package/task-list.ts +118 -0
  129. package/test-rm-rf.mjs +33 -0
  130. package/ui-dialogs.test.mjs +198 -0
  131. package/ui-dialogs.ts +310 -0
@@ -0,0 +1,170 @@
1
+ /**
2
+ * convert-saveas —— 老格式「转可编辑格式另存并打开」route 工厂(共享权威源,部署拷进扩展目录)。
3
+ *
4
+ * 场景(方案 §八 追加):.xls/.ods → .xlsx(Excel 编辑)、.doc → .docx(Word 编辑)。
5
+ * 规则:
6
+ * - soffice 无头转换;tmp 目录放在目标同目录(同文件系统,rename 不跨设备)
7
+ * - 新文件与源同目录,命名 `<stem>-from<ext>.<toExt>`(如 报告-fromxls.xlsx);
8
+ * 已存在则 `<stem>-from<ext>(1).<toExt>` 递增——绝不覆盖任何既有文件
9
+ * - 源文件不动;单 soffice 实例互斥(globalThis 级,跨扩展模块共享进程内互斥)
10
+ *
11
+ * 端点语义(POST,body JSON):{ filePath: string, cwd?: string }
12
+ * → 200 { ok: true, newPath, size }
13
+ * → 400 路径不在白名单 / 源扩展不支持
14
+ * → 409 目标并发竞争(罕见,客户端重试即可)
15
+ * → 500 soffice 转换失败
16
+ */
17
+ import { mkdirSync, renameSync, statSync } from "node:fs";
18
+ import { execFile } from "node:child_process";
19
+ import { homedir } from "node:os";
20
+ import { basename, dirname, isAbsolute, join, normalize, sep } from "node:path";
21
+
22
+ /** 异步 execFile(Promise 化)。性能红线(2026-09-13):原 execFileSync 同步跑 soffice
23
+ * 转换(timeout 90s)会把 pi-web 主线程冻结至秒/分钟级;改异步后语义不变、主线程不占用。 */
24
+ function execFileP(bin: string, args: string[], timeoutMs: number): Promise<void> {
25
+ return new Promise((resolve, reject) => {
26
+ execFile(bin, args, { timeout: timeoutMs, maxBuffer: 16 * 1024 * 1024, stdio: ["ignore", "ignore", "pipe"] }, (err) => (err ? reject(err) : resolve()));
27
+ });
28
+ }
29
+
30
+ function expandTildePath(p: string): string {
31
+ const home = homedir();
32
+ if (p === "~") return home;
33
+ if (p.startsWith("~/") || p.startsWith("~\\")) return join(home, p.slice(2));
34
+ return p;
35
+ }
36
+
37
+ /** 写白名单(对标 aiti-editor/blob-save-route M1 宽松版:workspace + 用户根) */
38
+ export function resolveAllowedWriteRoot(filePath: string, cwd?: string): string | null {
39
+ if (!filePath) return null;
40
+ const expanded = expandTildePath(filePath);
41
+ if (!isAbsolute(expanded)) return null;
42
+ const home = homedir();
43
+ const roots: string[] = [];
44
+ if (cwd && isAbsolute(cwd)) roots.push(normalize(cwd));
45
+ roots.push(join(home, "workspace"));
46
+ roots.push(home);
47
+ const fp = normalize(expanded);
48
+ return roots.some((r) => fp === r || fp.startsWith(r + sep)) ? fp : null;
49
+ }
50
+
51
+ export interface ConvertTarget {
52
+ /** 目标扩展名(不含点,如 "xlsx") */
53
+ toExt: string;
54
+ /** soffice --convert-to 过滤器(如 `xlsx:Calc MS Excel 2007 XML`;缺省用 toExt) */
55
+ filter?: string;
56
+ }
57
+
58
+ export interface ConvertSaveAsOptions {
59
+ extId: string;
60
+ /** fromExt(不含点)→ 转换目标 */
61
+ conversions: Record<string, ConvertTarget>;
62
+ /** 源文件大小上限(默认 50MB) */
63
+ maxBytes?: number;
64
+ /** soffice 定位器(_shared/soffice-locate 的 makeSofficeLocator);缺失 → 503 soffice-missing */
65
+ sofficePath: () => string | null;
66
+ }
67
+
68
+ /**
69
+ * 候选路径生成(纯函数,可测):<stem>-from<ext>.<toExt>,冲突递增 (n)。
70
+ * @param exists 路径存在性探测(注入以便测试)
71
+ */
72
+ export function nextSaveAsPath(dir: string, sourceName: string, fromExt: string, toExt: string, exists: (p: string) => boolean): string {
73
+ const stem = sourceName.replace(/\.[^.]+$/, "");
74
+ const tag = "-from" + fromExt.replace(/^\./, "");
75
+ let n = 0;
76
+ for (;;) {
77
+ const suffix = n === 0 ? "" : "(" + n + ")";
78
+ const candidate = join(dir, stem + tag + suffix + "." + toExt);
79
+ if (!exists(candidate)) return candidate;
80
+ n++;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * 生成 route handler:`if (p[p.length-1] === "convert-saveas") return await handle(req);`
86
+ */
87
+ export function createConvertSaveAsRoute(opts: ConvertSaveAsOptions) {
88
+ const maxBytes = opts.maxBytes ?? 50 * 1024 * 1024;
89
+ const log = (m: string) => console.log("[" + opts.extId + "][convert-saveas] " + m);
90
+ const mutex = (): number => ((globalThis as any).__aitiConvertBusy = (globalThis as any).__aitiConvertBusy || 0);
91
+ const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), {
92
+ status,
93
+ headers: { "content-type": "application/json", "cache-control": "no-store" },
94
+ });
95
+
96
+ return async function handle(req: Request): Promise<Response> {
97
+ let body: { filePath?: unknown; cwd?: unknown };
98
+ try {
99
+ body = await req.json();
100
+ } catch {
101
+ return json({ ok: false, error: "body 需为 JSON" }, 400);
102
+ }
103
+ const filePath = typeof body.filePath === "string" ? body.filePath : "";
104
+ const cwd = typeof body.cwd === "string" ? body.cwd : undefined;
105
+ if (!filePath) return json({ ok: false, error: "需要 filePath" }, 400);
106
+
107
+ const ext = (filePath.match(/\.([a-z0-9]+)$/i)?.[1] || "").toLowerCase();
108
+ const conv = opts.conversions[ext];
109
+ if (!conv) {
110
+ return json({ ok: false, error: "源扩展不支持(支持: " + Object.keys(opts.conversions).map((k) => "." + k).join(" ") + ")" }, 400);
111
+ }
112
+ const target = resolveAllowedWriteRoot(filePath, cwd);
113
+ if (!target) return json({ ok: false, error: "路径不在可写白名单内" }, 400);
114
+ let st;
115
+ try {
116
+ st = statSync(target);
117
+ } catch {
118
+ return json({ ok: false, error: "源文件不存在" }, 400);
119
+ }
120
+ if (!st.isFile()) return json({ ok: false, error: "目标不是文件" }, 400);
121
+ if (st.size > maxBytes) return json({ ok: false, error: "文件超过 " + Math.round(maxBytes / 1024 / 1024) + "MB 上限" }, 413);
122
+
123
+ // 候选名(转换前定一次;rename 前再校验一次防并发竞争)
124
+ const dir = dirname(target);
125
+ const sourceName = basename(target);
126
+ let finalPath = nextSaveAsPath(dir, sourceName, ext, conv.toExt, (p) => { try { statSync(p); return true; } catch { return false; } });
127
+
128
+ const soffice = opts.sofficePath();
129
+ if (!soffice) {
130
+ return json({
131
+ ok: false,
132
+ code: "soffice-missing",
133
+ error: "未找到 LibreOffice (soffice):老格式转换需要它。可安装 LibreOffice,或在 aiti-editor 功能配置 soffice.path",
134
+ }, 503);
135
+ }
136
+ if (mutex()) return json({ ok: false, error: "上一个转换还在进行,请稍后重试" }, 409);
137
+ const g = globalThis as any;
138
+ g.__aitiConvertBusy = 1;
139
+ const tmpOut = join(dir, "." + opts.extId + "-conv-" + process.pid + "-" + Date.now());
140
+ try {
141
+ mkdirSync(tmpOut, { recursive: true });
142
+ const filter = conv.filter || conv.toExt;
143
+ await execFileP(soffice, ["--headless", "--convert-to", filter, "--outdir", tmpOut, target], 90_000);
144
+ const producedName = sourceName.replace(/\.[^.]+$/, "") + "." + conv.toExt;
145
+ const produced = join(tmpOut, producedName);
146
+ const ps = statSync(produced); // 不存在会 throw → 落入 catch
147
+ if (ps.size === 0) throw new Error("转换产物为空");
148
+ // rename 前最终防覆盖(转换期间目标可能被并发创建)
149
+ finalPath = nextSaveAsPath(dir, sourceName, ext, conv.toExt, (p) => { try { statSync(p); return true; } catch { return false; } });
150
+ renameSync(produced, finalPath);
151
+ const size = statSync(finalPath).size;
152
+ log(sourceName + " → " + basename(finalPath) + " (" + size + " bytes)");
153
+ return json({ ok: true, newPath: finalPath, size });
154
+ } catch (e) {
155
+ const msg = String((e as Error).message || e);
156
+ if (msg.includes("ENOENT") && msg.includes(producedNameHint(sourceName, conv.toExt))) {
157
+ return json({ ok: false, error: "soffice 未产出转换结果(源文件可能损坏或格式不支持)" }, 500);
158
+ }
159
+ log("转换失败: " + msg.slice(0, 200));
160
+ return json({ ok: false, error: "转换失败: " + msg.slice(0, 200) }, 500);
161
+ } finally {
162
+ try { require("node:fs").rmSync(tmpOut, { recursive: true, force: true }); } catch { /* 忽略 */ }
163
+ g.__aitiConvertBusy = 0;
164
+ }
165
+ };
166
+ }
167
+
168
+ function producedNameHint(sourceName: string, toExt: string): string {
169
+ return sourceName.replace(/\.[^.]+$/, "") + "." + toExt;
170
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * copy-client-bundle — 扩展 client 构建产物部署 helper(含代码分块)。
3
+ *
4
+ * 背景(docs/aiti-ext-lazy-loading-plan.md 陷阱④;backend-queue G1 同源):
5
+ * 多数扩展 deploy 脚本按「单一 client/<ext>-client.mjs」清单拷贝——bundle 一旦
6
+ * 产生代码分块(vite 动态 import() / React.lazy → 独立 hash chunk),分块文件
7
+ * 不会被拷贝,运行时 import() 404(静默,只有 console 可见)。
8
+ *
9
+ * 用法(deploy.mjs 内替换单文件 copyFileSync):
10
+ * import { copyClientBuild } from "../../_shared/copy-client-bundle.mjs";
11
+ * copyClientBuild(root, extDir, "aiti-xxx-client.mjs");
12
+ *
13
+ * 行为:
14
+ * 1. 拷主 bundle(<main>.mjs)+ client/ 下全部 .mjs/.js 构建产物(src/ 不拷);
15
+ * 2. 清理目标目录中源目录已不存在的 .js(陈旧 hash 分块防累积);
16
+ * 3. 幂等,可重复调用。
17
+ */
18
+ import { copyFileSync, existsSync, mkdirSync, readdirSync, unlinkSync } from "node:fs";
19
+ import { resolve } from "node:path";
20
+
21
+ export function copyClientBuild(root, extDir, mainBundle) {
22
+ const srcClient = resolve(root, "client");
23
+ const dstClient = resolve(extDir, "client");
24
+ if (!existsSync(srcClient)) return;
25
+ mkdirSync(dstClient, { recursive: true });
26
+ const srcFiles = readdirSync(srcClient).filter((f) => f.endsWith(".mjs") || f.endsWith(".js"));
27
+ const main = resolve(srcClient, mainBundle);
28
+ if (existsSync(main)) copyFileSync(main, resolve(dstClient, mainBundle));
29
+ for (const f of srcFiles) {
30
+ if (f === mainBundle) continue;
31
+ copyFileSync(resolve(srcClient, f), resolve(dstClient, f));
32
+ }
33
+ // 清理目标目录陈旧分块(源目录已不含旧 hash 名)
34
+ for (const f of readdirSync(dstClient)) {
35
+ if (f.endsWith(".js") && !srcFiles.includes(f)) {
36
+ try { unlinkSync(resolve(dstClient, f)); } catch { /* noop */ }
37
+ }
38
+ }
39
+ }
@@ -0,0 +1,377 @@
1
+ /**
2
+ * cursor-cli-store —— Cursor Agent CLI 会话存储读取器(纯函数、零依赖)。
3
+ *
4
+ * 权威源:pi-web-ext/_shared/cursor-cli-store.ts(改动后同步到各扩展副本)。
5
+ * 当前副本:pi-web-ext/session-manager/lib/agents/cursor-cli-store.ts、
6
+ * pi-web-ext/aiti-cursor-agent/cursor-cli-store.ts
7
+ *
8
+ * 格式(clean-room 对齐本机数据 + xhluca/session-migrate 文档;官方私有格式,可能漂移):
9
+ *
10
+ * config root: $CURSOR_CONFIG_DIR → $XDG_CONFIG_HOME/cursor → ~/.cursor
11
+ * <root>/chats/<workspaceKey>/<chatId>/store.db ← 权威 resume 存储
12
+ * <root>/chats/<workspaceKey>/<chatId>/meta.json ← 廉价摘要(title/cwd/时间;title 可缺省)
13
+ * <root>/projects/<pathSlug>/agent-transcripts/<chatId>/<chatId>.jsonl ← 可读镜像
14
+ *
15
+ * store.db:blobs(id=sha256hex(data), data BLOB) + meta(key '0', hex JSON
16
+ * {agentId, latestRootBlobId, name, createdAt ms, mode, lastUsedModel, ...})。
17
+ * blob 图为 protobuf wire:
18
+ *
19
+ * root: repeated f8 = turn 引用(f1 = system/context 引用 — 忽略)
20
+ * turn: f1 = agent-turn
21
+ * agent-turn: f1 = user 消息(f1 文本, f2 uuid, f25/f26 ts ms);
22
+ * repeated f2 = steps(f1 assistant{f1 text,f2 ts},f2 工具调用,f3 thinking 摘要)
23
+ *
24
+ * 读取策略:store.db 图解码优先(权威,含 🛠 工具行 / 💭 thinking 摘要);
25
+ * 不可解时兑底可读 JSONL 转录(解 <timestamp>/<user_query> 包装)。
26
+ *
27
+ * 格式回归测试:session-manager/lib/agents/cursor-cli-store.test.mjs ——
28
+ * 自带独立 protobuf 编码器从零合成 store.db fixture 钉死本文件的 wire
29
+ * 假设(多轮/思考/工具/fork 去重/兑底/损坏兼容);改本文件或怀疑 cursor
30
+ * 升级破坏格式时先跑它。
31
+ */
32
+ import { existsSync, mkdirSync, copyFileSync, readFileSync, readdirSync, statSync, unlinkSync } from "node:fs";
33
+ import { homedir } from "node:os";
34
+ import { join } from "node:path";
35
+ import { DatabaseSync } from "node:sqlite";
36
+
37
+ const CACHE = () => join("/tmp", "sm-cursor-cache");
38
+
39
+ export function cursorCliConfigRoot(): string {
40
+ const env = process.env.CURSOR_CONFIG_DIR;
41
+ if (env) return env;
42
+ const xdg = process.env.XDG_CONFIG_HOME;
43
+ if (xdg) return join(xdg, "cursor");
44
+ return join(homedir(), ".cursor");
45
+ }
46
+
47
+ export function cursorCliChatsRoot(): string {
48
+ return join(cursorCliConfigRoot(), "chats");
49
+ }
50
+
51
+ export interface CursorCliChatRef { sid: string; dir: string; db: string; summary: string }
52
+
53
+ /** 单个 chat 目录的更新时间(meta.updatedAtMs 优先,兑底 store.db mtime)。 */
54
+ function chatUpdatedAtMs({ db, summary }: CursorCliChatRef): number {
55
+ try {
56
+ const d = JSON.parse(readFileSync(summary, "utf8")) as { updatedAtMs?: number };
57
+ if (typeof d.updatedAtMs === "number") return d.updatedAtMs;
58
+ } catch { /* fall through */ }
59
+ try { return statSync(db).mtimeMs; } catch { return 0; }
60
+ }
61
+
62
+ /**
63
+ * 枚举 CLI 会话目录(跳过 meta.json 明确 hasConversation:false 的)。
64
+ *
65
+ * 注意:`--resume <chatId>` 在不同 cwd 下会把同 chatId 分叉到新 workspaceKey
66
+ * 目录(CLI 按工作区隔离历史)——同 sid 多目录时只保留最近更新的那个。
67
+ */
68
+ export function listCursorCliChats(): CursorCliChatRef[] {
69
+ const root = cursorCliChatsRoot();
70
+ if (!existsSync(root)) return [];
71
+ const bySid = new Map<string, CursorCliChatRef>();
72
+ let ws: string[] = [];
73
+ try { ws = readdirSync(root); } catch { return []; }
74
+ for (const w of ws) {
75
+ const wd = join(root, w);
76
+ try { if (!statSync(wd).isDirectory()) continue; } catch { continue; }
77
+ let sids: string[] = [];
78
+ try { sids = readdirSync(wd); } catch { continue; }
79
+ for (const sid of sids) {
80
+ const dir = join(wd, sid);
81
+ try { if (!statSync(dir).isDirectory()) continue; } catch { continue; }
82
+ const db = join(dir, "store.db");
83
+ const summary = join(dir, "meta.json");
84
+ if (!existsSync(db) && !existsSync(summary)) continue;
85
+ if (existsSync(summary)) {
86
+ try {
87
+ const d = JSON.parse(readFileSync(summary, "utf8")) as { hasConversation?: boolean };
88
+ if (d.hasConversation === false) continue;
89
+ } catch { /* corrupt meta — 仍列出,parse 兑底 */ }
90
+ }
91
+ const ref: CursorCliChatRef = { sid, dir, db, summary };
92
+ const prev = bySid.get(sid);
93
+ if (!prev || chatUpdatedAtMs(ref) >= chatUpdatedAtMs(prev)) bySid.set(sid, ref);
94
+ }
95
+ }
96
+ return [...bySid.values()];
97
+ }
98
+
99
+ // ── protobuf wire 走读(有界、防御式) ─────────────────────────────────────
100
+
101
+ interface PbField { no: number; wt: number; varint?: number; bytes?: Uint8Array }
102
+
103
+ function readVarint(d: Uint8Array, i: number): { v: number; i: number } | null {
104
+ let v = 0, shift = 0;
105
+ for (;;) {
106
+ if (i >= d.length || shift > 63) return null;
107
+ const b = d[i++]!;
108
+ v += (b & 0x7f) * 2 ** shift;
109
+ shift += 7;
110
+ if (!(b & 0x80)) return { v, i };
111
+ }
112
+ }
113
+
114
+ function pbFields(d: Uint8Array): PbField[] {
115
+ const out: PbField[] = [];
116
+ let i = 0;
117
+ while (i < d.length) {
118
+ const key = readVarint(d, i);
119
+ if (!key) break;
120
+ i = key.i;
121
+ const no = Math.floor(key.v / 8), wt = key.v % 8;
122
+ if (wt === 0) {
123
+ const v = readVarint(d, i);
124
+ if (!v) break;
125
+ i = v.i;
126
+ out.push({ no, wt, varint: v.v });
127
+ } else if (wt === 2) {
128
+ const len = readVarint(d, i);
129
+ if (!len) break;
130
+ const start = len.i;
131
+ if (start + len.v > d.length) break;
132
+ out.push({ no, wt, bytes: d.subarray(start, start + len.v) });
133
+ i = start + len.v;
134
+ } else if (wt === 1) { out.push({ no, wt, bytes: d.subarray(i, i + 8) }); i += 8; }
135
+ else if (wt === 5) { out.push({ no, wt, bytes: d.subarray(i, i + 4) }); i += 4; }
136
+ else break; // groups 不支持 — 防御式停走
137
+ }
138
+ return out;
139
+ }
140
+
141
+ function utf8(d: Uint8Array): string | null {
142
+ try {
143
+ const s = new TextDecoder("utf-8", { fatal: true }).decode(d);
144
+ // eslint-disable-next-line no-control-regex
145
+ return /[\u0000-\u0008\u000b\u000c\u000e-\u001f]/.test(s) ? null : s;
146
+ } catch { return null; }
147
+ }
148
+
149
+ const hex = (d: Uint8Array): string => Buffer.from(d).toString("hex");
150
+
151
+ /** 字段值解析:32 字节 = blob 引用;更短的可能是内联子消息。 */
152
+ function resolveBlob(blobs: Map<string, Uint8Array>, f: PbField): Uint8Array | null {
153
+ if (!f.bytes) return null;
154
+ if (f.bytes.length === 32) return blobs.get(hex(f.bytes)) ?? null;
155
+ return f.bytes;
156
+ }
157
+
158
+ /** 从「{f1 text} 子消息或裸字符串」节点提取展示文本。 */
159
+ function textField(d: Uint8Array): string | null {
160
+ for (const f of pbFields(d)) {
161
+ if (f.no === 1 && f.wt === 2 && f.bytes) {
162
+ const t = utf8(f.bytes);
163
+ if (t !== null) return t;
164
+ }
165
+ }
166
+ return utf8(d);
167
+ }
168
+
169
+ /** 从不透明节点收割可读 utf-8 字符串字段(工具调用)。 */
170
+ function harvestTexts(d: Uint8Array, depth = 0): string[] {
171
+ const out: string[] = [];
172
+ if (depth > 6) return out;
173
+ for (const f of pbFields(d)) {
174
+ if (f.wt !== 2 || !f.bytes || f.bytes.length === 32) continue;
175
+ const t = utf8(f.bytes);
176
+ if (t !== null && t.trim()) out.push(t.trim());
177
+ else out.push(...harvestTexts(f.bytes, depth + 1));
178
+ }
179
+ return out;
180
+ }
181
+
182
+ // ── store.db 图解码 ─────────────────────────────────────────────────────────
183
+
184
+ export interface CursorCliStoreMeta {
185
+ agentId?: string; latestRootBlobId?: string; name?: string;
186
+ createdAt?: number; mode?: string; lastUsedModel?: string;
187
+ }
188
+
189
+ interface StoreRead { meta: CursorCliStoreMeta; copied: string }
190
+
191
+ /** mtime 门控 tmp 快照(+wal/shm),永不锁 cursor 的活文件。0700:含会话内容。 */
192
+ function snapshotDb(src: string): string | null {
193
+ try {
194
+ mkdirSync(CACHE(), { recursive: true, mode: 0o700 });
195
+ const dst = join(CACHE(), src.replace(/[/\\]/g, "_"));
196
+ let st: { mtimeMs: number };
197
+ try { st = statSync(src); } catch { return null; }
198
+ try {
199
+ if (statSync(dst).mtimeMs >= st.mtimeMs) return dst;
200
+ } catch { /* first copy */ }
201
+ copyFileSync(src, dst);
202
+ for (const suffix of ["-wal", "-shm"]) {
203
+ if (existsSync(src + suffix)) copyFileSync(src + suffix, dst + suffix);
204
+ else { try { unlinkSync(dst + suffix); } catch { /* absent */ } }
205
+ }
206
+ return dst;
207
+ } catch {
208
+ return null;
209
+ }
210
+ }
211
+
212
+ function readStoreMeta(dbPath: string): StoreRead | null {
213
+ const copied = snapshotDb(dbPath);
214
+ if (!copied) return null;
215
+ try {
216
+ const db = new DatabaseSync(copied, { readOnly: true });
217
+ try {
218
+ const row = db.prepare("SELECT value FROM meta WHERE key = '0'").get() as { value: string | Uint8Array } | undefined;
219
+ if (!row?.value) return null;
220
+ const raw = typeof row.value === "string" ? row.value : Buffer.from(row.value).toString("ascii");
221
+ return { meta: JSON.parse(Buffer.from(raw, "hex").toString("utf8")) as CursorCliStoreMeta, copied };
222
+ } finally { db.close(); }
223
+ } catch { return null; }
224
+ }
225
+
226
+ export interface CursorCliMessage { role: "user" | "assistant"; ts: string | null; text: string }
227
+
228
+ function decodeStoreGraph(copied: string, rootId: string): CursorCliMessage[] | null {
229
+ let db: DatabaseSync;
230
+ try { db = new DatabaseSync(copied, { readOnly: true }); } catch { return null; }
231
+ try {
232
+ const blobs = new Map<string, Uint8Array>();
233
+ for (const r of db.prepare("SELECT id, data FROM blobs").all() as Array<{ id: string; data: Uint8Array }>) {
234
+ blobs.set(r.id, r.data);
235
+ }
236
+ const root = blobs.get(rootId);
237
+ if (!root) return null;
238
+ const turnRefs = pbFields(root).filter((f) => f.no === 8 && f.wt === 2);
239
+ if (!turnRefs.length) return null; // 未知布局 → jsonl 兑底
240
+
241
+ const msgs: CursorCliMessage[] = [];
242
+ for (const tr of turnRefs) {
243
+ const turn = resolveBlob(blobs, tr);
244
+ if (!turn) continue;
245
+ const atRef = pbFields(turn).find((f) => f.no === 1 && f.wt === 2);
246
+ if (!atRef) continue;
247
+ const at = resolveBlob(blobs, atRef);
248
+ if (!at) continue;
249
+
250
+ let userText = "", userTs: number | null = null;
251
+ const stepTexts: string[] = [];
252
+ for (const f of pbFields(at)) {
253
+ if (f.wt !== 2) continue;
254
+ const body = resolveBlob(blobs, f);
255
+ if (!body) continue;
256
+ if (f.no === 1) {
257
+ for (const uf of pbFields(body)) {
258
+ if (uf.no === 1 && uf.wt === 2 && uf.bytes && !userText) {
259
+ const t = utf8(uf.bytes);
260
+ if (t !== null) userText = t;
261
+ } else if ((uf.no === 25 || uf.no === 26) && uf.varint && !userTs) {
262
+ userTs = uf.varint > 1e12 ? uf.varint : null; // ms epoch 合理性
263
+ }
264
+ }
265
+ } else if (f.no === 2) {
266
+ for (const sf of pbFields(body)) {
267
+ if (sf.wt !== 2 || !sf.bytes) continue;
268
+ const sub = resolveBlob(blobs, sf);
269
+ const text = sub ? textField(sub) : utf8(sf.bytes);
270
+ if (sf.no === 1 && text) stepTexts.push(text); // assistant
271
+ else if (sf.no === 3 && text) stepTexts.push("💭 " + text); // thinking 摘要
272
+ else if (sf.no === 2) { // 工具调用(不透明)
273
+ const parts = sub ? harvestTexts(sub) : [];
274
+ stepTexts.push("🛠 " + (parts.join(" ").slice(0, 300) || "(tool call)"));
275
+ }
276
+ }
277
+ }
278
+ }
279
+ if (userText.trim()) msgs.push({ role: "user", ts: userTs ? new Date(userTs).toISOString() : null, text: userText });
280
+ const aText = stepTexts.join("\n").trim();
281
+ if (aText) msgs.push({ role: "assistant", ts: null, text: aText });
282
+ }
283
+ return msgs.length ? msgs : null;
284
+ } finally { db.close(); }
285
+ }
286
+
287
+ // ── 可读 JSONL 转录兑底 ─────────────────────────────────────────────────────
288
+
289
+ function findTranscript(sid: string): string | null {
290
+ const projRoot = join(cursorCliConfigRoot(), "projects");
291
+ if (!existsSync(projRoot)) return null;
292
+ let slugs: string[] = [];
293
+ try { slugs = readdirSync(projRoot); } catch { return null; }
294
+ let best: { p: string; m: number } | null = null;
295
+ for (const slug of slugs) {
296
+ // 同 sid 可能因 --resume 换 cwd 分叉出多份转录 —— 取 mtime 最新
297
+ const p = join(projRoot, slug, "agent-transcripts", sid, `${sid}.jsonl`);
298
+ if (!existsSync(p)) continue;
299
+ try {
300
+ const m = statSync(p).mtimeMs;
301
+ if (!best || m > best.m) best = { p, m };
302
+ } catch { /* raced */ }
303
+ }
304
+ return best?.p ?? null;
305
+ }
306
+
307
+ function decodeTranscript(path: string): CursorCliMessage[] | null {
308
+ let raw = "";
309
+ try { raw = readFileSync(path, "utf8"); } catch { return null; }
310
+ const msgs: CursorCliMessage[] = [];
311
+ for (const line of raw.split("\n")) {
312
+ if (!line.trim()) continue;
313
+ let e: { role?: string; message?: { content?: unknown } };
314
+ try { e = JSON.parse(line) as typeof e; } catch { continue; }
315
+ const role = e.role === "assistant" ? "assistant" : "user";
316
+ const content = e.message?.content;
317
+ const text = Array.isArray(content)
318
+ ? content.filter((c) => c && typeof c === "object" && (c as { type?: string }).type === "text")
319
+ .map((c) => (c as { text?: string }).text ?? "").join("\n")
320
+ : "";
321
+ if (!text.trim()) continue;
322
+ // 解 "<timestamp>…</timestamp>\n<user_query>\n…\n</user_query>" 包装
323
+ const m = text.match(/<user_query>\n?([\s\S]*?)\n?<\/user_query>/);
324
+ const clean = (m ? m[1] : text).trim();
325
+ if (!clean) continue;
326
+ msgs.push({ role, ts: null, text: clean });
327
+ }
328
+ return msgs.length ? msgs : null;
329
+ }
330
+
331
+ // ── 会话级读取 ──────────────────────────────────────────────────────────────
332
+
333
+ export interface CursorCliSession {
334
+ sid: string;
335
+ dir: string;
336
+ name?: string;
337
+ cwd: string;
338
+ createdMs?: number;
339
+ updatedMs: number;
340
+ mode?: string;
341
+ model?: string;
342
+ messages: CursorCliMessage[];
343
+ }
344
+
345
+ /** 读一个 CLI 会话(store.db 权威 → jsonl 兑底)。dir 缺省时按 sid 扫描。 */
346
+ export function readCursorCliChat(sid: string, dir?: string): CursorCliSession | null {
347
+ let chatDir = dir;
348
+ if (!chatDir || !existsSync(chatDir)) {
349
+ chatDir = listCursorCliChats().find((c) => c.sid === sid)?.dir;
350
+ if (!chatDir) return null;
351
+ }
352
+ const dbPath = join(chatDir, "store.db");
353
+ const summaryPath = join(chatDir, "meta.json");
354
+
355
+ let summary: { title?: string; createdAtMs?: number; updatedAtMs?: number; cwd?: string } = {};
356
+ if (existsSync(summaryPath)) {
357
+ try { summary = JSON.parse(readFileSync(summaryPath, "utf8")) as typeof summary; } catch { /* corrupt */ }
358
+ }
359
+
360
+ const store = existsSync(dbPath) ? readStoreMeta(dbPath) : null;
361
+ const msgs = store?.meta.latestRootBlobId ? decodeStoreGraph(store.copied, store.meta.latestRootBlobId) : null;
362
+ const messages = msgs ?? (findTranscript(sid) ? decodeTranscript(findTranscript(sid)!) : null) ?? [];
363
+ if (!messages.length) return null;
364
+
365
+ const updatedMs = summary.updatedAtMs ?? (() => { try { return statSync(dbPath || chatDir).mtimeMs; } catch { return Date.now(); } })();
366
+ return {
367
+ sid,
368
+ dir: chatDir,
369
+ name: store?.meta.name || summary.title || undefined,
370
+ cwd: summary.cwd ?? "",
371
+ createdMs: store?.meta.createdAt ?? summary.createdAtMs,
372
+ updatedMs,
373
+ mode: store?.meta.mode,
374
+ model: store?.meta.lastUsedModel,
375
+ messages,
376
+ };
377
+ }
@@ -0,0 +1,71 @@
1
+ // dedupe-fetch 单测(node --test,直跑 TS:node ≥ 22.6 --experimental-strip-types)。
2
+ // 与 pi-web lib/dedupe-fetch.test.mjs 同源(复制同步,两处语义保持一致)。
3
+ import { dedupeFetch, resetDedupeFetch } from "./dedupe-fetch.ts";
4
+ import { test } from "node:test";
5
+ import assert from "node:assert/strict";
6
+ /** stub global fetch:记录调用次数,返回 (status, body) 或委托自定义实现 */
7
+ function stubFetch(impl) {
8
+ const calls = [];
9
+ const fn = (url, init) => {
10
+ calls.push({ url, init });
11
+ return Promise.resolve(impl(url, init, calls.length));
12
+ };
13
+ globalThis.fetch = fn;
14
+ return calls;
15
+ }
16
+
17
+ test("concurrent same-URL calls share one network round-trip; each gets an independent clone", async () => {
18
+ resetDedupeFetch();
19
+ const calls = stubFetch(() => new Response(JSON.stringify({ home: "/h" }), { status: 200 }));
20
+ const [a, b] = await Promise.all([dedupeFetch("/api/home"), dedupeFetch("/api/home")]);
21
+ assert.equal(calls.length, 1);
22
+ assert.notEqual(a, b, "each caller must get its own Response clone");
23
+ assert.deepEqual(await a.json(), { home: "/h" });
24
+ assert.deepEqual(await b.json(), { home: "/h" });
25
+ });
26
+
27
+ test("successful response is reused within ttlMs without a new request", async () => {
28
+ resetDedupeFetch();
29
+ const calls = stubFetch(() => new Response(JSON.stringify({ ok: 1 }), { status: 200 }));
30
+ await dedupeFetch("/x", { ttlMs: 50 }).then((r) => r.json());
31
+ assert.equal(calls.length, 1);
32
+ const again = await dedupeFetch("/x", { ttlMs: 50 });
33
+ assert.equal(calls.length, 1, "TTL window hit → zero network");
34
+ assert.deepEqual(await again.json(), { ok: 1 });
35
+ });
36
+
37
+ test("after ttl expiry a new request is issued", async () => {
38
+ resetDedupeFetch();
39
+ const calls = stubFetch(() => new Response("{}", { status: 200 }));
40
+ await dedupeFetch("/y", { ttlMs: 10 }).then((r) => r.json());
41
+ await new Promise((r) => setTimeout(r, 25));
42
+ await dedupeFetch("/y", { ttlMs: 10 });
43
+ assert.equal(calls.length, 2);
44
+ });
45
+
46
+ test("failed responses are not cached — next call retries", async () => {
47
+ resetDedupeFetch();
48
+ const calls = stubFetch(() => new Response("boom", { status: 500 }));
49
+ await assert.rejects(dedupeFetch("/f").then((r) => {
50
+ if (!r.ok) throw new Error(String(r.status));
51
+ return r.json();
52
+ }));
53
+ await dedupeFetch("/f");
54
+ assert.equal(calls.length, 2);
55
+ });
56
+
57
+ test("different URLs do not share cache entries", async () => {
58
+ resetDedupeFetch();
59
+ const calls = stubFetch(() => new Response("{}", { status: 200 }));
60
+ await Promise.all([dedupeFetch("/a"), dedupeFetch("/b")]);
61
+ assert.equal(calls.length, 2);
62
+ });
63
+
64
+ test("options are forwarded to fetch on the shared request", async () => {
65
+ resetDedupeFetch();
66
+ let seenInit;
67
+ stubFetch((_url, init) => { seenInit = init; return new Response("{}", { status: 200 }); });
68
+ await dedupeFetch("/opt", { cache: "no-store", headers: { "if-none-match": '"v1"' } });
69
+ assert.equal(seenInit.cache, "no-store");
70
+ assert.equal(seenInit.headers["if-none-match"], '"v1"');
71
+ });