@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,921 @@
1
+ // Agent in Chrome — 把 MCP server 注册进本机装着的各个 agent
2
+ //
3
+ // 规矩,一条都不省:
4
+ // - 探测 = 配置目录/文件真实存在(Claude Code 另认 PATH 上的 claude 二进制)。
5
+ // 没装的 agent 不注册、更不凭空建它的配置目录。
6
+ // - 交互模式(TTY)下一屏列全、默认全选、回车确认(见 pick.mjs);勾中的那些在
7
+ // 真正落盘前逐个把「哪个文件、写什么」原样打出来。
8
+ // 非交互(无 TTY,即 agent 代跑 / CI)或 --yes 时全部注册——那些场景没人在键盘前,
9
+ // 挂着等按键就是永远不返回。--agents=a,b 限定范围,--no-agents 全跳过。
10
+ // - 改前备份成 <文件>.bak-<时间戳>;已是期望内容就不写也不备份(重跑不膨胀)。
11
+ // - **同一家客户端不注册两遍**:Claude Desktop 的连接器和 Claude Code 的 user scope
12
+ // 注册同名,两条都在时桌面端里的 Claude Code 会话会被连接器抢走工具命名空间。
13
+ // 所以桌面端那条只在 user scope 注册不到位时才写,已经写过的会被主动摘掉。
14
+ // - 只动 mcpServers["agent-in-chrome"](Codex 是 [mcp_servers.agent-in-chrome] 表)
15
+ // 这一个键,文件里其他内容一个字不碰。卸载同理,只摘我们自己的键。
16
+ // - 令牌内容任何时候不打印(这个模块根本不 import token.mjs,想打也打不了)。
17
+ //
18
+ // 零依赖:Codex 的 TOML 不引解析器,按「表头到下一个表头」做保守的整块替换/删除,
19
+ // 不重排、不重新格式化文件的其余部分。
20
+
21
+ import fs from "node:fs";
22
+ import os from "node:os";
23
+ import path from "node:path";
24
+ import { execFileSync } from "node:child_process";
25
+ import { fileURLToPath } from "node:url";
26
+ import { pickMulti } from "./pick.mjs";
27
+
28
+ const MCP_NAME = "agent-in-chrome";
29
+ const PKG_NAME = JSON.parse(
30
+ fs.readFileSync(path.join(path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."), "package.json"), "utf8")
31
+ ).name;
32
+ const MARKER = `# 由 agent-in-chrome 安装器管理(卸载:npx ${PKG_NAME} uninstall)`;
33
+
34
+ const ok = (s) => console.log(` \x1b[32m✓\x1b[0m ${s}`);
35
+ const skip = (s) => console.log(` \x1b[90m·\x1b[0m ${s}`);
36
+ const warn = (s) => console.log(` \x1b[33m!\x1b[0m ${s}`);
37
+ let agentProblems = 0;
38
+ /* agents.mjs 这一节数出来的 ✗ 条数(install.mjs 汇总用) */
39
+ export const agentProblemCount = () => agentProblems;
40
+ const bad = (s) => {
41
+ agentProblems++;
42
+ console.log(` \x1b[31m✗\x1b[0m ${s}`);
43
+ };
44
+
45
+ const BACKUP_KEEP = 3;
46
+ const BACKUP_KEEP_UNINSTALL = 1;
47
+
48
+ function backupFile(file, keep = BACKUP_KEEP) {
49
+ const b = `${file}.bak-${new Date().toISOString().replace(/[:.]/g, "")}`;
50
+ fs.copyFileSync(file, b);
51
+ pruneBackups(file, keep);
52
+ return b;
53
+ }
54
+
55
+ export function pruneBackups(file, keep = BACKUP_KEEP) {
56
+ const dir = path.dirname(file);
57
+ const prefix = `${path.basename(file)}.bak-`;
58
+ let olds;
59
+ try {
60
+ olds = fs.readdirSync(dir).filter((f) => f.startsWith(prefix)).sort();
61
+ } catch {
62
+ return [];
63
+ }
64
+ const doomed = olds.slice(0, Math.max(0, olds.length - keep));
65
+ for (const f of doomed) {
66
+ try {
67
+ fs.unlinkSync(path.join(dir, f));
68
+ } catch {}
69
+ }
70
+ return doomed;
71
+ }
72
+
73
+ function findOnPath(bin, platform = process.platform) {
74
+ const names = platform === "win32" ? [bin, `${bin}.cmd`, `${bin}.exe`, `${bin}.bat`] : [bin];
75
+ for (const dir of String(process.env.PATH || "").split(path.delimiter)) {
76
+ if (!dir) continue;
77
+ for (const name of names) {
78
+ const p = path.join(dir, name);
79
+ try {
80
+ fs.accessSync(p, fs.constants.X_OK);
81
+ if (fs.statSync(p).isFile()) return p;
82
+ } catch {}
83
+ }
84
+ }
85
+ return null;
86
+ }
87
+
88
+ /*
89
+ * 各家把 MCP server 放在配置里的**哪一段**,形状还都不一样,所以段落写成一条键路径:
90
+ *
91
+ * Claude / Kimi / Gemini / WorkBuddy → ["mcpServers"]
92
+ * ZCode → ["mcp","servers"]
93
+ * opencode → ["mcp"](且条目形状也不同)
94
+ */
95
+ const DEFAULT_SECTION = ["mcpServers"];
96
+
97
+ function getIn(obj, keyPath) {
98
+ let cur = obj;
99
+ for (const k of keyPath) {
100
+ if (!cur || typeof cur !== "object") return undefined;
101
+ cur = cur[k];
102
+ }
103
+ return cur;
104
+ }
105
+ function setIn(obj, keyPath, value) {
106
+ let cur = obj;
107
+ for (const k of keyPath.slice(0, -1)) {
108
+ if (!cur[k] || typeof cur[k] !== "object") cur[k] = {};
109
+ cur = cur[k];
110
+ }
111
+ cur[keyPath[keyPath.length - 1]] = value;
112
+ }
113
+ function delIn(obj, keyPath) {
114
+ const parent = getIn(obj, keyPath.slice(0, -1));
115
+ if (parent && typeof parent === "object") delete parent[keyPath[keyPath.length - 1]];
116
+ }
117
+
118
+ const OUR_NAMES = [MCP_NAME, "zcode-in-chrome"];
119
+
120
+ /*
121
+ * 按**名字**在整份配置里找出我们的条目,返回它们的路径(不按位置找:位置会变)。
122
+ *
123
+ * 只认**完全相等**的键名:`agent-in-chrome-2`、`my-agent-in-chrome` 这种含而不等的
124
+ * 是别人的东西,一根汗毛都不能动。
125
+ */
126
+ function findOurEntries(cfg, names = OUR_NAMES) {
127
+ const found = [];
128
+ const walk = (node, keyPath) => {
129
+ if (!node || typeof node !== "object" || Array.isArray(node)) return;
130
+ for (const [k, v] of Object.entries(node)) {
131
+ if (names.includes(k)) found.push({ path: [...keyPath, k], name: k });
132
+ else walk(v, [...keyPath, k]);
133
+ }
134
+ };
135
+ walk(cfg, []);
136
+ return found;
137
+ }
138
+
139
+ const previewJson = (entry, section = DEFAULT_SECTION) => {
140
+ const shell = {};
141
+ setIn(shell, [...section, MCP_NAME], entry);
142
+ return JSON.stringify(shell, null, 2).split("\n");
143
+ };
144
+
145
+ function parseJsonOrEmpty(text) {
146
+ const t = String(text ?? "").trim();
147
+ return t ? JSON.parse(t) : {};
148
+ }
149
+
150
+ /* 写入/更新 mcpServers["agent-in-chrome"],其余键原样保留。 */
151
+ function installJsonEntry(name, file, entry, { section = DEFAULT_SECTION } = {}) {
152
+ const existed = fs.existsSync(file);
153
+ let cfg = {};
154
+ if (existed) {
155
+ try {
156
+ cfg = parseJsonOrEmpty(fs.readFileSync(file, "utf8"));
157
+ } catch (e) {
158
+ bad(`${name}: ${file} 不是合法 JSON(${e.message}),先修好再来,这次没动它`);
159
+ return false;
160
+ }
161
+ }
162
+ const cur = getIn(cfg, [...section, MCP_NAME]);
163
+ if (cur && JSON.stringify(cur) === JSON.stringify(entry)) {
164
+ ok(`${name}: 已是最新,未改动 ${file}`);
165
+ return;
166
+ }
167
+ const backup = existed ? backupFile(file) : null;
168
+ const stale = findOurEntries(cfg).filter((h) => h.path.join(".") !== [...section, MCP_NAME].join("."));
169
+ for (const h of stale) delIn(cfg, h.path);
170
+ setIn(cfg, [...section, MCP_NAME], entry);
171
+ const out = JSON.stringify(cfg, null, 2) + "\n";
172
+ JSON.parse(out);
173
+ fs.mkdirSync(path.dirname(file), { recursive: true });
174
+ fs.writeFileSync(file, out);
175
+ ok(
176
+ `${name}: 已写入 ${file} 的 ${section.join(".")}["${MCP_NAME}"]` +
177
+ (stale.length ? `,顺带清掉 ${stale.length} 条旧的(${stale.map((h) => h.path.join(".")).join("、")})` : "") +
178
+ (backup ? `(备份 ${path.basename(backup)})` : "(新建文件)")
179
+ );
180
+ }
181
+
182
+ function checkJsonEntry(name, file, expected, { execCheck = false, section = DEFAULT_SECTION, target: targetOverride = null } = {}) {
183
+ if (!fs.existsSync(file)) return bad(`${name}: 未注册(${file} 不存在)`);
184
+ let cfg;
185
+ try {
186
+ cfg = parseJsonOrEmpty(fs.readFileSync(file, "utf8"));
187
+ } catch (e) {
188
+ return bad(`${name}: ${file} 不是合法 JSON(${e.message})`);
189
+ }
190
+ const cur = getIn(cfg, [...section, MCP_NAME]);
191
+ if (!cur) return bad(`${name}: 未注册(${file} 里没有 ${section.join(".")}["${MCP_NAME}"])`);
192
+ const curCmd = Array.isArray(cur.command) ? cur.command[0] : cur.command;
193
+ const expCmd = Array.isArray(expected.command) ? expected.command[0] : expected.command;
194
+ const curArg1 = Array.isArray(cur.command) ? cur.command[1] : cur.args?.[0];
195
+ const expArg1 = Array.isArray(expected.command) ? expected.command[1] : expected.args?.[0];
196
+ const wrongCmd = curCmd !== expCmd;
197
+ const wrongArgs = (expArg1 || null) !== (curArg1 ?? null);
198
+ if (wrongCmd || wrongArgs)
199
+ return warn(
200
+ `${name}: 已注册但指向 ${curCmd} ${curArg1 || ""}(期望 ${expCmd} ${expArg1 || ""}),重装可修`
201
+ );
202
+ const target = targetOverride || expArg1 || expCmd;
203
+ if (!fs.existsSync(target)) return warn(`${name}: 已注册但 ${target} 不存在,跑一次 install 即可`);
204
+ if (execCheck && process.platform !== "win32" && !(fs.statSync(target).mode & 0o111)) return warn(`${name}: ${target} 没有可执行位`);
205
+ ok(`${name}: 已注册,command 指向的文件存在${execCheck ? "且可执行" : ""}`);
206
+ }
207
+
208
+ function uninstallJsonEntry(name, file, { section = DEFAULT_SECTION } = {}) {
209
+ if (!fs.existsSync(file)) return skip(`${name}: 配置文件不存在,本来就没注册`);
210
+ let cfg;
211
+ try {
212
+ cfg = parseJsonOrEmpty(fs.readFileSync(file, "utf8"));
213
+ } catch (e) {
214
+ return warn(`${name}: ${file} 不是合法 JSON(${e.message}),没动它`);
215
+ }
216
+ const hits = findOurEntries(cfg);
217
+ if (!hits.length) return skip(`${name}: 本来就没注册`);
218
+ const backup = backupFile(file, BACKUP_KEEP_UNINSTALL);
219
+ for (const h of hits) delIn(cfg, h.path);
220
+ fs.writeFileSync(file, JSON.stringify(cfg, null, 2) + "\n");
221
+ const where = hits.map((h) => h.path.join(".")).join("、");
222
+ ok(`${name}: 已从 ${file} 移除 ${where}(备份 ${path.basename(backup)},其余内容未动)`);
223
+ }
224
+
225
+ const CODEX_HEADER_RE = new RegExp(
226
+ `^\\s*\\[mcp_servers\\.(?:"(?:${OUR_NAMES.join("|")})"|(?:${OUR_NAMES.join("|")}))\\]\\s*$`
227
+ );
228
+
229
+ function codexBlock(serverPath) {
230
+ return [MARKER, `[mcp_servers.${MCP_NAME}]`, `command = "node"`, `args = [${JSON.stringify(serverPath)}]`];
231
+ }
232
+
233
+ function codexFindBlock(lines) {
234
+ const at = lines.findIndex((l) => CODEX_HEADER_RE.test(l));
235
+ if (at === -1) return null;
236
+ let start = at;
237
+ while (start > 0 && lines[start - 1].trim().startsWith("#") && lines[start - 1].includes(MCP_NAME)) start--;
238
+ let end = lines.length;
239
+ for (let i = at + 1; i < lines.length; i++) {
240
+ if (/^\s*\[/.test(lines[i])) {
241
+ end = i;
242
+ break;
243
+ }
244
+ }
245
+ return { start, end, headerAt: at };
246
+ }
247
+
248
+ /* 没有就追加,有就整块替换(表头到下一个表头),文件其余部分原样。 */
249
+ function codexUpsert(text, serverPath) {
250
+ const block = codexBlock(serverPath);
251
+ const lines = text.split("\n");
252
+ const found = codexFindBlock(lines);
253
+ if (!found) {
254
+ const base = text.replace(/\n*$/, "");
255
+ return (base ? base + "\n\n" : "") + block.join("\n") + "\n";
256
+ }
257
+ let end = found.end;
258
+ const tail = [];
259
+ while (end > found.headerAt + 1 && lines[end - 1].trim() === "") {
260
+ tail.unshift(lines[end - 1]);
261
+ end--;
262
+ }
263
+ return [...lines.slice(0, found.start), ...block, ...tail, ...lines.slice(found.end)].join("\n");
264
+ }
265
+
266
+ /* 只摘我们的表(含管理注释),返回 null 表示本来就没有。 */
267
+ function codexRemove(text) {
268
+ let out = text.split("\n");
269
+ let found = codexFindBlock(out);
270
+ if (!found) return null;
271
+ const seams = [];
272
+ while (found) {
273
+ out = [...out.slice(0, found.start), ...out.slice(found.end)];
274
+ seams.push(found.start);
275
+ found = codexFindBlock(out);
276
+ }
277
+ for (const at of seams.sort((a, b) => b - a)) {
278
+ while (at > 0 && out[at - 1] === "" && out[at] === "") out.splice(at, 1);
279
+ }
280
+ while (out.length > 1 && out[out.length - 1] === "" && out[out.length - 2] === "") out.pop();
281
+ return out.join("\n");
282
+ }
283
+
284
+ function codexInstall(name, file, serverPath) {
285
+ const existed = fs.existsSync(file);
286
+ if (!existed) fs.mkdirSync(path.dirname(file), { recursive: true });
287
+ const text = existed ? fs.readFileSync(file, "utf8") : "";
288
+ const next = codexUpsert(text, serverPath);
289
+ if (next === text) {
290
+ ok(`${name}: 已是最新,未改动 ${file}`);
291
+ return;
292
+ }
293
+ const backup = existed ? backupFile(file) : null;
294
+ fs.writeFileSync(file, next);
295
+ ok(
296
+ `${name}: 已写入 ${file} 的 [mcp_servers.${MCP_NAME}] 表` +
297
+ (backup ? `(备份 ${path.basename(backup)},其余表未动)` : "(新建文件)")
298
+ );
299
+ }
300
+
301
+ function codexCheck(name, file, serverPath) {
302
+ if (!fs.existsSync(file)) return bad(`${name}: 未注册(${file} 不存在)`);
303
+ const lines = fs.readFileSync(file, "utf8").split("\n");
304
+ const found = codexFindBlock(lines);
305
+ if (!found) return bad(`${name}: 未注册(${file} 里没有 [mcp_servers.${MCP_NAME}] 表)`);
306
+ const block = lines.slice(found.start, found.end).join("\n");
307
+ if (!/command\s*=\s*"node"/.test(block) || !block.includes(JSON.stringify(serverPath)))
308
+ return warn(`${name}: 已注册但 command/args 不是期望值,重装可修`);
309
+ if (!fs.existsSync(serverPath)) return warn(`${name}: 已注册但 ${serverPath} 不存在,跑一次 install 即可`);
310
+ ok(`${name}: 已注册,command 指向的文件存在`);
311
+ }
312
+
313
+ function codexUninstall(name, file) {
314
+ if (!fs.existsSync(file)) return skip(`${name}: 配置文件不存在,本来就没注册`);
315
+ const text = fs.readFileSync(file, "utf8");
316
+ const next = codexRemove(text);
317
+ if (next === null) return skip(`${name}: 本来就没注册`);
318
+ const backup = backupFile(file, BACKUP_KEEP_UNINSTALL);
319
+ fs.writeFileSync(file, next);
320
+ ok(`${name}: 已从 ${file} 移除 [mcp_servers.${MCP_NAME}] 表(备份 ${path.basename(backup)},其余表未动)`);
321
+ }
322
+
323
+ // 和 Codex 的 TOML 一样零依赖:不引 YAML 解析器(它的方言还带 !!js 标签,通用解析器
324
+ // 本来也啃不动),按「顶层列表项」做保守的整块替换/删除。只认三种文件形状:
325
+ // 不存在 / 空或 `[]` / 顶层全是 `- ` 列表项与注释——其余形状一律不动手,把手动片段
326
+ // 打出来让用户自己贴。宁可少装一家,不许把用户的 profile 写坏。
327
+
328
+ const DSH_ENTRY_ID = "mcp-agent-in-chrome";
329
+
330
+ const yamlStr = (s) => `'${String(s).replace(/'/g, "''")}'`;
331
+
332
+ function dshBlock(mcpLauncher, entry = { command: mcpLauncher, args: [] }) {
333
+ return [
334
+ MARKER,
335
+ "- insert:",
336
+ ` - id: ${DSH_ENTRY_ID}`,
337
+ " name: '@deepseek-ai/dsh-mcp-client'",
338
+ " config:",
339
+ ` serverName: ${MCP_NAME}`,
340
+ " transport: stdio",
341
+ ` command: ${yamlStr(entry.command)}`,
342
+ ` args: [${(entry.args || []).map(yamlStr).join(", ")}]`,
343
+ ];
344
+ }
345
+
346
+ function dshItemRanges(lines) {
347
+ const heads = [];
348
+ for (let i = 0; i < lines.length; i++) if (/^- /.test(lines[i]) || /^-$/.test(lines[i])) heads.push(i);
349
+ return heads.map((h, k) => {
350
+ let start = h;
351
+ while (start > 0 && lines[start - 1].trim().startsWith("#") && lines[start - 1].includes(MCP_NAME)) start--;
352
+ let end = k + 1 < heads.length ? heads[k + 1] : lines.length;
353
+ while (end > h + 1 && lines[end - 1].trim() === "") end--;
354
+ return { start, end, head: h };
355
+ });
356
+ }
357
+
358
+ function dshItemIsOurs(text) {
359
+ const names = OUR_NAMES.join("|");
360
+ return (
361
+ new RegExp(`serverName:\\s*['"]?(${names})['"]?\\s*$`, "m").test(text) ||
362
+ new RegExp(`-\\s+id:\\s*['"]?mcp-(${names})['"]?\\s*$`, "m").test(text)
363
+ );
364
+ }
365
+
366
+ /*
367
+ * 从 patch 文件里摘掉我们的条目。返回 { lines, removed, mixed }:
368
+ * mixed 是「含我们的 server 但同一项里还有别的条目」的项——那种整项删会连别人的
369
+ * 一起删掉,只警告不动手。
370
+ */
371
+ function dshStrip(lines) {
372
+ const ranges = dshItemRanges(lines);
373
+ const doomed = [];
374
+ const mixed = [];
375
+ for (const r of ranges) {
376
+ const text = lines.slice(r.start, r.end).join("\n");
377
+ if (!dshItemIsOurs(text)) continue;
378
+ const entries = text.match(/^\s+- id:/gm) || [];
379
+ if (entries.length <= 1) doomed.push(r);
380
+ else mixed.push(r);
381
+ }
382
+ let out = lines;
383
+ for (const r of [...doomed].sort((a, b) => b.start - a.start)) {
384
+ out = [...out.slice(0, r.start), ...out.slice(r.end)];
385
+ }
386
+ const clean = [];
387
+ for (const l of out) {
388
+ if (l.trim() === "" && clean.length && clean[clean.length - 1].trim() === "") continue;
389
+ clean.push(l);
390
+ }
391
+ return { lines: clean, removed: doomed.length, mixed: mixed.length };
392
+ }
393
+
394
+ function dshShapeKnown(lines) {
395
+ return lines.every((l) => l.trim() === "" || /^[\s#-]/.test(l));
396
+ }
397
+
398
+ function dshUpsert(text, mcpLauncher, entry) {
399
+ const trimmed = String(text || "").trim();
400
+ const block = dshBlock(mcpLauncher, entry);
401
+ if (!trimmed || trimmed === "[]") return { next: block.join("\n") + "\n" };
402
+ const lines = text.split("\n");
403
+ if (!dshShapeKnown(lines)) return { error: "不是顶层列表形状的 YAML" };
404
+ const { lines: stripped, mixed } = dshStrip(lines);
405
+ if (mixed) return { error: `有 ${mixed} 项把我们的 server 和别的条目写在一起` };
406
+ const base = stripped.join("\n").replace(/\n*$/, "");
407
+ return { next: (base ? base + "\n\n" : "") + block.join("\n") + "\n" };
408
+ }
409
+
410
+ function dshInstallProfile(name, file, mcpLauncher, entry) {
411
+ const existed = fs.existsSync(file);
412
+ const text = existed ? fs.readFileSync(file, "utf8") : "";
413
+ const r = dshUpsert(text, mcpLauncher, entry);
414
+ if (r.error) {
415
+ warn(`${name}: ${file} ${r.error},没动它。手动加这一段(HMR 会热加载):`);
416
+ for (const l of dshBlock(mcpLauncher, entry)) console.log(` ${l}`);
417
+ return;
418
+ }
419
+ if (r.next === text) {
420
+ ok(`${name}: 已是最新,未改动 ${file}`);
421
+ return;
422
+ }
423
+ const backup = existed ? backupFile(file) : null;
424
+ if (!existed) fs.mkdirSync(path.dirname(file), { recursive: true });
425
+ fs.writeFileSync(file, r.next);
426
+ ok(
427
+ `${name}: 已写入 ${file}(dsh 会热加载,无需重启)` +
428
+ (backup ? `(备份 ${path.basename(backup)})` : "(新建文件)")
429
+ );
430
+ }
431
+
432
+ function dshCheckProfile(name, file, mcpLauncher) {
433
+ if (!fs.existsSync(file)) return bad(`${name}: 未注册(${file} 不存在)`);
434
+ const lines = fs.readFileSync(file, "utf8").split("\n");
435
+ const ours = dshItemRanges(lines)
436
+ .map((r) => lines.slice(r.start, r.end).join("\n"))
437
+ .filter((t) => dshItemIsOurs(t));
438
+ if (!ours.length) return bad(`${name}: 未注册(${file} 里没有 serverName: ${MCP_NAME} 的条目)`);
439
+ if (!ours.some((t) => t.includes(yamlStr(mcpLauncher)) || t.includes(`command: ${mcpLauncher}`)))
440
+ return warn(`${name}: 已注册但 command 不是期望的 ${mcpLauncher},重装可修`);
441
+ if (!fs.existsSync(mcpLauncher)) return warn(`${name}: 已注册但 ${mcpLauncher} 不存在,跑一次 install 即可`);
442
+ if (process.platform !== "win32" && !(fs.statSync(mcpLauncher).mode & 0o111))
443
+ return warn(`${name}: ${mcpLauncher} 没有可执行位`);
444
+ ok(`${name}: 已注册,command 指向的文件存在且可执行`);
445
+ }
446
+
447
+ function dshUninstallProfile(name, file) {
448
+ if (!fs.existsSync(file)) return skip(`${name}: 配置文件不存在,本来就没注册`);
449
+ const lines = fs.readFileSync(file, "utf8").split("\n");
450
+ const { lines: stripped, removed, mixed } = dshStrip(lines);
451
+ if (mixed) warn(`${name}: ${file} 里有 ${mixed} 项把我们的 server 和别的条目写在一起,请手动摘(其余照常处理)`);
452
+ if (!removed) return mixed ? undefined : skip(`${name}: 本来就没注册`);
453
+ const backup = backupFile(file, BACKUP_KEEP_UNINSTALL);
454
+ fs.writeFileSync(file, stripped.join("\n"));
455
+ ok(`${name}: 已从 ${file} 移除我们的条目(备份 ${path.basename(backup)},其余内容未动)`);
456
+ }
457
+
458
+ function dshProfiles(home) {
459
+ const root = path.join(home, ".dsh", "profiles");
460
+ const out = [];
461
+ let names;
462
+ try {
463
+ names = fs.readdirSync(root);
464
+ } catch {
465
+ return out;
466
+ }
467
+ for (const n of names) {
468
+ if (n === "node_modules") continue;
469
+ try {
470
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, n, "package.json"), "utf8"));
471
+ if (pkg?.dsh?.profile) out.push({ name: n, patchFile: path.join(root, n, "cordis.patch.yml") });
472
+ } catch {}
473
+ }
474
+ return out;
475
+ }
476
+
477
+ /*
478
+ * 本机认得的 agent:返回一张清单,每项带 id / name / detected / target /
479
+ * preview / install / check / uninstall。
480
+ *
481
+ * detected 的判据分两类,别混:
482
+ * · **命令行工具**(Claude Code / opencode / Kimi / Gemini / Qoder CLI)认
483
+ * **PATH 上的二进制**,配置目录只是补充——刚装完还没跑过的 CLI 没有配置目录。
484
+ * · **GUI 应用**(各家 IDE/桌面端)认配置目录:它们没有能在 PATH 上找到的入口。
485
+ *
486
+ * 两类都**不给没装的 agent 建目录**——凭空建目录会让别的工具误以为用户装了它。
487
+ */
488
+ export function buildAgents({ home = os.homedir(), platform = process.platform, serverPath, mcpLauncher }) {
489
+ const childEnv =
490
+ home === os.homedir() ? process.env : { ...process.env, HOME: home, USERPROFILE: home };
491
+ const claudeBin = findOnPath("claude", platform);
492
+ const claudeJson = path.join(home, ".claude.json");
493
+ const claudeNeedsShell = platform === "win32" && /\.(cmd|bat)$/i.test(claudeBin || "");
494
+ const cmdq = (s) => (/[\s&|<>^"()]/.test(String(s)) ? `"${String(s).replace(/"/g, `""`)}"` : String(s));
495
+ const runClaude = (args) =>
496
+ claudeNeedsShell
497
+ ? execFileSync([claudeBin, ...args].map(cmdq).join(" "), {
498
+ stdio: "pipe",
499
+ env: childEnv,
500
+ shell: true,
501
+ windowsHide: true,
502
+ })
503
+ : execFileSync(claudeBin, args, { stdio: "pipe", env: childEnv });
504
+ const appData =
505
+ process.env.APPDATA && home === os.homedir() ? process.env.APPDATA : path.join(home, "AppData", "Roaming");
506
+ const desktopConfig =
507
+ platform === "darwin"
508
+ ? path.join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json")
509
+ : platform === "win32"
510
+ ? path.join(appData, "Claude", "claude_desktop_config.json")
511
+ : path.join(home, ".config", "Claude", "claude_desktop_config.json");
512
+ const workbuddyConfig = path.join(home, ".workbuddy", "mcp.json");
513
+ const workbuddyLegacyConfig = path.join(home, ".workbuddy", ".mcp.json");
514
+ const zcodeConfig = path.join(home, ".zcode", "cli", "config.json");
515
+ const opencodeConfig = path.join(home, ".config", "opencode", "opencode.json");
516
+ const kimiConfig = path.join(home, ".kimi", "mcp.json");
517
+ const geminiConfig = path.join(home, ".gemini", "settings.json");
518
+ const antigravityConfig = path.join(home, ".gemini", "config", "mcp_config.json");
519
+ const qoderCliConfig = path.join(home, ".qoder", "settings.json");
520
+ const qoderCliBin = findOnPath("qodercli", platform) || (fs.existsSync(path.join(home, ".qoder", "bin", "qodercli")) ? path.join(home, ".qoder", "bin", "qodercli") : null);
521
+ const qoderLive = (dataFolder, appDataName) => {
522
+ const b =
523
+ platform === "darwin"
524
+ ? path.join(home, "Library", "Application Support", appDataName, "SharedClientCache", "mcp.json")
525
+ : platform === "win32"
526
+ ? path.join(appData, appDataName, "SharedClientCache", "mcp.json")
527
+ : path.join(home, ".config", appDataName, "SharedClientCache", "mcp.json");
528
+ const a = path.join(home, dataFolder, "mcp.json");
529
+ return { live: fs.existsSync(b) ? b : a, all: [a, b] };
530
+ };
531
+ const qoderIde = qoderLive(".qoder", "Qoder");
532
+ const qoderIdeConfig = qoderIde.live;
533
+ const qoderCnCliConfig = path.join(home, ".qoder-cn", "settings.json");
534
+ const qoderCnCliBin = findOnPath("qoderclicn", platform) || (fs.existsSync(path.join(home, ".qoder-cn", "bin", "qoderclicn")) ? path.join(home, ".qoder-cn", "bin", "qoderclicn") : null);
535
+ const qoderCnIde = qoderLive(".qoder-cn", "QoderCN");
536
+ const qoderCnIdeConfig = qoderCnIde.live;
537
+ const traeCnConfig =
538
+ platform === "darwin"
539
+ ? path.join(home, "Library", "Application Support", "Trae CN", "User", "mcp.json")
540
+ : platform === "win32"
541
+ ? path.join(appData, "Trae CN", "User", "mcp.json")
542
+ : path.join(home, ".config", "Trae CN", "User", "mcp.json");
543
+ const traeConfig =
544
+ platform === "darwin"
545
+ ? path.join(home, "Library", "Application Support", "Trae", "User", "mcp.json")
546
+ : platform === "win32"
547
+ ? path.join(appData, "Trae", "User", "mcp.json")
548
+ : path.join(home, ".config", "Trae", "User", "mcp.json");
549
+ const codexConfig = path.join(home, ".codex", "config.toml");
550
+
551
+ const userScopeRegistered = () => {
552
+ try {
553
+ return !!JSON.parse(fs.readFileSync(claudeJson, "utf8"))?.mcpServers?.[MCP_NAME];
554
+ } catch {
555
+ return false;
556
+ }
557
+ };
558
+ const desktopHasOurs = () => {
559
+ try {
560
+ return !!JSON.parse(fs.readFileSync(desktopConfig, "utf8"))?.mcpServers?.[MCP_NAME];
561
+ } catch {
562
+ return false;
563
+ }
564
+ };
565
+ const DESKTOP_WHY =
566
+ `同名连接器会抢走桌面端里 Claude Code 会话的工具命名空间(那个会话自己拉起了 server 却用不上,` +
567
+ `四段身份全断、多轮对话共用一个 sid);而桌面端的本地 agent 模式跑的就是 Claude Code 引擎、` +
568
+ `带 --setting-sources=user,project,local,user scope 那条它自己就读得到`;
569
+
570
+ const nodeEntry = { command: "node", args: [serverPath] };
571
+ const ZCODE_SECTION = ["mcp", "servers"];
572
+ const OPENCODE_SECTION = ["mcp"];
573
+ const guiEntry = () =>
574
+ platform === "win32"
575
+ ? { command: "cmd", args: ["/c", mcpLauncher] }
576
+ : { command: mcpLauncher, args: [] };
577
+ const zcodeDesktopEntry = { type: "stdio", ...guiEntry(), timeoutMs: 60000 };
578
+ const opencodeEntry = { type: "local", command: ["node", serverPath], enabled: true };
579
+ const claudeEntry = { type: "stdio", command: "node", args: [serverPath], env: {} };
580
+ const desktopEntry = guiEntry();
581
+ const workbuddyEntry = { type: "stdio", ...guiEntry(), disabled: false };
582
+ const guiCheck = { execCheck: true, target: mcpLauncher };
583
+
584
+ return [
585
+ {
586
+ id: "claude-code",
587
+ name: "Claude Code",
588
+ binOnPath: !!claudeBin,
589
+ detected: !!claudeBin || fs.existsSync(claudeJson),
590
+ target: claudeBin ? `${claudeJson}(经 claude mcp add,scope: user)` : claudeJson,
591
+ preview: claudeBin
592
+ ? [`$ claude mcp remove --scope user ${MCP_NAME} # 已注册时先清掉,失败忽略`, `$ claude mcp add --scope user ${MCP_NAME} -- node ${serverPath}`]
593
+ : previewJson(claudeEntry),
594
+ install() {
595
+ if (claudeBin) {
596
+ try {
597
+ runClaude(["mcp", "remove", "--scope", "user", MCP_NAME]);
598
+ } catch {}
599
+ try {
600
+ runClaude(["mcp", "add", "--scope", "user", MCP_NAME, "--", "node", serverPath]);
601
+ ok(`Claude Code: claude mcp add 完成(scope: user,落在 ${claudeJson})`);
602
+ return;
603
+ } catch (e) {
604
+ warn(`Claude Code: claude mcp add 失败(${String(e.stderr || e.message).trim().slice(0, 160)}),退回直接编辑 ${claudeJson}`);
605
+ }
606
+ }
607
+ installJsonEntry("Claude Code", claudeJson, claudeEntry);
608
+ },
609
+ check() {
610
+ checkJsonEntry("Claude Code", claudeJson, claudeEntry);
611
+ },
612
+ uninstall() {
613
+ if (claudeBin) {
614
+ try {
615
+ runClaude(["mcp", "remove", "--scope", "user", MCP_NAME]);
616
+ ok(`Claude Code: claude mcp remove 完成(scope: user)`);
617
+ } catch {}
618
+ }
619
+ let still = false;
620
+ try {
621
+ still = !!JSON.parse(fs.readFileSync(claudeJson, "utf8"))?.mcpServers?.[MCP_NAME];
622
+ } catch {}
623
+ if (still) uninstallJsonEntry("Claude Code", claudeJson);
624
+ else if (!claudeBin) skip("Claude Code: 本来就没注册");
625
+ },
626
+ },
627
+ {
628
+ id: "claude-desktop",
629
+ name: "Claude Desktop",
630
+ detected: fs.existsSync(path.dirname(desktopConfig)),
631
+ target: desktopConfig,
632
+ get preview() {
633
+ if (!userScopeRegistered()) return previewJson(desktopEntry);
634
+ return desktopHasOurs()
635
+ ? [`# 摘掉 mcpServers["${MCP_NAME}"]:${DESKTOP_WHY}`]
636
+ : [`# 不写:Claude Code 已在 user scope 注册(${claudeJson}),${DESKTOP_WHY}`];
637
+ },
638
+ install() {
639
+ if (!userScopeRegistered()) return installJsonEntry("Claude Desktop", desktopConfig, desktopEntry);
640
+ if (desktopHasOurs()) {
641
+ uninstallJsonEntry("Claude Desktop", desktopConfig);
642
+ return warn(`Claude Desktop: 上面这条是**主动摘掉**的 —— ${DESKTOP_WHY}`);
643
+ }
644
+ skip(`Claude Desktop: 不注册(Claude Code 已在 user scope 注册)—— ${DESKTOP_WHY}`);
645
+ },
646
+ check() {
647
+ if (!userScopeRegistered()) return checkJsonEntry("Claude Desktop", desktopConfig, desktopEntry, guiCheck);
648
+ if (desktopHasOurs()) return warn(`Claude Desktop: 有一条和 Claude Code user scope 同名的连接器,重跑 install 会摘掉它 —— ${DESKTOP_WHY}`);
649
+ skip(`Claude Desktop: 有意不注册(走 Claude Code 的 user scope)`);
650
+ },
651
+ uninstall: () => uninstallJsonEntry("Claude Desktop", desktopConfig),
652
+ },
653
+ {
654
+ id: "workbuddy",
655
+ name: "WorkBuddy",
656
+ detected: fs.existsSync(path.join(home, ".workbuddy")),
657
+ target: workbuddyConfig,
658
+ preview: previewJson(workbuddyEntry),
659
+ install() {
660
+ uninstallJsonEntry("WorkBuddy", workbuddyLegacyConfig);
661
+ installJsonEntry("WorkBuddy", workbuddyConfig, workbuddyEntry);
662
+ },
663
+ check() {
664
+ try {
665
+ if (JSON.parse(fs.readFileSync(workbuddyLegacyConfig, "utf8"))?.mcpServers?.[MCP_NAME])
666
+ warn(`WorkBuddy: ${workbuddyLegacyConfig} 里有一条没人读的注册(那是 WorkBuddy 自己的输出文件),重跑 install 会摘掉它`);
667
+ } catch {}
668
+ checkJsonEntry("WorkBuddy", workbuddyConfig, workbuddyEntry, guiCheck);
669
+ },
670
+ uninstall() {
671
+ uninstallJsonEntry("WorkBuddy", workbuddyConfig);
672
+ uninstallJsonEntry("WorkBuddy", workbuddyLegacyConfig);
673
+ },
674
+ },
675
+ {
676
+ id: "zcode",
677
+ name: "ZCode",
678
+ detected: fs.existsSync(path.join(home, ".zcode")),
679
+ target: zcodeConfig,
680
+ preview: previewJson(zcodeDesktopEntry, ZCODE_SECTION),
681
+ install: () => installJsonEntry("ZCode", zcodeConfig, zcodeDesktopEntry, { section: ZCODE_SECTION }),
682
+ check: () => checkJsonEntry("ZCode", zcodeConfig, zcodeDesktopEntry, { ...guiCheck, section: ZCODE_SECTION }),
683
+ uninstall: () => uninstallJsonEntry("ZCode", zcodeConfig, { section: ZCODE_SECTION }),
684
+ },
685
+ {
686
+ id: "opencode",
687
+ name: "opencode",
688
+ binOnPath: !!findOnPath("opencode", platform),
689
+ detected: !!findOnPath("opencode", platform) || fs.existsSync(path.join(home, ".config", "opencode")),
690
+ target: opencodeConfig,
691
+ preview: previewJson(opencodeEntry, OPENCODE_SECTION),
692
+ install: () => installJsonEntry("opencode", opencodeConfig, opencodeEntry, { section: OPENCODE_SECTION }),
693
+ check: () => checkJsonEntry("opencode", opencodeConfig, opencodeEntry, { section: OPENCODE_SECTION }),
694
+ uninstall: () => uninstallJsonEntry("opencode", opencodeConfig, { section: OPENCODE_SECTION }),
695
+ },
696
+ {
697
+ id: "kimi",
698
+ name: "Kimi CLI",
699
+ binOnPath: !!findOnPath("kimi", platform),
700
+ detected: !!findOnPath("kimi", platform) || fs.existsSync(path.join(home, ".kimi")),
701
+ target: kimiConfig,
702
+ preview: previewJson(nodeEntry),
703
+ install: () => installJsonEntry("Kimi CLI", kimiConfig, nodeEntry),
704
+ check: () => checkJsonEntry("Kimi CLI", kimiConfig, nodeEntry),
705
+ uninstall: () => uninstallJsonEntry("Kimi CLI", kimiConfig),
706
+ },
707
+ {
708
+ id: "gemini",
709
+ name: "Gemini CLI",
710
+ binOnPath: !!findOnPath("gemini", platform),
711
+ detected: !!findOnPath("gemini", platform) || fs.existsSync(path.join(home, ".gemini")),
712
+ target: geminiConfig,
713
+ preview: previewJson(nodeEntry),
714
+ install: () => installJsonEntry("Gemini CLI", geminiConfig, nodeEntry),
715
+ check: () => checkJsonEntry("Gemini CLI", geminiConfig, nodeEntry),
716
+ uninstall: () => uninstallJsonEntry("Gemini CLI", geminiConfig),
717
+ },
718
+ {
719
+ id: "antigravity",
720
+ name: "Antigravity",
721
+ detected: fs.existsSync(path.join(home, ".gemini", "config")),
722
+ target: antigravityConfig,
723
+ preview: previewJson(desktopEntry),
724
+ install: () => installJsonEntry("Antigravity", antigravityConfig, desktopEntry),
725
+ check: () => checkJsonEntry("Antigravity", antigravityConfig, desktopEntry, guiCheck),
726
+ uninstall: () => uninstallJsonEntry("Antigravity", antigravityConfig),
727
+ },
728
+ {
729
+ id: "qoder-cli",
730
+ name: "Qoder CLI",
731
+ binOnPath: !!qoderCliBin,
732
+ detected: !!qoderCliBin,
733
+ target: qoderCliConfig,
734
+ preview: previewJson(nodeEntry),
735
+ install: () => installJsonEntry("Qoder CLI", qoderCliConfig, nodeEntry),
736
+ check: () => checkJsonEntry("Qoder CLI", qoderCliConfig, nodeEntry),
737
+ uninstall: () => uninstallJsonEntry("Qoder CLI", qoderCliConfig),
738
+ },
739
+ {
740
+ id: "qoder-cli-cn",
741
+ name: "Qoder CN CLI",
742
+ binOnPath: !!qoderCnCliBin,
743
+ detected: !!qoderCnCliBin,
744
+ target: qoderCnCliConfig,
745
+ preview: previewJson(nodeEntry),
746
+ install: () => installJsonEntry("Qoder CN CLI", qoderCnCliConfig, nodeEntry),
747
+ check: () => checkJsonEntry("Qoder CN CLI", qoderCnCliConfig, nodeEntry),
748
+ uninstall: () => uninstallJsonEntry("Qoder CN CLI", qoderCnCliConfig),
749
+ },
750
+ {
751
+ id: "qoder-ide-cn",
752
+ name: "Qoder CN IDE",
753
+ detected: fs.existsSync(path.join(home, ".qoder-cn")),
754
+ target: qoderCnIdeConfig,
755
+ preview: previewJson(desktopEntry),
756
+ install: () => installJsonEntry("Qoder CN IDE", qoderCnIdeConfig, desktopEntry),
757
+ check: () => checkJsonEntry("Qoder CN IDE", qoderCnIdeConfig, desktopEntry, guiCheck),
758
+ uninstall: () => qoderCnIde.all.filter((f) => fs.existsSync(f)).forEach((f) => uninstallJsonEntry("Qoder CN IDE", f)),
759
+ },
760
+ {
761
+ id: "trae-cn",
762
+ name: "Trae CN",
763
+ detected: fs.existsSync(path.dirname(traeCnConfig)),
764
+ target: traeCnConfig,
765
+ preview: previewJson(desktopEntry),
766
+ install: () => installJsonEntry("Trae CN", traeCnConfig, desktopEntry),
767
+ check: () => checkJsonEntry("Trae CN", traeCnConfig, desktopEntry, guiCheck),
768
+ uninstall: () => uninstallJsonEntry("Trae CN", traeCnConfig),
769
+ },
770
+ {
771
+ id: "qoder-ide",
772
+ name: "Qoder IDE",
773
+ detected: fs.existsSync(path.join(home, ".qoder")),
774
+ target: qoderIdeConfig,
775
+ preview: previewJson(desktopEntry),
776
+ install: () => installJsonEntry("Qoder IDE", qoderIdeConfig, desktopEntry),
777
+ check: () => checkJsonEntry("Qoder IDE", qoderIdeConfig, desktopEntry, guiCheck),
778
+ uninstall: () => qoderIde.all.filter((f) => fs.existsSync(f)).forEach((f) => uninstallJsonEntry("Qoder IDE", f)),
779
+ },
780
+ {
781
+ id: "trae",
782
+ name: "Trae",
783
+ detected: fs.existsSync(path.dirname(traeConfig)),
784
+ target: traeConfig,
785
+ preview: previewJson(desktopEntry),
786
+ install: () => installJsonEntry("Trae", traeConfig, desktopEntry),
787
+ check: () => checkJsonEntry("Trae", traeConfig, desktopEntry, guiCheck),
788
+ uninstall: () => uninstallJsonEntry("Trae", traeConfig),
789
+ },
790
+ {
791
+ id: "deepseek-harness",
792
+ name: "DeepSeek Harness",
793
+ detected: dshProfiles(home).length > 0,
794
+ target: dshProfiles(home).map((p) => p.patchFile).join("、") || path.join(home, ".dsh", "profiles"),
795
+ preview: dshBlock(mcpLauncher, guiEntry()),
796
+ install() {
797
+ for (const p of dshProfiles(home)) dshInstallProfile(`DeepSeek Harness (${p.name})`, p.patchFile, mcpLauncher, guiEntry());
798
+ },
799
+ check() {
800
+ for (const p of dshProfiles(home)) dshCheckProfile(`DeepSeek Harness (${p.name})`, p.patchFile, mcpLauncher);
801
+ },
802
+ uninstall() {
803
+ for (const p of dshProfiles(home)) dshUninstallProfile(`DeepSeek Harness (${p.name})`, p.patchFile);
804
+ },
805
+ },
806
+ {
807
+ id: "codex",
808
+ name: "Codex CLI",
809
+ detected: fs.existsSync(path.join(home, ".codex")),
810
+ target: codexConfig,
811
+ preview: codexBlock(serverPath),
812
+ install: () => codexInstall("Codex CLI", codexConfig, serverPath),
813
+ check: () => codexCheck("Codex CLI", codexConfig, serverPath),
814
+ uninstall: () => codexUninstall("Codex CLI", codexConfig),
815
+ },
816
+ ];
817
+ }
818
+
819
+ /*
820
+ * mode: "install" | "check" | "uninstall"
821
+ * opts: { serverPath, mcpLauncher, yes, agents(id 数组或 null), noAgents, home, platform }
822
+ *
823
+ * 返回 { installed, skipped, cancelled }(id 数组 / 布尔)——装完那一屏要能说出
824
+ * 「注册了哪几家、怎么单独摘掉」。默认全装的正当性全靠这句话,不能只在日志里一闪而过。
825
+ */
826
+ export async function runAgents(mode, opts = {}) {
827
+ const empty = { installed: [], skipped: [], failed: [], cancelled: false };
828
+ if (opts.noAgents) {
829
+ skip("按 --no-agents 跳过 agent 注册");
830
+ if (mode === "install") printGenericSnippet(opts.serverPath);
831
+ return empty;
832
+ }
833
+ const agents = buildAgents(opts);
834
+ const known = new Set(agents.map((a) => a.id));
835
+ const only = opts.agents ? new Set(opts.agents) : null;
836
+ if (only) {
837
+ for (const id of only)
838
+ if (!known.has(id)) warn(`--agents 里的 "${id}" 不认识(可选:${[...known].join(", ")})`);
839
+ }
840
+
841
+ const targets = [];
842
+ for (const a of agents) {
843
+ if (only && !only.has(a.id)) {
844
+ skip(`${a.name}: 按 --agents 跳过`);
845
+ continue;
846
+ }
847
+ if (!a.detected) {
848
+ skip(`${a.name}: 未检测到`);
849
+ continue;
850
+ }
851
+ if (mode === "check") {
852
+ a.check();
853
+ continue;
854
+ }
855
+ if (mode === "uninstall") {
856
+ a.uninstall();
857
+ continue;
858
+ }
859
+ targets.push(a);
860
+ }
861
+
862
+ if (mode !== "install") return empty;
863
+ if (!targets.length) {
864
+ skip("没有探测到任何已安装的 agent 客户端");
865
+ printGenericSnippet(opts.serverPath);
866
+ return empty;
867
+ }
868
+
869
+ const input = opts.input || process.stdin;
870
+ const output = opts.output || process.stdout;
871
+ const interactive = !opts.yes && !!input.isTTY;
872
+ let chosen = targets.map((_, i) => i);
873
+ if (interactive) {
874
+ const picked = await pickMulti(
875
+ targets.map((a) => ({ label: a.name, note: a.target })),
876
+ {
877
+ title: `\n 探测到 ${targets.length} 个客户端,默认\x1b[1m全部注册\x1b[0m。不想装哪个就取消勾选:`,
878
+ input,
879
+ output,
880
+ platform: opts.platform,
881
+ }
882
+ );
883
+ if (picked === null) {
884
+ warn("已取消,没有改动任何配置文件");
885
+ return { installed: [], skipped: targets.map((a) => a.id), failed: [], cancelled: true };
886
+ }
887
+ chosen = picked;
888
+ }
889
+
890
+ const pickedSet = new Set(chosen);
891
+ const installed = [];
892
+ const skipped = [];
893
+ const failedIds = [];
894
+ for (let i = 0; i < targets.length; i++) {
895
+ const a = targets[i];
896
+ if (!pickedSet.has(i)) {
897
+ skip(`${a.name}: 按你的选择跳过`);
898
+ skipped.push(a.id);
899
+ continue;
900
+ }
901
+ console.log(` \x1b[1m${a.name}\x1b[0m — 将修改 ${a.target}`);
902
+ for (const line of a.preview) console.log(` ${line}`);
903
+ try {
904
+ if (a.install() === false) failedIds.push(a.id);
905
+ else installed.push(a.id);
906
+ } catch (e) {
907
+ bad(`${a.name}: 写入失败(${e.message}),跳过它继续装别的`);
908
+ failedIds.push(a.id);
909
+ }
910
+ }
911
+
912
+ printGenericSnippet(opts.serverPath);
913
+ return { installed, skipped, failed: failedIds, cancelled: false };
914
+ }
915
+
916
+ function printGenericSnippet(serverPath) {
917
+ console.log(`
918
+ 其他 MCP 客户端手动登记用这段(stdio):
919
+ { "mcpServers": { "${MCP_NAME}": { "command": "node", "args": [${JSON.stringify(serverPath)}] } } }
920
+ 不想固定安装路径的话,command 也可以用:npx -y ${PKG_NAME} serve`);
921
+ }