@liang-hz/agent-in-chrome 0.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/.ext-id.txt +4 -0
  2. package/LICENSE +202 -0
  3. package/NOTICE +5 -0
  4. package/PRIVACY.md +86 -0
  5. package/README.en.md +419 -0
  6. package/README.md +406 -0
  7. package/bin/agent-in-chrome.mjs +97 -0
  8. package/commands/agent-in-chrome.md +18 -0
  9. package/commands/install-agent-in-chrome.md +22 -0
  10. package/docs/AGENTS.md +94 -0
  11. package/docs/CLI.md +297 -0
  12. package/docs/client-compat.json +23 -0
  13. package/extension/about-toc.js +25 -0
  14. package/extension/about.html +240 -0
  15. package/extension/about.js +44 -0
  16. package/extension/agent-window.html +100 -0
  17. package/extension/icons/icon-128.png +0 -0
  18. package/extension/icons/icon-16.png +0 -0
  19. package/extension/icons/icon-24.png +0 -0
  20. package/extension/icons/icon-32.png +0 -0
  21. package/extension/icons/icon-48.png +0 -0
  22. package/extension/icons/icon-64.png +0 -0
  23. package/extension/icons/icon-attention-128.png +0 -0
  24. package/extension/icons/icon-attention-16.png +0 -0
  25. package/extension/icons/icon-attention-24.png +0 -0
  26. package/extension/icons/icon-attention-32.png +0 -0
  27. package/extension/icons/icon-attention-48.png +0 -0
  28. package/extension/icons/icon-attention-64.png +0 -0
  29. package/extension/icons/icon-attention.svg +18 -0
  30. package/extension/icons/icon-failed-128.png +0 -0
  31. package/extension/icons/icon-failed-16.png +0 -0
  32. package/extension/icons/icon-failed-24.png +0 -0
  33. package/extension/icons/icon-failed-32.png +0 -0
  34. package/extension/icons/icon-failed-48.png +0 -0
  35. package/extension/icons/icon-failed-64.png +0 -0
  36. package/extension/icons/icon-failed.svg +18 -0
  37. package/extension/icons/icon-idle-128.png +0 -0
  38. package/extension/icons/icon-idle-16.png +0 -0
  39. package/extension/icons/icon-idle-24.png +0 -0
  40. package/extension/icons/icon-idle-32.png +0 -0
  41. package/extension/icons/icon-idle-48.png +0 -0
  42. package/extension/icons/icon-idle-64.png +0 -0
  43. package/extension/icons/icon-idle.svg +18 -0
  44. package/extension/icons/icon-mark.svg +10 -0
  45. package/extension/icons/icon-running-128.png +0 -0
  46. package/extension/icons/icon-running-16.png +0 -0
  47. package/extension/icons/icon-running-24.png +0 -0
  48. package/extension/icons/icon-running-32.png +0 -0
  49. package/extension/icons/icon-running-48.png +0 -0
  50. package/extension/icons/icon-running-64.png +0 -0
  51. package/extension/icons/icon-running.svg +18 -0
  52. package/extension/icons/icon.svg +18 -0
  53. package/extension/manifest.json +44 -0
  54. package/extension/popup-ui.js +38 -0
  55. package/extension/popup.html +350 -0
  56. package/extension/popup.js +741 -0
  57. package/extension/sw.js +11127 -0
  58. package/extension/update-check.js +66 -0
  59. package/extension/welcome.html +110 -0
  60. package/extension/welcome.js +18 -0
  61. package/mcp/agent-identity.mjs +1007 -0
  62. package/mcp/cdp/bridge.mjs +239 -0
  63. package/mcp/cdp/browser-launch.mjs +1127 -0
  64. package/mcp/cdp/chrome-shim.mjs +1124 -0
  65. package/mcp/cdp/client.mjs +443 -0
  66. package/mcp/cli-invocation.mjs +67 -0
  67. package/mcp/config.mjs +191 -0
  68. package/mcp/foreground-guard.mjs +295 -0
  69. package/mcp/proc-win.mjs +112 -0
  70. package/mcp/secret-shape.mjs +155 -0
  71. package/mcp/server.mjs +3437 -0
  72. package/mcp/session-id.mjs +281 -0
  73. package/mcp/token.mjs +260 -0
  74. package/mcp/tool-tiers.mjs +84 -0
  75. package/mcp/trace.mjs +528 -0
  76. package/mcp/update-cli.mjs +163 -0
  77. package/mcp/update-notice.mjs +194 -0
  78. package/native-host/host.mjs +356 -0
  79. package/native-host/mac-foreground/aic-fg.swift +114 -0
  80. package/native-host/mac-foreground/build.mjs +43 -0
  81. package/package.json +46 -0
  82. package/scripts/agents.mjs +921 -0
  83. package/scripts/borrow-login.mjs +935 -0
  84. package/scripts/cli-browser.mjs +148 -0
  85. package/scripts/e2e-sweep.mjs +192 -0
  86. package/scripts/e2e.mjs +3911 -0
  87. package/scripts/fixture-server.mjs +1419 -0
  88. package/scripts/guard-publish.mjs +175 -0
  89. package/scripts/install.mjs +1383 -0
  90. package/scripts/launcher-provenance.mjs +74 -0
  91. package/scripts/pack-crx.mjs +82 -0
  92. package/scripts/pick.mjs +114 -0
  93. package/scripts/test-agents.mjs +968 -0
  94. package/scripts/test-borrow.mjs +289 -0
  95. package/scripts/test-config.mjs +618 -0
  96. package/scripts/test-e2e-sweep.mjs +251 -0
  97. package/scripts/test-foreground-guard.mjs +383 -0
  98. package/scripts/test-identity.mjs +1141 -0
  99. package/scripts/test-install-skill.mjs +378 -0
  100. package/scripts/test-protocol.mjs +712 -0
  101. package/scripts/test-security.mjs +1360 -0
  102. package/scripts/test-sw.mjs +14526 -0
  103. package/scripts/test-update.mjs +301 -0
  104. package/skills/agent-in-chrome/SKILL.md +60 -0
  105. package/skills/agent-in-chrome/references/actions-and-waits.md +136 -0
  106. package/skills/agent-in-chrome/references/amap-dir-dropdown.md +66 -0
  107. package/skills/agent-in-chrome/references/geetest-click-captcha.md +55 -0
  108. package/skills/agent-in-chrome/references/network-debugging.md +20 -0
  109. package/skills/agent-in-chrome/references/reading-pages.md +30 -0
  110. package/skills/agent-in-chrome/references/recovery.md +25 -0
  111. package/skills/agent-in-chrome/references/tabs-and-sessions.md +34 -0
  112. package/skills/install-agent-in-chrome/SKILL.md +252 -0
@@ -0,0 +1,1141 @@
1
+ #!/usr/bin/env node
2
+
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+
7
+ import zlib from "node:zlib";
8
+
9
+ import {
10
+ bundleName,
11
+ bundleMatch,
12
+ plainName,
13
+ binShimName,
14
+ isDshClient,
15
+ decodeZstdFrames,
16
+ readDshSession,
17
+ antigravityDataDir,
18
+ antigravityConversationId,
19
+ readAntigravityWorkspace,
20
+ readSessionIdentity,
21
+ hasTty,
22
+ walkSurface,
23
+ resolveClientPid,
24
+ readWorkspace,
25
+ readClientSessionFile,
26
+ readHostSessionTitle,
27
+ readWorkbuddySessionTitle,
28
+ informativeName,
29
+ composeAgent,
30
+ probeLocal,
31
+ readSessionTitle,
32
+ readZcodeSessionTitle,
33
+ zcodeDataDir,
34
+ traeDataDir,
35
+ userDataDirFrom,
36
+ readTraeSessionTitle,
37
+ resetTitleMemo,
38
+ readClaudeSubagent,
39
+ resetSubagentMemo,
40
+ procSource,
41
+ exePathOf,
42
+ } from "../mcp/agent-identity.mjs";
43
+ import { isLauncherFor } from "../mcp/session-id.mjs";
44
+ import { makeWinProcSource } from "../mcp/proc-win.mjs";
45
+
46
+ let passed = 0;
47
+ let failed = 0;
48
+ const check = (name, cond, extra = "") => {
49
+ if (cond) {
50
+ console.log(` \x1b[32m✓\x1b[0m ${name}`);
51
+ passed++;
52
+ } else {
53
+ console.log(` \x1b[31m✗\x1b[0m ${name}${extra ? ` — ${extra}` : ""}`);
54
+ failed++;
55
+ }
56
+ };
57
+
58
+ const CHAINS = {
59
+ claudeDesktop: new Map([
60
+ [900, { ppid: 901, tty: "??", command: "/Users/u/.nvm/versions/node/v24.11.1/bin/node /Users/u/.agent-in-chrome/agent-in-chrome/server.mjs" }],
61
+ [901, { ppid: 902, tty: "??", command: "/Applications/Claude.app/Contents/Helpers/disclaimer /Users/u/.agent-in-chrome/agent-in-chrome/mcp-launcher.sh" }],
62
+ [902, { ppid: 1, tty: "??", command: "/Applications/Claude.app/Contents/MacOS/Claude" }],
63
+ ]),
64
+ claudeCodeDesktop: new Map([
65
+ [910, { ppid: 911, tty: "??", command: "node /Users/u/OpenSource/agent-in-chrome/mcp/server.mjs" }],
66
+ [911, { ppid: 912, tty: "??", command: `/Users/u/Library/Application Support/Claude/claude-code/2.1.227/claude.app/Contents/MacOS/claude --output-format stream-json --mcp-config {"mcpServers":{"agent-in-chrome":{"command":"node","args":["/Users/u/.agent-in-chrome/agent-in-chrome/server.mjs"]}}}` }],
67
+ [912, { ppid: 1, tty: "??", command: "/Applications/Claude.app/Contents/MacOS/Claude" }],
68
+ ]),
69
+ cli: new Map([
70
+ [920, { ppid: 921, tty: "??", command: "node /Users/u/.agent-in-chrome/agent-in-chrome/server.mjs" }],
71
+ [921, { ppid: 922, tty: "ttys001", command: "/Users/u/.local/bin/claude" }],
72
+ [922, { ppid: 923, tty: "ttys001", command: "-/bin/zsh" }],
73
+ [923, { ppid: 1, tty: "??", command: "/Applications/iTerm.app/Contents/MacOS/iTerm2" }],
74
+ ]),
75
+ zcode: new Map([
76
+ [930, { ppid: 931, tty: "??", command: "/Users/u/.nvm/versions/node/v24.11.1/bin/node /Users/u/.agent-in-chrome/agent-in-chrome/server.mjs" }],
77
+ [931, { ppid: 932, tty: "??", command: "zcode-cli" }],
78
+ [932, { ppid: 933, tty: "??", command: "zcode-host-local-1" }],
79
+ [933, { ppid: 1, tty: "??", command: "ZCode" }],
80
+ ]),
81
+ qoder: new Map([
82
+ [940, { ppid: 941, tty: "??", command: "/Users/u/.nvm/versions/node/v24.11.1/bin/node /Users/u/.agent-in-chrome/agent-in-chrome/server.mjs" }],
83
+ [941, { ppid: 942, tty: "??", command: "/Applications/Qoder CN.app/Contents/Resources/app/resources/bin/aarch64_darwin/QoderCN start --workDir /Users/u/Library" }],
84
+ [942, { ppid: 1, tty: "??", command: "/Applications/Qoder CN.app/Contents/MacOS/Electron" }],
85
+ ]),
86
+ trae: new Map([
87
+ [960, { ppid: 961, tty: "??", command: "/Users/u/.nvm/versions/node/v24.11.1/bin/node /Users/u/.agent-in-chrome/agent-in-chrome/server.mjs" }],
88
+ [961, { ppid: 962, tty: "??", command: "/Applications/Trae CN.app/Contents/Frameworks/Trae CN Helper (Plugin).app/Contents/MacOS/Trae CN Helper (Plugin) --type=utility --utility-sub-type=node.mojom.NodeService" }],
89
+ [962, { ppid: 1, tty: "??", command: "/Applications/Trae CN.app/Contents/MacOS/Electron" }],
90
+ ]),
91
+ workbuddy: new Map([
92
+ [970, { ppid: 971, tty: "??", command: "/Users/u/.nvm/versions/node/v24.11.1/bin/node /Users/u/.agent-in-chrome/agent-in-chrome/server.mjs" }],
93
+ [971, { ppid: 1, tty: "??", command: "/Applications/WorkBuddy.app/Contents/MacOS/Electron /Applications/WorkBuddy.app/Contents/Resources/app.asar/main/daemon-app-server-entry.js --stdio" }],
94
+ ]),
95
+ };
96
+
97
+ const SELF = "/Users/u/.agent-in-chrome/agent-in-chrome/server.mjs";
98
+
99
+ console.log("\n\x1b[1m形态与品牌:认父进程链上的证据\x1b[0m");
100
+ {
101
+ const walk = (chain, serverPid) => {
102
+ const snap = CHAINS[chain];
103
+ return walkSurface(resolveClientPid(snap.get(serverPid).ppid, snap, SELF), snap, {});
104
+ };
105
+
106
+ const d = walk("claudeDesktop", 900);
107
+ check("Claude 桌面端:跳过一次性启动器,认到 Claude.app", d.surface === "app" && d.brand === "Claude", JSON.stringify(d));
108
+
109
+ const cc = walk("claudeCodeDesktop", 910);
110
+ check("桌面端里的 Claude Code:是桌面端形态", cc.surface === "app", JSON.stringify(cc));
111
+ check(
112
+ "引擎 argv 里嵌着我们的路径也不算启动器:锚点停在引擎上",
113
+ resolveClientPid(911, CHAINS.claudeCodeDesktop, SELF) === 911,
114
+ String(resolveClientPid(911, CHAINS.claudeCodeDesktop, SELF))
115
+ );
116
+ check(
117
+ "旧连接器的 disclaimer 层照旧跳过",
118
+ resolveClientPid(901, CHAINS.claudeDesktop, SELF) === 902,
119
+ String(resolveClientPid(901, CHAINS.claudeDesktop, SELF))
120
+ );
121
+
122
+ const c = walk("cli", 920);
123
+ check("终端里的 CLI:撞见 tty 就判 CLI,不再往上走到 iTerm.app", c.surface === "cli", JSON.stringify(c));
124
+
125
+ const z = walk("zcode", 930);
126
+ check("ZCode:一路到 launchd 都没终端 = 桌面端,argv0 当品牌", z.surface === "app" && z.brand === "ZCode", JSON.stringify(z));
127
+
128
+ const q = walk("qoder", 940);
129
+ check("Qoder:认 .app 包名而不是可执行文件名 Electron", q.surface === "app" && q.brand === "Qoder CN", JSON.stringify(q));
130
+ check("认出 .app 包时连包路径一起给(版本号要从它的 Info.plist 读)", q.appDir === "/Applications/Qoder CN.app", JSON.stringify(q));
131
+
132
+ const t = walk("trae", 960);
133
+ check("Trae(VS Code 系):extensionHost 往上认到 Trae CN.app", t.surface === "app" && t.brand === "Trae CN", JSON.stringify(t));
134
+
135
+ const w = walk("workbuddy", 970);
136
+ check("WorkBuddy:Electron 主进程直接 spawn,认包名", w.surface === "app" && w.brand === "WorkBuddy", JSON.stringify(w));
137
+
138
+ const none = walkSurface(950, new Map(), {});
139
+ check("查不到进程就报没有形态,不猜", none.surface === null && none.brand === null, JSON.stringify(none));
140
+ }
141
+
142
+ console.log("\n\x1b[1m包名与裸名字\x1b[0m");
143
+ {
144
+ check("包名带空格也认得出", bundleName("/Applications/Qoder CN.app/Contents/MacOS/Electron") === "Qoder CN");
145
+ check("参数里出现的包路径不算数", bundleName("/usr/bin/open -a /Applications/Claude.app/Contents/MacOS/Claude") === null);
146
+ check("相对路径不算数(认不出是不是本进程自己)", bundleName("Claude.app/Contents/MacOS/Claude") === null);
147
+ check("运行时的名字不当品牌", plainName("node /x/y.mjs") === null && plainName("/usr/bin/python3 -m x") === null);
148
+ check("改过 argv0 的 GUI 进程当品牌", plainName("ZCode") === "ZCode");
149
+ check("ps 的 ?? 不算终端", !hasTty("??") && !hasTty("") && hasTty("ttys001"));
150
+ }
151
+
152
+ console.log("\n\x1b[1m工作区:先 git 仓库名,再目录名\x1b[0m");
153
+ {
154
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "aic-ident-"));
155
+ const repo = path.join(tmp, "my-repo");
156
+ fs.mkdirSync(path.join(repo, "mcp"), { recursive: true });
157
+ fs.mkdirSync(path.join(repo, ".git"));
158
+ const plain = path.join(tmp, "just-a-dir");
159
+ fs.mkdirSync(plain);
160
+
161
+ check("仓库里的子目录报的是仓库名", JSON.stringify(readWorkspace(path.join(repo, "mcp"), { tmp: "/nope" })) === JSON.stringify({ name: "my-repo", kind: "git" }));
162
+ check("没有 git 就报目录名", JSON.stringify(readWorkspace(plain, { tmp: "/nope" })) === JSON.stringify({ name: "just-a-dir", kind: "dir" }));
163
+ check("cwd 是 / 的(桌面端就这么拉起 server)没有工作区", readWorkspace("/", { tmp: "/nope" }) === null);
164
+ check("cwd 就是家目录也不算工作区", readWorkspace(tmp, { home: tmp, tmp: "/nope" }) === null);
165
+
166
+ const wt = path.join(tmp, "wt-branch");
167
+ fs.mkdirSync(wt);
168
+ fs.writeFileSync(path.join(wt, ".git"), "gitdir: /somewhere/.git/worktrees/wt-branch\n");
169
+ check("worktree 的 .git 是文件,照样认得出", readWorkspace(wt, { tmp: "/nope" })?.kind === "git" && readWorkspace(wt, { tmp: "/nope" })?.name === "wt-branch");
170
+
171
+ const hiddenWt = path.join(repo, ".claude", "worktrees", "agent-a2edbaa72");
172
+ fs.mkdirSync(hiddenWt, { recursive: true });
173
+ fs.writeFileSync(path.join(hiddenWt, ".git"), `gitdir: ${path.join(repo, ".git", "worktrees", "agent-a2edbaa72")}\n`);
174
+ check(
175
+ "隐藏目录下的 worktree 照样认得出(.claude/worktrees 就是这形状)",
176
+ JSON.stringify(readWorkspace(hiddenWt, { tmp: "/nope" })) === JSON.stringify({ name: "agent-a2edbaa72", kind: "git" })
177
+ );
178
+
179
+ const sub = path.join(repo, "vendor", "libfoo");
180
+ fs.mkdirSync(sub, { recursive: true });
181
+ fs.writeFileSync(path.join(sub, ".git"), "gitdir: ../../.git/modules/libfoo\n");
182
+ check(
183
+ "子模块检出报的是子模块自己的目录名,不是超级仓库",
184
+ JSON.stringify(readWorkspace(sub, { tmp: "/nope" })) === JSON.stringify({ name: "libfoo", kind: "git" })
185
+ );
186
+
187
+ fs.rmSync(tmp, { recursive: true, force: true });
188
+ }
189
+
190
+ console.log("\n\x1b[1m会话标题:客户端写在磁盘上的那份\x1b[0m");
191
+ {
192
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "aic-home-"));
193
+ const sessions = path.join(home, ".claude", "sessions");
194
+ fs.mkdirSync(sessions, { recursive: true });
195
+ fs.writeFileSync(
196
+ path.join(sessions, "7001.json"),
197
+ JSON.stringify({ pid: 7001, sessionId: "abc", cwd: "/tmp/x", entrypoint: "cli", name: "agent-in-chrome-07", nameSource: "derived" })
198
+ );
199
+ fs.writeFileSync(path.join(sessions, "7002.json"), JSON.stringify({ pid: 9999, cwd: "/tmp/y", entrypoint: "cli" }));
200
+
201
+ check("读得到客户端的会话记录", readClientSessionFile(7001, { home })?.entrypoint === "cli");
202
+ check("pid 对不上的残留文件当没有", readClientSessionFile(7002, { home }) === null);
203
+ check("凑出来的会话名(derived)不当标题——它跟工作区那段重复", readSessionTitle({ clientPid: 7001, hostSessionId: null }, { home }) === null);
204
+
205
+ fs.writeFileSync(
206
+ path.join(sessions, "7003.json"),
207
+ JSON.stringify({ pid: 7003, cwd: "/tmp/z", entrypoint: "cli", name: "查竞品定价", nameSource: "auto" })
208
+ );
209
+ check("不是凑出来的会话名就当标题", readSessionTitle({ clientPid: 7003, hostSessionId: null }, { home }) === "查竞品定价");
210
+
211
+ const hostDir = path.join(home, "Library", "Application Support", "Claude", "claude-code-sessions", "org1", "user1");
212
+ fs.mkdirSync(hostDir, { recursive: true });
213
+ fs.writeFileSync(path.join(hostDir, "local_abc-123.json"), JSON.stringify({ title: "修 sid 漂移与组认领", titleSource: "auto" }));
214
+ check("宿主管的标题读得到(逐级列目录找到那两层)", readHostSessionTitle("local_abc-123", { home }) === "修 sid 漂移与组认领");
215
+ check("没有这个会话 id 就是没有", readHostSessionTitle("local_nope", { home }) === null);
216
+ check("会话 id 里有路径分隔符一律不认(别人给的字符串,不许拼进路径)", readHostSessionTitle("../../etc/passwd", { home }) === null);
217
+ check("宿主的标题优先于客户端记的会话名", readSessionTitle({ clientPid: 7003, hostSessionId: "local_abc-123" }, { home }) === "修 sid 漂移与组认领");
218
+
219
+ const late = path.join(hostDir, "local_late.json");
220
+ check("标题还没生成时就是没有", readSessionTitle({ clientPid: 0, hostSessionId: "local_late" }, { home }) === null);
221
+ fs.writeFileSync(late, JSON.stringify({ title: "后来才有的标题" }));
222
+ check("标题后来出现了要能读到(所以不能只在握手时读一次)", readSessionTitle({ clientPid: 0, hostSessionId: "local_late" }, { home }) === "后来才有的标题");
223
+
224
+ fs.rmSync(home, { recursive: true, force: true });
225
+ }
226
+
227
+ console.log("\n\x1b[1mWorkBuddy 的会话标题:活着的对话恰好一个才归属\x1b[0m");
228
+ {
229
+ const wb = fs.mkdtempSync(path.join(os.tmpdir(), "aic-wb-"));
230
+ fs.mkdirSync(path.join(wb, "sessions"));
231
+ const put = (pid, extra) => fs.writeFileSync(path.join(wb, "sessions", `${pid}.json`), JSON.stringify({ pid, ...extra }));
232
+ put(7100, { kind: "interactive", sessionId: "649aa100-f37d-4bff-b8db-7518eef9a95d" });
233
+ put(7101, { kind: "interactive", sessionId: "interactive-7101" });
234
+ put(7102, { kind: "prewarm", sessionId: "0f179b98-cf6a-4c42-a9e5-02766f6d131f" });
235
+ put(7103, { kind: "interactive", sessionId: "0f179b98-cf6a-4c42-a9e5-02766f6d131f" });
236
+
237
+ const env = { WORKBUDDY_CONFIG_DIR: wb };
238
+ let asked = null;
239
+ const fakeExec = (bin, args) => {
240
+ asked = { bin, sql: args[args.length - 1] };
241
+ return "查竞品定价\n";
242
+ };
243
+
244
+ const one = readWorkbuddySessionTitle({ env, exec: fakeExec, alive: (p) => p === 7100 });
245
+ check("恰好一个活着的对话:读它的标题", one === "查竞品定价", JSON.stringify(one));
246
+ check("查库带的是那段对话的 uuid(先验过形状才拼 SQL)", /649aa100-f37d-4bff-b8db-7518eef9a95d/.test(asked?.sql || ""), asked?.sql);
247
+ check("CLI host / prewarm 的假会话不算对话", one === "查竞品定价");
248
+ check("两段对话都活着:分不出是谁,不猜", readWorkbuddySessionTitle({ env, exec: fakeExec, alive: () => true }) === null);
249
+ check("对话都结束了就是没有", readWorkbuddySessionTitle({ env, exec: fakeExec, alive: () => false }) === null);
250
+ check("没有 WORKBUDDY_CONFIG_DIR(别家客户端)一律 null", readWorkbuddySessionTitle({ env: {}, exec: fakeExec }) === null);
251
+ check("库读不动就不显示,不许编", readWorkbuddySessionTitle({ env, exec: () => { throw new Error("no db"); }, alive: (p) => p === 7100 }) === null);
252
+ {
253
+ const evil = fs.mkdtempSync(path.join(os.tmpdir(), "aic-wb-evil-"));
254
+ fs.mkdirSync(path.join(evil, "sessions"));
255
+ fs.writeFileSync(path.join(evil, "sessions", "8000.json"),
256
+ JSON.stringify({ pid: 8000, kind: "interactive", sessionId: "1' or '1'='1" }));
257
+ check("带引号的 sessionId 不进 SQL(正则先挡)",
258
+ readWorkbuddySessionTitle({ env: { WORKBUDDY_CONFIG_DIR: evil }, exec: () => { throw new Error("绝不该拿注入载荷查库"); }, alive: () => true }) === null);
259
+ fs.rmSync(evil, { recursive: true, force: true });
260
+ }
261
+
262
+ const t = readSessionTitle({ clientPid: 0, hostSessionId: null }, { home: wb, env, exec: fakeExec, alive: (p) => p === 7100 });
263
+ check("readSessionTitle 兜到 WorkBuddy 这条来源", t === "查竞品定价", JSON.stringify(t));
264
+
265
+ fs.rmSync(wb, { recursive: true, force: true });
266
+ }
267
+
268
+ console.log("\n\x1b[1m拼出显示用的那个对象\x1b[0m");
269
+ {
270
+ const local = { brandFallback: "Claude", surface: "app", workspace: "agent-in-chrome", workspaceKind: "git" };
271
+
272
+ const a = composeAgent({ name: "claude-code", title: "Claude Code", version: "2.1.227" }, local, "修 sid 漂移");
273
+ check("有 title 就用 title 当品牌", a.brand === "Claude Code", JSON.stringify(a));
274
+ check("四段齐了", a.surface === "app" && a.workspace === "agent-in-chrome" && a.session === "修 sid 漂移", JSON.stringify(a));
275
+ check("客户端自报的原文照旧带上(tooltip 要用)", a.name === "claude-code" && a.version === "2.1.227", JSON.stringify(a));
276
+
277
+ const b = composeAgent({ name: "local-agent-mode-agent-in-chrome", title: null, version: "1.0.0" }, local, null);
278
+ check("local-agent-mode-* 不当品牌,退回父进程链认到的", b.brand === "Claude", JSON.stringify(b));
279
+ check("但原文还在,tooltip 里说得清为什么", b.name === "local-agent-mode-agent-in-chrome", JSON.stringify(b));
280
+ check("认不出品牌就不显示品牌(不猜)", informativeName("local-agent-mode-x") === null && informativeName("cursor-vscode") === "cursor-vscode");
281
+
282
+ const c = composeAgent(null, { surface: "cli", workspace: "myapp", workspaceKind: "dir" }, null);
283
+ check("客户端不报家门时,本机取证的那几段照样有", c.surface === "cli" && c.workspace === "myapp", JSON.stringify(c));
284
+ check("不报家门就不许编品牌名", c.brand === null && c.name === null && c.title === null, JSON.stringify(c));
285
+
286
+ check("一段证据都没有就返回 null(帧里连 agent 键都不加)", composeAgent(null, null, null) === null);
287
+ check("过长的字段一律截断", composeAgent({ name: "x".repeat(80) }, null, "y".repeat(200)).session.length === 60);
288
+ }
289
+
290
+ console.log("\n\x1b[1m品牌优先级与版本同源(Qoder/Trae/WorkBuddy 的真机实样)\x1b[0m");
291
+ {
292
+ const fakeExec = (bin, args) => {
293
+ const known = { "/Applications/Qoder CN.app/Contents/Info.plist": "1.23.0\n", "/Applications/Trae CN.app/Contents/Info.plist": "3.3.83\n" };
294
+ const out = known[String(args[args.length - 1]).split(path.sep).join("/")];
295
+ if (!out) throw new Error("no plist");
296
+ return out;
297
+ };
298
+
299
+ const qoderLocal = { brandFallback: "Qoder CN", brandAppDir: "/Applications/Qoder CN.app", surface: "app" };
300
+ const q = composeAgent({ name: "mcphost", title: null, version: "0.1.0" }, qoderLocal, null, { exec: fakeExec });
301
+ check("没报 title 时,父进程链认到的包名压过中间件的 name", q.brand === "Qoder CN", JSON.stringify(q));
302
+ check("品牌来自 .app 包时,版本读包的 Info.plist,不拿中间件的 0.1.0", q.version === "1.23.0", JSON.stringify(q));
303
+ check("中间件自报的原文照旧带上(tooltip 排查用)", q.name === "mcphost", JSON.stringify(q));
304
+
305
+ const traeLocal = { brandFallback: "Trae CN", brandAppDir: "/Applications/Trae CN.app", surface: "app" };
306
+ const t = composeAgent({ name: "Trae", title: null, version: "1.107.1" }, traeLocal, null, { exec: fakeExec });
307
+ check("Trae:品牌与版本都来自主包(3.3.83,不是 VS Code 的 1.107.1)", t.brand === "Trae CN" && t.version === "3.3.83", JSON.stringify(t));
308
+
309
+ const wbLocal = { brandFallback: "WorkBuddy", brandAppDir: "/Applications/WorkBuddy.app", surface: "app" };
310
+ const w = composeAgent({ name: "connector:custom-mcp:agent-in-chrome", title: null, version: "1.0.0" }, wbLocal, null, { exec: fakeExec });
311
+ check("WorkBuddy:品牌是包名;包版本读不到就不显示,不许拿代理的 1.0.0 顶上", w.brand === "WorkBuddy" && w.version === null, JSON.stringify(w));
312
+ check("带冒号的命名空间串判为不含身份", informativeName("connector:custom-mcp:x") === null);
313
+
314
+ const cli = composeAgent({ name: "mcphost", title: null, version: "0.1.0" }, { brandFallback: null, surface: "cli" }, null, { exec: fakeExec });
315
+ check("裸 CLI 场景 name 照常显示,版本同源", cli.brand === "mcphost" && cli.version === "0.1.0", JSON.stringify(cli));
316
+
317
+ const z = composeAgent({ name: "zc-mw", title: null, version: "9.9.9" }, { brandFallback: "ZCode", brandAppDir: null, surface: "app" }, null, { exec: fakeExec });
318
+ check("品牌来自裸进程名时不显示版本(不许拿中间件的错配)", z.brand === "ZCode" && z.version === null, JSON.stringify(z));
319
+
320
+ const cc = composeAgent({ name: "claude-code", title: "Claude Code", version: "2.1.227" }, { brandFallback: "claude", brandAppDir: "/x/claude.app", surface: "app" }, null, { exec: fakeExec });
321
+ check("有 title 时照旧 title + clientInfo.version", cc.brand === "Claude Code" && cc.version === "2.1.227", JSON.stringify(cc));
322
+
323
+ check("嵌套包认最外层:Helper (Plugin) 不是品牌", JSON.stringify(bundleMatch("/Applications/Trae CN.app/Contents/Frameworks/Trae CN Helper (Plugin).app/Contents/MacOS/Trae CN Helper (Plugin)")) === JSON.stringify({ name: "Trae CN", appDir: "/Applications/Trae CN.app" }));
324
+ }
325
+
326
+ console.log("\n\x1b[1m工作区的噪音过滤:客户端的管道工程不是项目\x1b[0m");
327
+ {
328
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "aic-noise-"));
329
+ const home = path.join(tmp, "home");
330
+ const plumbing = path.join(home, ".workbuddy", "logs", "mcp-runtime", "custom-mcp_agent-in-chrome-0b59ed7c");
331
+ fs.mkdirSync(plumbing, { recursive: true });
332
+ check("隐藏目录下的 cwd 不算工作区", readWorkspace(plumbing, { home, tmp: "/nope" }) === null);
333
+ const proj = path.join(home, "work", "shop-api");
334
+ fs.mkdirSync(proj, { recursive: true });
335
+ check("正常目录不受影响", readWorkspace(proj, { home, tmp: "/nope" })?.name === "shop-api");
336
+ check("临时目录下的 cwd 不算工作区", readWorkspace(path.join(tmp, "spawn-here"), { home, tmp }) === null);
337
+
338
+ const realRepo = path.join(home, "work", "shop-web");
339
+ fs.mkdirSync(path.join(realRepo, ".git"), { recursive: true });
340
+ const deep = path.join(realRepo, ".venv", "lib", "python3.11", "site-packages");
341
+ fs.mkdirSync(deep, { recursive: true });
342
+ check(
343
+ "cwd 埋在仓库的点目录里时报的是仓库,不是 null",
344
+ JSON.stringify(readWorkspace(deep, { home, tmp: "/nope" })) === JSON.stringify({ name: "shop-web", kind: "git" })
345
+ );
346
+
347
+ fs.rmSync(tmp, { recursive: true, force: true });
348
+ }
349
+
350
+ console.log("\n\x1b[1m整条取证路:注进假进程表跑一遍\x1b[0m");
351
+ {
352
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "aic-home2-"));
353
+ const repo = path.join(home, "work", "shop-api");
354
+ fs.mkdirSync(path.join(repo, ".git"), { recursive: true });
355
+ const sessions = path.join(home, ".claude", "sessions");
356
+ fs.mkdirSync(sessions, { recursive: true });
357
+ fs.writeFileSync(
358
+ path.join(sessions, "911.json"),
359
+ JSON.stringify({ pid: 911, cwd: repo, entrypoint: "claude-desktop", name: "shop-api-3f", nameSource: "derived" })
360
+ );
361
+
362
+ const local = probeLocal({
363
+ env: { CLAUDE_CODE_HOST_SESSION_ID: "local_zzz" },
364
+ cwd: "/",
365
+ ppid: 911,
366
+ self: SELF,
367
+ snap: CHAINS.claudeCodeDesktop,
368
+ home,
369
+ tmp: "/nope",
370
+ });
371
+ check("工作区来自客户端记的 cwd,不是它 spawn 我们时给的那个", local.workspace === "shop-api" && local.workspaceKind === "git", JSON.stringify(local));
372
+ check("形态认出来是桌面端", local.surface === "app", JSON.stringify(local));
373
+
374
+ fs.writeFileSync(path.join(sessions, "911.json"), JSON.stringify({ pid: 911, cwd: repo, entrypoint: "cli" }));
375
+ const local2 = probeLocal({ env: {}, cwd: "/", ppid: 911, self: SELF, snap: CHAINS.claudeCodeDesktop, home, tmp: "/nope" });
376
+ check("客户端自报 entrypoint=cli 时按 CLI 算", local2.surface === "cli", JSON.stringify(local2));
377
+
378
+ fs.rmSync(home, { recursive: true, force: true });
379
+ }
380
+
381
+ console.log("\n\x1b[1mZCode 的会话标题:_meta.session_id 精确归属\x1b[0m");
382
+ {
383
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "aic-zc-"));
384
+ fs.mkdirSync(path.join(home, ".zcode", "cli", "db"), { recursive: true });
385
+ fs.writeFileSync(path.join(home, ".zcode", "cli", "db", "db.sqlite"), "");
386
+ const SID = "sess_0a33b40d-8caa-431f-8d42-ca951e3366f4";
387
+ let asked = null;
388
+ const fakeExec = (bin, args) => {
389
+ asked = { bin, sql: args[args.length - 1] };
390
+ return "接管浏览器标签组并打开谷歌搜索\n";
391
+ };
392
+ const at = (meta, exec = fakeExec) => {
393
+ resetTitleMemo();
394
+ return readZcodeSessionTitle(meta, { home, exec, env: {} });
395
+ };
396
+
397
+ check("主会话:按 _meta.session_id 读它自己的标题", at({ session_id: SID, runtime_scope: "main" }) === "接管浏览器标签组并打开谷歌搜索");
398
+ check("查的是 session 表、只认 generated/custom", /from session where id='sess_0a33b40d/.test(asked?.sql || "") && /title_source in \('generated','custom'\)/.test(asked?.sql || ""), asked?.sql);
399
+ check("走的是系统自带 sqlite3 的只读模式", asked?.bin === "/usr/bin/sqlite3");
400
+ check("没给 runtime_scope 也认(老版本客户端)", at({ session_id: SID }) === "接管浏览器标签组并打开谷歌搜索");
401
+ const SUB = "sess_subagent_agent_a1100314-0000-4000-8000-000000000000";
402
+ check("subagent 的调用报的是主会话的名字", at({ session_id: SUB, runtime_scope: "subagent" }) === "接管浏览器标签组并打开谷歌搜索");
403
+ check(
404
+ "subagent 走的是 parent_id 那一跳,不读它自己那行的 first_input",
405
+ /where id=\(select parent_id from session where id='sess_subagent_agent_a1100314/.test(asked?.sql || "") &&
406
+ /title_source in \('generated','custom'\)/.test(asked?.sql || ""),
407
+ asked?.sql
408
+ );
409
+ check(
410
+ "subagent 的 id 形状也要卡死(它同样直接拼进 SQL)",
411
+ readZcodeSessionTitle(
412
+ { session_id: "sess_subagent_agent_a1100314-0000-4000-8000-000000000000' or '1'='1" },
413
+ { home, env: {}, exec: () => { throw new Error("绝不该拿注入载荷去查库"); } }
414
+ ) === null
415
+ );
416
+ check("形状不对的 id 一律不拼进 SQL", at({ session_id: "sess_'; drop table session; --" }) === null);
417
+ for (const bad of [
418
+ "sess_0a33b40d-8caa-431f-8d42-ca951e3366f4'",
419
+ "sess_0a33b40d-8caa-431f-8d42-ca951e3366f4' or '1'='1",
420
+ "sess_0a33b40d-8caa-431f-8d42-ca951e3366f4'--",
421
+ "sess_0a33b40d-8caa-431f-8d42-ca951e3366f4 union select 1",
422
+ "sess_0a33b40d%2d8caa",
423
+ ]) {
424
+ check(`注入载荷被正则拦下,绝不起 sqlite3:${bad.slice(30) || bad}`,
425
+ readZcodeSessionTitle({ session_id: bad }, { home, env: {}, exec: () => { throw new Error("绝不该拿注入载荷去查库"); } }) === null);
426
+ }
427
+ check("别家客户端的 _meta(没有 session_id)不认", at({ progressToken: 1 }) === null);
428
+ check("没有 _meta 也不能抛", at(null) === null && at(undefined) === null);
429
+ check("库读不动就不显示,不许编", at({ session_id: SID }, () => { throw new Error("locked"); }) === null);
430
+ check("标题还没生成(查出来是空)就是没有", at({ session_id: SID }, () => "\n") === null);
431
+
432
+ resetTitleMemo();
433
+ let calls = 0;
434
+ const counting = () => { calls++; return "标题\n"; };
435
+ readZcodeSessionTitle({ session_id: SID }, { home, env: {}, exec: counting });
436
+ readZcodeSessionTitle({ session_id: SID }, { home, env: {}, exec: counting });
437
+ readZcodeSessionTitle({ session_id: SID }, { home, env: {}, exec: counting });
438
+ check("查到过的标题记住,不再重复起 sqlite3", calls === 1, `起了 ${calls} 次`);
439
+
440
+ const bare = fs.mkdtempSync(path.join(os.tmpdir(), "aic-zc0-"));
441
+ check("本机没装 ZCode 就直接不查", readZcodeSessionTitle({ session_id: SID }, { home: bare, env: {}, exec: () => { throw new Error("不该被调用"); } }) === null);
442
+ fs.rmSync(home, { recursive: true, force: true });
443
+ fs.rmSync(bare, { recursive: true, force: true });
444
+ }
445
+
446
+ console.log("\n\x1b[1m数据目录:先问客户端自己(--user-data-dir),再退到包里的 product.json\x1b[0m");
447
+ {
448
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "aic-dd-"));
449
+ const apps = path.join(home, "Applications");
450
+ const mkApp = (bundleName, product, dataName) => {
451
+ const b = path.join(apps, `${bundleName}.app`);
452
+ fs.mkdirSync(path.join(b, "Contents", "Resources", "app"), { recursive: true });
453
+ fs.writeFileSync(path.join(b, "Contents", "Resources", "app", "product.json"), JSON.stringify(product));
454
+ if (dataName) fs.mkdirSync(path.join(home, "Library", "Application Support", dataName, "logs"), { recursive: true });
455
+ return b;
456
+ };
457
+ const cn = mkApp("Trae CN", { applicationName: "trae-cn", nameLong: "Trae CN" }, "Trae CN");
458
+ const intl = mkApp("Trae", { applicationName: "trae", nameLong: "Trae" }, "Trae");
459
+ const qoder = mkApp("Qoder CN", { applicationName: "qoder-cn", nameLong: "Qoder CN" }, "Qoder CN");
460
+ const fresh = mkApp("Trae Fresh", { applicationName: "trae", nameLong: "Trae Fresh" }, null);
461
+ const renamed = mkApp("我的Trae", { applicationName: "trae-cn", nameLong: "Trae CN" }, "Trae CN");
462
+
463
+ const at = (o) => traeDataDir({ home, env: {}, ...o });
464
+
465
+ {
466
+ const DATA = path.join(home, "Library", "Application Support", "Trae CN");
467
+ const snapOf = (m) => ({ get: (pid) => m[pid] || null });
468
+ const helper = `/Applications/Trae CN.app/Contents/Frameworks/Trae CN Helper (Plugin).app/Contents/MacOS/Trae CN Helper (Plugin) --type=utility --user-data-dir=${DATA} --standard-schemes=vscode-webview --enable-sandbox`;
469
+ const snap = snapOf({
470
+ 100: { ppid: 101, tty: "??", command: "node /x/server.mjs" },
471
+ 101: { ppid: 102, tty: "??", command: helper },
472
+ 102: { ppid: 1, tty: "??", command: "/Applications/Trae CN.app/Contents/MacOS/Electron" },
473
+ });
474
+ check("从进程链上取到 --user-data-dir(路径里有空格也要完整)", userDataDirFrom(100, snap, { fs }) === DATA);
475
+ check("它就是数据目录,不用再去 /Applications 推", at({ userDataDir: userDataDirFrom(100, snap, { fs }) }) === DATA);
476
+ const tail = snapOf({ 100: { ppid: 1, tty: "??", command: `/x/Electron --type=utility --user-data-dir=${DATA}` } });
477
+ check("--user-data-dir 在行尾也切得对", userDataDirFrom(100, tail, { fs }) === DATA);
478
+ const bad = snapOf({ 100: { ppid: 1, tty: "??", command: "/x/Electron --user-data-dir=/tmp/根本没有这个目录 --foo" } });
479
+ check("写了开关但值对不上真实目录 → null(不半路猜)", userDataDirFrom(100, bad, { fs }) === null);
480
+ const rel = snapOf({ 100: { ppid: 1, tty: "??", command: "/x/Electron --user-data-dir=relative/path --foo" } });
481
+ check("非绝对路径不认", userDataDirFrom(100, rel, { fs }) === null);
482
+ check("链上没这个开关就是 null", userDataDirFrom(100, snapOf({ 100: { ppid: 1, tty: "??", command: "/x/zcode-cli" } }), { fs }) === null);
483
+ check("ps 不可用(snap 全空)不抛", userDataDirFrom(100, snapOf({}), { fs }) === null);
484
+ check(
485
+ "有 --user-data-dir 时优先于按包推(包指向另一家也不受影响)",
486
+ traeDataDir({ home, env: {}, userDataDir: DATA, appDir: qoder }) === DATA
487
+ );
488
+ }
489
+ check("按包里的 product.json 算出数据目录", at({ appDir: cn }) === path.join(home, "Library", "Application Support", "Trae CN"));
490
+ check("国际版算到国际版那个目录", at({ appDir: intl }) === path.join(home, "Library", "Application Support", "Trae"));
491
+ check("别家的 VS Code 分支(有 product.json)不许当成 Trae", at({ appDir: qoder }) === null);
492
+ check("包名被用户改过也认得(认 product.json,不认文件名)", at({ appDir: renamed }) === path.join(home, "Library", "Application Support", "Trae CN"));
493
+ check("算出来的目录不存在就是没有(不许退回去猜别的)", at({ appDir: fresh }) === null);
494
+ check("不是 .app、或者根本没有包 → null", at({ appDir: "/tmp/x" }) === null && at({}) === null);
495
+ check("没有 product.json 的包(不是 VS Code 系)→ null", at({ appDir: path.join(apps, "无此.app") }) === null);
496
+ check(
497
+ "ps 不可用时退回我们自己 env 里的 RG_PATH(Trae spawn 时带的)",
498
+ at({ env: { RG_PATH: path.join(cn, "Contents/Resources/app/node_modules/@vscode/ripgrep/bin/rg") } }) ===
499
+ path.join(home, "Library", "Application Support", "Trae CN")
500
+ );
501
+ check("RG_PATH 指向别家的包也不认", at({ env: { RG_PATH: path.join(qoder, "Contents/Resources/app/x/rg") } }) === null);
502
+ check(
503
+ "进程链认到的是别家的包时,不就此放弃,还有 env 里的 RG_PATH 这条独立证据",
504
+ at({ appDir: qoder, env: { RG_PATH: path.join(cn, "Contents/Resources/app/x/rg") } }) ===
505
+ path.join(home, "Library", "Application Support", "Trae CN")
506
+ );
507
+ check("两条证据都不指向 Trae 就是 null", at({ appDir: qoder, env: { RG_PATH: path.join(qoder, "x/rg") } }) === null);
508
+ check("nameLong 里带路径分隔符不许拼进路径", at({ appDir: mkApp("坏", { applicationName: "trae", nameLong: "../../../etc" }, null) }) === null);
509
+
510
+ check("ZCode 默认是 $HOME/.zcode", zcodeDataDir({ env: {}, home }) === path.join(home, ".zcode"));
511
+ check("ZCode 认 ZCODE_DATA_BASE_DIR 覆盖(写死路径会读到另一个安装的库)", zcodeDataDir({ env: { ZCODE_DATA_BASE_DIR: "/tmp/zz" }, home }) === path.join("/tmp/zz", ".zcode"));
512
+ check("ZCODE_DATA_BASE_DIR 是空白串时按没设算", zcodeDataDir({ env: { ZCODE_DATA_BASE_DIR: " " }, home }) === path.join(home, ".zcode"));
513
+ fs.rmSync(home, { recursive: true, force: true });
514
+ }
515
+
516
+ console.log("\n\x1b[1mTrae 的会话标题:chatSessionId 自己说了该去哪个文件的哪一段找\x1b[0m");
517
+ {
518
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "aic-trae-"));
519
+ const AT = (iso) => Date.parse(iso);
520
+ const objectId = (ms, tail) => Math.floor(ms / 1000).toString(16).padStart(8, "0") + tail;
521
+ const RUN1 = AT("2026-08-13T15:10:39+08:00");
522
+ const RUN2 = AT("2026-08-13T16:56:56+08:00");
523
+ const A_AT = AT("2026-08-13T17:00:00+08:00");
524
+ const B_AT = AT("2026-08-13T15:13:37+08:00");
525
+ const ID_A = objectId(A_AT, "8dd5dc6e3bd60c6c");
526
+ const ID_B = objectId(B_AT, "8dd5dc6e3bd60be4");
527
+
528
+ const stamp = (ms) => new Date(ms + 8 * 3600e3).toISOString().replace(/[-:]/g, "").slice(0, 15);
529
+ const at = (ms) => new Date(ms + 8 * 3600e3).toISOString().replace("Z", "+08:00");
530
+ const noise = (ms, n, step = 10) => Array.from({ length: n }, (_, i) => `${at(ms + i * step)} INFO 无关的日志行 ${"x".repeat(200)}`).join("\n") + "\n";
531
+ const titleLine = (ms, id, t) =>
532
+ `${at(ms)} INFO generate_session_title_and_icon: ai_agent::domain::chat::service: ` +
533
+ `rust: generate_session_title_and_icon_cloud: session_id: "${id}", title: "${t}", icon: "personal"\n`;
534
+ const DATA = path.join(home, "Library", "Application Support", "Trae CN");
535
+ const OTHER = path.join(home, "Library", "Application Support", "Trae");
536
+ const mk = (dataDir, runMs, body) => {
537
+ const d = path.join(dataDir, "logs", stamp(runMs), "Modular");
538
+ fs.mkdirSync(d, { recursive: true });
539
+ fs.writeFileSync(path.join(d, `ai-agent_0_${runMs}_stdout.log`), body);
540
+ };
541
+ mk(DATA, RUN1, noise(RUN1, 8000, Math.floor((B_AT - RUN1) / 8000)) + titleLine(B_AT + 5000, ID_B, "第一次生成的") + titleLine(B_AT + 9000, ID_B, "查询杭州天气") + noise(B_AT + 10000, 4000));
542
+ mk(DATA, RUN2, noise(RUN2, 500) + titleLine(A_AT + 37000, ID_A, "查询杭州天气及预警") + noise(A_AT + 40000, 200));
543
+ mk(OTHER, AT("2026-08-13T16:00:00+08:00"), titleLine(A_AT + 37000, ID_A, "串到国际版去了"));
544
+
545
+ const read = (meta, dataDir = DATA) => {
546
+ resetTitleMemo();
547
+ return readTraeSessionTitle(meta, { dataDir });
548
+ };
549
+
550
+ check("按 chatSessionId 读到标题", read({ chatSessionId: ID_A, isCurrentSession: true }) === "查询杭州天气及预警");
551
+ check("同一会话被生成多次时取最后一条", read({ chatSessionId: ID_B }) === "查询杭州天气");
552
+ check("会话落在哪次运行是算出来的:B 在 run1,不去 run2 找", read({ chatSessionId: ID_B }) === "查询杭州天气");
553
+ check("只读给定的那个数据目录,串不到另一家去", read({ chatSessionId: ID_A }) === "查询杭州天气及预警");
554
+ check("给的是另一家的目录就读另一家的(说明真的按目录走)", read({ chatSessionId: ID_A }, OTHER) === "串到国际版去了");
555
+ check("拿不到数据目录时一个字节都不读", read({ chatSessionId: ID_A }, null) === null);
556
+
557
+ {
558
+ resetTitleMemo();
559
+ let bytes = 0;
560
+ const counting = { ...fs, readSync: (...a) => { const n = fs.readSync(...a); bytes += n; return n; } };
561
+ const f = path.join(DATA, "logs", stamp(RUN1), "Modular", `ai-agent_0_${RUN1}_stdout.log`);
562
+ const total = fs.statSync(f).size;
563
+ readTraeSessionTitle({ chatSessionId: ID_B }, { dataDir: DATA, fs: counting });
564
+ check(`二分到创建时刻再往后扫,不是整文件翻一遍(读了 ${bytes} / ${total} 字节)`, bytes < total * 0.5, `${bytes}/${total}`);
565
+ }
566
+
567
+ check("日志里没有这段会话就是没有(不许拿最近一条顶上)", read({ chatSessionId: objectId(A_AT, "ffffffffffffffff") }) === null);
568
+ check("比现存日志都早的会话找不回来,也不许乱认", read({ chatSessionId: objectId(AT("2020-01-01T00:00:00+08:00"), "aaaaaaaaaaaaaaaa") }) === null);
569
+ check("侧边栏那种非当前会话不许盖掉主会话的名字", read({ chatSessionId: ID_A, isCurrentSession: false }) === null);
570
+ check("形状不对的 id 一律不查", read({ chatSessionId: "../../etc/passwd" }) === null && read({ chatSessionId: "6a7d7ebd" }) === null);
571
+ check("别家客户端的 _meta(没有 chatSessionId)不认", read({ session_id: "sess_x" }) === null);
572
+ check("没有 _meta 也不能抛", read(null) === null && read(undefined) === null);
573
+ check("查到过就不再读盘(这函数在每帧的刷新路径上)", (() => {
574
+ resetTitleMemo();
575
+ let opens = 0;
576
+ const counting = { ...fs, openSync: (...a) => { opens++; return fs.openSync(...a); } };
577
+ for (let i = 0; i < 3; i++) readTraeSessionTitle({ chatSessionId: ID_A }, { dataDir: DATA, fs: counting });
578
+ return opens === 1;
579
+ })());
580
+ check("记忆化按数据目录分开记(同一个 id 在两家目录下是两回事)", (() => {
581
+ resetTitleMemo();
582
+ return readTraeSessionTitle({ chatSessionId: ID_A }, { dataDir: DATA }) === "查询杭州天气及预警" &&
583
+ readTraeSessionTitle({ chatSessionId: ID_A }, { dataDir: OTHER }) === "串到国际版去了";
584
+ })());
585
+ fs.rmSync(home, { recursive: true, force: true });
586
+ }
587
+
588
+ console.log("\n\x1b[1m标题的取用顺序:先协议级(_meta),后本机取证\x1b[0m");
589
+ {
590
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "aic-ord-"));
591
+ fs.mkdirSync(path.join(home, ".zcode", "cli", "db"), { recursive: true });
592
+ fs.writeFileSync(path.join(home, ".zcode", "cli", "db", "db.sqlite"), "");
593
+ fs.mkdirSync(path.join(home, ".claude", "sessions"), { recursive: true });
594
+ fs.writeFileSync(
595
+ path.join(home, ".claude", "sessions", "7003.json"),
596
+ JSON.stringify({ pid: 7003, sessionId: "s", name: "本机取证认到的名字", nameSource: "generated" })
597
+ );
598
+ const local = { clientPid: 7003, hostSessionId: null, sessionName: null };
599
+ const exec = () => "协议级认到的名字\n";
600
+ resetTitleMemo();
601
+ check(
602
+ "_meta 报了会话身份时,用它,不用本机取证那条",
603
+ readSessionTitle(local, { home, exec, meta: { session_id: "sess_0a33b40d-8caa-431f-8d42-ca951e3366f4" } }) === "协议级认到的名字"
604
+ );
605
+ resetTitleMemo();
606
+ check("没有 _meta 的客户端行为一字不变", readSessionTitle(local, { home, exec: () => { throw new Error("不该查库"); } }) === "本机取证认到的名字");
607
+ resetTitleMemo();
608
+ check(
609
+ "Qoder 那种一个 _meta 字段都不发的,走回原来的路(不猜)",
610
+ readSessionTitle(local, { home, exec: () => { throw new Error("不该查库"); }, meta: { progressToken: 1 } }) === "本机取证认到的名字"
611
+ );
612
+ fs.rmSync(home, { recursive: true, force: true });
613
+ }
614
+
615
+ console.log("\n\x1b[1mbin shim:node …/node_modules/.bin/<名> 的 CLI 认得出品牌\x1b[0m");
616
+ {
617
+ check("dsh 的 npx 启动串认出「dsh」", binShimName("node /Users/u/.npm/_npx/1e7f/node_modules/.bin/dsh web") === "dsh");
618
+ check("Windows 的 .cmd shim 去掉扩展名", binShimName("node C:\\u\\node_modules\\.bin\\dsh.cmd web") === "dsh");
619
+ check("shim 名撞上运行时名单(node)不算品牌", binShimName("node /a/node_modules/.bin/node x") === null);
620
+ check("不在 node_modules/.bin 下的脚本不认(内部管道不是品牌)", binShimName("node /a/daemon-app-server-entry.js --stdio") === null);
621
+ check("裸 bin 目录(~/.nvm/…/bin/claude)不走这条", binShimName("/Users/u/.nvm/versions/node/v24.11.1/bin/claude") === null);
622
+
623
+ const snap = new Map([
624
+ [800, { ppid: 801, tty: "??", command: "node /Users/u/.agent-in-chrome/agent-in-chrome/server.mjs" }],
625
+ [801, { ppid: 802, tty: "ttys002", command: "node /Users/u/.npm/_npx/1e7f/node_modules/.bin/dsh web" }],
626
+ ]);
627
+ const walked = walkSurface(801, snap);
628
+ check("dsh 链:形态是 CLI,品牌从 shim 认出「dsh」", walked.surface === "cli" && walked.brand === "dsh", JSON.stringify(walked));
629
+ const agent = composeAgent(
630
+ { name: "dsh-mcp-client", title: null, version: "0.0.1" },
631
+ { brandFallback: walked.brand, brandAppDir: null, surface: walked.surface, workspace: null, workspaceKind: null },
632
+ null
633
+ );
634
+ check("品牌是链上的「dsh」,不是中间件自报的 dsh-mcp-client", agent.brand === "dsh", JSON.stringify(agent));
635
+ check("版本不许拿中间件的 0.0.1 顶上(品牌与版本必须同源)", agent.version === null, JSON.stringify(agent));
636
+ }
637
+
638
+ console.log("\n\x1b[1mDeepSeek Harness:会话归属与标题/工作区\x1b[0m");
639
+ if (typeof zlib.zstdCompressSync !== "function") {
640
+ console.log(" \x1b[90m·\x1b[0m 这个 Node 没有 zstd(<22.15),跳过 dsh 会话用例;decodeZstdFrames 应答 null 而不是抛");
641
+ check("没有 zstd 时 decodeZstdFrames 返回 null", decodeZstdFrames(Buffer.from("x")) === null);
642
+ } else {
643
+ const DSH_CMD = "node /Users/u/.npm/_npx/1e7f/node_modules/.bin/dsh web";
644
+ const localFor = (cmd = DSH_CMD) => ({ clientCommand: cmd, clientPid: 1, hostSessionId: null, sessionName: null });
645
+ const frames = (lines) => Buffer.concat(lines.map((l) => zlib.zstdCompressSync(Buffer.from(l + "\n"))));
646
+ const ev = (o) => JSON.stringify(o);
647
+
648
+ const makeDshHome = (sessions) => {
649
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "aic-dsh-"));
650
+ for (const s of sessions) {
651
+ const dir = path.join(home, ".dsh", "sessions", "--proj--", s.id);
652
+ fs.mkdirSync(dir, { recursive: true });
653
+ const lines = [ev({ type: "session", version: 0, id: s.id, createdAt: 1, cwd: s.cwd, delegationDepth: 0 })];
654
+ let seq = 10;
655
+ for (const [kind, title] of s.titles || []) lines.push(ev({ type: "session/title", seq: seq++, data: { title, source: { kind } } }));
656
+ const f = path.join(dir, "session.jsonl.zstd");
657
+ fs.writeFileSync(f, frames(lines));
658
+ if (s.ageMs) {
659
+ const t = new Date(Date.now() - s.ageMs);
660
+ fs.utimesSync(f, t, t);
661
+ }
662
+ }
663
+ return home;
664
+ };
665
+
666
+ check("isDshClient 认 npx/pnpm 的 bin shim", isDshClient(DSH_CMD));
667
+ check("isDshClient 认包路径(全局装的形态)", isDshClient("node /usr/lib/node_modules/@deepseek-ai/dsh/lib/bin.js web"));
668
+ check("别家的 node 进程不算 dsh", !isDshClient("node /Users/u/.workbuddy/daemon-app-server-entry.js"));
669
+
670
+ {
671
+ const parts = frames(['{"a":1}', '{"b":2}', '{"c":3}']);
672
+ const out = decodeZstdFrames(parts);
673
+ check("多帧拼接的 zstd 逐帧全解开(dsh 的日志就是这个形状)", out === '{"a":1}\n{"b":2}\n{"c":3}\n', JSON.stringify(out));
674
+ }
675
+
676
+ {
677
+ const home = makeDshHome([
678
+ { id: "session-11111111-1111-1111-1111-111111111111", cwd: "/Users/u/proj-a", titles: [["fallback", "你好"], ["provider", "调研杭州天气"]] },
679
+ ]);
680
+ resetTitleMemo();
681
+ const s = readDshSession(localFor(), { home });
682
+ check("一个活跃会话:归属成立,标题是 LLM 生成的那条", s?.title === "调研杭州天气", JSON.stringify(s));
683
+ check("cwd 来自会话日志的 header", s?.cwd === "/Users/u/proj-a", JSON.stringify(s));
684
+ resetTitleMemo();
685
+ check("拉起我们的不是 dsh 时一个字都不读", readDshSession(localFor("node /a/other.js"), { home }) === null);
686
+ fs.rmSync(home, { recursive: true, force: true });
687
+ }
688
+
689
+ {
690
+ const home = makeDshHome([
691
+ { id: "session-22222222-2222-2222-2222-222222222222", cwd: "/Users/u/proj-b", titles: [["fallback", "帮我看看这个"]] },
692
+ ]);
693
+ resetTitleMemo();
694
+ const s = readDshSession(localFor(), { home });
695
+ check("fallback 标题不显示(同 ZCode 拒 first_input 的理由)", s !== null && s.title === null, JSON.stringify(s));
696
+ check("标题缺席不拖累 cwd", s?.cwd === "/Users/u/proj-b", JSON.stringify(s));
697
+ fs.rmSync(home, { recursive: true, force: true });
698
+ }
699
+
700
+ {
701
+ const home = makeDshHome([
702
+ { id: "session-33333333-3333-3333-3333-333333333333", cwd: "/x", titles: [["provider", "自动名"], ["user", "我改的名"]] },
703
+ ]);
704
+ resetTitleMemo();
705
+ check("用户改名后取最后一条", readDshSession(localFor(), { home })?.title === "我改的名");
706
+ fs.rmSync(home, { recursive: true, force: true });
707
+ }
708
+
709
+ {
710
+ const home = makeDshHome([
711
+ { id: "session-44444444-4444-4444-4444-444444444444", cwd: "/x", titles: [["provider", "甲"]] },
712
+ { id: "session-55555555-5555-5555-5555-555555555555", cwd: "/y", titles: [["provider", "乙"]] },
713
+ ]);
714
+ resetTitleMemo();
715
+ check("两个活跃会话:null,不猜", readDshSession(localFor(), { home }) === null);
716
+ fs.rmSync(home, { recursive: true, force: true });
717
+ }
718
+
719
+ {
720
+ const home = makeDshHome([
721
+ { id: "session-66666666-6666-6666-6666-666666666666", cwd: "/x", titles: [["provider", "活的"]] },
722
+ { id: "session-77777777-7777-7777-7777-777777777777", cwd: "/y", titles: [["provider", "冷的"]], ageMs: 20 * 60_000 },
723
+ ]);
724
+ resetTitleMemo();
725
+ check("超出活跃窗口的旧会话不算,归属落在活的那个", readDshSession(localFor(), { home })?.title === "活的");
726
+ fs.rmSync(home, { recursive: true, force: true });
727
+ }
728
+
729
+ {
730
+ const home = makeDshHome([]);
731
+ const proj = path.join(home, "repos", "my-cool-repo");
732
+ fs.mkdirSync(path.join(proj, ".git"), { recursive: true });
733
+ const dir = path.join(home, ".dsh", "sessions", "--proj--", "session-88888888-8888-8888-8888-888888888888");
734
+ fs.mkdirSync(dir, { recursive: true });
735
+ fs.writeFileSync(
736
+ path.join(dir, "session.jsonl.zstd"),
737
+ frames([ev({ type: "session", version: 0, id: "s", createdAt: 1, cwd: proj, delegationDepth: 0 }), ev({ type: "session/title", seq: 10, data: { title: "改注册器", source: { kind: "provider" } } })])
738
+ );
739
+ resetTitleMemo();
740
+ const idn = readSessionIdentity(localFor(), { home, tmp: path.join(home, "unused-tmp") });
741
+ check("标题与工作区同源于同一段会话", idn.title === "改注册器" && idn.workspace === "my-cool-repo" && idn.workspaceKind === "git", JSON.stringify(idn));
742
+ resetTitleMemo();
743
+ const other = readSessionIdentity({ clientCommand: "node /a/b.js", clientPid: 1, hostSessionId: null, sessionName: null }, { home });
744
+ check("非 dsh 客户端走 readSessionIdentity 行为不变(工作区不盖)", other.title === null && other.workspace === null, JSON.stringify(other));
745
+ fs.rmSync(home, { recursive: true, force: true });
746
+ }
747
+ }
748
+
749
+ console.log("\n\x1b[1mAntigravity:数据目录自报 + 会话库里的工作区\x1b[0m");
750
+ {
751
+ const ID = "cd33cae1-3e75-4d59-baa4-92ca4e29df69";
752
+ const AG_CMD =
753
+ "/Applications/Antigravity.app/Contents/Resources/app/extensions/antigravity/bin/language_server_macos_arm --app_data_dir antigravity-ide --enable_lsp";
754
+ const localFor = (cmd = AG_CMD) => ({ clientCommand: cmd, clientPid: 1, hostSessionId: null, sessionName: null });
755
+ const metaFor = (id = ID) => ({ "antigravity.google/conversation_id": id, progressToken: "p1" });
756
+ const geminiDir = (name) => path.join("/h", ".gemini", name);
757
+
758
+ check("--app_data_dir 自报的名字算数(同 --user-data-dir 那条证据链)", antigravityDataDir(AG_CMD, { home: "/h" }) === geminiDir("antigravity-ide"));
759
+ check("等号写法一样认", antigravityDataDir("x --app_data_dir=ag-next", { home: "/h" }) === geminiDir("ag-next"));
760
+ check("没报就退到真机见过的那个名字", antigravityDataDir("node /a/b.js", { home: "/h" }) === geminiDir("antigravity-ide"));
761
+ check("--app_data_dir .. 跳不出 ~/.gemini", antigravityDataDir("x --app_data_dir ..", { home: "/h" }) === geminiDir("antigravity-ide"));
762
+ check("--app_data_dir . 也不认", antigravityDataDir("x --app_data_dir .", { home: "/h" }) === geminiDir("antigravity-ide"));
763
+ check("名字里夹着 .. 一样不认", antigravityDataDir("x --app_data_dir a..b", { home: "/h" }) === geminiDir("antigravity-ide"));
764
+
765
+ check("会话 id 只认 UUID 形状", antigravityConversationId({ "antigravity.google/conversation_id": ID }) === ID);
766
+ check("会话 id 两头的空白不算差异(sid 那一路和这一路要给同一个答案)", antigravityConversationId({ "antigravity.google/conversation_id": ` ${ID}\n` }) === ID);
767
+ check("带路径分隔的 id 一概不收", antigravityConversationId({ "antigravity.google/conversation_id": "../../etc/passwd" }) === null);
768
+
769
+ const agHome = () => {
770
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "aic-ag-"));
771
+ fs.mkdirSync(path.join(home, ".gemini", "antigravity-ide", "conversations"), { recursive: true });
772
+ return home;
773
+ };
774
+ const pbVarint = (n) => {
775
+ const out = [];
776
+ do {
777
+ const b = n & 0x7f;
778
+ n = Math.floor(n / 128);
779
+ out.push(n ? b | 0x80 : b);
780
+ } while (n);
781
+ return Buffer.from(out);
782
+ };
783
+ const pbStr = (field, s) => Buffer.concat([pbVarint((field << 3) | 2), pbVarint(Buffer.byteLength(s)), Buffer.from(s, "utf8")]);
784
+ const agBytes = (id, uri, { tail = Buffer.from([0x7a, 0xa8, 0x03]), decoys = true } = {}) =>
785
+ Buffer.concat([
786
+ Buffer.from([0x1a, 0x24]),
787
+ Buffer.from("b24f57a3-74f6-489c-abb5-f150d1d66ea1"),
788
+ decoys ? Buffer.concat([pbStr(6, id), pbStr(26, "\u0012")]) : Buffer.alloc(0),
789
+ pbStr(6, id),
790
+ pbStr(7, `file://${uri}`),
791
+ tail,
792
+ ]);
793
+ const writeRaw = (home, name, buf) => fs.writeFileSync(path.join(home, ".gemini", "antigravity-ide", "conversations", name), buf);
794
+ const homeWith = (uri, { name = `${ID}.db`, ...opts } = {}) => {
795
+ const home = agHome();
796
+ writeRaw(home, name, agBytes(ID, uri, opts));
797
+ return home;
798
+ };
799
+ const wsOf = (home, meta = metaFor()) => {
800
+ resetTitleMemo();
801
+ return readAntigravityWorkspace(meta, localFor(), { home });
802
+ };
803
+
804
+ {
805
+ const proj = "/Users/u/PycharmProjects/onework-demo-self";
806
+ const home = homeWith(proj);
807
+ const dir = wsOf(home);
808
+ check("按长度前缀精确取:路径不必存在也认得出", dir === proj, String(dir));
809
+ check("id 出现多次时只认后面跟着 file:// 的那一处", !String(dir).includes("\u0012"), String(dir));
810
+ check("别的会话 id 不认(锚定 id 才躲得开库里提示词文本中的 file://)", wsOf(home, metaFor("11111111-2222-3333-4444-555555555555")) === null);
811
+ fs.rmSync(home, { recursive: true, force: true });
812
+ }
813
+
814
+ {
815
+ const home = agHome();
816
+ const proj = "/Users/u/repos/wal-only";
817
+ writeRaw(home, `${ID}.db`, Buffer.from("别的内容,没有那个字段"));
818
+ writeRaw(home, `${ID}.db-wal`, agBytes(ID, proj));
819
+ check("主库里没有就接着扫 -wal", wsOf(home) === proj);
820
+ fs.rmSync(home, { recursive: true, force: true });
821
+ }
822
+
823
+ {
824
+ const proj = "/Users/u/repos/ag-tail";
825
+ const home = homeWith(proj, { tail: Buffer.from("zabcdefghij", "latin1") });
826
+ check("尾巴接 11 个都在 URI 字符集里的字节,取出来仍然精确", wsOf(home) === proj, String(wsOf(home)));
827
+ fs.rmSync(home, { recursive: true, force: true });
828
+ }
829
+
830
+ {
831
+ const proj = "/Users/u/" + "a".repeat(200);
832
+ const home = homeWith(proj);
833
+ check("多字节 varint 长度(>127)读得对", wsOf(home) === proj);
834
+ fs.rmSync(home, { recursive: true, force: true });
835
+ }
836
+
837
+ {
838
+ const proj = "/Users/u/项目/我的仓库";
839
+ const home = homeWith(proj);
840
+ check("中文目录名不糊(按 utf8 解)", wsOf(home) === proj, String(wsOf(home)));
841
+ fs.rmSync(home, { recursive: true, force: true });
842
+ }
843
+
844
+ {
845
+ const proj = "/Users/u/repos/my proj (v2),a'b";
846
+ const home = homeWith(proj.replace(/ /g, "%20"));
847
+ check("空格转义与 ' , ( ) 原文都还原得回来", wsOf(home) === proj, String(wsOf(home)));
848
+ fs.rmSync(home, { recursive: true, force: true });
849
+ }
850
+
851
+ {
852
+ const raw = "/Users/u/repos/decode-fail%zz";
853
+ const home = homeWith(raw);
854
+ check("decodeURIComponent 抛了就用原文,不吞掉整条路", wsOf(home) === raw, String(wsOf(home)));
855
+ fs.rmSync(home, { recursive: true, force: true });
856
+ }
857
+
858
+ {
859
+ for (const [label, uri, want] of [
860
+ ["file:///C:/…", "/C:/Users/u/repo", "C:/Users/u/repo"],
861
+ ["file:///c%3A/…", "/c%3A/Users/u/repo", "c:/Users/u/repo"],
862
+ ]) {
863
+ const home = homeWith(uri);
864
+ const d = wsOf(home);
865
+ check(`${label}:盘符归一,绝不会变成 /C`, d !== "/C" && d === (process.platform === "win32" ? want : null), String(d));
866
+ fs.rmSync(home, { recursive: true, force: true });
867
+ }
868
+ }
869
+
870
+ {
871
+ const home = homeWith("not/absolute/half");
872
+ check("相对路径直接拒收,不交给 readWorkspace", wsOf(home) === null);
873
+ fs.rmSync(home, { recursive: true, force: true });
874
+ }
875
+
876
+ {
877
+ const home = agHome();
878
+ writeRaw(
879
+ home,
880
+ `${ID}.db`,
881
+ Buffer.concat([
882
+ pbVarint((6 << 3) | 2),
883
+ pbVarint(ID.length),
884
+ Buffer.from(ID),
885
+ pbVarint((7 << 3) | 2),
886
+ Buffer.from([0x80, 0x80, 0x80, 0x80, 0x80]),
887
+ Buffer.from("file:///Users/u/repos/varint-broken"),
888
+ Buffer.from([0x7a]),
889
+ ])
890
+ );
891
+ check("长度 varint 坏掉:null,不猜", wsOf(home) === null, String(wsOf(home)));
892
+ fs.rmSync(home, { recursive: true, force: true });
893
+ }
894
+
895
+ {
896
+ const home = agHome();
897
+ writeRaw(
898
+ home,
899
+ `${ID}.db`,
900
+ Buffer.concat([
901
+ pbVarint((6 << 3) | 2),
902
+ pbVarint(ID.length),
903
+ Buffer.from(ID),
904
+ pbVarint((7 << 3) | 2),
905
+ pbVarint(4000),
906
+ Buffer.from("file:///Users/u/repos/len-overflow"),
907
+ ])
908
+ );
909
+ check("长度越界:null,不按剩下的字节凑一条", wsOf(home) === null, String(wsOf(home)));
910
+ fs.rmSync(home, { recursive: true, force: true });
911
+ }
912
+
913
+ {
914
+ const home = homeWith("/Users/u/" + "b".repeat(5000));
915
+ check("URI 超 4096 不收", wsOf(home) === null);
916
+ fs.rmSync(home, { recursive: true, force: true });
917
+ }
918
+
919
+ {
920
+ let reads = 0;
921
+ const bigFs = {
922
+ statSync: () => ({ size: 300 * 1024 * 1024 }),
923
+ readFileSync: () => {
924
+ reads++;
925
+ throw new Error("不该读:这份库超上限了");
926
+ },
927
+ existsSync: () => false,
928
+ };
929
+ resetTitleMemo();
930
+ check("超 256MB 的会话库跳过,而且没整份读进内存", readAntigravityWorkspace(metaFor(), localFor(), { fs: bigFs, home: "/h" }) === null && reads === 0);
931
+ }
932
+
933
+ {
934
+ const noFs = {
935
+ statSync: () => {
936
+ throw new Error("不该 stat");
937
+ },
938
+ readFileSync: () => {
939
+ throw new Error("不该读盘");
940
+ },
941
+ };
942
+ resetTitleMemo();
943
+ check("非 UUID 的 id 直接 null,一个字节都不读", readAntigravityWorkspace({ "antigravity.google/conversation_id": "../../etc/passwd" }, localFor(), { fs: noFs, home: "/h" }) === null);
944
+ check("不是它家的帧(压根没那个键)也是 null", readAntigravityWorkspace({ session_id: "sess_x" }, localFor(), { fs: noFs, home: "/h" }) === null);
945
+ check("_meta 缺席不抛", readAntigravityWorkspace(null, localFor(), { fs: noFs, home: "/h" }) === null);
946
+ }
947
+
948
+ {
949
+ const home = agHome();
950
+ const proj = "/Users/u/repos/late-db";
951
+ resetTitleMemo();
952
+ check("库还没落盘:null", readAntigravityWorkspace(metaFor(), localFor(), { home }) === null);
953
+ writeRaw(home, `${ID}.db`, agBytes(ID, proj));
954
+ check("重试窗内不重扫(否则每帧都要扫一遍大库)", readAntigravityWorkspace(metaFor(), localFor(), { home }) === null);
955
+ resetTitleMemo();
956
+ check("重试窗过后扫到了", readAntigravityWorkspace(metaFor(), localFor(), { home }) === proj);
957
+ fs.rmSync(path.join(home, ".gemini"), { recursive: true, force: true });
958
+ check("扫到过就记住,库读不到了也不改口", readAntigravityWorkspace(metaFor(), localFor(), { home }) === proj);
959
+ fs.rmSync(home, { recursive: true, force: true });
960
+ }
961
+
962
+ {
963
+ const home = agHome();
964
+ const proj = path.join(home, "repos", "ag-wired");
965
+ fs.mkdirSync(path.join(proj, ".git"), { recursive: true });
966
+ writeRaw(home, `${ID}.db`, agBytes(ID, proj));
967
+ resetTitleMemo();
968
+ const idn = readSessionIdentity(localFor(), { home, meta: metaFor(), tmp: path.join(home, "unused-tmp") });
969
+ check("readSessionIdentity 接上了:工作区来自会话库", idn.workspace === "ag-wired" && idn.workspaceKind === "git", JSON.stringify(idn));
970
+ check("会话标题本地没有证据:返回 null,不猜", idn.title === null, JSON.stringify(idn));
971
+ resetTitleMemo();
972
+ const bare = readSessionIdentity(localFor(), { home, meta: { progressToken: "p1" }, tmp: path.join(home, "unused-tmp") });
973
+ check("同一个客户端、帧里没有会话 id 时不盖工作区", bare.workspace === null, JSON.stringify(bare));
974
+ fs.rmSync(home, { recursive: true, force: true });
975
+ }
976
+ }
977
+
978
+ console.log("\n\x1b[1mWindows:同样四段身份,换一套证据\x1b[0m");
979
+ {
980
+ const WSELF = "C:\\Users\\u\\.agent-in-chrome\\agent-in-chrome\\server.mjs";
981
+ const winDesktop = new Map([
982
+ [800, { ppid: 801, tty: null, name: "node.exe", command: `"C:\\Program Files\\nodejs\\node.exe" "${WSELF}"` }],
983
+ [801, { ppid: 802, tty: null, name: "cmd.exe", command: 'C:\\Windows\\system32\\cmd.exe /d /s /c "C:\\Users\\u\\.agent-in-chrome\\agent-in-chrome\\mcp-launcher.bat"' }],
984
+ [802, { ppid: 803, tty: null, name: "claude.exe", command: "C:\\Users\\u\\AppData\\Roaming\\Claude\\claude-code\\2.1.237\\claude.exe --output-format stream-json" }],
985
+ [803, { ppid: 804, tty: null, name: "Claude.exe", command: '"C:\\Program Files\\WindowsApps\\Claude_1.34493.1.0_x64__p\\app\\Claude.exe"' }],
986
+ [804, { ppid: 5, tty: null, name: "explorer.exe", command: "C:\\Windows\\Explorer.EXE" }],
987
+ ]);
988
+ const winCli = new Map([
989
+ [810, { ppid: 811, tty: null, name: "node.exe", command: `node ${WSELF}` }],
990
+ [811, { ppid: 812, tty: null, name: "claude.exe", command: "C:\\Users\\u\\AppData\\Local\\claude\\claude.exe" }],
991
+ [812, { ppid: 813, tty: null, name: "WindowsTerminal.exe", command: "C:\\Program Files\\WindowsTerminal\\WindowsTerminal.exe" }],
992
+ ]);
993
+
994
+ const cp = resolveClientPid(801, winDesktop, WSELF);
995
+ check("Windows:跳过 cmd /c mcp-launcher.bat,锚到 claude.exe", cp === 802, String(cp));
996
+
997
+ const wd = walkSurface(cp, winDesktop, { platform: "win32" });
998
+ check("Windows 桌面端:撞见 explorer.exe 就取它下面那一跳当品牌", wd.surface === "app" && wd.brand === "Claude", JSON.stringify(wd));
999
+ check("Windows 品牌那一跳连 exe 路径一起给(版本号要从它的版本资源读)", /Claude\.exe$/.test(wd.appDir || ""), JSON.stringify(wd));
1000
+
1001
+ const wc = walkSurface(resolveClientPid(811, winCli, WSELF), winCli, { platform: "win32" });
1002
+ check("Windows CLI:撞见终端宿主进程 = 从命令行起来的", wc.surface === "cli", JSON.stringify(wc));
1003
+
1004
+ const broken = new Map([[820, { ppid: 821, tty: null, name: "node.exe", command: `node ${WSELF}` }], [821, { ppid: 822, tty: null, name: "ZCode.exe", command: "C:\\x\\ZCode.exe" }]]);
1005
+ const wb = walkSurface(821, broken, { platform: "win32" });
1006
+ check("Windows:链断在半路,按最后见到的那一跳算桌面端", wb.surface === "app" && wb.brand === "ZCode", JSON.stringify(wb));
1007
+ const mb = walkSurface(821, broken, { platform: "darwin" });
1008
+ check("同一条链在 macOS 上仍然「不猜」:断了就是没有证据", mb.surface === null && mb.brand === null, JSON.stringify(mb));
1009
+
1010
+ check("Windows 路径 + 引号 + .exe 后缀都认得出裸名字", plainName('"C:\\Program Files\\nodejs\\node.exe" x') === null && plainName("C:\\x\\y\\Claude.exe --a") === "Claude");
1011
+ check("Windows 上 exe 路径就是「品牌所在的那个东西」", exePathOf('"C:\\a b\\Claude.exe" -x') === "C:\\a b\\Claude.exe" && exePathOf("node x.mjs") === null);
1012
+ check("Windows 的启动器后缀也要认(不认就锚在 cmd.exe 上)", isLauncherFor('cmd /d /s /c "C:\\x\\mcp-launcher.bat"', WSELF) && isLauncherFor("/x/mcp-launcher.sh", WSELF));
1013
+
1014
+ {
1015
+ let calls = 0;
1016
+ const fakeExec = () => {
1017
+ calls++;
1018
+ return JSON.stringify([
1019
+ { pid: 800, ppid: 801, name: "node.exe", cmd: "node server.mjs", start: "134327533025719003" },
1020
+ { pid: 801, ppid: 802, name: "cmd.exe", cmd: "cmd /c x.bat", start: "134327533025719111" },
1021
+ ]);
1022
+ };
1023
+ const src = makeWinProcSource(fakeExec);
1024
+ const a = src.get(800);
1025
+ const b = src.get(801);
1026
+ check("Windows 快照:一次查询把整条链都填进来", a?.ppid === 801 && b?.name === "cmd.exe" && calls === 1, `calls=${calls} ${JSON.stringify([a, b])}`);
1027
+ check("Windows 快照:tty 留 null,不拿进程名冒充终端证据", a.tty === null);
1028
+ src.get(999);
1029
+ src.get(998);
1030
+ src.get(997);
1031
+ check("Windows 快照:查不到的 pid 不会无限起子进程", calls <= 3, `calls=${calls}`);
1032
+
1033
+ const dead = makeWinProcSource(() => {
1034
+ throw new Error("PowerShell 被策略挡下了");
1035
+ });
1036
+ check("PowerShell 不可用时退回 null,不抛", dead.get(800) === null);
1037
+ }
1038
+
1039
+ {
1040
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "aic-win-"));
1041
+ const appdata = path.join(home, "AppData", "Roaming");
1042
+ const dir = path.join(appdata, "Claude", "claude-code-sessions", "org", "acct");
1043
+ fs.mkdirSync(dir, { recursive: true });
1044
+ fs.writeFileSync(path.join(dir, "local_abc-1.json"), JSON.stringify({ title: "Windows/Mac 功能对齐" }));
1045
+ check(
1046
+ "Windows:会话标题从 %APPDATA%\\Claude\\claude-code-sessions 读得到",
1047
+ readHostSessionTitle("local_abc-1", { home, env: { APPDATA: appdata } }) === "Windows/Mac 功能对齐"
1048
+ );
1049
+ check("没有 APPDATA 时按 home\\AppData\\Roaming 兜底", readHostSessionTitle("local_abc-1", { home, env: {} }) === "Windows/Mac 功能对齐");
1050
+ check("对不上的会话 id 照旧返回 null", readHostSessionTitle("local_nope", { home, env: { APPDATA: appdata } }) === null);
1051
+ fs.rmSync(home, { recursive: true, force: true });
1052
+ }
1053
+ }
1054
+
1055
+ console.log("\n\x1b[1m这一帧是主会话发的,还是哪个 subagent 发的\x1b[0m");
1056
+ {
1057
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "aic-sub-"));
1058
+ const PID = 30982;
1059
+ const SID = "987a526a-b5b3-44fd-b79d-707f94409cc4";
1060
+ const cwd = "/Users/u/OpenSource/agent-in-chrome";
1061
+ fs.mkdirSync(path.join(home, ".claude", "sessions"), { recursive: true });
1062
+ fs.writeFileSync(
1063
+ path.join(home, ".claude", "sessions", `${PID}.json`),
1064
+ JSON.stringify({ pid: PID, sessionId: SID, cwd, kind: "interactive", name: "agent-in-chrome-58", nameSource: "derived" })
1065
+ );
1066
+ const subs = path.join(home, ".claude", "projects", cwd.replace(/[^A-Za-z0-9]/g, "-"), SID, "subagents");
1067
+ fs.mkdirSync(subs, { recursive: true });
1068
+ const write = (id, toolUseIds, meta) => {
1069
+ fs.writeFileSync(
1070
+ path.join(subs, `agent-${id}.jsonl`),
1071
+ toolUseIds.map((t) => JSON.stringify({ type: "assistant", message: { content: [{ type: "tool_use", id: t }] } })).join("\n") + "\n"
1072
+ );
1073
+ if (meta) fs.writeFileSync(path.join(subs, `agent-${id}.meta.json`), JSON.stringify(meta));
1074
+ };
1075
+ write("a73ac2b489179315f", ["toolu_01HffyAX2CFDpPnabnxt6Dr6"], { agentType: "general-purpose", description: "插件卡片会话名取证" });
1076
+ write("b0000000000000001", ["toolu_01ZZZZZZZZZZZZZZZZZZZZZZ"], { agentType: "Explore", description: "另一路并行子任务" });
1077
+ const local = { clientPid: PID };
1078
+ const at = (id, opts = {}) => {
1079
+ resetSubagentMemo();
1080
+ return readClaudeSubagent({ "claudecode/toolUseId": id }, local, { home, ...opts });
1081
+ };
1082
+
1083
+ const hit = at("toolu_01HffyAX2CFDpPnabnxt6Dr6");
1084
+ check("按 toolUseId 认出是哪个子任务发的", hit?.label === "插件卡片会话名取证", JSON.stringify(hit));
1085
+ check("子任务类型也带上(进 tooltip)", hit?.type === "general-purpose");
1086
+ check("并行子任务各认各的,不串", at("toolu_01ZZZZZZZZZZZZZZZZZZZZZZ")?.label === "另一路并行子任务");
1087
+ check("主会话自己发的那一帧:没有任何子任务认领它 → null", at("toolu_01MainMainMainMainMainMa") === null);
1088
+ check("id 形状不对一律不查(它要被拼进文件比对)", at("../../etc/passwd") === null && at("") === null);
1089
+ check("没有 _meta / 没有本机取证时不抛", readClaudeSubagent(null, local, { home }) === null && readClaudeSubagent({}, null, { home }) === null);
1090
+
1091
+ const moved = path.join(home, ".claude", "projects", "some-other-encoding", SID, "subagents");
1092
+ fs.mkdirSync(moved, { recursive: true });
1093
+ fs.writeFileSync(path.join(moved, "agent-c1.jsonl"), JSON.stringify({ id: "toolu_01Moved0000000000000000" }) + "\n");
1094
+ fs.writeFileSync(path.join(moved, "agent-c1.meta.json"), JSON.stringify({ agentType: "Plan", description: "换了目录名也认得出" }));
1095
+ fs.rmSync(path.join(home, ".claude", "projects", cwd.replace(/[^A-Za-z0-9]/g, "-")), { recursive: true, force: true });
1096
+ check("cwd 转写拼不中时,在 projects 底下按会话 id 找得到", at("toolu_01Moved0000000000000000")?.label === "换了目录名也认得出");
1097
+ fs.rmSync(moved, { recursive: true, force: true });
1098
+
1099
+ const bare = path.join(home, ".claude", "projects", "x", SID, "subagents");
1100
+ fs.mkdirSync(bare, { recursive: true });
1101
+ fs.writeFileSync(path.join(bare, "agent-d1.jsonl"), JSON.stringify({ id: "toolu_01NoMeta00000000000000" }) + "\n");
1102
+ check("只有记录没有 meta:不显示,不编", at("toolu_01NoMeta00000000000000") === null);
1103
+
1104
+ fs.writeFileSync(path.join(bare, "agent-e1.jsonl"), JSON.stringify({ id: "toolu_01Stale000000000000000" }) + "\n");
1105
+ fs.writeFileSync(path.join(bare, "agent-e1.meta.json"), JSON.stringify({ agentType: "x", description: "一小时前那个" }));
1106
+ const old = new Date(Date.now() - 60 * 60 * 1000);
1107
+ fs.utimesSync(path.join(bare, "agent-e1.jsonl"), old, old);
1108
+ check("陈旧的子任务记录不再读", at("toolu_01Stale000000000000000") === null);
1109
+
1110
+ fs.rmSync(bare, { recursive: true, force: true });
1111
+ const subs2 = path.join(home, ".claude", "projects", "y", SID, "subagents");
1112
+ fs.mkdirSync(subs2, { recursive: true });
1113
+ fs.writeFileSync(path.join(subs2, "agent-f1.jsonl"), JSON.stringify({ id: "toolu_01Memo00000000000000000" }) + "\n");
1114
+ fs.writeFileSync(path.join(subs2, "agent-f1.meta.json"), JSON.stringify({ agentType: "x", description: "记住我" }));
1115
+ resetSubagentMemo();
1116
+ const first = readClaudeSubagent({ "claudecode/toolUseId": "toolu_01Memo00000000000000000" }, local, { home });
1117
+ fs.rmSync(subs2, { recursive: true, force: true });
1118
+ const again = readClaudeSubagent({ "claudecode/toolUseId": "toolu_01Memo00000000000000000" }, local, { home });
1119
+ check("查到过就记住,盘上没了也照旧答得出", first?.label === "记住我" && again?.label === "记住我");
1120
+
1121
+ fs.rmSync(home, { recursive: true, force: true });
1122
+ }
1123
+
1124
+ console.log("\n\x1b[1m真机上跑一遍:不许抛,也不许卡住\x1b[0m");
1125
+ {
1126
+ const t0 = Date.now();
1127
+ let local = null;
1128
+ let threw = null;
1129
+ try {
1130
+ local = probeLocal({ snap: procSource() });
1131
+ } catch (e) {
1132
+ threw = e;
1133
+ }
1134
+ const ms = Date.now() - t0;
1135
+ check("在这台机器上取证不抛异常", !threw, String(threw));
1136
+ check(`取证够快(实测 ${ms}ms,握手之后才做,但也不能拖住第一次调用)`, ms < 1500, `${ms}ms`);
1137
+ check("形态只会是这三种取值之一", local && (local.surface === null || local.surface === "cli" || local.surface === "app"), JSON.stringify(local));
1138
+ }
1139
+
1140
+ console.log(failed ? `\n\x1b[31m${passed} 通过, ${failed} 失败\x1b[0m` : `\n\x1b[32m${passed} 通过, 0 失败\x1b[0m`);
1141
+ process.exit(failed ? 1 : 0);