trusted-user-agent 0.0.0-stage → 0.4.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 (100) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +232 -2
  3. package/dist/acp/agent.js +719 -0
  4. package/dist/acp/agents/connection.js +298 -0
  5. package/dist/acp/agents/manager.js +363 -0
  6. package/dist/acp/agents/registry.js +201 -0
  7. package/dist/acp/agents/relay-session.js +371 -0
  8. package/dist/acp/agents/session-index.js +102 -0
  9. package/dist/acp/backend.js +2 -0
  10. package/dist/acp/config-options.js +26 -0
  11. package/dist/acp/mock-backend.js +277 -0
  12. package/dist/acp/sdk-backend.js +495 -0
  13. package/dist/browser/mcp-acp-client.js +81 -0
  14. package/dist/browser/provider.js +1049 -0
  15. package/dist/browser/schemas.js +221 -0
  16. package/dist/capability-registry.js +92 -0
  17. package/dist/client-heartbeat.js +118 -0
  18. package/dist/compose/schemas.js +90 -0
  19. package/dist/contacts/schemas.js +26 -0
  20. package/dist/installer/cli.js +70 -0
  21. package/dist/installer/common.js +93 -0
  22. package/dist/installer/index.js +366 -0
  23. package/dist/installer/mcp-clients.js +555 -0
  24. package/dist/installer/mcp.js +166 -0
  25. package/dist/installer/platforms.js +277 -0
  26. package/dist/logger.js +54 -0
  27. package/dist/mail/schemas.js +98 -0
  28. package/dist/mutation/schemas.js +31 -0
  29. package/dist/native-host/broker-ipc.js +344 -0
  30. package/dist/native-host/framing.js +76 -0
  31. package/dist/native-host/main.js +545 -0
  32. package/dist/native-host/mcp-server.js +333 -0
  33. package/dist/native-host/mcp-stdio-bridge.js +184 -0
  34. package/dist/native-host/mcp-stdio-main.js +13 -0
  35. package/dist/native-host/relay.js +84 -0
  36. package/dist/native-host/skills-startup.js +167 -0
  37. package/dist/native-host/transport.js +248 -0
  38. package/dist/permission-store.js +207 -0
  39. package/dist/repl/fs-sandbox.js +187 -0
  40. package/dist/repl/provider.js +252 -0
  41. package/dist/repl/runtime.js +436 -0
  42. package/dist/repl/types.js +10 -0
  43. package/dist/repl/worker.js +731 -0
  44. package/dist/skills/extension.js +99 -0
  45. package/dist/skills/grants-file.js +145 -0
  46. package/dist/skills/isolated-runner.js +259 -0
  47. package/dist/skills/mock-session-factory.js +49 -0
  48. package/dist/skills/package-roots.js +25 -0
  49. package/dist/skills/pi-bridge.js +8 -0
  50. package/dist/skills/pi-integration.js +110 -0
  51. package/dist/skills/planner.js +128 -0
  52. package/dist/skills/registry.js +104 -0
  53. package/dist/skills/skills-protocol.js +253 -0
  54. package/dist/skills/skills-service.js +195 -0
  55. package/dist/tool-bridge.js +8 -0
  56. package/dist/workspace.js +70 -0
  57. package/extensions/pi-browser-tools.ts +65 -0
  58. package/extensions/pi-browser.ts +60 -0
  59. package/extensions/pi-skills.ts +14 -0
  60. package/native/pi-agent-host +2 -0
  61. package/native/pi-browser-host +5 -0
  62. package/native/pi-browser-host.cmd +3 -0
  63. package/node_modules/@pi-browser/protocol/.bundled-by-trusted-user-agent +0 -0
  64. package/node_modules/@pi-browser/protocol/dist/acp.d.ts +10 -0
  65. package/node_modules/@pi-browser/protocol/dist/acp.js +9 -0
  66. package/node_modules/@pi-browser/protocol/dist/agents.d.ts +51 -0
  67. package/node_modules/@pi-browser/protocol/dist/agents.js +44 -0
  68. package/node_modules/@pi-browser/protocol/dist/browser-tools.d.ts +33 -0
  69. package/node_modules/@pi-browser/protocol/dist/browser-tools.js +478 -0
  70. package/node_modules/@pi-browser/protocol/dist/callers.d.ts +123 -0
  71. package/node_modules/@pi-browser/protocol/dist/callers.js +58 -0
  72. package/node_modules/@pi-browser/protocol/dist/compose-tools.d.ts +30 -0
  73. package/node_modules/@pi-browser/protocol/dist/compose-tools.js +175 -0
  74. package/node_modules/@pi-browser/protocol/dist/contacts-tools.d.ts +23 -0
  75. package/node_modules/@pi-browser/protocol/dist/contacts-tools.js +63 -0
  76. package/node_modules/@pi-browser/protocol/dist/control-tools.d.ts +32 -0
  77. package/node_modules/@pi-browser/protocol/dist/control-tools.js +201 -0
  78. package/node_modules/@pi-browser/protocol/dist/errors.d.ts +63 -0
  79. package/node_modules/@pi-browser/protocol/dist/errors.js +109 -0
  80. package/node_modules/@pi-browser/protocol/dist/index.d.ts +17 -0
  81. package/node_modules/@pi-browser/protocol/dist/index.js +17 -0
  82. package/node_modules/@pi-browser/protocol/dist/integration.d.ts +414 -0
  83. package/node_modules/@pi-browser/protocol/dist/integration.js +270 -0
  84. package/node_modules/@pi-browser/protocol/dist/jsonrpc.d.ts +33 -0
  85. package/node_modules/@pi-browser/protocol/dist/jsonrpc.js +31 -0
  86. package/node_modules/@pi-browser/protocol/dist/mail-mutation-tools.d.ts +27 -0
  87. package/node_modules/@pi-browser/protocol/dist/mail-mutation-tools.js +88 -0
  88. package/node_modules/@pi-browser/protocol/dist/mail-tools.d.ts +133 -0
  89. package/node_modules/@pi-browser/protocol/dist/mail-tools.js +245 -0
  90. package/node_modules/@pi-browser/protocol/dist/permission.d.ts +113 -0
  91. package/node_modules/@pi-browser/protocol/dist/permission.js +257 -0
  92. package/node_modules/@pi-browser/protocol/dist/skills.d.ts +304 -0
  93. package/node_modules/@pi-browser/protocol/dist/skills.js +473 -0
  94. package/node_modules/@pi-browser/protocol/dist/tool-capabilities.d.ts +18 -0
  95. package/node_modules/@pi-browser/protocol/dist/tool-capabilities.js +52 -0
  96. package/node_modules/@pi-browser/protocol/dist/transport.d.ts +17 -0
  97. package/node_modules/@pi-browser/protocol/dist/transport.js +17 -0
  98. package/node_modules/@pi-browser/protocol/package.json +14 -0
  99. package/package.json +69 -4
  100. package/skills/browser-walk/SKILL.md +98 -0
@@ -0,0 +1,555 @@
1
+ /**
2
+ * `mcp <install|status|uninstall> [client]` for MCP clients other than pi
3
+ * (openspec external-mcp-callers, D7): Claude Code, Codex, Cursor, Gemini
4
+ * CLI and VS Code each get the same stdio bridge entry, named `pi-browser`,
5
+ * at user (global) scope.
6
+ *
7
+ * | Client | Install / uninstall | Status (read-only) |
8
+ * |--------|---------------------------------------------|-------------------------------|
9
+ * | pi | ~/.pi/agent/mcp.json `mcpServers` (mcp.ts) | same file |
10
+ * | claude | `claude mcp add-json\|remove --scope user` | ~/.claude.json `mcpServers` |
11
+ * | codex | `codex mcp add\|remove`; TOML table edit | ~/.codex/config.toml |
12
+ * | cursor | ~/.cursor/mcp.json `mcpServers` | same file |
13
+ * | gemini | ~/.gemini/settings.json `mcpServers` | same file |
14
+ * | vscode | user mcp.json `servers` (type "stdio") | same file |
15
+ *
16
+ * Rules (spec mcp-client-installers):
17
+ * - only the `pi-browser` entry changes; other servers and settings stay,
18
+ * and keys the user added to the entry are kept;
19
+ * - an unchanged launch is reported `current` and nothing is written;
20
+ * - a file that can't be parsed is never written: the error is reported
21
+ * and the other requested clients still run;
22
+ * - a client whose config its running app rewrites (Claude Code) is changed
23
+ * through its CLI only.
24
+ */
25
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
26
+ import path from "node:path";
27
+ import { MCP_SERVER_NAME, mcpBridgePath, runMcpCommand } from "./mcp.js";
28
+ export const MCP_CLIENTS = ["pi", "claude", "codex", "cursor", "gemini", "vscode"];
29
+ export function isMcpClientTarget(value) {
30
+ return value === "all" || MCP_CLIENTS.includes(value);
31
+ }
32
+ function expectedLaunch(ctx) {
33
+ return { command: ctx.nodePath ?? process.execPath, args: [mcpBridgePath(ctx.pkgRoot)] };
34
+ }
35
+ function sameLaunch(state, launch) {
36
+ return (state.kind === "present" &&
37
+ state.command === launch.command &&
38
+ JSON.stringify(state.args) === JSON.stringify(launch.args));
39
+ }
40
+ function describeLaunch(command, args) {
41
+ return `${String(command)} ${Array.isArray(args) ? args.join(" ") : ""}`.trim();
42
+ }
43
+ // ---------------------------------------------------------------------------
44
+ // CLI lookup
45
+ // ---------------------------------------------------------------------------
46
+ /** Find an executable on PATH (Windows: .exe, then .cmd). */
47
+ export function findExecutable(name, ctx) {
48
+ const pathVar = ctx.env.PATH ?? ctx.env.Path ?? "";
49
+ const sep = ctx.platform === "win32" ? ";" : ":";
50
+ const exts = ctx.platform === "win32" ? [".exe", ".cmd"] : [""];
51
+ for (const dir of pathVar.split(sep)) {
52
+ if (!dir)
53
+ continue;
54
+ for (const ext of exts) {
55
+ const candidate = path.join(dir.replace(/^"|"$/g, ""), name + ext);
56
+ if (existsSync(candidate))
57
+ return candidate;
58
+ }
59
+ }
60
+ return undefined;
61
+ }
62
+ /** Run a CLI found by findExecutable (.cmd shims go through cmd.exe). */
63
+ async function runCli(ctx, exe, args) {
64
+ const res = /\.cmd$/i.test(exe)
65
+ ? await ctx.exec(ctx.env.ComSpec ?? "cmd.exe", ["/d", "/c", exe, ...args])
66
+ : await ctx.exec(exe, args);
67
+ return { code: res.code, out: `${res.stdout}\n${res.stderr}`.trim() };
68
+ }
69
+ function isObject(v) {
70
+ return typeof v === "object" && v !== null && !Array.isArray(v);
71
+ }
72
+ /** Read a JSON config: undefined when missing; throws a readable error when unparseable. */
73
+ function readJsonConfig(file) {
74
+ if (!existsSync(file))
75
+ return undefined;
76
+ const text = readFileSync(file, "utf8");
77
+ if (text.trim() === "")
78
+ return {};
79
+ let parsed;
80
+ try {
81
+ parsed = JSON.parse(text);
82
+ }
83
+ catch (err) {
84
+ throw new Error(`${file} is not valid JSON (${err instanceof Error ? err.message : String(err)}) — left unchanged`);
85
+ }
86
+ if (!isObject(parsed))
87
+ throw new Error(`${file} does not hold a JSON object — left unchanged`);
88
+ return parsed;
89
+ }
90
+ function writeJsonConfig(file, config) {
91
+ mkdirSync(path.dirname(file), { recursive: true });
92
+ writeFileSync(file, `${JSON.stringify(config, null, 2)}\n`);
93
+ }
94
+ function jsonFileAdapter(spec) {
95
+ return {
96
+ id: spec.id,
97
+ label: spec.label,
98
+ location: (ctx) => spec.file(ctx),
99
+ detect: (ctx) => existsSync(spec.marker(ctx)) || (spec.cli && findExecutable(spec.cli, ctx))
100
+ ? undefined
101
+ : `${spec.label} not found (no ${spec.marker(ctx)})`,
102
+ async read(ctx) {
103
+ let config;
104
+ try {
105
+ config = readJsonConfig(spec.file(ctx));
106
+ }
107
+ catch (err) {
108
+ return { kind: "error", message: err.message };
109
+ }
110
+ const servers = config?.[spec.serversKey];
111
+ const entry = isObject(servers) ? servers[MCP_SERVER_NAME] : undefined;
112
+ if (!isObject(entry))
113
+ return { kind: "missing" };
114
+ return { kind: "present", command: entry.command, args: entry.args };
115
+ },
116
+ async write(ctx, launch) {
117
+ const file = spec.file(ctx);
118
+ const config = readJsonConfig(file) ?? {};
119
+ const servers = isObject(config[spec.serversKey]) ? config[spec.serversKey] : {};
120
+ const existing = isObject(servers[MCP_SERVER_NAME]) ? servers[MCP_SERVER_NAME] : {};
121
+ servers[MCP_SERVER_NAME] = { ...existing, ...(spec.extra ?? {}), command: launch.command, args: launch.args };
122
+ config[spec.serversKey] = servers;
123
+ writeJsonConfig(file, config);
124
+ },
125
+ async remove(ctx) {
126
+ const file = spec.file(ctx);
127
+ const config = readJsonConfig(file);
128
+ const servers = config?.[spec.serversKey];
129
+ if (!config || !isObject(servers) || !(MCP_SERVER_NAME in servers))
130
+ return false;
131
+ delete servers[MCP_SERVER_NAME];
132
+ writeJsonConfig(file, config);
133
+ return true;
134
+ },
135
+ };
136
+ }
137
+ // ---------------------------------------------------------------------------
138
+ // Codex: ~/.codex/config.toml [mcp_servers.pi-browser]
139
+ // ---------------------------------------------------------------------------
140
+ export function codexConfigPath(ctx) {
141
+ return path.join(ctx.env.CODEX_HOME || path.join(ctx.homeDir, ".codex"), "config.toml");
142
+ }
143
+ const CODEX_HEADER = /^\s*\[\s*mcp_servers\s*\.\s*(?:pi-browser|"pi-browser")\s*\]\s*(?:#.*)?$/;
144
+ const CODEX_SUBTABLE = /^\s*\[\s*mcp_servers\s*\.\s*(?:pi-browser|"pi-browser")\s*\./;
145
+ const TABLE_HEADER = /^\s*\[/;
146
+ /** Line range [start, end) of the [mcp_servers.pi-browser] table body (header included). */
147
+ function codexTableRange(lines) {
148
+ const start = lines.findIndex((l) => CODEX_HEADER.test(l));
149
+ if (start === -1)
150
+ return undefined;
151
+ let end = start + 1;
152
+ while (end < lines.length && !TABLE_HEADER.test(lines[end]))
153
+ end++;
154
+ return { start, end };
155
+ }
156
+ /** A TOML basic string (JSON escapes are valid TOML escapes). */
157
+ function tomlString(s) {
158
+ return JSON.stringify(s);
159
+ }
160
+ /** Parse `key = value` for a string or a (possibly multi-line) string array. */
161
+ function codexValue(body, key) {
162
+ const re = new RegExp(`^\\s*${key}\\s*=\\s*(.*)$`);
163
+ for (let i = 0; i < body.length; i++) {
164
+ const m = re.exec(body[i]);
165
+ if (!m)
166
+ continue;
167
+ let text = m[1];
168
+ let to = i + 1;
169
+ let parsed = parseTomlValue(text);
170
+ // A multi-line array continues on the following lines.
171
+ while (parsed.incomplete && to < body.length) {
172
+ text += `\n${body[to++]}`;
173
+ parsed = parseTomlValue(text);
174
+ }
175
+ return { value: parsed.ok ? parsed.value : Symbol.for("unparsed"), from: i, to };
176
+ }
177
+ return undefined;
178
+ }
179
+ /**
180
+ * Parse a TOML value that is a string or an array of strings: basic
181
+ * ("…", with escapes) or literal ('…', none) strings, comments, newlines and
182
+ * trailing commas. Codex's own CLI writes literal strings for Windows paths.
183
+ * `incomplete` means the text ended inside an array or string.
184
+ */
185
+ export function parseTomlValue(text) {
186
+ let i = 0;
187
+ const skip = () => {
188
+ for (;;) {
189
+ while (i < text.length && /[\s,]/.test(text[i]))
190
+ i++;
191
+ if (text[i] === "#") {
192
+ while (i < text.length && text[i] !== "\n")
193
+ i++;
194
+ continue;
195
+ }
196
+ return;
197
+ }
198
+ };
199
+ const str = () => {
200
+ const quote = text[i++];
201
+ let out = "";
202
+ while (i < text.length) {
203
+ const c = text[i++];
204
+ if (c === quote)
205
+ return { ok: true, value: out };
206
+ if (c === "\n")
207
+ return { ok: false };
208
+ if (quote === '"' && c === "\\") {
209
+ const e = text[i++];
210
+ const simple = { b: "\b", t: "\t", n: "\n", f: "\f", r: "\r", '"': '"', "\\": "\\" };
211
+ if (e in simple)
212
+ out += simple[e];
213
+ else if (e === "u" || e === "U") {
214
+ const len = e === "u" ? 4 : 8;
215
+ out += String.fromCodePoint(parseInt(text.slice(i, i + len), 16));
216
+ i += len;
217
+ }
218
+ else
219
+ return { ok: false };
220
+ }
221
+ else
222
+ out += c;
223
+ }
224
+ return { ok: false, incomplete: true };
225
+ };
226
+ skip();
227
+ if (text[i] === '"' || text[i] === "'") {
228
+ const s = str();
229
+ if (!s.ok)
230
+ return s;
231
+ skip();
232
+ return i >= text.length ? s : { ok: false };
233
+ }
234
+ if (text[i] !== "[")
235
+ return { ok: false };
236
+ i++;
237
+ const items = [];
238
+ for (;;) {
239
+ skip();
240
+ if (i >= text.length)
241
+ return { ok: false, incomplete: true };
242
+ if (text[i] === "]") {
243
+ i++;
244
+ skip();
245
+ return i >= text.length ? { ok: true, value: items } : { ok: false };
246
+ }
247
+ if (text[i] !== '"' && text[i] !== "'")
248
+ return { ok: false };
249
+ const s = str();
250
+ if (!s.ok)
251
+ return s;
252
+ items.push(s.value);
253
+ }
254
+ }
255
+ /** Insert or replace the managed keys of [mcp_servers.pi-browser]; other text is untouched. */
256
+ export function upsertCodexToml(text, launch) {
257
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
258
+ const lines = text === "" ? [] : text.split(/\r?\n/);
259
+ const commandLine = `command = ${tomlString(launch.command)}`;
260
+ const argsLine = `args = [${launch.args.map(tomlString).join(", ")}]`;
261
+ const range = codexTableRange(lines);
262
+ if (!range) {
263
+ const out = [...lines];
264
+ while (out.length > 0 && out[out.length - 1] === "")
265
+ out.pop();
266
+ if (out.length > 0)
267
+ out.push("");
268
+ out.push("[mcp_servers.pi-browser]", commandLine, argsLine, "");
269
+ return out.join(eol);
270
+ }
271
+ const body = lines.slice(range.start + 1, range.end);
272
+ for (const [key, line] of [["command", commandLine], ["args", argsLine]]) {
273
+ const found = codexValue(body, key);
274
+ if (found)
275
+ body.splice(found.from, found.to - found.from, line);
276
+ else
277
+ body.splice(key === "command" ? 0 : Math.min(1, body.length), 0, line);
278
+ }
279
+ return [...lines.slice(0, range.start + 1), ...body, ...lines.slice(range.end)].join(eol);
280
+ }
281
+ /** Remove [mcp_servers.pi-browser] and its sub-tables; other text is untouched. */
282
+ export function removeCodexToml(text) {
283
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
284
+ const lines = text.split(/\r?\n/);
285
+ const range = codexTableRange(lines);
286
+ if (!range)
287
+ return undefined;
288
+ let end = range.end;
289
+ // Sub-tables ([mcp_servers.pi-browser.env], ...) belong to the entry.
290
+ while (end < lines.length && CODEX_SUBTABLE.test(lines[end])) {
291
+ end++;
292
+ while (end < lines.length && !TABLE_HEADER.test(lines[end]))
293
+ end++;
294
+ }
295
+ // Blank lines after the table separate it from the next one: keep them.
296
+ while (end > range.start + 1 && lines[end - 1].trim() === "")
297
+ end--;
298
+ const out = [...lines.slice(0, range.start), ...lines.slice(end)];
299
+ // Collapse the double blank line the removal leaves behind.
300
+ if (range.start > 0 && out[range.start - 1] === "" && (range.start >= out.length || out[range.start] === "")) {
301
+ out.splice(range.start - 1, 1);
302
+ }
303
+ return out.join(eol);
304
+ }
305
+ export function readCodexEntry(text) {
306
+ const lines = text.split(/\r?\n/);
307
+ if (lines.some((l) => /^\s*"?pi-browser"?\s*=\s*\{/.test(l))) {
308
+ return { kind: "error", message: "pi-browser is an inline table in config.toml — edit it by hand or remove it, then retry" };
309
+ }
310
+ const range = codexTableRange(lines);
311
+ if (!range)
312
+ return { kind: "missing" };
313
+ const body = lines.slice(range.start + 1, range.end);
314
+ return {
315
+ kind: "present",
316
+ command: codexValue(body, "command")?.value,
317
+ args: codexValue(body, "args")?.value,
318
+ };
319
+ }
320
+ const codexAdapter = {
321
+ id: "codex",
322
+ label: "Codex",
323
+ location: (ctx) => codexConfigPath(ctx),
324
+ detect: (ctx) => existsSync(path.dirname(codexConfigPath(ctx))) || findExecutable("codex", ctx)
325
+ ? undefined
326
+ : `Codex not found (no ${path.dirname(codexConfigPath(ctx))})`,
327
+ async read(ctx) {
328
+ const file = codexConfigPath(ctx);
329
+ if (!existsSync(file))
330
+ return { kind: "missing" };
331
+ return readCodexEntry(readFileSync(file, "utf8"));
332
+ },
333
+ async write(ctx, launch) {
334
+ const file = codexConfigPath(ctx);
335
+ const exe = findExecutable("codex", ctx);
336
+ if (exe) {
337
+ // The CLI edits config.toml itself (format-preserving).
338
+ await runCli(ctx, exe, ["mcp", "remove", MCP_SERVER_NAME]);
339
+ const res = await runCli(ctx, exe, ["mcp", "add", MCP_SERVER_NAME, "--", launch.command, ...launch.args]);
340
+ if (res.code !== 0)
341
+ throw new Error(`codex mcp add failed (exit ${res.code}): ${res.out}`);
342
+ return;
343
+ }
344
+ const text = existsSync(file) ? readFileSync(file, "utf8") : "";
345
+ const state = readCodexEntry(text);
346
+ if (state.kind === "error")
347
+ throw new Error(state.message);
348
+ mkdirSync(path.dirname(file), { recursive: true });
349
+ writeFileSync(file, upsertCodexToml(text, launch));
350
+ },
351
+ async remove(ctx) {
352
+ const file = codexConfigPath(ctx);
353
+ if (!existsSync(file))
354
+ return false;
355
+ const exe = findExecutable("codex", ctx);
356
+ if (exe) {
357
+ if ((await this.read(ctx)).kind === "missing")
358
+ return false;
359
+ const res = await runCli(ctx, exe, ["mcp", "remove", MCP_SERVER_NAME]);
360
+ if (res.code !== 0)
361
+ throw new Error(`codex mcp remove failed (exit ${res.code}): ${res.out}`);
362
+ return true;
363
+ }
364
+ const next = removeCodexToml(readFileSync(file, "utf8"));
365
+ if (next === undefined)
366
+ return false;
367
+ writeFileSync(file, next);
368
+ return true;
369
+ },
370
+ };
371
+ // ---------------------------------------------------------------------------
372
+ // Claude Code: user scope through its CLI; status from ~/.claude.json
373
+ /** Claude Code's user config (inside CLAUDE_CONFIG_DIR when that is set). */
374
+ export function claudeConfigPath(ctx) {
375
+ return path.join(ctx.env.CLAUDE_CONFIG_DIR || ctx.homeDir, ".claude.json");
376
+ }
377
+ // ---------------------------------------------------------------------------
378
+ const claudeAdapter = {
379
+ id: "claude",
380
+ label: "Claude Code",
381
+ location: (ctx) => `${claudeConfigPath(ctx)} (user scope, via the claude CLI)`,
382
+ detect: (ctx) => (findExecutable("claude", ctx) ? undefined : "Claude Code CLI (claude) not found on PATH"),
383
+ async read(ctx) {
384
+ // Read-only: Claude Code rewrites this file while it runs.
385
+ try {
386
+ const config = readJsonConfig(claudeConfigPath(ctx));
387
+ const servers = config?.mcpServers;
388
+ const entry = isObject(servers) ? servers[MCP_SERVER_NAME] : undefined;
389
+ if (!isObject(entry))
390
+ return { kind: "missing" };
391
+ return { kind: "present", command: entry.command, args: entry.args };
392
+ }
393
+ catch (err) {
394
+ return { kind: "error", message: err.message };
395
+ }
396
+ },
397
+ async write(ctx, launch) {
398
+ const exe = findExecutable("claude", ctx);
399
+ if (!exe)
400
+ throw new Error("Claude Code CLI (claude) not found on PATH");
401
+ await runCli(ctx, exe, ["mcp", "remove", "--scope", "user", MCP_SERVER_NAME]);
402
+ const json = JSON.stringify({ type: "stdio", command: launch.command, args: launch.args });
403
+ const res = await runCli(ctx, exe, ["mcp", "add-json", "--scope", "user", MCP_SERVER_NAME, json]);
404
+ if (res.code !== 0)
405
+ throw new Error(`claude mcp add-json failed (exit ${res.code}): ${res.out}`);
406
+ },
407
+ async remove(ctx) {
408
+ if ((await this.read(ctx)).kind === "missing")
409
+ return false;
410
+ const exe = findExecutable("claude", ctx);
411
+ if (!exe)
412
+ throw new Error("Claude Code CLI (claude) not found on PATH");
413
+ const res = await runCli(ctx, exe, ["mcp", "remove", "--scope", "user", MCP_SERVER_NAME]);
414
+ if (res.code !== 0)
415
+ throw new Error(`claude mcp remove failed (exit ${res.code}): ${res.out}`);
416
+ return true;
417
+ },
418
+ };
419
+ // ---------------------------------------------------------------------------
420
+ // VS Code user mcp.json
421
+ // ---------------------------------------------------------------------------
422
+ export function vscodeUserDir(ctx) {
423
+ if (ctx.platform === "win32")
424
+ return path.join(ctx.env.APPDATA || path.join(ctx.homeDir, "AppData", "Roaming"), "Code", "User");
425
+ if (ctx.platform === "darwin")
426
+ return path.join(ctx.homeDir, "Library", "Application Support", "Code", "User");
427
+ return path.join(ctx.env.XDG_CONFIG_HOME || path.join(ctx.homeDir, ".config"), "Code", "User");
428
+ }
429
+ const ADAPTERS = {
430
+ claude: claudeAdapter,
431
+ codex: codexAdapter,
432
+ cursor: jsonFileAdapter({
433
+ id: "cursor",
434
+ label: "Cursor",
435
+ file: (ctx) => path.join(ctx.homeDir, ".cursor", "mcp.json"),
436
+ marker: (ctx) => path.join(ctx.homeDir, ".cursor"),
437
+ cli: "cursor",
438
+ serversKey: "mcpServers",
439
+ }),
440
+ gemini: jsonFileAdapter({
441
+ id: "gemini",
442
+ label: "Gemini CLI",
443
+ file: (ctx) => path.join(ctx.homeDir, ".gemini", "settings.json"),
444
+ marker: (ctx) => path.join(ctx.homeDir, ".gemini"),
445
+ cli: "gemini",
446
+ serversKey: "mcpServers",
447
+ }),
448
+ vscode: jsonFileAdapter({
449
+ id: "vscode",
450
+ label: "VS Code",
451
+ file: (ctx) => path.join(vscodeUserDir(ctx), "mcp.json"),
452
+ marker: (ctx) => vscodeUserDir(ctx),
453
+ serversKey: "servers",
454
+ extra: { type: "stdio" },
455
+ }),
456
+ };
457
+ async function runForAdapter(sub, adapter, ctx, skipMissingClient) {
458
+ const where = adapter.location(ctx);
459
+ const tag = `mcp ${adapter.id}:`;
460
+ const notFound = adapter.detect(ctx);
461
+ if (notFound && (skipMissingClient || sub === "install")) {
462
+ return { outcome: "skipped", lines: [`${tag} skipped — ${notFound}`] };
463
+ }
464
+ const launch = expectedLaunch(ctx);
465
+ const state = await adapter.read(ctx);
466
+ try {
467
+ switch (sub) {
468
+ case "install": {
469
+ if (state.kind === "error")
470
+ return { outcome: "error", lines: [`${tag} error — ${state.message}`] };
471
+ if (sameLaunch(state, launch))
472
+ return { outcome: "current", lines: [`${tag} already current in ${where}`] };
473
+ await adapter.write(ctx, launch);
474
+ return {
475
+ outcome: "installed",
476
+ lines: [`${tag} ${state.kind === "present" ? "updated" : "installed"} ${MCP_SERVER_NAME} in ${where}`],
477
+ };
478
+ }
479
+ case "status": {
480
+ if (state.kind === "error")
481
+ return { outcome: "error", lines: [`${tag} error — ${state.message}`] };
482
+ if (state.kind === "missing")
483
+ return { outcome: "missing", lines: [`${tag} missing (${where})`] };
484
+ if (sameLaunch(state, launch))
485
+ return { outcome: "current", lines: [`${tag} current (${where})`] };
486
+ return {
487
+ outcome: "stale",
488
+ lines: [
489
+ `${tag} stale (${where})`,
490
+ ` configured: ${describeLaunch(state.command, state.args)}`,
491
+ ` expected: ${describeLaunch(launch.command, launch.args)}`,
492
+ ],
493
+ };
494
+ }
495
+ case "uninstall": {
496
+ if (state.kind === "error")
497
+ return { outcome: "error", lines: [`${tag} error — ${state.message}`] };
498
+ const removed = await adapter.remove(ctx);
499
+ return removed
500
+ ? { outcome: "removed", lines: [`${tag} removed ${MCP_SERVER_NAME} from ${where}`] }
501
+ : { outcome: "absent", lines: [`${tag} nothing to remove`] };
502
+ }
503
+ }
504
+ }
505
+ catch (err) {
506
+ return { outcome: "error", lines: [`${tag} error — ${err instanceof Error ? err.message : String(err)}`] };
507
+ }
508
+ return { outcome: "error", lines: [`${tag} unknown sub-command ${String(sub)}`] };
509
+ }
510
+ /** pi through the original installer (unchanged output), mapped to an outcome. */
511
+ function runPi(sub, ctx) {
512
+ const result = runMcpCommand(sub, ctx.homeDir, { pkgRoot: ctx.pkgRoot, ...(ctx.nodePath ? { nodePath: ctx.nodePath } : {}) });
513
+ const first = result.lines[0] ?? "";
514
+ let outcome;
515
+ if (sub === "install")
516
+ outcome = !result.ok ? "error" : first.includes("already configured") ? "current" : "installed";
517
+ else if (sub === "status")
518
+ outcome = result.ok ? "current" : first.includes("STALE") ? "stale" : first.includes("not valid JSON") ? "error" : "missing";
519
+ else
520
+ outcome = first.includes("nothing to remove") ? "absent" : "removed";
521
+ return { outcome, lines: result.lines, result };
522
+ }
523
+ /**
524
+ * Run an mcp sub-command for one client or `all`. `pi` alone keeps the
525
+ * original output; `all` reports one block per client and is ok unless a
526
+ * client failed (or, for status, is not current).
527
+ */
528
+ export async function runMcpClients(sub, target, ctx) {
529
+ if (target === "pi")
530
+ return runPi(sub, ctx).result;
531
+ if (target !== "all") {
532
+ const r = await runForAdapter(sub, ADAPTERS[target], ctx, false);
533
+ return { ok: isOk(sub, r.outcome), lines: r.lines };
534
+ }
535
+ const lines = [];
536
+ let ok = true;
537
+ const summary = [];
538
+ for (const id of MCP_CLIENTS) {
539
+ const r = id === "pi" ? runPi(sub, ctx) : await runForAdapter(sub, ADAPTERS[id], ctx, true);
540
+ lines.push(...(id === "pi" ? r.lines.map((l, i) => (i === 0 ? `mcp pi: ${l.replace(/^mcp: /, "")}` : l)) : r.lines));
541
+ summary.push(`${id}=${r.outcome}`);
542
+ if (r.outcome !== "skipped" && !isOk(sub, r.outcome))
543
+ ok = false;
544
+ }
545
+ lines.push(`mcp: ${summary.join(" ")}`);
546
+ return { ok, lines };
547
+ }
548
+ function isOk(sub, outcome) {
549
+ if (outcome === "error")
550
+ return false;
551
+ if (sub === "status")
552
+ return outcome === "current";
553
+ return true;
554
+ }
555
+ //# sourceMappingURL=mcp-clients.js.map