@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,968 @@
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
+ import { PassThrough } from "node:stream";
7
+ import { execFileSync, spawn } from "node:child_process";
8
+ import { fileURLToPath } from "node:url";
9
+
10
+ import { runAgents, buildAgents } from "./agents.mjs";
11
+ import * as install from "./install.mjs";
12
+ import { pickMulti } from "./pick.mjs";
13
+
14
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
15
+ const SERVER_PATH = path.join(ROOT, "mcp", "server.mjs");
16
+
17
+ {
18
+ const linkDir = fs.mkdtempSync(path.join(os.tmpdir(), "aic-noclaude-"));
19
+ try {
20
+ fs.symlinkSync(process.execPath, path.join(linkDir, "node"));
21
+ } catch {}
22
+ process.env.PATH = [linkDir, "/usr/bin", "/bin", "/usr/sbin", "/sbin"].join(path.delimiter);
23
+ }
24
+
25
+ const REAL_HOME = os.homedir();
26
+ const GUARDED = [
27
+ path.join(REAL_HOME, ".claude.json"),
28
+ path.join(REAL_HOME, ".codex", "config.toml"),
29
+ path.join(REAL_HOME, "Library", "Application Support", "Claude", "claude_desktop_config.json"),
30
+ path.join(REAL_HOME, ".config", "Claude", "claude_desktop_config.json"),
31
+ path.join(REAL_HOME, ".kimi", "mcp.json"),
32
+ path.join(REAL_HOME, ".config", "opencode", "opencode.json"),
33
+ path.join(REAL_HOME, ".gemini", "settings.json"),
34
+ path.join(REAL_HOME, ".gemini", "config", "mcp_config.json"),
35
+ path.join(REAL_HOME, ".workbuddy", "mcp.json"),
36
+ path.join(REAL_HOME, ".qoder", "settings.json"),
37
+ path.join(REAL_HOME, ".qoder-cn", "settings.json"),
38
+ ];
39
+ const readOr = (f) => {
40
+ try {
41
+ return fs.readFileSync(f, "utf8");
42
+ } catch {
43
+ return null;
44
+ }
45
+ };
46
+ const entrySnapshot = (text) => {
47
+ if (text == null) return null;
48
+ try {
49
+ const e = JSON.parse(text)?.mcpServers?.["agent-in-chrome"];
50
+ return e === undefined ? null : JSON.stringify(e);
51
+ } catch {
52
+ return text.includes("[mcp_servers.agent-in-chrome]") ? "toml" : null;
53
+ }
54
+ };
55
+ const LIVE_WRITTEN = path.join(REAL_HOME, ".claude.json");
56
+ const REAL_SNAPSHOT = Object.fromEntries(GUARDED.map((f) => [f, readOr(f)]));
57
+ const REAL_ENTRY_BEFORE = Object.fromEntries(GUARDED.map((f) => [f, entrySnapshot(readOr(f))]));
58
+ const SANDBOX_HOMES = [];
59
+
60
+ let passed = 0;
61
+ let failed = 0;
62
+ const check = (name, cond, extra = "") => {
63
+ if (cond) {
64
+ console.log(` \x1b[32m✓\x1b[0m ${name}`);
65
+ passed++;
66
+ } else {
67
+ console.log(` \x1b[31m✗\x1b[0m ${name}${extra ? ` — ${extra}` : ""}`);
68
+ failed++;
69
+ }
70
+ };
71
+
72
+ async function quiet(fn) {
73
+ const real = console.log;
74
+ const lines = [];
75
+ console.log = (...a) => lines.push(a.join(" "));
76
+ try {
77
+ return { value: await fn(), lines };
78
+ } finally {
79
+ console.log = real;
80
+ }
81
+ }
82
+
83
+ function makeHome(fixtures) {
84
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "aic-agents-"));
85
+ SANDBOX_HOMES.push(home);
86
+ for (const [rel, text] of fixtures) {
87
+ const f = path.join(home, rel);
88
+ fs.mkdirSync(path.dirname(f), { recursive: true });
89
+ fs.writeFileSync(f, text);
90
+ }
91
+ return home;
92
+ }
93
+
94
+ function readAll(home, rels) {
95
+ return Object.fromEntries(rels.map((r) => [r, fs.readFileSync(path.join(home, r), "utf8")]));
96
+ }
97
+ function backupsOf(home, rel) {
98
+ const dir = path.join(home, path.dirname(rel));
99
+ const base = path.basename(rel);
100
+ return fs.readdirSync(dir).filter((f) => f.startsWith(`${base}.bak-`));
101
+ }
102
+
103
+ const opts = (home) => ({
104
+ home,
105
+ platform: "linux",
106
+ serverPath: SERVER_PATH,
107
+ mcpLauncher: path.join(ROOT, "bin", "agent-in-chrome.mjs"),
108
+ yes: true,
109
+ });
110
+
111
+ const canonicalJson = (o) => JSON.stringify(o, null, 2) + "\n";
112
+
113
+ console.log("\n\x1b[1m卸载:只摘我们的键\x1b[0m");
114
+ {
115
+ const rels = [".kimi/mcp.json", ".gemini/settings.json"];
116
+ const before = {
117
+ [rels[0]]: canonicalJson({
118
+ mcpServers: {
119
+ "some-other-server": { command: "node", args: ["/opt/other.js"] },
120
+ },
121
+ someUnrelatedSetting: { deep: { nested: true } },
122
+ }),
123
+ [rels[1]]: canonicalJson({
124
+ theme: "dark",
125
+ mcpServers: { filesystem: { command: "npx", args: ["-y", "@x/fs"] } },
126
+ }),
127
+ };
128
+ const home = makeHome(Object.entries(before));
129
+
130
+ const ins = await quiet(() => runAgents("install", opts(home)));
131
+ const afterInstall = readAll(home, rels);
132
+ check(
133
+ "install 把条目写进了每一家",
134
+ rels.every((r) => afterInstall[r].includes("agent-in-chrome")),
135
+ JSON.stringify(ins.value)
136
+ );
137
+
138
+ await quiet(() => runAgents("uninstall", opts(home)));
139
+ const afterUninstall = readAll(home, rels);
140
+ for (const r of rels) {
141
+ check(`${r}:我们的键摘干净了,其余内容一个字没动`, afterUninstall[r] === before[r], diffHint(before[r], afterUninstall[r]));
142
+ check(`${r}:改动前留了备份`, backupsOf(home, r).length >= 1);
143
+ }
144
+ fs.rmSync(home, { recursive: true, force: true });
145
+ }
146
+
147
+ {
148
+ const rel = ".kimi/mcp.json";
149
+ const home = makeHome([[rel, canonicalJson({ mcpServers: { other: { command: "old" } } })]]);
150
+ await quiet(() => runAgents("install", opts(home)));
151
+
152
+ const f = path.join(home, rel);
153
+ const mid = JSON.parse(fs.readFileSync(f, "utf8"));
154
+ mid.mcpServers.other.command = "用户后来改的";
155
+ mid.mcpServers.addedLater = { command: "用户后来加的" };
156
+ mid.theme = "dark";
157
+ fs.writeFileSync(f, canonicalJson(mid));
158
+
159
+ await quiet(() => runAgents("uninstall", opts(home)));
160
+ const after = JSON.parse(fs.readFileSync(f, "utf8"));
161
+ check("卸载后我们的键没了", !("agent-in-chrome" in after.mcpServers));
162
+ check("用户中途改的条目保持改后的值(不是还原成装之前)", after.mcpServers.other?.command === "用户后来改的");
163
+ check("用户中途新加的条目还在", after.mcpServers.addedLater?.command === "用户后来加的");
164
+ check("用户中途新加的顶层设置还在", after.theme === "dark");
165
+ fs.rmSync(home, { recursive: true, force: true });
166
+ }
167
+
168
+ {
169
+ const rel = ".kimi/mcp.json";
170
+ const home = makeHome([
171
+ [rel, canonicalJson({ mcpServers: { "agent-in-chrome": { command: "node", args: ["/手写的/path.mjs"] }, keep: { command: "keep" } } })],
172
+ ]);
173
+ await quiet(() => runAgents("uninstall", opts(home)));
174
+ const after = JSON.parse(fs.readFileSync(path.join(home, rel), "utf8"));
175
+ check("没经我们装、本来就在的条目照样摘掉", !("agent-in-chrome" in after.mcpServers));
176
+ check("同一份文件里别人的条目不受影响", after.mcpServers.keep?.command === "keep");
177
+ fs.rmSync(home, { recursive: true, force: true });
178
+ }
179
+
180
+ {
181
+ const rel = ".kimi/mcp.json";
182
+ const before = canonicalJson({ mcpServers: { other: { command: "x" } } });
183
+ const home = makeHome([[rel, before]]);
184
+ await quiet(() => runAgents("install", opts(home)));
185
+ await quiet(() => runAgents("uninstall", opts(home)));
186
+ const n1 = backupsOf(home, rel).length;
187
+ const text1 = fs.readFileSync(path.join(home, rel), "utf8");
188
+ await quiet(() => runAgents("uninstall", opts(home)));
189
+ check("再卸一次:文件没被碰", fs.readFileSync(path.join(home, rel), "utf8") === text1);
190
+ check("再卸一次:不再产生新备份", backupsOf(home, rel).length === n1);
191
+ fs.rmSync(home, { recursive: true, force: true });
192
+ }
193
+
194
+ {
195
+ const rel = ".kimi/mcp.json";
196
+ const home = makeHome([
197
+ [
198
+ rel,
199
+ canonicalJson({
200
+ mcpServers: {
201
+ "zcode-in-chrome": { command: "node", args: ["/gone/old-runtime.mjs"] },
202
+ keep: { command: "keep-me" },
203
+ },
204
+ }),
205
+ ],
206
+ ]);
207
+ await quiet(() => runAgents("uninstall", opts(home)));
208
+ const cfg = JSON.parse(fs.readFileSync(path.join(home, rel), "utf8"));
209
+ check("卸载连改名前的 zcode-in-chrome 一起摘", !("zcode-in-chrome" in cfg.mcpServers));
210
+ check("别人的条目一根汗毛没动", cfg.mcpServers.keep?.command === "keep-me");
211
+ fs.rmSync(home, { recursive: true, force: true });
212
+ }
213
+
214
+ {
215
+ const rel = ".kimi/mcp.json";
216
+ const before = canonicalJson({
217
+ mcpServers: {
218
+ "agent-in-chrome-2": { command: "someone-elses" },
219
+ "my-agent-in-chrome": { command: "also-not-ours" },
220
+ },
221
+ });
222
+ const home = makeHome([[rel, before]]);
223
+ await quiet(() => runAgents("uninstall", opts(home)));
224
+ check("agent-in-chrome-2 / my-agent-in-chrome 不是我们的,没动", fs.readFileSync(path.join(home, rel), "utf8") === before);
225
+ fs.rmSync(home, { recursive: true, force: true });
226
+ }
227
+
228
+ console.log("\n\x1b[1m卸载:Codex TOML 文本手术\x1b[0m");
229
+ {
230
+ const rel = ".codex/config.toml";
231
+ const before = `model = "o3"
232
+
233
+ [mcp_servers.filesystem]
234
+ command = "npx"
235
+ args = ["-y", "@x/fs"]
236
+
237
+ [tui]
238
+ theme = "dark"
239
+ `;
240
+ const home = makeHome([[rel, before]]);
241
+ await quiet(() => runAgents("install", opts(home)));
242
+ const mid = fs.readFileSync(path.join(home, rel), "utf8");
243
+ check("Codex:写进去了", mid.includes("[mcp_servers.agent-in-chrome]"));
244
+ check("Codex:别人的表还在", mid.includes("[mcp_servers.filesystem]") && mid.includes("[tui]"));
245
+
246
+ await quiet(() => runAgents("uninstall", opts(home)));
247
+ const after = fs.readFileSync(path.join(home, rel), "utf8");
248
+ check("Codex:我们的表摘干净了,其余内容一个字没动", after === before, diffHint(before, after));
249
+ fs.rmSync(home, { recursive: true, force: true });
250
+ }
251
+
252
+ console.log("\n\x1b[1m非规范格式的 JSON(记录已知行为)\x1b[0m");
253
+ {
254
+ const rel = ".kimi/mcp.json";
255
+ const before = JSON.stringify({ mcpServers: { other: { command: "x" } }, tail: [1, 2] }, null, 4) + "\n";
256
+ const home = makeHome([[rel, before]]);
257
+ await quiet(() => runAgents("install", opts(home)));
258
+ await quiet(() => runAgents("uninstall", opts(home)));
259
+ const after = fs.readFileSync(path.join(home, rel), "utf8");
260
+ check("非规范格式:其余内容语义完全相同", JSON.stringify(JSON.parse(after)) === JSON.stringify(JSON.parse(before)));
261
+ check("非规范格式:缩进被规范化成 2 空格(已知,非回归)", after.includes('\n "mcpServers"'));
262
+ fs.rmSync(home, { recursive: true, force: true });
263
+ }
264
+
265
+ console.log("\n\x1b[1m非交互默认\x1b[0m");
266
+ {
267
+ const home = makeHome([
268
+ [".kimi/mcp.json", canonicalJson({ mcpServers: {} })],
269
+ [".gemini/settings.json", canonicalJson({ mcpServers: {} })],
270
+ ]);
271
+ const noTty = new PassThrough();
272
+ const r = await quiet(() => runAgents("install", { ...opts(home), yes: false, input: noTty }));
273
+ check("非 TTY 时不弹清单、直接全装", r.value.installed.length >= 2, JSON.stringify(r.value));
274
+ check("非 TTY 时不报「取消」", r.value.cancelled === false);
275
+ fs.rmSync(home, { recursive: true, force: true });
276
+ }
277
+
278
+ console.log("\n\x1b[1m单家失败的隔离\x1b[0m");
279
+ {
280
+ const rel = ".kimi/mcp.json";
281
+ const home = makeHome([[rel, canonicalJson({ mcpServers: {} })]]);
282
+ const binDir = path.join(home, "fakebin");
283
+ fs.mkdirSync(binDir, { recursive: true });
284
+ const qoderBin = path.join(binDir, "qodercli");
285
+ fs.writeFileSync(qoderBin, "#!/bin/sh\nexit 0\n");
286
+ fs.chmodSync(qoderBin, 0o755);
287
+
288
+ const realPath = process.env.PATH;
289
+ process.env.PATH = `${binDir}${path.delimiter}${realPath}`;
290
+ let r;
291
+ try {
292
+ r = await quiet(() => runAgents("install", opts(home)));
293
+ } finally {
294
+ process.env.PATH = realPath;
295
+ }
296
+
297
+ const said = r.lines.join("\n");
298
+ check("配置目录不存在时不崩(qoder-cli:探测看 PATH、写入看 ~/.qoder/)", !!r, said.slice(-300));
299
+ check("已探测到的客户端:建父目录并注册成功", fs.existsSync(path.join(home, ".qoder", "settings.json")));
300
+ check("这不算失败(不进 failed)", !r.value.failed.includes("qoder-cli"), JSON.stringify(r.value));
301
+ check("同一轮里别家照样装上", r.value.installed.includes("kimi"), JSON.stringify(r.value));
302
+ check("kimi 的配置真的写进去了", fs.readFileSync(path.join(home, rel), "utf8").includes("agent-in-chrome"));
303
+ fs.rmSync(home, { recursive: true, force: true });
304
+ }
305
+
306
+ console.log("\n\x1b[1m技能资产:references/ 要跟着装\x1b[0m");
307
+ {
308
+ const skill = (install.ASSETS || []).find((a) => a.label === "skill");
309
+ check("安装器登记了 skill 资产", !!skill);
310
+ check(
311
+ "skill 资产指的是整个技能目录,不是单个 SKILL.md",
312
+ !!skill && fs.existsSync(skill.from) && fs.statSync(skill.from).isDirectory(),
313
+ String(skill?.from)
314
+ );
315
+
316
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "aic-skill-"));
317
+ const to = path.join(dir, "agent-in-chrome");
318
+ let copied = true;
319
+ try {
320
+ install.copyAsset(skill.from, to);
321
+ } catch (e) {
322
+ copied = false;
323
+ check("拷贝资产不报错", false, String(e && e.message).slice(0, 120));
324
+ }
325
+ if (copied) {
326
+ check("装完 SKILL.md 在", fs.existsSync(path.join(to, "SKILL.md")));
327
+ const skillText = fs.existsSync(path.join(to, "SKILL.md")) ? fs.readFileSync(path.join(to, "SKILL.md"), "utf8") : "";
328
+ const linked = [...skillText.matchAll(/\(references\/([\w.-]+\.md)\)/g)].map((m) => m[1]);
329
+ check("SKILL.md 里确实有 references/ 索引(没有的话这组测试就白守了)", linked.length >= 3, String(linked.length));
330
+ const missing = linked.filter((f) => !fs.existsSync(path.join(to, "references", f)));
331
+ check("索引里的每一份 reference 都装到位了(链接不是死的)", missing.length === 0, missing.join("、"));
332
+ }
333
+ fs.rmSync(dir, { recursive: true, force: true });
334
+ }
335
+
336
+ console.log("\n\x1b[1mClaude Desktop:user scope 在,就不写第二条同名的\x1b[0m");
337
+
338
+ async function withoutClaudeCli(fn) {
339
+ const real = process.env.PATH;
340
+ const empty = fs.mkdtempSync(path.join(os.tmpdir(), "aic-nopath-"));
341
+ process.env.PATH = empty;
342
+ try {
343
+ return await fn();
344
+ } finally {
345
+ process.env.PATH = real;
346
+ fs.rmSync(empty, { recursive: true, force: true });
347
+ }
348
+ }
349
+
350
+ const DESK_REL = ".config/Claude/claude_desktop_config.json";
351
+ const deskCfg = (home) => JSON.parse(fs.readFileSync(path.join(home, DESK_REL), "utf8"));
352
+
353
+ {
354
+ const home = makeHome([
355
+ [DESK_REL, canonicalJson({ globalShortcut: "Alt+C", mcpServers: { keepme: { command: "keep" } } })],
356
+ [".claude.json", canonicalJson({ numStartups: 7, mcpServers: {} })],
357
+ ]);
358
+ const r = await withoutClaudeCli(() => quiet(() => runAgents("install", opts(home))));
359
+ const cc = JSON.parse(fs.readFileSync(path.join(home, ".claude.json"), "utf8"));
360
+ check("user scope 注册上了", !!cc.mcpServers?.["agent-in-chrome"], JSON.stringify(cc.mcpServers));
361
+ check("同一轮里桌面端连接器不写", !deskCfg(home).mcpServers["agent-in-chrome"], JSON.stringify(deskCfg(home)));
362
+ check("桌面端配置里别人的键一个没动", deskCfg(home).mcpServers.keepme?.command === "keep" && deskCfg(home).globalShortcut === "Alt+C");
363
+ check("不写也就不留备份(没改过文件)", backupsOf(home, DESK_REL).length === 0);
364
+ check("说清楚了为什么不写", r.lines.join("\n").includes("工具命名空间"), r.lines.join("\n").slice(-300));
365
+ fs.rmSync(home, { recursive: true, force: true });
366
+ }
367
+
368
+ {
369
+ const home = makeHome([
370
+ [
371
+ DESK_REL,
372
+ canonicalJson({
373
+ globalShortcut: "Alt+C",
374
+ mcpServers: { keepme: { command: "keep" }, "agent-in-chrome": { command: "/老的/mcp-launcher.sh", args: [] } },
375
+ }),
376
+ ],
377
+ [".claude.json", canonicalJson({ mcpServers: {} })],
378
+ ]);
379
+ await withoutClaudeCli(() => quiet(() => runAgents("install", opts(home))));
380
+ check("已有的桌面端连接器被主动摘掉", !deskCfg(home).mcpServers["agent-in-chrome"], JSON.stringify(deskCfg(home)));
381
+ check("摘的时候只摘我们的键", deskCfg(home).mcpServers.keepme?.command === "keep" && deskCfg(home).globalShortcut === "Alt+C");
382
+ check("摘之前留了备份", backupsOf(home, DESK_REL).length >= 1);
383
+ const c = await withoutClaudeCli(() => quiet(() => runAgents("check", opts(home))));
384
+ check("check:有意不注册时不报成「未注册」的错", !/Claude Desktop: 未注册/.test(c.lines.join("\n")), c.lines.join("\n").slice(-300));
385
+ fs.rmSync(home, { recursive: true, force: true });
386
+ }
387
+
388
+ {
389
+ const home = makeHome([
390
+ [DESK_REL, canonicalJson({ mcpServers: {} })],
391
+ [".claude.json", "{ 这不是 JSON"],
392
+ ]);
393
+ const r = await withoutClaudeCli(() => quiet(() => runAgents("install", opts(home))));
394
+ check("user scope 写不成时,桌面端连接器照写", deskCfg(home).mcpServers["agent-in-chrome"]?.command === opts(home).mcpLauncher, JSON.stringify(deskCfg(home)));
395
+ check("坏掉的 ~/.claude.json 没被我们改坏", fs.readFileSync(path.join(home, ".claude.json"), "utf8") === "{ 这不是 JSON", r.lines.join("\n").slice(-200));
396
+ fs.rmSync(home, { recursive: true, force: true });
397
+ }
398
+
399
+ {
400
+ const home = makeHome([
401
+ [DESK_REL, canonicalJson({ mcpServers: { "agent-in-chrome": { command: "/x/mcp-launcher.sh" }, keepme: { command: "keep" } } })],
402
+ [".claude.json", canonicalJson({ mcpServers: { "agent-in-chrome": { command: "node" }, existing: { command: "x" } } })],
403
+ ]);
404
+ await withoutClaudeCli(() => quiet(() => runAgents("uninstall", opts(home))));
405
+ check("uninstall:桌面端那条照旧摘掉", !deskCfg(home).mcpServers["agent-in-chrome"] && deskCfg(home).mcpServers.keepme?.command === "keep");
406
+ const cc = JSON.parse(fs.readFileSync(path.join(home, ".claude.json"), "utf8"));
407
+ check("uninstall:user scope 那条也摘掉", !cc.mcpServers["agent-in-chrome"] && cc.mcpServers.existing?.command === "x");
408
+ fs.rmSync(home, { recursive: true, force: true });
409
+ }
410
+
411
+ console.log("\n\x1b[1mDeepSeek Harness:cordis.patch.yml 的整块手术\x1b[0m");
412
+ {
413
+ const MARKER = "# 由 agent-in-chrome 安装器管理(卸载:npx @liang-hz/agent-in-chrome uninstall)";
414
+ const REL = ".dsh/profiles/web/cordis.patch.yml";
415
+ const PROFILE_PKG = [".dsh/profiles/web/package.json", JSON.stringify({ name: "dsh-profile-web", private: true, dsh: { profile: { bundles: ["@deepseek-ai/dsh-base"] } } })];
416
+ const LAUNCHER = path.join(ROOT, "bin", "agent-in-chrome.mjs");
417
+ const ourBlock = [
418
+ MARKER,
419
+ "- insert:",
420
+ " - id: mcp-agent-in-chrome",
421
+ " name: '@deepseek-ai/dsh-mcp-client'",
422
+ " config:",
423
+ " serverName: agent-in-chrome",
424
+ " transport: stdio",
425
+ ` command: '${LAUNCHER}'`,
426
+ " args: []",
427
+ ].join("\n");
428
+ const othersItem = ["- insert:", " - id: some-other-plugin", " name: '@deepseek-ai/dsh-mcp-client'", " config:", " serverName: github", " transport: stdio", " command: npx", " args: ['-y', 'gh-mcp']"].join("\n");
429
+ const dshOnly = { ...opts(""), agents: ["deepseek-harness"] };
430
+ const run = (home, mode) => quiet(() => runAgents(mode, { ...dshOnly, home }));
431
+
432
+ {
433
+ const before = othersItem + "\n";
434
+ const home = makeHome([PROFILE_PKG, [REL, before]]);
435
+ await run(home, "install");
436
+ const after = fs.readFileSync(path.join(home, REL), "utf8");
437
+ check("装:别人的条目一字不动,我们的块带管理注释追加在后", after === `${othersItem}\n\n${ourBlock}\n`, diffHint(`${othersItem}\n\n${ourBlock}\n`, after));
438
+ const { lines } = await run(home, "install");
439
+ check("重装幂等:内容没变就不写", fs.readFileSync(path.join(home, REL), "utf8") === after && lines.some((l) => l.includes("已是最新")));
440
+ check("幂等的那次不再备份", backupsOf(home, REL).length === 1);
441
+ await run(home, "uninstall");
442
+ check("卸载后逐字回到装之前", fs.readFileSync(path.join(home, REL), "utf8") === before, diffHint(before, fs.readFileSync(path.join(home, REL), "utf8")));
443
+ fs.rmSync(home, { recursive: true, force: true });
444
+ }
445
+
446
+ {
447
+ const hand = ["- insert:", " - id: mcp-agent-in-chrome", " name: '@deepseek-ai/dsh-mcp-client'", " config:", " serverName: agent-in-chrome", " transport: stdio", " command: /Users/u/old/mcp-launcher.sh", " args: []", " reconnect:", " enabled: true"].join("\n");
448
+ const home = makeHome([PROFILE_PKG, [REL, `${othersItem}\n\n${hand}\n`]]);
449
+ await run(home, "install");
450
+ const after = fs.readFileSync(path.join(home, REL), "utf8");
451
+ check("手写的旧条目被受管条目替换,不留双份", after === `${othersItem}\n\n${ourBlock}\n`, diffHint(`${othersItem}\n\n${ourBlock}\n`, after));
452
+ fs.rmSync(home, { recursive: true, force: true });
453
+ }
454
+
455
+ {
456
+ const mixed = ["- insert:", " - id: mcp-agent-in-chrome", " name: '@deepseek-ai/dsh-mcp-client'", " config:", " serverName: agent-in-chrome", " - id: other", " name: '@deepseek-ai/dsh-mcp-client'", " config:", " serverName: other"].join("\n");
457
+ const home = makeHome([PROFILE_PKG, [REL, mixed + "\n"]]);
458
+ await run(home, "install");
459
+ check("混写的项不动(装)", fs.readFileSync(path.join(home, REL), "utf8") === mixed + "\n");
460
+ await run(home, "uninstall");
461
+ check("混写的项不动(卸)", fs.readFileSync(path.join(home, REL), "utf8") === mixed + "\n");
462
+ fs.rmSync(home, { recursive: true, force: true });
463
+ }
464
+
465
+ {
466
+ const home = makeHome([PROFILE_PKG, [REL, "[]\n"]]);
467
+ await run(home, "install");
468
+ check("`[]` 换成我们的块", fs.readFileSync(path.join(home, REL), "utf8") === ourBlock + "\n");
469
+ fs.rmSync(home, { recursive: true, force: true });
470
+ }
471
+
472
+ {
473
+ const home = makeHome([PROFILE_PKG, [REL, "foo: bar\n"]]);
474
+ const { lines } = await run(home, "install");
475
+ check("认不出的形状不动手,只给手动片段", fs.readFileSync(path.join(home, REL), "utf8") === "foo: bar\n" && lines.some((l) => l.includes("没动它")));
476
+ fs.rmSync(home, { recursive: true, force: true });
477
+ }
478
+
479
+ {
480
+ const home = makeHome([PROFILE_PKG]);
481
+ await run(home, "install");
482
+ check("没有 patch 文件时新建", fs.readFileSync(path.join(home, REL), "utf8") === ourBlock + "\n");
483
+ fs.rmSync(home, { recursive: true, force: true });
484
+ }
485
+
486
+ {
487
+ const home = makeHome([[".dsh/settings.yaml", "locale:\n preference: zh\n"]]);
488
+ const { lines } = await run(home, "install");
489
+ check("没有 profile 就是未检测到", lines.some((l) => l.includes("未检测到")) && !fs.existsSync(path.join(home, ".dsh", "profiles")));
490
+ fs.rmSync(home, { recursive: true, force: true });
491
+ }
492
+ }
493
+
494
+ console.log("\n\x1b[1mAntigravity:空配置文件 + 和 Gemini CLI 共用 ~/.gemini\x1b[0m");
495
+ {
496
+ const REL = ".gemini/config/mcp_config.json";
497
+ const home = makeHome([
498
+ [REL, ""],
499
+ [".gemini/config/.migrated", ""],
500
+ [".gemini/settings.json", canonicalJson({ theme: "dark", mcpServers: {} })],
501
+ ]);
502
+
503
+ const ins = await quiet(() => runAgents("install", { ...opts(home), agents: ["antigravity"] }));
504
+ const written = JSON.parse(fs.readFileSync(path.join(home, REL), "utf8"));
505
+ check("0 字节的配置文件按 {} 算,照样注册得上", !!written.mcpServers?.["agent-in-chrome"], JSON.stringify(written));
506
+ check(
507
+ "GUI 应用走 launcher(拿不到终端 PATH),同 Claude Desktop / Trae",
508
+ written.mcpServers["agent-in-chrome"].command === path.join(ROOT, "bin", "agent-in-chrome.mjs"),
509
+ JSON.stringify(written.mcpServers["agent-in-chrome"])
510
+ );
511
+ check("装的是 antigravity 这一家", ins.value.installed.includes("antigravity"), JSON.stringify(ins.value));
512
+ check("改动前留了备份", backupsOf(home, REL).length >= 1);
513
+ check("Gemini CLI 的 settings.json 没被顺手改(--agents 只圈了 antigravity)", fs.readFileSync(path.join(home, ".gemini/settings.json"), "utf8").includes('"theme": "dark"') && !fs.readFileSync(path.join(home, ".gemini/settings.json"), "utf8").includes("agent-in-chrome"));
514
+
515
+ const chk = await quiet(() => runAgents("check", { ...opts(home), agents: ["antigravity"] }));
516
+ check("check 认得出已注册", chk.lines.some((l) => /Antigravity: 已注册/.test(l)), chk.lines.join("\n"));
517
+
518
+ await quiet(() => runAgents("uninstall", { ...opts(home), agents: ["antigravity"] }));
519
+ const after = JSON.parse(fs.readFileSync(path.join(home, REL), "utf8"));
520
+ check("卸载把我们那一个键摘干净(它自己 read-merge-write 这份文件,别的键不能动)", !after.mcpServers?.["agent-in-chrome"], JSON.stringify(after));
521
+ const chk2 = await quiet(() => runAgents("check", { ...opts(home), agents: ["antigravity"] }));
522
+ check("卸载后 check 报未注册", chk2.lines.some((l) => /Antigravity: 未注册/.test(l)), chk2.lines.join("\n"));
523
+ fs.rmSync(home, { recursive: true, force: true });
524
+ }
525
+ {
526
+ const onlyGemini = makeHome([[".gemini/settings.json", canonicalJson({ mcpServers: {} })], [".gemini/oauth_creds.json", "{}"]]);
527
+ const ids = (home) => buildAgents({ ...opts(home) }).filter((a) => a.detected).map((a) => a.id);
528
+ check("只装了 Gemini CLI 的机器不会被误判成装了 Antigravity", !ids(onlyGemini).includes("antigravity") && ids(onlyGemini).includes("gemini"), ids(onlyGemini).join(","));
529
+ fs.rmSync(onlyGemini, { recursive: true, force: true });
530
+
531
+ const withAg = makeHome([[".gemini/config/mcp_config.json", ""]]);
532
+ check("有 ~/.gemini/config 目录就认", buildAgents({ ...opts(withAg) }).find((a) => a.id === "antigravity")?.detected === true);
533
+ fs.rmSync(withAg, { recursive: true, force: true });
534
+ }
535
+ {
536
+ const home = makeHome([[".gemini/config/mcp_config.json", " \n\t "], [".kimi/mcp.json", "{ 这不是 JSON"]]);
537
+ const r = await quiet(() => runAgents("install", { ...opts(home), agents: ["antigravity", "kimi"] }));
538
+ check("纯空白的配置文件也按 {} 算", !!JSON.parse(fs.readFileSync(path.join(home, ".gemini/config/mcp_config.json"), "utf8")).mcpServers?.["agent-in-chrome"]);
539
+ check("坏 JSON 照旧拒写、原样留着", fs.readFileSync(path.join(home, ".kimi/mcp.json"), "utf8") === "{ 这不是 JSON");
540
+ check("坏 JSON 那家算失败,不拖累别家", r.value.failed.includes("kimi") && r.value.installed.includes("antigravity"), JSON.stringify(r.value));
541
+ fs.rmSync(home, { recursive: true, force: true });
542
+ }
543
+ {
544
+ const listed = (install.FLAGS_USAGE.match(/--agents=a,b[\s\S]*?--no-agents/) || [""])[0]
545
+ .split(/[\s、,,]+/)
546
+ .filter((w) => /^[a-z][a-z-]+$/.test(w));
547
+ const all = buildAgents({ home: "/nonexistent-home", platform: "linux", serverPath: SERVER_PATH, mcpLauncher: SERVER_PATH }).map((a) => a.id);
548
+ const missing = all.filter((id) => !listed.includes(id));
549
+ check("--agents 的帮助文本列全了每一家(漏了就没法单独装它)", missing.length === 0, `漏:${missing.join(",")}`);
550
+ }
551
+
552
+ console.log("\n\x1b[1m--check 的 socket 权限体检:按 defaultSockName 的规则枚举\x1b[0m");
553
+ {
554
+ const { listSocks } = await import("./install.mjs");
555
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "aic-socks-"));
556
+ for (const n of [
557
+ "agent-in-chrome.sock",
558
+ "agent-in-chrome-cli.sock",
559
+ "agent-in-chrome-cli-1a2b3c4d.sock",
560
+ "token",
561
+ "agent-in-chrome.log",
562
+ ])
563
+ fs.writeFileSync(path.join(dir, n), "");
564
+ const found = listSocks(dir).map(([, p]) => path.basename(p));
565
+ check(
566
+ "派生名的 sock 也在体检范围里",
567
+ found.includes("agent-in-chrome-cli-1a2b3c4d.sock"),
568
+ JSON.stringify(found)
569
+ );
570
+ check("三条 sock 都枚举到了", found.length === 3, JSON.stringify(found));
571
+ check("同目录的非 sock 文件不进来", !found.some((n) => n === "token" || n.endsWith(".log")), JSON.stringify(found));
572
+ check("桌面那条的标签仍然是「桌面」", listSocks(dir).find(([, p]) => p.endsWith("/agent-in-chrome.sock"))?.[0] === "桌面");
573
+ check("目录不存在时返回空数组,不抛", JSON.stringify(listSocks(path.join(dir, "没有这个目录"))) === "[]");
574
+ fs.rmSync(dir, { recursive: true, force: true });
575
+ }
576
+
577
+ console.log("\n\x1b[1mQoder IDE:SharedClientCache 的位置按平台分\x1b[0m");
578
+ {
579
+ const home = makeHome([["AppData/Roaming/Qoder/SharedClientCache/mcp.json", "{}\n"], [".qoder/mcp.json", "{}\n"]]);
580
+ const { lines } = await quiet(() =>
581
+ runAgents("install", { ...opts(home), platform: "win32", agents: ["qoder-ide"] })
582
+ );
583
+ const b = path.join(home, "AppData", "Roaming", "Qoder", "SharedClientCache", "mcp.json");
584
+ check(
585
+ "win32 上 B 存在就写 B(不是退回 A)",
586
+ !!JSON.parse(fs.readFileSync(b, "utf8"))?.mcpServers?.["agent-in-chrome"],
587
+ fs.readFileSync(b, "utf8")
588
+ );
589
+ check(
590
+ "A 那份不动(它只是首启迁移源)",
591
+ !JSON.parse(fs.readFileSync(path.join(home, ".qoder", "mcp.json"), "utf8"))?.mcpServers,
592
+ lines.join("\n").slice(0, 200)
593
+ );
594
+ fs.rmSync(home, { recursive: true, force: true });
595
+ }
596
+
597
+ console.log("\n\x1b[1m终端多选清单\x1b[0m");
598
+
599
+ function fakeTty() {
600
+ const s = new PassThrough();
601
+ s.isTTY = true;
602
+ s.setRawMode = () => {};
603
+ return s;
604
+ }
605
+ const sink = () => ({ write: () => {} });
606
+ const items = [{ label: "A" }, { label: "B" }, { label: "C" }];
607
+
608
+ async function drive(keys) {
609
+ const input = fakeTty();
610
+ const p = pickMulti(items, { input, output: sink(), platform: "linux" });
611
+ await new Promise((r) => setImmediate(r));
612
+ for (const k of keys) {
613
+ input.emit("keypress", k.str ?? "", k);
614
+ await new Promise((r) => setImmediate(r));
615
+ }
616
+ return p;
617
+ }
618
+
619
+ check("默认全选,回车直接确认", JSON.stringify(await drive([{ name: "return" }])) === "[0,1,2]");
620
+ check(
621
+ "空格取消当前项",
622
+ JSON.stringify(await drive([{ name: "space", str: " " }, { name: "return" }])) === "[1,2]"
623
+ );
624
+ check(
625
+ "下移再取消,去掉的是第二项",
626
+ JSON.stringify(await drive([{ name: "down" }, { name: "space", str: " " }, { name: "return" }])) === "[0,2]"
627
+ );
628
+ check("a 键全不选(默认是全选,按一次翻面)", JSON.stringify(await drive([{ name: "a" }, { name: "return" }])) === "[]");
629
+ check("a 键按两次回到全选", JSON.stringify(await drive([{ name: "a" }, { name: "a" }, { name: "return" }])) === "[0,1,2]");
630
+ check("上移在头部回绕到末项", JSON.stringify(await drive([{ name: "up" }, { name: "space", str: " " }, { name: "return" }])) === "[0,1]");
631
+ check("Ctrl-C 返回 null(取消,不是全不选)", (await drive([{ name: "c", ctrl: true }])) === null);
632
+ check("Esc 返回 null", (await drive([{ name: "escape" }])) === null);
633
+ check("无关按键不影响结果", JSON.stringify(await drive([{ name: "x" }, { name: "f5" }, { name: "return" }])) === "[0,1,2]");
634
+
635
+ {
636
+ const notTty = new PassThrough();
637
+ const r = await pickMulti(items, { input: notTty, output: sink() });
638
+ check("非 TTY:不进交互,直接返回默认全选", JSON.stringify(r) === "[0,1,2]");
639
+ }
640
+ {
641
+ const notTty = new PassThrough();
642
+ const r = await pickMulti(items, { input: notTty, output: sink(), selected: [true, false, true] });
643
+ check("非 TTY:尊重传入的默认勾选", JSON.stringify(r) === "[0,2]");
644
+ }
645
+ check("空清单直接返回空", JSON.stringify(await pickMulti([], { input: fakeTty(), output: sink() })) === "[]");
646
+
647
+ console.log("\n\x1b[1m运行时同步:原子替换 + 镜像语义\x1b[0m");
648
+
649
+ function runInstaller(args, home, extraEnv = {}) {
650
+ const env = { ...process.env, HOME: home, USERPROFILE: home, ...extraEnv };
651
+ try {
652
+ const out = execFileSync(process.execPath, [path.join(ROOT, "scripts", "install.mjs"), ...args], {
653
+ env,
654
+ encoding: "utf8",
655
+ timeout: 180000,
656
+ });
657
+ return { status: 0, out };
658
+ } catch (e) {
659
+ return { status: e.status ?? 1, out: String(e.stdout || "") + String(e.stderr || "") };
660
+ }
661
+ }
662
+
663
+ function fakeBrowserDir(home) {
664
+ const d =
665
+ process.platform === "darwin"
666
+ ? path.join(home, "Library", "Application Support", "Google", "Chrome")
667
+ : path.join(home, ".config", "google-chrome");
668
+ fs.mkdirSync(d, { recursive: true });
669
+ return d;
670
+ }
671
+
672
+ function nextJsonLine(stream) {
673
+ return new Promise((resolve, reject) => {
674
+ let buf = "";
675
+ const onData = (d) => {
676
+ buf += d;
677
+ const i = buf.indexOf("\n");
678
+ if (i < 0) return;
679
+ stream.off("data", onData);
680
+ try {
681
+ resolve(JSON.parse(buf.slice(0, i)));
682
+ } catch (e) {
683
+ reject(new Error(`不是 JSON:${buf.slice(0, 200)}`));
684
+ }
685
+ };
686
+ stream.setEncoding("utf8");
687
+ stream.on("data", onData);
688
+ stream.on("close", () => reject(new Error(`子进程没吐出结果就退了:${buf.slice(0, 200)}`)));
689
+ });
690
+ }
691
+
692
+ {
693
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "aic-runtime-"));
694
+ SANDBOX_HOMES.push(home);
695
+ fakeBrowserDir(home);
696
+ const RT = path.join(home, ".agent-in-chrome", "agent-in-chrome");
697
+ const serverRt = path.join(RT, "server.mjs");
698
+
699
+ const first = runInstaller(["--yes", "--no-agents"], home);
700
+ check("受控 HOME 里装得起来(退出码 0)", first.status === 0, first.out.slice(-400));
701
+ check("运行时里有 server.mjs", fs.existsSync(serverRt));
702
+
703
+ const SENTINEL = "// 上一版(哨兵)\n";
704
+ fs.writeFileSync(serverRt, SENTINEL);
705
+ const oldIno = String(fs.statSync(serverRt).ino);
706
+
707
+ const holderSrc = path.join(home, "holder.mjs");
708
+ fs.writeFileSync(
709
+ holderSrc,
710
+ `import fs from "node:fs";
711
+ import { pathToFileURL } from "node:url";
712
+ const target = process.argv[2];
713
+ const liveModule = process.argv[3];
714
+ await import(pathToFileURL(liveModule).href); // 真的在跑运行时里的代码
715
+ const fd = fs.openSync(target, "r");
716
+ const st0 = fs.fstatSync(fd);
717
+ let enoent = 0, samples = 0;
718
+ const inos = new Set();
719
+ const timer = setInterval(() => {
720
+ samples++;
721
+ try { inos.add(String(fs.statSync(target).ino)); }
722
+ catch (e) { if (e.code === "ENOENT") enoent++; }
723
+ }, 1);
724
+ process.stdout.write(JSON.stringify({ ready: true, ino: String(st0.ino) }) + "\\n");
725
+ process.stdin.on("data", () => {
726
+ clearInterval(timer);
727
+ const st = fs.fstatSync(fd);
728
+ const buf = Buffer.alloc(st.size);
729
+ fs.readSync(fd, buf, 0, st.size, 0);
730
+ process.stdout.write(JSON.stringify({ heldIno: String(st.ino), held: buf.toString("utf8"), enoent, samples, inos: [...inos] }) + "\\n");
731
+ process.exit(0);
732
+ });
733
+ `
734
+ );
735
+ const holder = spawn(process.execPath, [holderSrc, serverRt, path.join(RT, "session-id.mjs")], {
736
+ stdio: ["pipe", "pipe", "pipe"],
737
+ env: { ...process.env, HOME: home, USERPROFILE: home },
738
+ });
739
+ const ready = await nextJsonLine(holder.stdout);
740
+ check("替换前:子进程握住的就是那个 inode", ready.ino === oldIno, `${ready.ino} vs ${oldIno}`);
741
+
742
+ const second = runInstaller(["--yes", "--no-agents"], home);
743
+ check("有进程正握着运行时文件时,重装照样成功", second.status === 0, second.out.slice(-400));
744
+
745
+ holder.stdin.write("go\n");
746
+ const held = await nextJsonLine(holder.stdout);
747
+ const srcText = fs.readFileSync(path.join(ROOT, "mcp", "server.mjs"), "utf8");
748
+ const newIno = String(fs.statSync(serverRt).ino);
749
+
750
+ check("替换后:旧进程读到的仍是旧 inode", held.heldIno === oldIno, `${held.heldIno} vs ${oldIno}`);
751
+ check("旧 inode 的内容一个字没被动过(不是原地截断重写)", held.held === SENTINEL, JSON.stringify(held.held.slice(0, 80)));
752
+ check("新文件是另一个 inode", newIno !== oldIno, `${newIno} vs ${oldIno}`);
753
+ check("新文件的内容就是仓库里的源码", fs.readFileSync(serverRt, "utf8") === srcText);
754
+ check(
755
+ `替换过程没有缺失窗口(${held.samples} 次 stat 全部命中)`,
756
+ held.enoent === 0 && held.samples > 20,
757
+ `ENOENT ${held.enoent} 次 / 共 ${held.samples} 次`
758
+ );
759
+ check(
760
+ "采样窗口确实跨过了那次替换(旧新 inode 都采到了)",
761
+ held.inos.includes(oldIno) && held.inos.includes(newIno),
762
+ `采到 ${JSON.stringify(held.inos)},旧 ${oldIno} 新 ${newIno}`
763
+ );
764
+ check("替换用的临时文件没留下", fs.readdirSync(RT).filter((f) => f.includes(".incoming-")).length === 0, fs.readdirSync(RT).join(","));
765
+
766
+ const stale = [
767
+ ["zombie.mjs", path.join(RT, "zombie.mjs")],
768
+ ["cdp/zombie.mjs", path.join(RT, "cdp", "zombie.mjs")],
769
+ ["extension/stale.js", path.join(RT, "extension", "stale.js")],
770
+ ];
771
+ for (const [, f] of stale) fs.writeFileSync(f, "// 上一版留下的\n");
772
+ const keepProfile = path.join(RT, "cli-profile", "Default", "Cookies");
773
+ fs.mkdirSync(path.dirname(keepProfile), { recursive: true });
774
+ fs.writeFileSync(keepProfile, "用户的登录态");
775
+ const keepProfileMjs = path.join(RT, "cli-profile", "手工.mjs");
776
+ fs.writeFileSync(keepProfileMjs, "// profile 里的,照样不许碰");
777
+ const keepLauncher = path.join(RT, "mcp-launcher-headless.sh");
778
+ fs.writeFileSync(keepLauncher, "#!/bin/sh\n# 人手工建的\n");
779
+
780
+ const third = runInstaller(["--yes", "--no-agents"], home);
781
+ check("再装一次仍是 0", third.status === 0, third.out.slice(-400));
782
+ for (const [label, f] of stale) check(`陈旧文件被清掉:${label}`, !fs.existsSync(f));
783
+ check("清掉的文件在输出里点了名", /清掉运行时里已不在清单中的旧文件/.test(third.out), third.out.slice(-300));
784
+ check("cli-profile 里的用户数据没被碰", fs.existsSync(keepProfile) && fs.existsSync(keepProfileMjs));
785
+ check("手工建的启动器没被碰", fs.existsSync(keepLauncher));
786
+ const manifestOk = ["host.mjs", "server.mjs", "token.mjs", "session-id.mjs", path.join("cdp", "bridge.mjs"), path.join("extension", "sw.js"), path.join("extension", "manifest.json")].filter(
787
+ (r) => !fs.existsSync(path.join(RT, r))
788
+ );
789
+ check("清单内的文件都还在", manifestOk.length === 0, manifestOk.join("、"));
790
+
791
+ fs.rmSync(home, { recursive: true, force: true });
792
+ }
793
+
794
+ console.log("\n\x1b[1m退出码:--check 报了红就得非零退出\x1b[0m");
795
+ {
796
+ const fresh = fs.mkdtempSync(path.join(os.tmpdir(), "aic-exit-"));
797
+ SANDBOX_HOMES.push(fresh);
798
+ const red = runInstaller(["--check"], fresh);
799
+ check("必红的自检退出码是 1", red.status === 1, `status=${red.status}\n${red.out.slice(-300)}`);
800
+ check("红的条数也说了出来", /项没过/.test(red.out), red.out.slice(-300));
801
+ fakeBrowserDir(fresh);
802
+ const green = runInstaller(["--yes", "--no-agents"], fresh);
803
+ check("全绿的安装退出码是 0", green.status === 0, `status=${green.status}\n${green.out.slice(-400)}`);
804
+ check("全绿时不打「项没过」", !/项没过/.test(green.out), green.out.slice(-200));
805
+
806
+ const bare = fs.mkdtempSync(path.join(os.tmpdir(), "aic-bare-"));
807
+ SANDBOX_HOMES.push(bare);
808
+ const pos = runInstaller(["check"], bare);
809
+ check("裸位置参数被拒", pos.status === 2 && /不认识的旗标/.test(pos.out), `status=${pos.status}\n${pos.out.slice(0, 200)}`);
810
+ check("被拒的那次没有落盘副作用", !fs.existsSync(path.join(bare, ".agent-in-chrome")), fs.readdirSync(bare).join(","));
811
+ const spaced = runInstaller(["--agents", "kimi"], bare);
812
+ check("`--agents kimi`(该用等号)也被拒,不会静默变成注册全部", spaced.status === 2 && /kimi/.test(spaced.out), `status=${spaced.status}\n${spaced.out.slice(0, 200)}`);
813
+
814
+ check("parseFlags:裸参数进 unknown", JSON.stringify(install.parseFlags(["check"]).unknown) === '["check"]');
815
+ check("parseFlags:认得的旗标不进 unknown", install.parseFlags(["--check", "--yes", "--agents=kimi"]).unknown.length === 0);
816
+ check("parseFlags:--agents= 仍解析得出", JSON.stringify(install.parseFlags(["--agents=a,b"]).agents) === '["a","b"]');
817
+
818
+ fs.rmSync(fresh, { recursive: true, force: true });
819
+ fs.rmSync(bare, { recursive: true, force: true });
820
+ }
821
+
822
+ console.log("\n\x1b[1mWindows 的 GUI 条目形状:cmd /c\x1b[0m");
823
+ {
824
+ const WIN_LAUNCHER = "C:\\Users\\me\\.agent-in-chrome\\agent-in-chrome\\mcp-launcher.bat";
825
+ const winAgents = buildAgents({ home: "/nonexistent-home", platform: "win32", serverPath: "C:\\rt\\server.mjs", mcpLauncher: WIN_LAUNCHER });
826
+ const darwinAgents = buildAgents({ home: "/nonexistent-home", platform: "darwin", serverPath: "/rt/server.mjs", mcpLauncher: "/rt/mcp-launcher.sh" });
827
+ const entryOf = (list, id) => {
828
+ const p = list.find((a) => a.id === id)?.preview;
829
+ return JSON.stringify((typeof p === "function" ? p() : p) || []);
830
+ };
831
+ for (const id of ["claude-desktop", "workbuddy", "zcode", "antigravity", "qoder-ide", "trae", "qoder-ide-cn", "trae-cn"]) {
832
+ const p = entryOf(winAgents, id);
833
+ check(`${id}:win32 上是 cmd /c 包一层`, p.includes('\\"command\\": \\"cmd\\"') && p.includes("/c") && p.includes("mcp-launcher.bat"), p.slice(0, 200));
834
+ }
835
+ check(
836
+ "dsh 也跟着包(它同样是拿不到终端 PATH 的常驻进程)",
837
+ entryOf(winAgents, "deepseek-harness").includes("command: 'cmd'") &&
838
+ entryOf(winAgents, "deepseek-harness").includes("args: ['/c'"),
839
+ entryOf(winAgents, "deepseek-harness")
840
+ );
841
+ check("CLI 客户端不受影响(还是 node + server.mjs)", entryOf(winAgents, "kimi").includes('\\"command\\": \\"node\\"'), entryOf(winAgents, "kimi"));
842
+ for (const id of ["claude-desktop", "workbuddy", "zcode", "trae"]) {
843
+ const p = entryOf(darwinAgents, id);
844
+ check(`${id}:darwin 形状不变(command 就是启动器本身)`, p.includes("/rt/mcp-launcher.sh") && !p.includes("cmd"), p.slice(0, 200));
845
+ }
846
+ }
847
+
848
+ {
849
+ const home = makeHome([]);
850
+ const launcher = path.join(home, "mcp-launcher.bat");
851
+ fs.writeFileSync(launcher, "@echo off\r\n");
852
+ fs.chmodSync(launcher, 0o755);
853
+ const cfgRel = path.join("AppData", "Roaming", "Claude", "claude_desktop_config.json");
854
+ const cfg = path.join(home, cfgRel);
855
+ fs.mkdirSync(path.dirname(cfg), { recursive: true });
856
+ fs.writeFileSync(cfg, canonicalJson({ mcpServers: { "agent-in-chrome": { command: "cmd", args: ["/c", launcher] } } }));
857
+ const winOpts = { home, platform: "win32", serverPath: SERVER_PATH, mcpLauncher: launcher, yes: true, agents: ["claude-desktop"] };
858
+ const r = await quiet(() => runAgents("check", winOpts));
859
+ const said = r.lines.join("\n");
860
+ check("win32 的 check 认得出「已注册」", /Claude Desktop: 已注册/.test(said), said.slice(-300));
861
+ check("check 不再去找一个叫 /c 的文件", !/\/c 不存在/.test(said), said.slice(-300));
862
+
863
+ fs.writeFileSync(cfg, canonicalJson({ mcpServers: { keepme: { command: "keep" }, "agent-in-chrome": { command: launcher, args: [] } } }));
864
+ await quiet(() => runAgents("install", winOpts));
865
+ const after = JSON.parse(fs.readFileSync(cfg, "utf8"));
866
+ check("旧形状被更新成 cmd /c", after.mcpServers["agent-in-chrome"].command === "cmd" && after.mcpServers["agent-in-chrome"].args[0] === "/c" && after.mcpServers["agent-in-chrome"].args[1] === launcher, JSON.stringify(after));
867
+ check("更新时别人的键没动", after.mcpServers.keepme?.command === "keep", JSON.stringify(after));
868
+ check("更新前留了备份", backupsOf(home, cfgRel).length >= 1, backupsOf(home, cfgRel).join(","));
869
+ const n = backupsOf(home, cfgRel).length;
870
+ const again = await quiet(() => runAgents("install", winOpts));
871
+ check("已是新形状时不写也不备份", backupsOf(home, cfgRel).length === n && again.lines.join("\n").includes("已是最新"), again.lines.join("\n").slice(-200));
872
+ }
873
+
874
+ console.log("\n\x1b[1mclaude mcp add:子进程继承调用方的 HOME\x1b[0m");
875
+ {
876
+ const binDir = fs.mkdtempSync(path.join(os.tmpdir(), "aic-fakeclaude-"));
877
+ const fake = path.join(binDir, "claude");
878
+ fs.writeFileSync(fake, `#!/bin/sh\nprintf '%s\\n' "$HOME" "$@" >> "$HOME/claude-cli.log"\n`);
879
+ fs.chmodSync(fake, 0o755);
880
+ const home = makeHome([]);
881
+ const realPath = process.env.PATH;
882
+ process.env.PATH = `${binDir}${path.delimiter}${realPath}`;
883
+ try {
884
+ await quiet(() => runAgents("install", { ...opts(home), agents: ["claude-code"] }));
885
+ } finally {
886
+ process.env.PATH = realPath;
887
+ }
888
+ const log = readOr(path.join(home, "claude-cli.log")) || "";
889
+ check("claude 子进程看到的 HOME 是我们给的那个假 home", log.split("\n")[0] === home, JSON.stringify(log.slice(0, 200)));
890
+ check("真的把 mcp add 发出去了", log.includes("mcp") && log.includes("add") && log.includes(SERVER_PATH), JSON.stringify(log.slice(0, 300)));
891
+ check("真实 HOME 下没有被写出日志(没走穿)", !fs.existsSync(path.join(REAL_HOME, "claude-cli.log")));
892
+ fs.rmSync(binDir, { recursive: true, force: true });
893
+ }
894
+
895
+ {
896
+ const binDir = fs.mkdtempSync(path.join(os.tmpdir(), "aic-fakecmd-"));
897
+ const spaced = path.join(binDir, "bin dir (x86)");
898
+ fs.mkdirSync(spaced, { recursive: true });
899
+ const fake = path.join(spaced, "claude.cmd");
900
+ fs.writeFileSync(fake, `#!/bin/sh\nprintf '%s\\n' "$HOME" "$@" >> "$HOME/claude-cli.log"\n`);
901
+ fs.chmodSync(fake, 0o755);
902
+ const home = makeHome([]);
903
+ const srvDir = path.join(binDir, "srv dir");
904
+ fs.mkdirSync(srvDir, { recursive: true });
905
+ const serverPath = path.join(srvDir, "server.mjs");
906
+ fs.writeFileSync(serverPath, "");
907
+ const realPath = process.env.PATH;
908
+ process.env.PATH = `${spaced}${path.delimiter}${realPath}`;
909
+ let said = "";
910
+ try {
911
+ const r = await quiet(() =>
912
+ runAgents("install", { home, platform: "win32", serverPath, mcpLauncher: path.join(home, "mcp-launcher.bat"), yes: true, agents: ["claude-code"] })
913
+ );
914
+ said = r.lines.join("\n");
915
+ } finally {
916
+ process.env.PATH = realPath;
917
+ }
918
+ const lines = (readOr(path.join(home, "claude-cli.log")) || "").split("\n");
919
+ check("win32 的 .cmd shim 这条路真的跑起来了(不是退回直接编辑)", /claude mcp add 完成/.test(said), said.slice(-300));
920
+ check(".cmd 子进程看到的也是我们给的 HOME", lines[0] === home, JSON.stringify(lines.slice(0, 3)));
921
+ check("带空格和括号的路径原样到达(引号是自己加的)", lines.includes(serverPath), JSON.stringify(lines));
922
+ check("stderr 上没有 DEP0190 弃用警告(整条命令拼成字符串走的)", !/DEP0190/.test(said), said.slice(-200));
923
+ fs.rmSync(binDir, { recursive: true, force: true });
924
+ }
925
+
926
+ console.log("\n\x1b[1m探测:没有证据就不算装着\x1b[0m");
927
+ {
928
+ const empty = path.join(os.tmpdir(), `aic-empty-${process.pid}-${Date.now()}`);
929
+ const detected = buildAgents({ home: empty, platform: "linux", serverPath: SERVER_PATH, mcpLauncher: SERVER_PATH }).filter((a) => a.detected);
930
+ const noEvidence = detected.filter((a) => !a.binOnPath);
931
+ check("没有任何证据时不会认出客户端", noEvidence.length === 0, noEvidence.map((a) => a.id).join(",") || "none");
932
+ check("探测本身不给不存在的客户端建目录", !fs.existsSync(empty), fs.existsSync(empty) ? fs.readdirSync(empty).join(",") : "什么都没建");
933
+ const fakeBin = fs.mkdtempSync(path.join(os.tmpdir(), "aic-onpath-"));
934
+ fs.writeFileSync(path.join(fakeBin, "kimi"), "#!/bin/sh\n");
935
+ fs.chmodSync(path.join(fakeBin, "kimi"), 0o755);
936
+ const realPath = process.env.PATH;
937
+ process.env.PATH = `${fakeBin}${path.delimiter}${realPath}`;
938
+ const withBin = buildAgents({ home: empty, platform: "linux", serverPath: SERVER_PATH, mcpLauncher: SERVER_PATH }).find((a) => a.id === "kimi");
939
+ process.env.PATH = realPath;
940
+ const withoutBin = buildAgents({ home: empty, platform: "linux", serverPath: SERVER_PATH, mcpLauncher: SERVER_PATH }).find((a) => a.id === "kimi");
941
+ check("PATH 上有二进制时 binOnPath 为真", withBin.binOnPath === true && withBin.detected === true);
942
+ check("撤掉之后就为假(这个字段不是恒真的摆设)", withoutBin.binOnPath === false, `本机 PATH 上是不是真装着 kimi:${withoutBin.binOnPath}`);
943
+ fs.rmSync(fakeBin, { recursive: true, force: true });
944
+ }
945
+
946
+ function diffHint(a, b) {
947
+ if (a === b) return "";
948
+ for (let i = 0; i < Math.max(a.length, b.length); i++)
949
+ if (a[i] !== b[i]) return `第 ${i} 个字符起不同:期望 ${JSON.stringify(a.slice(i, i + 40))},实际 ${JSON.stringify(b.slice(i, i + 40))}`;
950
+ return "";
951
+ }
952
+
953
+ {
954
+ const leaked = GUARDED.filter((f) => {
955
+ const now = readOr(f);
956
+ if (f === LIVE_WRITTEN)
957
+ return entrySnapshot(now) !== REAL_ENTRY_BEFORE[f] || SANDBOX_HOMES.some((h) => (now || "").includes(h));
958
+ return now !== REAL_SNAPSHOT[f];
959
+ });
960
+ check(
961
+ "SAFETY: 跑完这一轮,真实客户端配置一个字没动",
962
+ leaked.length === 0,
963
+ leaked.length ? `${leaked.join("、")} —— 发版前先查清楚` : "clean"
964
+ );
965
+ }
966
+
967
+ console.log(`\n${failed ? "\x1b[31m" : "\x1b[32m"}${passed} 通过,${failed} 失败\x1b[0m\n`);
968
+ process.exit(failed ? 1 : 0);