@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,1383 @@
1
+ #!/usr/bin/env node
2
+ // 安装 / 卸载 / 自检
3
+ //
4
+ // node scripts/install.mjs 装(npx @liang-hz/agent-in-chrome install 等价)
5
+ // node scripts/install.mjs --check 只检查,不改任何东西
6
+ // node scripts/install.mjs --uninstall 卸
7
+ //
8
+ // 会动的东西只有三处,全部可逆:
9
+ // 1. 各 Chromium 浏览器的 NativeMessagingHosts/org.liangai.agent_in_chrome.json (新增文件)
10
+ // 2. 本机各 agent(Claude Code / Claude Desktop / WorkBuddy / ZCode / opencode / Kimi /
11
+ // Gemini / Antigravity / Trae / Qoder / Codex)的 MCP 配置里
12
+ // mcpServers["agent-in-chrome"] 这一个键(改前自动备份,详见 scripts/agents.mjs)
13
+ // 3. ~/.agent-in-chrome/skills/{agent-in-chrome,install-agent-in-chrome}/ 与
14
+ // ~/.agent-in-chrome/commands/{agent-in-chrome,install-agent-in-chrome}.md(新增文件)
15
+ //
16
+ // 本文件同时被 bin/agent-in-chrome.mjs(npx 入口)import:主流程包在 run(mode, opts)
17
+ // 里导出,直接 node 跑本文件时走文件末尾的主守卫,两个入口行为一致。
18
+
19
+ import fs from "node:fs";
20
+ import os from "node:os";
21
+ import path from "node:path";
22
+ import { execFileSync } from "node:child_process";
23
+ import net from "node:net";
24
+ import { fileURLToPath, pathToFileURL } from "node:url";
25
+ import { getToken, tokenPath, ensureDataDir, permStatus, bridgeEndpoint } from "../mcp/token.mjs";
26
+ import { runAgents, buildAgents, agentProblemCount } from "./agents.mjs";
27
+ import { orphansFrom, pidAlive, readProfileRecord, stopBrowser } from "../mcp/cdp/browser-launch.mjs";
28
+
29
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
30
+ const HOME = os.homedir();
31
+ const HOST_NAME = "org.liangai.agent_in_chrome";
32
+ const MCP_NAME = "agent-in-chrome";
33
+ const PKG_NAME = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).name;
34
+
35
+ let MODE = "install";
36
+
37
+ // 默认走「加载已解压」——改完代码点一下刷新就生效,不用重新打包。
38
+ // --with-crx 才会把签名 CRX 写进 Chrome 的 External Extensions 目录自动装载;
39
+ // 「往浏览器里自动装扩展」是恶意软件的典型手法,所以做成显式选项而不是默认。
40
+ let WITH_CRX = false;
41
+
42
+ const EXT_IDS = fs
43
+ .readFileSync(path.join(ROOT, ".ext-id.txt"), "utf8")
44
+ .split("\n")
45
+ .map((l) => l.trim())
46
+ .filter((l) => l && !l.startsWith("#"));
47
+ const EXT_ID = EXT_IDS[0];
48
+ const DATA_DIR = path.join(HOME, ".agent-in-chrome");
49
+
50
+ const RUNTIME_DIR = path.join(DATA_DIR, "agent-in-chrome");
51
+ const HOST_SRC = path.join(ROOT, "native-host", "host.mjs");
52
+ const FG_SWIFT_SRC = path.join(ROOT, "native-host", "mac-foreground", "aic-fg.swift");
53
+ const SERVER_SRC = path.join(ROOT, "mcp", "server.mjs");
54
+ const HOST_PATH = path.join(RUNTIME_DIR, "host.mjs");
55
+ const SERVER_PATH = path.join(RUNTIME_DIR, "server.mjs");
56
+ const MCP_DIR = path.join(ROOT, "mcp");
57
+ function scanDeps(entryAbs, out = new Set()) {
58
+ let src;
59
+ try {
60
+ src = fs.readFileSync(entryAbs, "utf8");
61
+ } catch {
62
+ return out;
63
+ }
64
+ const specs = [
65
+ ...src.matchAll(/(?:from|import)\s*\(?\s*["'](\.[^"']+)["']/g),
66
+ ].map((m) => m[1]);
67
+ for (const spec of specs) {
68
+ const abs = path.resolve(path.dirname(entryAbs), spec);
69
+ if (!fs.existsSync(abs)) continue;
70
+ const rel = path.relative(MCP_DIR, abs);
71
+ if (rel.startsWith("..") || path.isAbsolute(rel)) continue;
72
+ if (out.has(rel)) continue;
73
+ out.add(rel);
74
+ scanDeps(abs, out);
75
+ }
76
+ return out;
77
+ }
78
+ const SERVER_DEPS = [...scanDeps(SERVER_SRC, scanDeps(HOST_SRC))].sort();
79
+ const EXT_FILES = ["sw.js", "manifest.json"];
80
+ const EXT_STABLE_DIR = path.join(DATA_DIR, "extension");
81
+ const IS_GIT_CHECKOUT = fs.existsSync(path.join(ROOT, ".git"));
82
+ const REINSTALL_CMD = IS_GIT_CHECKOUT ? "node scripts/install.mjs" : `npx ${PKG_NAME}@latest install`;
83
+ const WIN = process.platform === "win32";
84
+ const LAUNCHER = path.join(RUNTIME_DIR, WIN ? "native-host-launcher.bat" : "native-host-launcher.sh");
85
+ const MCP_LAUNCHER = path.join(RUNTIME_DIR, WIN ? "mcp-launcher.bat" : "mcp-launcher.sh");
86
+ const WIN_HOST_MANIFEST = path.join(RUNTIME_DIR, `${HOST_NAME}.json`);
87
+
88
+ const RUNTIME_KEEP_DIRS = new Set(["cli-profile"]);
89
+
90
+ function smokeTestRuntime() {
91
+ const srcVersion = /const VERSION = "([^"]+)"/.exec(fs.readFileSync(SERVER_SRC, "utf8"))?.[1];
92
+ const req =
93
+ JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-11-25", capabilities: {} } }) +
94
+ "\n" +
95
+ JSON.stringify({ jsonrpc: "2.0", id: 2, method: "tools/list", params: {} }) +
96
+ "\n";
97
+ const smokeSock = path.join(os.tmpdir(), `aic-check-${process.pid}.sock`);
98
+ let out;
99
+ const opts = {
100
+ input: req,
101
+ encoding: "utf8",
102
+ timeout: 20000,
103
+ stdio: ["pipe", "pipe", "pipe"],
104
+ env: { ...process.env, AGENT_IN_CHROME_SOCK: smokeSock },
105
+ };
106
+ try {
107
+ out = WIN ? runBat(MCP_LAUNCHER, [], opts) : execFileSync(MCP_LAUNCHER, [], opts);
108
+ } catch (e) {
109
+ const why = String(e.stderr || e.message || "").trim().split("\n").slice(0, 3).join(" ").slice(0, 240);
110
+ return bad(
111
+ `装好的 MCP server 起不来:${why}\n → 跑 ${REINSTALL_CMD} 重装;agent 那边看到的会是一句 Connection closed` +
112
+ (WIN ? `\n (这条是连着启动器一起验的:${path.basename(MCP_LAUNCHER)} 本身被 cmd 读坏时也会报在这里)` : "")
113
+ );
114
+ }
115
+ const msgs = out
116
+ .split("\n")
117
+ .filter(Boolean)
118
+ .map((l) => {
119
+ try {
120
+ return JSON.parse(l);
121
+ } catch {
122
+ return null;
123
+ }
124
+ })
125
+ .filter(Boolean);
126
+ try {
127
+ fs.unlinkSync(smokeSock);
128
+ } catch {}
129
+ const init = msgs.find((m) => m.id === 1)?.result;
130
+ const tools = msgs.find((m) => m.id === 2)?.result?.tools;
131
+ if (!init) return bad("装好的 MCP server 没能完成 initialize 握手,重装试试");
132
+ if (!tools?.length) return bad("装好的 MCP server 一个工具都没列出来,重装试试");
133
+ if (srcVersion && init.serverInfo?.version !== srcVersion) {
134
+ return warn(
135
+ `装的是 v${init.serverInfo?.version},${IS_GIT_CHECKOUT ? "仓库里" : "这个包"}是 v${srcVersion} —— 没重装,agent 用的还是旧代码。跑 ${REINSTALL_CMD}`
136
+ );
137
+ }
138
+ ok(`装好的 MCP server 真的起得来(v${init.serverInfo?.version},${tools.length} 个工具)`);
139
+ }
140
+
141
+ export function procSnapshot() {
142
+ if (WIN) {
143
+ const tmp = path.join(os.tmpdir(), `aic-ps-${process.pid}-${Math.random().toString(36).slice(2)}.txt`);
144
+ const script = `
145
+ $ProgressPreference = 'SilentlyContinue'
146
+ Get-CimInstance Win32_Process -Property ProcessId,CommandLine | ForEach-Object {
147
+ if ($_.CommandLine) { $_.ProcessId.ToString() + "\`t" + ($_.CommandLine -replace "[\`r\`n]", " ") }
148
+ } | Out-File -FilePath ${JSON.stringify(tmp)} -Encoding utf8`;
149
+ try {
150
+ execFileSync(
151
+ path.join(SYSTEM32, "WindowsPowerShell", "v1.0", "powershell.exe"),
152
+ ["-NoProfile", "-NonInteractive", "-EncodedCommand", Buffer.from(script, "utf16le").toString("base64")],
153
+ { stdio: ["ignore", "pipe", "pipe"], timeout: 30000 }
154
+ );
155
+ const procs = fs
156
+ .readFileSync(tmp, "utf8")
157
+ .replace(/^/, "")
158
+ .split("\n")
159
+ .map((l) => /^(\d+)\t(.*)$/.exec(l.trim()))
160
+ .filter(Boolean)
161
+ .map((m) => ({ pid: Number(m[1]), cmd: m[2] }));
162
+ return { procs, err: null };
163
+ } catch (e) {
164
+ return { procs: null, err: String(e?.message || e).split("\n")[0].slice(0, 120) };
165
+ } finally {
166
+ try {
167
+ fs.unlinkSync(tmp);
168
+ } catch {}
169
+ }
170
+ }
171
+ try {
172
+ const out = execFileSync("/bin/ps", ["-eo", "pid=,command="], { encoding: "utf8", maxBuffer: 8 << 20 });
173
+ return {
174
+ procs: out
175
+ .split("\n")
176
+ .map((l) => /^\s*(\d+)\s+(.*)$/.exec(l))
177
+ .filter(Boolean)
178
+ .map((m) => ({ pid: Number(m[1]), cmd: m[2] })),
179
+ err: null,
180
+ };
181
+ } catch (e) {
182
+ return { procs: null, err: String(e?.message || e).split("\n")[0].slice(0, 120) };
183
+ }
184
+ }
185
+
186
+ export function strayStatus({ procs, err }, isAlive = pidAlive) {
187
+ if (!procs) return { kind: "unavailable", err, pids: [] };
188
+ const readRecord = (dir) => readProfileRecord(String(dir).replace(/^"|"$/g, ""));
189
+ const pids = orphansFrom(procs, isAlive, { readRecord });
190
+ return { kind: pids.length ? "stray" : "clean", err: null, pids };
191
+ }
192
+
193
+ export function probeBridgeOwner(endpoint, ms = 1500) {
194
+ return new Promise((resolve) => {
195
+ let done = false;
196
+ const c = net.connect(endpoint);
197
+ const finish = (v) => {
198
+ if (done) return;
199
+ done = true;
200
+ try {
201
+ c.destroy();
202
+ } catch {}
203
+ resolve(v);
204
+ };
205
+ const t = setTimeout(() => finish("legacy"), ms);
206
+ t.unref?.();
207
+ c.setEncoding("utf8");
208
+ c.on("data", (d) => {
209
+ clearTimeout(t);
210
+ finish(/"type"\s*:\s*"challenge"/.test(d) ? "modern" : "legacy");
211
+ });
212
+ c.on("error", () => {
213
+ clearTimeout(t);
214
+ finish("free");
215
+ });
216
+ c.on("close", () => {
217
+ clearTimeout(t);
218
+ finish("free");
219
+ });
220
+ });
221
+ }
222
+
223
+ export function serverProcs({ procs, err }, serverPath = SERVER_PATH) {
224
+ if (!procs) return { kind: "unavailable", err, procs: [] };
225
+ const norm = (x) => String(x || "").toLowerCase().split("/").join("\\");
226
+ const needles = [norm(serverPath), "\\mcp\\server.mjs", "\\agent-in-chrome\\server.mjs"];
227
+ const hit = procs.filter((p) => {
228
+ const c = norm(p.cmd);
229
+ return needles.some((n) => c.includes(n));
230
+ });
231
+ return { kind: hit.length ? "found" : "none", err: null, procs: hit };
232
+ }
233
+
234
+ async function bridgeState() {
235
+ const endpoint = bridgeEndpoint(path.join(DATA_DIR, "agent-in-chrome.sock"));
236
+ const owner = await probeBridgeOwner(endpoint);
237
+ return { endpoint, owner, stale: owner === "legacy" ? serverProcs(procSnapshot()) : null };
238
+ }
239
+
240
+ function reportBridge({ owner, stale }) {
241
+ if (owner === "free") return skip("未建立 —— agent 没在跑,或 MCP server 没起来");
242
+ if (owner === "modern") return ok("已建立,且对面走的是本版握手(agent 侧的 MCP server 在跑)");
243
+
244
+ const hasPids = !!stale && stale.kind === "found" && stale.procs.length > 0;
245
+ const who =
246
+ !stale || stale.kind === "unavailable"
247
+ ? "\n (进程表查不了,请自己在任务管理器里找 node.exe)"
248
+ : hasPids
249
+ ? "\n 本机在跑的我们的 server:" +
250
+ stale.procs.map((p) => "pid " + p.pid).join("、") +
251
+ "(占着端点的是其中之一——零依赖下拿不到管道属主的 pid,只能把在跑的都列出来)"
252
+ : "\n 进程表里没认出我们自己的 server —— 可能它是从别处跑起来的,也可能是别的程序占着这个端点名";
253
+ const why = WIN
254
+ ? "这条桥现在是**不通**的:本版拨号方在管道上等不到出题就一个字节都不发(fail-closed,令牌不会泄露,但也连不上)。"
255
+ : "unix socket 上本版会退回老握手,所以还能用;但两边版本不一致,建议一并升上来。";
256
+ (WIN ? bad : warn)(
257
+ "端点有人占着,但对面不出题 —— 多半是升级前就在跑的旧版 MCP server。\n " +
258
+ why +
259
+ who +
260
+ "\n 修:先把还开着的 agent 客户端里的 MCP 重连一次(Claude Code / WorkBuddy 跑 /mcp);" +
261
+ (hasPids
262
+ ? "\n 重连仍不通,再从上面那些进程里挑着结束 —— 客户端下次用到时会自己重起新版。"
263
+ : "\n 仍不通的话,在任务管理器里找占着这个端点的 node.exe 结束掉。")
264
+ );
265
+ }
266
+
267
+ function checkStrayBrowsers() {
268
+ const st = strayStatus(procSnapshot());
269
+ if (st.kind === "unavailable")
270
+ return warn(`查不了本机进程表(${st.err}),这条没法判:残留的自启浏览器要靠你自己看`);
271
+ if (st.kind === "clean") return ok("没有残留的自启浏览器");
272
+ warn(
273
+ `发现 ${st.pids.length} 个残留的浏览器进程(pid ${st.pids.join(", ")}):它们是本工具起的,` +
274
+ `主人已经退出但没收干净。\n 它们用的是你自己那个浏览器——` +
275
+ (WIN
276
+ ? `你可能会看到「Chrome 已在运行」、点图标没反应。\n 收掉:taskkill /PID ${st.pids.join(" /PID ")} /F`
277
+ : `macOS 只认 app bundle,会因此认为「Chrome 已在运行」,你点 Dock 图标可能什么都不会发生。\n 收掉:kill ${st.pids.join(" ")}`)
278
+ );
279
+ }
280
+
281
+ /*
282
+ * 原子替换:拷到**同目录**的临时名,再 rename 盖上去。三件事都靠它——
283
+ * 不存在「文件缺失」的窗口:正在并发拉起 host/server 的 Chrome 或 agent 客户端
284
+ * 不会撞见 ENOENT(升级恰好发生在拉起的那一刻,是最常见也最难复现的失败);
285
+ * 正在跑的旧进程继续用旧 inode,内核层面互不干扰——它们的 import 缓存和文件
286
+ * 映射都指向被替换掉的那个 inode,不会读到半截新文件;
287
+ * 也从不「原地截断重写」一个可能正被读取或执行的文件。
288
+ * 同目录是硬要求:跨设备的 rename 会 EXDEV,而 os.tmpdir() 在很多机器上是另一个卷。
289
+ */
290
+ function replaceAtomically(from, to, mode = 0o644) {
291
+ fs.mkdirSync(path.dirname(to), { recursive: true });
292
+ const tmp = `${to}.incoming-${process.pid}`;
293
+ fs.copyFileSync(from, tmp);
294
+ if (!WIN) fs.chmodSync(tmp, mode);
295
+ try {
296
+ fs.renameSync(tmp, to);
297
+ } catch (e) {
298
+ try {
299
+ fs.unlinkSync(tmp);
300
+ } catch {}
301
+ throw e;
302
+ }
303
+ }
304
+
305
+ function runtimeManifest() {
306
+ return [
307
+ ["host.mjs", HOST_SRC, 0o755],
308
+ ["server.mjs", SERVER_SRC, 0o755],
309
+ ...SERVER_DEPS.map((d) => [d, path.join(ROOT, "mcp", d), 0o644]),
310
+ ...EXT_FILES.map((f) => [path.join("extension", f), path.join(ROOT, "extension", f), 0o644]),
311
+ ...(process.platform === "darwin" ? [[path.join("mac-foreground", "aic-fg.swift"), FG_SWIFT_SRC, 0o644]] : []),
312
+ ];
313
+ }
314
+
315
+ function sweepRuntime(keep) {
316
+ const removed = [];
317
+ const owned = (rel, name) =>
318
+ name.endsWith(".mjs") ||
319
+ /\.incoming-\d+$/.test(name) ||
320
+ rel.split(path.sep)[0] === "extension";
321
+ const walk = (dir, rel) => {
322
+ let ents;
323
+ try {
324
+ ents = fs.readdirSync(dir, { withFileTypes: true });
325
+ } catch {
326
+ return;
327
+ }
328
+ for (const e of ents) {
329
+ const childRel = rel ? path.join(rel, e.name) : e.name;
330
+ const child = path.join(dir, e.name);
331
+ if (e.isDirectory()) {
332
+ if (RUNTIME_KEEP_DIRS.has(childRel)) continue;
333
+ walk(child, childRel);
334
+ continue;
335
+ }
336
+ if (!e.isFile() || !owned(childRel, e.name)) continue;
337
+ if (keep.has(childRel)) continue;
338
+ try {
339
+ fs.unlinkSync(child);
340
+ removed.push(childRel);
341
+ } catch {}
342
+ }
343
+ };
344
+ walk(RUNTIME_DIR, "");
345
+ return removed;
346
+ }
347
+
348
+ function syncRuntime() {
349
+ ensureDataDir(DATA_DIR);
350
+ fs.mkdirSync(RUNTIME_DIR, { recursive: true });
351
+ const manifest = runtimeManifest();
352
+ for (const [rel, src, mode] of manifest) replaceAtomically(src, path.join(RUNTIME_DIR, rel), mode);
353
+ if (!IS_GIT_CHECKOUT) {
354
+ fs.rmSync(EXT_STABLE_DIR, { recursive: true, force: true });
355
+ fs.cpSync(path.join(ROOT, "extension"), EXT_STABLE_DIR, { recursive: true });
356
+ }
357
+ return sweepRuntime(new Set(manifest.map(([rel]) => rel)));
358
+ }
359
+
360
+ // Chrome 和 agent 桌面端都是 GUI 应用,PATH 里没有 nvm / homebrew 的 node——
361
+ // `#!/usr/bin/env node` 在它们手里必然 ENOENT。所以到处都必须写绝对路径。
362
+ // 用跑安装脚本的这个 node(process.execPath 是绝对路径),不依赖调用方的 PATH。
363
+ function resolveRuntime() {
364
+ return { command: process.execPath, env: {}, label: `系统 node (${process.execPath})` };
365
+ }
366
+ const RUNTIME = resolveRuntime();
367
+
368
+ const shq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
369
+
370
+ const ok = (s) => console.log(` \x1b[32m✓\x1b[0m ${s}`);
371
+ const skip = (s) => console.log(` \x1b[90m·\x1b[0m ${s}`);
372
+ const warn = (s) => console.log(` \x1b[33m!\x1b[0m ${s}`);
373
+ let problems = 0;
374
+ const bad = (s) => {
375
+ problems++;
376
+ console.log(` \x1b[31m✗\x1b[0m ${s}`);
377
+ };
378
+
379
+ const LEFTOVERS = [];
380
+
381
+ function step(what, fn) {
382
+ try {
383
+ return fn();
384
+ } catch (e) {
385
+ stepFailed(what, e);
386
+ return undefined;
387
+ }
388
+ }
389
+
390
+ async function stepAsync(what, fn) {
391
+ try {
392
+ return await fn();
393
+ } catch (e) {
394
+ stepFailed(what, e);
395
+ return undefined;
396
+ }
397
+ }
398
+
399
+ function stepFailed(what, e) {
400
+ const why = String(e?.code || e?.message || e).slice(0, 160);
401
+ bad(`${what} 失败:${why}(其余步骤照常继续)`);
402
+ LEFTOVERS.push({ what, why });
403
+ }
404
+
405
+ function removeTree(target) {
406
+ const failed = [];
407
+ const walk = (p) => {
408
+ let st;
409
+ try {
410
+ st = fs.lstatSync(p);
411
+ } catch {
412
+ return;
413
+ }
414
+ if (st.isDirectory() && !st.isSymbolicLink()) {
415
+ let entries = [];
416
+ try {
417
+ entries = fs.readdirSync(p);
418
+ } catch (e) {
419
+ failed.push([p, e.code || e.message]);
420
+ return;
421
+ }
422
+ for (const e of entries) walk(path.join(p, e));
423
+ }
424
+ try {
425
+ fs.rmSync(p, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
426
+ } catch (e) {
427
+ failed.push([p, e.code || e.message]);
428
+ }
429
+ };
430
+ walk(target);
431
+ return failed;
432
+ }
433
+
434
+ function removeAndReport(label, target, hint = "") {
435
+ if (!fs.existsSync(target)) return skip(`${label}: 本来就没有`);
436
+ const failed = removeTree(target);
437
+ if (!failed.length) return ok(`${label}已移除 ${target}`);
438
+ const [first, code] = failed[0];
439
+ bad(
440
+ `${label}没能全部移除(${failed.length} 项没删掉,第一个:${first} — ${code})` +
441
+ (hint ? `\n ${hint}` : "")
442
+ );
443
+ LEFTOVERS.push({ what: label, why: `${failed.length} 项残留于 ${target}`, hint });
444
+ }
445
+
446
+ function browserCandidates() {
447
+ const mac = path.join(HOME, "Library", "Application Support");
448
+ const lin = path.join(HOME, ".config");
449
+ const candidates =
450
+ process.platform === "darwin"
451
+ ? [
452
+ ["Chrome", path.join(mac, "Google/Chrome")],
453
+ ["Chrome Beta", path.join(mac, "Google/Chrome Beta")],
454
+ ["Chrome Canary", path.join(mac, "Google/Chrome Canary")],
455
+ ["Chromium", path.join(mac, "Chromium")],
456
+ ["Edge", path.join(mac, "Microsoft Edge")],
457
+ ["Brave", path.join(mac, "BraveSoftware/Brave-Browser")],
458
+ ["Vivaldi", path.join(mac, "Vivaldi")],
459
+ ["Opera", path.join(mac, "com.operasoftware.Opera")],
460
+ ["Arc", path.join(mac, "Arc/User Data")],
461
+ ]
462
+ : [
463
+ ["Chrome", path.join(lin, "google-chrome")],
464
+ ["Chromium", path.join(lin, "chromium")],
465
+ ["Edge", path.join(lin, "microsoft-edge")],
466
+ ["Brave", path.join(lin, "BraveSoftware/Brave-Browser")],
467
+ ["Vivaldi", path.join(lin, "vivaldi")],
468
+ ];
469
+ return candidates;
470
+ }
471
+
472
+ function browserDirs() {
473
+ return browserCandidates()
474
+ .filter(([, base]) => fs.existsSync(base))
475
+ .map(([name, base]) => [name, path.join(base, "NativeMessagingHosts")]);
476
+ }
477
+
478
+ function hostManifest() {
479
+ return {
480
+ name: HOST_NAME,
481
+ description: "Agent in Chrome native host",
482
+ path: LAUNCHER,
483
+ type: "stdio",
484
+ allowed_origins: EXT_IDS.map((id) => `chrome-extension://${id}/`),
485
+ };
486
+ }
487
+
488
+ const LOCALAPPDATA = process.env.LOCALAPPDATA || path.join(HOME, "AppData", "Local");
489
+ const REG_ROOT = (() => {
490
+ const v = process.env.AGENT_IN_CHROME_REG_ROOT;
491
+ if (!v) return "HKCU\\Software";
492
+ if (!/^HKCU\\Software\\[A-Za-z0-9_-]{1,64}$/.test(v))
493
+ throw new Error(
494
+ `AGENT_IN_CHROME_REG_ROOT=${JSON.stringify(v)} 不合法(只接受 HKCU\\Software\\<单层名>)。` +
495
+ `拒绝继续:回落到真实注册表根会改掉你当前生效的安装。`
496
+ );
497
+ return v;
498
+ })();
499
+ function winBrowserKeys() {
500
+ const candidates = [
501
+ ["Chrome", `${REG_ROOT}\\Google\\Chrome\\NativeMessagingHosts\\${HOST_NAME}`, path.join(LOCALAPPDATA, "Google", "Chrome", "User Data")],
502
+ ["Edge", `${REG_ROOT}\\Microsoft\\Edge\\NativeMessagingHosts\\${HOST_NAME}`, path.join(LOCALAPPDATA, "Microsoft", "Edge", "User Data")],
503
+ ["Brave", `${REG_ROOT}\\BraveSoftware\\Brave-Browser\\NativeMessagingHosts\\${HOST_NAME}`, path.join(LOCALAPPDATA, "BraveSoftware", "Brave-Browser", "User Data")],
504
+ ["Vivaldi", `${REG_ROOT}\\Vivaldi\\NativeMessagingHosts\\${HOST_NAME}`, path.join(LOCALAPPDATA, "Vivaldi", "User Data")],
505
+ ["Chromium", `${REG_ROOT}\\Chromium\\NativeMessagingHosts\\${HOST_NAME}`, path.join(LOCALAPPDATA, "Chromium", "User Data")],
506
+ ];
507
+ return candidates.filter(([, , userData]) => fs.existsSync(userData)).map(([name, key]) => [name, key]);
508
+ }
509
+
510
+ const REG_EXE = path.join(process.env.SystemRoot || "C:\\Windows", "System32", "reg.exe");
511
+
512
+ export function parseRegExport(text) {
513
+ const sz = /^@="((?:[^"\\]|\\.)*)"/m.exec(text || "");
514
+ if (sz) return sz[1].replace(/\\(.)/g, "$1");
515
+ const hex = /^@=hex\((?:1|2)\):((?:[0-9a-fA-F,\s\\])+)/m.exec(text || "");
516
+ if (hex) {
517
+ const bytes = hex[1]
518
+ .replace(/[\s\\]/g, "")
519
+ .split(",")
520
+ .filter((b) => b)
521
+ .map((b) => parseInt(b, 16));
522
+ return Buffer.from(bytes).toString("utf16le").replace(/\0+$/, "");
523
+ }
524
+ return null;
525
+ }
526
+
527
+ function regQueryDefault(key) {
528
+ const tmp = path.join(os.tmpdir(), `aic-reg-${process.pid}-${Math.random().toString(36).slice(2)}.reg`);
529
+ try {
530
+ execFileSync(REG_EXE, ["export", key, tmp, "/y"], { stdio: "pipe" });
531
+ return parseRegExport(fs.readFileSync(tmp, "utf16le"));
532
+ } catch {
533
+ try {
534
+ const out = execFileSync(REG_EXE, ["query", key, "/ve"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
535
+ const m = /REG_SZ\s+(.+)$/m.exec(out);
536
+ return m ? m[1].trim() : null;
537
+ } catch {
538
+ return null;
539
+ }
540
+ } finally {
541
+ try {
542
+ fs.unlinkSync(tmp);
543
+ } catch {}
544
+ }
545
+ }
546
+
547
+ function regSetDefault(key, value) {
548
+ execFileSync(REG_EXE, ["add", key, "/ve", "/t", "REG_SZ", "/d", value, "/f"], { stdio: "pipe" });
549
+ }
550
+
551
+ function regDeleteKey(key) {
552
+ try {
553
+ execFileSync(REG_EXE, ["delete", key, "/f"], { stdio: "pipe" });
554
+ return true;
555
+ } catch {
556
+ return false;
557
+ }
558
+ }
559
+
560
+ function doHostsWin() {
561
+ const body = JSON.stringify(hostManifest(), null, 2) + "\n";
562
+ if (MODE === "install") fs.writeFileSync(WIN_HOST_MANIFEST, body);
563
+ else if (MODE === "check") {
564
+ if (!fs.existsSync(WIN_HOST_MANIFEST)) bad(`host manifest 不存在(${WIN_HOST_MANIFEST}),请重新安装`);
565
+ else {
566
+ const cur = JSON.parse(fs.readFileSync(WIN_HOST_MANIFEST, "utf8"));
567
+ if (cur.path !== LAUNCHER) warn(`host manifest 指向 ${cur.path},应为 ${LAUNCHER},重装可修`);
568
+ else if (!EXT_IDS.every((id) => cur.allowed_origins?.includes(`chrome-extension://${id}/`)))
569
+ warn("host manifest 的扩展 ID 清单不全,重新安装可修");
570
+ else ok(`host manifest: ${WIN_HOST_MANIFEST}`);
571
+ }
572
+ }
573
+
574
+ const keys = winBrowserKeys();
575
+ if (keys.length === 0) {
576
+ bad("没找到任何 Chromium 系浏览器的用户数据目录");
577
+ return;
578
+ }
579
+ for (const [name, key] of keys) {
580
+ if (MODE === "check") {
581
+ const cur = regQueryDefault(key);
582
+ if (cur === null) bad(`${name}: 注册表未登记`);
583
+ else if (cur !== WIN_HOST_MANIFEST) warn(`${name}: 已登记但指向 ${cur},重装可修`);
584
+ else ok(`${name}: 注册表已登记`);
585
+ continue;
586
+ }
587
+ if (MODE === "uninstall") {
588
+ regDeleteKey(key) ? ok(`${name}: 注册表键已删除`) : skip(`${name}: 本来就没有`);
589
+ continue;
590
+ }
591
+ regSetDefault(key, WIN_HOST_MANIFEST);
592
+ ok(`${name}: ${key} → ${WIN_HOST_MANIFEST}`);
593
+ }
594
+ }
595
+
596
+ export function winLauncherBody(script) {
597
+ const envLines = Object.entries(RUNTIME.env)
598
+ .map(([k, v]) => `set "${k}=${v}"`)
599
+ .join("\r\n");
600
+ return (
601
+ `@echo off\r\n` +
602
+ `chcp 65001 >nul\r\n` +
603
+ `rem Generated by scripts/install.mjs. Do not edit (reinstall overwrites).\r\n` +
604
+ `rem chcp 65001 is required: cmd reads this file in the OEM code page,\r\n` +
605
+ `rem and a non-ASCII path (e.g. a Chinese user name) would be mangled.\r\n` +
606
+ (envLines ? envLines + "\r\n" : "") +
607
+ `"${RUNTIME.command}" "${script}" %*\r\n`
608
+ );
609
+ }
610
+
611
+ const SYSTEM32 = path.join(process.env.SystemRoot || "C:\\Windows", "System32");
612
+ const CMD_EXE = process.env.ComSpec || path.join(SYSTEM32, "cmd.exe");
613
+
614
+ function consoleCp() {
615
+ try {
616
+ const out = execFileSync(path.join(SYSTEM32, "chcp.com"), [], { encoding: "latin1", stdio: ["ignore", "pipe", "pipe"] });
617
+ const n = Number(/(\d{3,5})/.exec(out)?.[1]);
618
+ return Number.isInteger(n) && n > 0 ? n : null;
619
+ } catch {
620
+ return null;
621
+ }
622
+ }
623
+
624
+ function runBat(bat, args = [], opts = {}) {
625
+ const line = `/d /s /c ""${bat}"${args.map((a) => ` "${a}"`).join("")}"`;
626
+ const cp = consoleCp();
627
+ try {
628
+ return execFileSync(CMD_EXE, [line], { windowsVerbatimArguments: true, ...opts });
629
+ } finally {
630
+ if (cp && cp !== consoleCp()) {
631
+ try {
632
+ execFileSync(path.join(SYSTEM32, "chcp.com"), [String(cp)], { stdio: "ignore" });
633
+ } catch {}
634
+ }
635
+ }
636
+ }
637
+
638
+ function writeLauncher(dest, script, note) {
639
+ if (WIN) {
640
+ fs.writeFileSync(dest, winLauncherBody(script));
641
+ return;
642
+ }
643
+ const envLines = Object.entries(RUNTIME.env)
644
+ .map(([k, v]) => `export ${k}=${shq(v)}`)
645
+ .join("\n");
646
+ const body = `#!/bin/sh
647
+ # 由 scripts/install.mjs 生成,请勿手改(重装会覆盖)。
648
+ # ${note}
649
+ ${envLines}
650
+ exec ${shq(RUNTIME.command)} ${shq(script)} "$@"
651
+ `;
652
+ fs.writeFileSync(dest, body);
653
+ fs.chmodSync(dest, 0o755);
654
+ }
655
+
656
+ async function doForegroundHelper() {
657
+ const outDir = path.join(RUNTIME_DIR, "mac-foreground");
658
+ const bin = path.join(outDir, "aic-fg");
659
+ if (process.platform !== "darwin") return skip("前台归还 helper:只在 macOS 上有意义");
660
+ if (MODE === "uninstall") {
661
+ if (fs.existsSync(outDir)) removeAndReport("前台归还 helper", outDir);
662
+ else skip("前台归还 helper:本来就没有");
663
+ return;
664
+ }
665
+ if (MODE === "check") {
666
+ if (fs.existsSync(bin)) ok(`前台归还 helper: ${bin}`);
667
+ else warn("前台归还 helper 没编出来(没装 Xcode CLT?)——自开新页抢前台时走 open -b 兜底,慢一点但能用");
668
+ return;
669
+ }
670
+ const { buildForegroundHelper } = await import(
671
+ pathToFileURL(path.join(ROOT, "native-host", "mac-foreground", "build.mjs")).href
672
+ );
673
+ const r = buildForegroundHelper(outDir);
674
+ if (r.ok) ok(`前台归还 helper 已编译: ${r.out}`);
675
+ else warn(`前台归还 helper 未编译(${r.why})——自开新页抢前台时走 open -b 兜底`);
676
+ }
677
+
678
+ function doHosts() {
679
+ if (MODE === "install") {
680
+ const swept = syncRuntime();
681
+ ok(`运行时已同步到 ${RUNTIME_DIR}(避开 ~/Documents 的 TCC 限制)`);
682
+ if (swept.length) ok(`清掉运行时里已不在清单中的旧文件:${swept.join("、")}`);
683
+ writeLauncher(
684
+ LAUNCHER,
685
+ HOST_PATH,
686
+ "Chrome 以 GUI 应用身份拉起 native host,PATH 里没有 nvm/homebrew,必须写绝对路径。"
687
+ );
688
+ ok(`启动器: ${LAUNCHER} → ${RUNTIME.label}`);
689
+ } else if (MODE === "check") {
690
+ if (!fs.existsSync(LAUNCHER)) bad(`启动器 ${path.basename(LAUNCHER)} 不存在,请重新安装`);
691
+ else if (!WIN && !(fs.statSync(LAUNCHER).mode & 0o111)) bad("启动器没有可执行位");
692
+ else {
693
+ ok(`启动器: ${LAUNCHER}`);
694
+ if (WIN && fs.readFileSync(LAUNCHER, "utf8") !== winLauncherBody(HOST_PATH))
695
+ warn(`启动器是旧版本生成的(内容和现在会生成的不一致),跑一次 ${REINSTALL_CMD} 覆盖掉它`);
696
+ }
697
+ } else if (MODE === "uninstall") {
698
+ step("收掉自启的浏览器", () => {
699
+ if (stopBrowser({ force: true })) ok("已收掉本工具自启的浏览器(好让它的 profile 能删)");
700
+ });
701
+ removeAndReport(
702
+ "运行时目录",
703
+ RUNTIME_DIR,
704
+ "多半是浏览器还开着锁住了 cli-profile:关掉它再跑一次卸载,或手动删这个目录。"
705
+ );
706
+ }
707
+
708
+ if (WIN) return doHostsWin();
709
+
710
+ const dirs = browserDirs();
711
+ if (dirs.length === 0) {
712
+ bad(
713
+ `没找到任何 Chromium 系浏览器的配置目录(找过:${browserCandidates().map(([n]) => n).join("、")})\n` +
714
+ ` → 装了 Chrome 但从没打开过?先启动一次让它建出 profile,再重跑一遍安装器。\n` +
715
+ ` → 机器上确实没有桌面浏览器:插件模式用不上,改走 CLI 模式(AGENT_IN_CHROME_LAUNCH=1,见 docs/CLI.md)。`
716
+ );
717
+ return;
718
+ }
719
+ const body = JSON.stringify(hostManifest(), null, 2) + "\n";
720
+ for (const [name, dir] of dirs) {
721
+ const file = path.join(dir, `${HOST_NAME}.json`);
722
+ if (MODE === "check") {
723
+ if (!fs.existsSync(file)) {
724
+ bad(`${name}: 未安装`);
725
+ } else {
726
+ const cur = JSON.parse(fs.readFileSync(file, "utf8"));
727
+ if (cur.path !== LAUNCHER) warn(`${name}: 已安装但指向 ${cur.path}`);
728
+ else if (!EXT_IDS.every((id) => cur.allowed_origins?.includes(`chrome-extension://${id}/`)))
729
+ warn(`${name}: 已安装但扩展 ID 清单不全,重新安装可修`);
730
+ else ok(`${name}: 已安装`);
731
+ }
732
+ continue;
733
+ }
734
+ if (MODE === "uninstall") {
735
+ if (fs.existsSync(file)) {
736
+ fs.unlinkSync(file);
737
+ ok(`${name}: 已移除`);
738
+ } else skip(`${name}: 本来就没有`);
739
+ continue;
740
+ }
741
+ fs.mkdirSync(dir, { recursive: true });
742
+ fs.writeFileSync(file, body);
743
+ ok(`${name}: ${file}`);
744
+ }
745
+ }
746
+
747
+ const CHROME_BASE =
748
+ process.platform === "darwin"
749
+ ? path.join(HOME, "Library", "Application Support", "Google", "Chrome")
750
+ : WIN
751
+ ? path.join(LOCALAPPDATA, "Google", "Chrome", "User Data")
752
+ : path.join(HOME, ".config", "google-chrome");
753
+ const EXT_EXT_DIR = path.join(CHROME_BASE, "External Extensions");
754
+ const CRX_SRC = path.join(ROOT, "dist", "agent-in-chrome.crx");
755
+ const CRX_DST = path.join(EXT_EXT_DIR, "agent-in-chrome.crx");
756
+ const CRX_JSON = path.join(EXT_EXT_DIR, `${EXT_ID}.json`);
757
+
758
+ function extVersion() {
759
+ return JSON.parse(fs.readFileSync(path.join(ROOT, "extension", "manifest.json"), "utf8")).version;
760
+ }
761
+
762
+ function extensionLoadedIn() {
763
+ if (!fs.existsSync(CHROME_BASE)) return null;
764
+ for (const p of fs.readdirSync(CHROME_BASE)) {
765
+ const dir = path.join(CHROME_BASE, p);
766
+ if (!fs.existsSync(path.join(dir, "Preferences")) && !fs.existsSync(path.join(dir, "Secure Preferences")))
767
+ continue;
768
+ for (const id of EXT_IDS) {
769
+ if (fs.existsSync(path.join(dir, "Extensions", id))) return { profile: p, how: "打包安装" };
770
+ }
771
+ for (const f of ["Secure Preferences", "Preferences"]) {
772
+ const file = path.join(dir, f);
773
+ if (!fs.existsSync(file)) continue;
774
+ try {
775
+ const settings = JSON.parse(fs.readFileSync(file, "utf8"))?.extensions?.settings;
776
+ for (const id of EXT_IDS) {
777
+ const s = settings?.[id];
778
+ if (s) return { profile: p, how: s.location === 4 ? "加载已解压" : `location=${s.location}` };
779
+ }
780
+ } catch {}
781
+ }
782
+ }
783
+ return null;
784
+ }
785
+
786
+ function doCrx() {
787
+ if (!fs.existsSync(CHROME_BASE)) {
788
+ skip("没找到 Chrome,跳过扩展自动安装");
789
+ return;
790
+ }
791
+
792
+ if (MODE === "check") {
793
+ if (!fs.existsSync(CRX_JSON)) return bad("External Extensions 清单未安装");
794
+ if (!fs.existsSync(CRX_DST)) return bad("CRX 文件不在位");
795
+ const cur = JSON.parse(fs.readFileSync(CRX_JSON, "utf8"));
796
+ if (cur.external_version !== extVersion())
797
+ return warn(`已安装 v${cur.external_version},但源码是 v${extVersion()},重装以更新`);
798
+ const hit = extensionLoadedIn();
799
+ if (hit) ok(`扩展已被 Chrome 装载(${hit.profile},${hit.how})`);
800
+ else warn("清单就位但 Chrome 尚未装载 —— 自动装载走的是 External Extensions 目录,Chrome 只在启动时扫它,得重开一次 Chrome");
801
+ return;
802
+ }
803
+
804
+ if (MODE === "uninstall") {
805
+ for (const f of [CRX_JSON, CRX_DST]) {
806
+ if (fs.existsSync(f)) {
807
+ fs.unlinkSync(f);
808
+ ok(`已移除 ${path.basename(f)}`);
809
+ }
810
+ }
811
+ return;
812
+ }
813
+
814
+ if (!fs.existsSync(CRX_SRC)) {
815
+ bad(`还没打包 CRX,先跑 node scripts/pack-crx.mjs`);
816
+ return;
817
+ }
818
+ fs.mkdirSync(EXT_EXT_DIR, { recursive: true });
819
+ replaceAtomically(CRX_SRC, CRX_DST, 0o644);
820
+ fs.writeFileSync(
821
+ CRX_JSON,
822
+ JSON.stringify({ external_crx: CRX_DST, external_version: extVersion() }, null, 2) + "\n"
823
+ );
824
+ ok(`CRX: ${CRX_DST}`);
825
+ ok(`清单: ${CRX_JSON} (v${extVersion()})`);
826
+ }
827
+
828
+ function doMcp() {
829
+ if (MODE === "install") {
830
+ writeLauncher(
831
+ MCP_LAUNCHER,
832
+ SERVER_PATH,
833
+ "agent 桌面端不一定把 env 传给 MCP 进程;node 路径和环境都固化在这个 wrapper 里,跟调用方无关。"
834
+ );
835
+ ok(`启动器: ${MCP_LAUNCHER}`);
836
+ } else if (MODE === "check") {
837
+ if (!fs.existsSync(MCP_LAUNCHER)) bad("MCP 启动器不存在,请重新安装");
838
+ else if (!WIN && !(fs.statSync(MCP_LAUNCHER).mode & 0o111)) bad("MCP 启动器没有可执行位");
839
+ else ok(`启动器: ${MCP_LAUNCHER}`);
840
+ const missing = SERVER_DEPS.filter((d) => !fs.existsSync(path.join(RUNTIME_DIR, d)));
841
+ if (missing.length) bad(`运行时缺少 server.mjs 依赖的模块:${missing.join(", ")},跑 ${REINSTALL_CMD} 重装`);
842
+ else ok(`server 依赖模块齐全(${SERVER_DEPS.join(", ")})`);
843
+ smokeTestRuntime();
844
+ checkStrayBrowsers();
845
+ const extMissing = EXT_FILES.filter((f) => !fs.existsSync(path.join(RUNTIME_DIR, "extension", f)));
846
+ if (extMissing.length)
847
+ warn(`运行时没有 extension/${extMissing.join("、")}:CLI/headless 模式(AGENT_IN_CHROME_LAUNCH=1)起不来,重装即可(桌面模式不受影响)`);
848
+ else {
849
+ const a = JSON.parse(fs.readFileSync(path.join(ROOT, "extension", "manifest.json"), "utf8")).version;
850
+ const b = JSON.parse(fs.readFileSync(path.join(RUNTIME_DIR, "extension", "manifest.json"), "utf8")).version;
851
+ if (a !== b) warn(`运行时里的工具层是 v${b},源码是 v${a} —— CLI 模式跑的是旧代码,重装以更新`);
852
+ else ok(`CLI 模式的工具层就位(extension v${b})`);
853
+ }
854
+ }
855
+ }
856
+
857
+ export const ASSETS = [
858
+ {
859
+ label: "skill",
860
+ from: path.join(ROOT, "skills", "agent-in-chrome"),
861
+ to: path.join(DATA_DIR, "skills", "agent-in-chrome"),
862
+ removeWith: path.join(DATA_DIR, "skills", "agent-in-chrome"),
863
+ },
864
+ {
865
+ label: "command",
866
+ from: path.join(ROOT, "commands", "agent-in-chrome.md"),
867
+ to: path.join(DATA_DIR, "commands", "agent-in-chrome.md"),
868
+ },
869
+ {
870
+ label: "install skill",
871
+ from: path.join(ROOT, "skills", "install-agent-in-chrome"),
872
+ to: path.join(DATA_DIR, "skills", "install-agent-in-chrome"),
873
+ removeWith: path.join(DATA_DIR, "skills", "install-agent-in-chrome"),
874
+ },
875
+ {
876
+ label: "install command",
877
+ from: path.join(ROOT, "commands", "install-agent-in-chrome.md"),
878
+ to: path.join(DATA_DIR, "commands", "install-agent-in-chrome.md"),
879
+ },
880
+ ];
881
+
882
+ /*
883
+ * 拷一份资产过去:文件就是文件,目录连子目录一起。
884
+ *
885
+ * 覆盖式(force)而不是先删后拷:升级时目录里可能有用户或别的工具放的东西,
886
+ * 整个删掉是越界;同名文件覆盖到最新即可。
887
+ */
888
+ export function copyAsset(from, to) {
889
+ fs.mkdirSync(path.dirname(to), { recursive: true });
890
+ if (fs.statSync(from).isDirectory()) fs.cpSync(from, to, { recursive: true, force: true });
891
+ else fs.copyFileSync(from, to);
892
+ }
893
+
894
+ function doAssets() {
895
+ for (const a of ASSETS) {
896
+ if (MODE === "check") {
897
+ fs.existsSync(a.to) ? ok(`${a.label}: ${a.to}`) : bad(`${a.label}: 未安装`);
898
+ continue;
899
+ }
900
+ if (MODE === "uninstall") {
901
+ if (fs.existsSync(a.to)) removeAndReport(a.label, a.removeWith || a.to);
902
+ else skip(`${a.label}: 本来就没有`);
903
+ continue;
904
+ }
905
+ copyAsset(a.from, a.to);
906
+ ok(`${a.label}: ${a.to}`);
907
+ }
908
+ }
909
+
910
+ export function listSocks(dir) {
911
+ let names = [];
912
+ try {
913
+ names = fs.readdirSync(dir);
914
+ } catch {
915
+ return [];
916
+ }
917
+ return names
918
+ .filter((n) => /^agent-in-chrome.*\.sock$/.test(n))
919
+ .sort()
920
+ .map((n) => [n === "agent-in-chrome.sock" ? "桌面" : `CLI(${n})`, path.join(dir, n)]);
921
+ }
922
+
923
+ function doToken() {
924
+ const file = tokenPath(DATA_DIR);
925
+
926
+ if (MODE === "uninstall") {
927
+ if (fs.existsSync(file)) step("删除桥接令牌", () => (fs.unlinkSync(file), ok(`桥接令牌已删除 ${file}`)));
928
+ else skip("桥接令牌: 本来就没有");
929
+ return;
930
+ }
931
+
932
+ if (MODE === "install") {
933
+ getToken(DATA_DIR);
934
+ const st = permStatus(DATA_DIR);
935
+ ok(`桥接令牌: ${file}(权限 ${(st.tokenMode ?? 0).toString(8).padStart(4, "0")},内容不打印也不上传)`);
936
+ ok(`数据目录已收到 0700: ${DATA_DIR}`);
937
+ return;
938
+ }
939
+
940
+ const before = permStatus(DATA_DIR);
941
+ if (!before.tokenExists) bad(`没有桥接令牌 ${file},跑 ${REINSTALL_CMD} 生成`);
942
+ else if (WIN) ok(`桥接令牌就位(隔离交给 NTFS ACL,%USERPROFILE% 默认仅本人可读)`);
943
+ else if (before.tokenMode !== 0o600)
944
+ warn(`桥接令牌权限是 ${before.tokenMode.toString(8)},应为 600:chmod 600 ${file}`);
945
+ else ok(`桥接令牌就位(600)`);
946
+
947
+ if (WIN) return;
948
+
949
+ if (before.dirMode === null) {
950
+ skip(`数据目录还不存在 ${DATA_DIR}(装一次就有了)`);
951
+ } else if (before.dirMode !== 0o700) {
952
+ ensureDataDir(DATA_DIR);
953
+ warn(`数据目录原本是 ${before.dirMode.toString(8)}(别的用户能进来),已收紧为 700`);
954
+ } else if (before.dirMode === 0o700) ok("数据目录 700");
955
+
956
+ for (const [label, sock] of listSocks(DATA_DIR)) {
957
+ if (!fs.existsSync(sock)) continue;
958
+ const m = fs.statSync(sock).mode & 0o777;
959
+ if (m !== 0o600) warn(`${label} socket 权限是 ${m.toString(8)}(应为 600),重启 MCP server 即可修正`);
960
+ else ok(`${label} socket 600`);
961
+ }
962
+ }
963
+
964
+ const COOKIE_DIR = path.resolve(process.env.AGENT_IN_CHROME_COOKIE_DIR || path.join(DATA_DIR, "cookies"));
965
+ const TRACE_DIR = path.resolve(process.env.AGENT_IN_CHROME_TRACE_DIR || path.join(DATA_DIR, "traces"));
966
+ const SHOT_DIR = path.resolve(process.env.AGENT_IN_CHROME_SHOT_DIR || path.join(DATA_DIR, "screenshots"));
967
+ const LOG_FILES = [
968
+ path.join(DATA_DIR, "agent-in-chrome-cli.log"),
969
+ path.join(DATA_DIR, "agent-in-chrome-host.log"),
970
+ ];
971
+
972
+ function countFiles(dir) {
973
+ let n = 0;
974
+ const walk = (p) => {
975
+ let entries;
976
+ try {
977
+ entries = fs.readdirSync(p, { withFileTypes: true });
978
+ } catch {
979
+ return;
980
+ }
981
+ for (const e of entries) (e.isDirectory() ? walk : () => n++)(path.join(p, e.name));
982
+ };
983
+ if (fs.existsSync(dir)) walk(dir);
984
+ return n;
985
+ }
986
+
987
+ const insideDataDir = (p) => {
988
+ const rel = path.relative(DATA_DIR, p);
989
+ return !!rel && !rel.startsWith("..") && !path.isAbsolute(rel);
990
+ };
991
+
992
+ function doLeftovers() {
993
+ if (MODE !== "uninstall") return;
994
+
995
+ if (fs.existsSync(EXT_STABLE_DIR))
996
+ removeAndReport(`扩展副本(${countFiles(EXT_STABLE_DIR)} 个文件)`, EXT_STABLE_DIR);
997
+ else skip("扩展副本: 本来就没有(git 检出的用户直接从仓库加载)");
998
+
999
+ for (const f of LOG_FILES) {
1000
+ if (!fs.existsSync(f)) continue;
1001
+ step(`删除日志 ${path.basename(f)}`, () => (fs.unlinkSync(f), ok(`日志已删除 ${f}`)));
1002
+ }
1003
+
1004
+ const cookies = countFiles(COOKIE_DIR);
1005
+ if (cookies && insideDataDir(COOKIE_DIR))
1006
+ removeAndReport(`导出的 cookie(${cookies} 个文件,完整会话凭据的明文,不能留在盘上)`, COOKIE_DIR);
1007
+ else if (cookies)
1008
+ warn(`导出的 cookie 还在 ${COOKIE_DIR}(${cookies} 个文件,**完整会话凭据的明文**):\n 这个位置是你自己用 AGENT_IN_CHROME_COOKIE_DIR 指定的,不替你删,请自己处理。`);
1009
+
1010
+ for (const [label, dir, env] of [
1011
+ ["操作留痕 trace", TRACE_DIR, "AGENT_IN_CHROME_TRACE_DIR"],
1012
+ ["截图", SHOT_DIR, "AGENT_IN_CHROME_SHOT_DIR"],
1013
+ ]) {
1014
+ const n = countFiles(dir);
1015
+ if (n) warn(`${label}还留在 ${dir}(${n} 个文件):那是你让工具产出的东西,卸载不替你删。不要了自己删掉即可。`);
1016
+ }
1017
+
1018
+ step("移除空的数据目录", () => {
1019
+ if (fs.existsSync(DATA_DIR) && fs.readdirSync(DATA_DIR).length === 0) {
1020
+ fs.rmdirSync(DATA_DIR);
1021
+ ok(`数据目录已移除 ${DATA_DIR}`);
1022
+ }
1023
+ });
1024
+ }
1025
+
1026
+ const STORE_URL = EXT_IDS[1] ? `https://chromewebstore.google.com/detail/${EXT_IDS[1]}` : null;
1027
+
1028
+ export function configPathsOf(target) {
1029
+ return String(target || "")
1030
+ .split("、")
1031
+ .map((s) => s.replace(/(.*$/, "").trim())
1032
+ .filter(Boolean);
1033
+ }
1034
+
1035
+ function hasKeyDeep(node, name) {
1036
+ if (!node || typeof node !== "object" || Array.isArray(node)) return false;
1037
+ for (const [k, v] of Object.entries(node)) {
1038
+ if (k === name) return true;
1039
+ if (hasKeyDeep(v, name)) return true;
1040
+ }
1041
+ return false;
1042
+ }
1043
+
1044
+ export function configHasOurEntry(file, name = MCP_NAME) {
1045
+ let text;
1046
+ try {
1047
+ text = fs.readFileSync(file, "utf8");
1048
+ } catch {
1049
+ return false;
1050
+ }
1051
+ try {
1052
+ return hasKeyDeep(JSON.parse(text), name);
1053
+ } catch {}
1054
+ return text.includes(name);
1055
+ }
1056
+
1057
+ function launcherEntry() {
1058
+ return WIN ? { command: "cmd", args: ["/c", MCP_LAUNCHER], env: {} } : { command: MCP_LAUNCHER, args: [], env: {} };
1059
+ }
1060
+ function npxEntry() {
1061
+ return { command: "npx", args: ["-y", PKG_NAME, "serve"], env: {} };
1062
+ }
1063
+
1064
+ const browserKey = (n) => n.toLowerCase().replace(/\s+/g, "-");
1065
+
1066
+ /* 机器可读的安装事实。纯读,不改任何东西。 */
1067
+ export function configFacts() {
1068
+ const version = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8")).version;
1069
+ const nativeHost = { name: HOST_NAME, manifestPaths: {} };
1070
+ if (WIN) {
1071
+ nativeHost.registryKeys = {};
1072
+ for (const [name, key] of winBrowserKeys()) {
1073
+ nativeHost.manifestPaths[browserKey(name)] = WIN_HOST_MANIFEST;
1074
+ nativeHost.registryKeys[browserKey(name)] = key;
1075
+ }
1076
+ } else {
1077
+ for (const [name, dir] of browserDirs()) nativeHost.manifestPaths[browserKey(name)] = path.join(dir, `${HOST_NAME}.json`);
1078
+ }
1079
+ return {
1080
+ version,
1081
+ runtimeDir: RUNTIME_DIR,
1082
+ serverPath: SERVER_PATH,
1083
+ installed: fs.existsSync(MCP_LAUNCHER),
1084
+ mcp: { name: MCP_NAME, launcher: launcherEntry(), npx: npxEntry() },
1085
+ extension: {
1086
+ dir: IS_GIT_CHECKOUT ? path.join(ROOT, "extension") : EXT_STABLE_DIR,
1087
+ id: EXT_ID,
1088
+ ids: EXT_IDS,
1089
+ storeUrl: STORE_URL,
1090
+ },
1091
+ nativeHost,
1092
+ agents: buildAgents({ serverPath: SERVER_PATH, mcpLauncher: MCP_LAUNCHER }).map((a) => ({
1093
+ id: a.id,
1094
+ name: a.name,
1095
+ detected: !!a.detected,
1096
+ configPath: a.target,
1097
+ registered: configPathsOf(a.target).some((f) => configHasOurEntry(f)),
1098
+ })),
1099
+ };
1100
+ }
1101
+
1102
+ const tomlStr = (s) => JSON.stringify(String(s));
1103
+
1104
+ export const PRINT_FORMATS = ["json", "toml", "claude-cli"];
1105
+
1106
+ /* 把事实渲染成一种格式。返回的字符串就是 stdout 的全部内容。 */
1107
+ export function renderConfig(fmt, facts = configFacts()) {
1108
+ if (fmt === "json") return JSON.stringify(facts, null, 2) + "\n";
1109
+ const { launcher, npx } = facts.mcp;
1110
+ if (fmt === "toml") {
1111
+ return (
1112
+ `# agent-in-chrome v${facts.version} — Codex 风格的 MCP 配置\n` +
1113
+ `# 本机 launcher 版:路径在安装后稳定,且固化了 node 绝对路径(GUI 客户端没有终端 PATH)\n` +
1114
+ `[mcp_servers.${MCP_NAME}]\n` +
1115
+ `command = ${tomlStr(launcher.command)}\n` +
1116
+ `args = [${launcher.args.map(tomlStr).join(", ")}]\n` +
1117
+ `\n# 不依赖安装路径的版本(和上面二选一,同名表不能同时存在):\n` +
1118
+ `# [mcp_servers.${MCP_NAME}]\n` +
1119
+ `# command = ${tomlStr(npx.command)}\n` +
1120
+ `# args = [${npx.args.map(tomlStr).join(", ")}]\n`
1121
+ );
1122
+ }
1123
+ if (fmt === "claude-cli") {
1124
+ return (
1125
+ `claude mcp add --scope user ${MCP_NAME} -- node ${facts.serverPath}\n` +
1126
+ `\n# 不依赖安装路径的版本(和上面二选一):\n` +
1127
+ `# claude mcp add --scope user ${MCP_NAME} -- ${npx.command} ${npx.args.join(" ")}\n`
1128
+ );
1129
+ }
1130
+ throw new Error(`未知格式 ${fmt}`);
1131
+ }
1132
+
1133
+ function doPrintConfig(fmt, mode) {
1134
+ if (!PRINT_FORMATS.includes(fmt)) {
1135
+ console.error(`--print-config 的格式只认 ${PRINT_FORMATS.join(" / ")},收到的是 ${JSON.stringify(fmt)}`);
1136
+ return 2;
1137
+ }
1138
+ let text;
1139
+ try {
1140
+ text = renderConfig(fmt);
1141
+ } catch (e) {
1142
+ console.error(`生成配置失败:${String(e?.message || e)}`);
1143
+ return 1;
1144
+ }
1145
+ console.error(`# agent-in-chrome --print-config=${fmt}(只读:没有检查、也没有改动任何文件)`);
1146
+ if (mode !== "check") console.error(`# 注意:--print-config 忽略了 ${mode} 这个动作,什么都没装/没卸。`);
1147
+ process.stdout.write(text);
1148
+ return 0;
1149
+ }
1150
+
1151
+ function chmod() {
1152
+ if (MODE !== "install") return;
1153
+ ok(`运行时: ${RUNTIME.label}`);
1154
+ }
1155
+
1156
+ /*
1157
+ * 主流程。mode: "install" | "check" | "uninstall"。
1158
+ * opts: { withCrx, yes, agents(agent id 数组或 null), noAgents }
1159
+ *
1160
+ * bin/agent-in-chrome.mjs 和文件末尾的主守卫都走这里,git 克隆用户和 npx 用户
1161
+ * 拿到的是同一套行为。
1162
+ *
1163
+ * **返回退出码**(0 = 一条 ✗ 都没有,1 = 有)。两个入口都 process.exit 它:
1164
+ * `npm run check` 和 CI 里的 `&&` 才有可能看出失败。同一个进程里连着跑两次的
1165
+ * (测试就是这么用的)也对:计数每次进来清零。
1166
+ */
1167
+ export async function run(mode, opts = {}) {
1168
+ MODE = mode;
1169
+ problems = 0;
1170
+ if (opts.printConfig) return doPrintConfig(opts.printConfig, mode);
1171
+ WITH_CRX = !!opts.withCrx;
1172
+ if (WITH_CRX && !IS_GIT_CHECKOUT) {
1173
+ console.log("\n \x1b[33m!\x1b[0m --with-crx 只对克隆了仓库的开发者可用(需要 ext-key.pem 私钥,npm 包里不含)。");
1174
+ console.log(" 已改走默认的手动加载模式(效果一样,只是要你自己在 chrome://extensions 加载一次)。");
1175
+ WITH_CRX = false;
1176
+ }
1177
+ if (WITH_CRX && WIN) {
1178
+ console.log("\n \x1b[33m!\x1b[0m Windows 上 Chrome 不接受商店外的本地 CRX 自动装载,--with-crx 无效。");
1179
+ console.log(" 已改走手动加载模式(chrome://extensions 加载已解压)。");
1180
+ WITH_CRX = false;
1181
+ }
1182
+
1183
+ const TITLE = { install: "安装", uninstall: "卸载", check: "自检" }[MODE];
1184
+ console.log(`\n\x1b[1mAgent in Chrome — ${TITLE}\x1b[0m`);
1185
+ console.log(` 插件目录 ${ROOT}`);
1186
+ console.log(` 扩展 ID ${EXT_IDS.join("、")}\n`);
1187
+
1188
+ console.log("\x1b[1m1. 浏览器 native host\x1b[0m");
1189
+ step("浏览器 native host", doHosts);
1190
+ await stepAsync("前台归还 helper", doForegroundHelper);
1191
+ console.log("\n\x1b[1m2. Chrome 扩展\x1b[0m");
1192
+ if (!WITH_CRX && MODE === "install") {
1193
+ skip("手动加载模式(加 --with-crx 可改为自动装载)");
1194
+ } else if (!WITH_CRX && MODE === "check") {
1195
+ const hit = extensionLoadedIn();
1196
+ hit
1197
+ ? ok(`Chrome 已装载(${hit.profile},${hit.how})`)
1198
+ : bad("Chrome 尚未装载扩展(去 chrome://extensions 加载已解压)");
1199
+ } else {
1200
+ if (MODE === "install") {
1201
+ try {
1202
+ execFileSync(process.execPath, [path.join(ROOT, "scripts", "pack-crx.mjs")], { stdio: "pipe" });
1203
+ ok(`CRX 已打包 (v${extVersion()})`);
1204
+ } catch (e) {
1205
+ bad(`打包 CRX 失败: ${String(e.stderr || e.message).slice(0, 200)}`);
1206
+ }
1207
+ }
1208
+ step("Chrome 扩展", doCrx);
1209
+ }
1210
+ console.log("\n\x1b[1m3. agent MCP 注册\x1b[0m");
1211
+ step("MCP 启动器", doMcp);
1212
+ const agentResult =
1213
+ (await stepAsync("agent 注册", () =>
1214
+ runAgents(MODE, {
1215
+ serverPath: SERVER_PATH,
1216
+ mcpLauncher: MCP_LAUNCHER,
1217
+ yes: !!opts.yes,
1218
+ agents: opts.agents || null,
1219
+ noAgents: !!opts.noAgents,
1220
+ })
1221
+ )) || null;
1222
+ problems += agentProblemCount();
1223
+ console.log("\n\x1b[1m4. skill / command\x1b[0m");
1224
+ step("skill / command", doAssets);
1225
+ console.log("\n\x1b[1m5. 桥接令牌与权限\x1b[0m");
1226
+ step("桥接令牌", doToken);
1227
+ if (MODE === "uninstall") {
1228
+ console.log("\n\x1b[1m6. 其余产物\x1b[0m");
1229
+ doLeftovers();
1230
+ }
1231
+ if (MODE === "check") {
1232
+ console.log("\n\x1b[1m6. 桥接通道\x1b[0m");
1233
+ reportBridge(await bridgeState());
1234
+ }
1235
+ if (MODE === "install") {
1236
+ const st = await bridgeState();
1237
+ if (st.owner === "legacy") {
1238
+ console.log("\n\x1b[1m桥接通道\x1b[0m");
1239
+ reportBridge(st);
1240
+ }
1241
+ }
1242
+ if (MODE === "install") {
1243
+ console.log("");
1244
+ chmod();
1245
+ }
1246
+
1247
+ printOutro(agentResult);
1248
+ if (problems) console.log(`\x1b[31m${problems} 项没过\x1b[0m(往上翻看 ✗ 那几行),退出码 1\n`);
1249
+ return problems ? 1 : 0;
1250
+ }
1251
+
1252
+ function printRegistered(res) {
1253
+ if (MODE !== "install" || !res) return;
1254
+ const { installed = [], skipped = [] } = res;
1255
+ if (!installed.length) return;
1256
+ console.log(`
1257
+ \x1b[1m已注册进这 ${installed.length} 个客户端:\x1b[0m ${installed.join("、")}${
1258
+ skipped.length ? `\n(跳过:${skipped.join("、")})` : ""
1259
+ }
1260
+ 不想要其中某一家:\x1b[36mnpx ${PKG_NAME} uninstall --agents=${installed[0]}\x1b[0m
1261
+ 全部摘掉: \x1b[36mnpx ${PKG_NAME} uninstall\x1b[0m
1262
+ 只会删掉配置里 "${MCP_NAME}" 这一个键,改前自动备份,文件其余内容不动。`);
1263
+ }
1264
+
1265
+ function printOutro(agentResult) {
1266
+ printRegistered(agentResult);
1267
+ if (MODE === "install") {
1268
+ const steps = WITH_CRX
1269
+ ? ` \x1b[33m完全退出 Chrome 再重开\x1b[0m(⌘Q,不是关窗口)——只有\x1b[1m自动装扩展\x1b[0m
1270
+ 这条路要重启(Chrome 只在启动时扫 External Extensions 目录)。
1271
+ Chrome 可能弹一个「已添加新扩展程序」的气泡,点启用即可。`
1272
+ : ` chrome://extensions → 右上角开「开发者模式」→「加载已解压的扩展程序」→ 选:
1273
+ ${IS_GIT_CHECKOUT ? path.join(ROOT, "extension") : EXT_STABLE_DIR}${
1274
+ IS_GIT_CHECKOUT
1275
+ ? ""
1276
+ : `
1277
+ (这是安装器复制出来的稳定副本。npx 的缓存目录会被清理,不能从那里加载;
1278
+ 以后升级重跑一次 npx ${PKG_NAME}@latest install,这份副本会跟着更新。)`
1279
+ }
1280
+ macOS 的文件选择器默认不显示 . 开头的目录:按 ⌘⇧G 粘上面这条路径,或 ⌘⇧. 显示隐藏文件。
1281
+ 装上后核对卡片上的扩展 ID = ${EXT_ID},对不上就是选错目录了。
1282
+
1283
+ \x1b[1m把扩展钉到工具栏\x1b[0m:地址栏右边的拼图图标 🧩 → Agent in Chrome → 点图钉。
1284
+ 下面每一句「点扩展图标」都是指它,不钉住就得每次翻拼图菜单。
1285
+
1286
+ \x1b[1m不用重启 Chrome。\x1b[0m扩展每 30 秒会自己重连一次,装完等一下就通了;
1287
+ 等不及就点一下扩展图标 →「重连」,立即生效。
1288
+ (Chrome 是在每次 connectNative 时现读 native host 配置的,不是只在启动时读——
1289
+ 这一条 0.31.0 实测推翻了旧说法。)`;
1290
+
1291
+ console.log(`
1292
+ \x1b[1m还差这些:\x1b[0m
1293
+
1294
+ ${steps}
1295
+
1296
+ 然后在 agent 里让 MCP 生效——\x1b[1m同样不用重启\x1b[0m:
1297
+ Claude Code / WorkBuddy 跑 \x1b[36m/mcp\x1b[0m 重连即可;别的客户端在 Settings → MCP 里
1298
+ 重连一下 "${MCP_NAME}"。只有完全没有重连入口的客户端才需要重开。
1299
+
1300
+ \x1b[1m然后直接在 agent 里验:\x1b[0m说「列一下我打开的标签页」,或跑 /agent-in-chrome。
1301
+ 能列出你真实的标签页,就说明整条链路通了。
1302
+
1303
+ 要是不通,\x1b[33m先退出 agent\x1b[0m,再跑这条逐项自检看卡在哪:
1304
+ npx ${PKG_NAME}@latest check
1305
+
1306
+ (桥接 socket 是单主的:agent 开着的时候它占着通道,自检插不进去。
1307
+ 所以自检要在 agent 关闭时跑。装不上、连不通的完整排查步骤在 /install-agent-in-chrome 里。)
1308
+ `);
1309
+ } else if (MODE === "check") {
1310
+ console.log("\n上面有 ✗ 的项就是没装好的地方。全绿仍连不上:点扩展图标看弹窗里的断开原因,或点「重连」(不用重启 Chrome)。\n");
1311
+ } else {
1312
+ if (LEFTOVERS.length) {
1313
+ console.log(`\n\x1b[33m卸载没能全部完成\x1b[0m,这 ${LEFTOVERS.length} 项没收干净:`);
1314
+ for (const l of LEFTOVERS) console.log(` · ${l.what}:${l.why}${l.hint ? `\n ${l.hint}` : ""}`);
1315
+ console.log(` 其余步骤都已经跑完了。把上面挡路的东西(多半是还开着的浏览器)处理掉,再跑一次卸载即可。`);
1316
+ }
1317
+ console.log(`
1318
+ 卸载${LEFTOVERS.length ? "(部分)" : ""}完成。还剩两件事需要你手动做:
1319
+ 1. 到 chrome://extensions 里移除「Agent in Chrome」扩展
1320
+ 2. 在 agent 里刷新 MCP 列表(Claude Code / WorkBuddy 跑 /mcp),不用重启
1321
+ `);
1322
+ }
1323
+ }
1324
+
1325
+ /* bin/agent-in-chrome.mjs 也用它解析旗标,两个入口认同一套写法 */
1326
+ export function parseFlags(argv) {
1327
+ const agentsArg = argv.find((a) => a.startsWith("--agents="));
1328
+ const printArg = argv.find((a) => a === "--print-config" || a.startsWith("--print-config="));
1329
+ const KNOWN = new Set(["--uninstall", "--check", "--with-crx", "--yes", "-y", "--no-agents", "--help", "-h", "--print-config"]);
1330
+ return {
1331
+ printConfig: printArg ? printArg.slice("--print-config=".length) || "json" : null,
1332
+ mode: argv.includes("--uninstall") ? "uninstall" : argv.includes("--check") ? "check" : "install",
1333
+ help: argv.includes("--help") || argv.includes("-h"),
1334
+ withCrx: argv.includes("--with-crx"),
1335
+ yes: argv.includes("--yes") || argv.includes("-y"),
1336
+ noAgents: argv.includes("--no-agents"),
1337
+ agents: agentsArg
1338
+ ? agentsArg
1339
+ .slice("--agents=".length)
1340
+ .split(",")
1341
+ .map((s) => s.trim())
1342
+ .filter(Boolean)
1343
+ : null,
1344
+ unknown: argv.filter((a) => !KNOWN.has(a) && !a.startsWith("--agents=") && !a.startsWith("--print-config=")),
1345
+ };
1346
+ }
1347
+
1348
+ export const FLAGS_USAGE = `用法:node scripts/install.mjs [--check | --uninstall] [旗标]
1349
+
1350
+ 不带模式旗标就是安装。旗标:
1351
+ --check 自检:逐项检查装好没有,不改任何东西
1352
+ --uninstall 卸载:移除安装写入的一切(agent 配置只摘我们自己的键,改前有备份)
1353
+ --yes / -y 跳过逐个确认
1354
+ --agents=a,b 只注册这些 agent。可用 id 见 --check 的输出,当前是:
1355
+ claude-code、claude-desktop、workbuddy、zcode、opencode、kimi、
1356
+ gemini、antigravity、qoder-cli、qoder-cli-cn、qoder-ide-cn、
1357
+ trae-cn、qoder-ide、trae、deepseek-harness、codex
1358
+ --no-agents 跳过 agent 注册
1359
+ --print-config[=json|toml|claude-cli]
1360
+ 只把安装事实(路径、启动方式、扩展目录、各 agent 状态)打到 stdout,
1361
+ 一个字节都不写盘。其余提示走 stderr,便于管道接 jq。
1362
+ 给安装器没收录的客户端手动登记时用这个,不要凭记忆猜路径。
1363
+ --with-crx 自动装载扩展(仅克隆仓库的开发者,需要签名私钥)
1364
+ --help / -h 显示本帮助`;
1365
+
1366
+ const isMain = (() => {
1367
+ try {
1368
+ return !!process.argv[1] && fs.realpathSync(process.argv[1]) === fs.realpathSync(fileURLToPath(import.meta.url));
1369
+ } catch {
1370
+ return false;
1371
+ }
1372
+ })();
1373
+ if (isMain) {
1374
+ const flags = parseFlags(process.argv.slice(2));
1375
+ if (flags.help) {
1376
+ console.log(FLAGS_USAGE);
1377
+ } else if (flags.unknown.length) {
1378
+ console.error(`不认识的旗标:${flags.unknown.join(" ")}\n\n${FLAGS_USAGE}`);
1379
+ process.exit(2);
1380
+ } else {
1381
+ process.exitCode = await run(flags.mode, flags);
1382
+ }
1383
+ }