hmcp-web 0.2.2 → 0.2.4

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 (63) hide show
  1. package/dist/api.d.ts +15 -0
  2. package/dist/api.js +36 -8
  3. package/dist/model/app-connect-note.d.ts +114 -0
  4. package/dist/model/app-connect-note.js +199 -0
  5. package/dist/model/app-servers.d.ts +24 -1
  6. package/dist/model/app-servers.js +54 -6
  7. package/dist/model/apps.d.ts +24 -0
  8. package/dist/model/apps.js +18 -0
  9. package/dist/model/bring-in.d.ts +185 -0
  10. package/dist/model/bring-in.js +756 -0
  11. package/dist/model/console-settings.d.ts +2 -2
  12. package/dist/model/import-record.d.ts +4 -0
  13. package/dist/model/import-record.js +22 -1
  14. package/dist/model/new-toolbox.d.ts +84 -0
  15. package/dist/model/new-toolbox.js +209 -0
  16. package/dist/model/protection.d.ts +4 -1
  17. package/dist/model/protection.js +12 -9
  18. package/dist/model/provisional-tools.d.ts +56 -0
  19. package/dist/model/provisional-tools.js +145 -0
  20. package/dist/model/server-names.d.ts +25 -0
  21. package/dist/model/server-names.js +158 -0
  22. package/dist/model/toolbox-label.d.ts +22 -0
  23. package/dist/model/toolbox-label.js +42 -0
  24. package/dist/model/tools.d.ts +20 -5
  25. package/dist/model/tools.js +22 -11
  26. package/dist/routes/connect-app.d.ts +54 -0
  27. package/dist/routes/connect-app.js +1049 -0
  28. package/dist/routes/connect-import.d.ts +21 -6
  29. package/dist/routes/connect-import.js +162 -546
  30. package/dist/routes/connect.d.ts +30 -0
  31. package/dist/routes/connect.js +74 -126
  32. package/dist/routes/github.js +2 -1
  33. package/dist/routes/guard.js +4 -0
  34. package/dist/routes/runtime.js +21 -22
  35. package/dist/routes/servers-add.d.ts +1 -0
  36. package/dist/routes/servers-add.js +6 -5
  37. package/dist-ui/assets/Activity-CQw7bFh4.js +1 -0
  38. package/dist-ui/assets/Approvals-_rFRWRyy.js +1 -0
  39. package/dist-ui/assets/AttachApp-eNBD48eb.js +5 -0
  40. package/dist-ui/assets/Connections-_AV8r8_W.js +2 -0
  41. package/dist-ui/assets/{Gallery-DB_OO7Vw.js → Gallery-0iiv1H9e.js} +3 -3
  42. package/dist-ui/assets/{PreApprovals-C-2ZGYfc.js → PreApprovals-Bwrhm8hr.js} +1 -1
  43. package/dist-ui/assets/Protection-CM1fEDmQ.js +1 -0
  44. package/dist-ui/assets/Safety-BbtS6-Sw.js +1 -0
  45. package/dist-ui/assets/{Settings-CSyTOe8X.js → Settings-BjarVZaa.js} +1 -1
  46. package/dist-ui/assets/StartPage-CUFNfiyY.js +1 -0
  47. package/dist-ui/assets/{Suggestions-CaQ_ifWR.js → Suggestions-CfqM3_Ik.js} +1 -1
  48. package/dist-ui/assets/Tools-jM5XlNbn.js +4 -0
  49. package/dist-ui/assets/connect-app-words-Dy16Vpfd.js +1 -0
  50. package/dist-ui/assets/index-DywhXnhV.js +16 -0
  51. package/dist-ui/assets/{kit-DRVm92_t.js → kit-BHB_ha4i.js} +1 -1
  52. package/dist-ui/assets/server-name-D9u6r07i.js +1 -0
  53. package/dist-ui/index.html +3 -2
  54. package/package.json +4 -4
  55. package/dist-ui/assets/Activity-CoVSFaRd.js +0 -1
  56. package/dist-ui/assets/Approvals-BSEDgiNu.js +0 -1
  57. package/dist-ui/assets/AttachApp-Cpm6DOaX.js +0 -5
  58. package/dist-ui/assets/Connections-D5Xd9vH8.js +0 -2
  59. package/dist-ui/assets/Protection-B4Ltb5iP.js +0 -1
  60. package/dist-ui/assets/Safety-CSQhoL9D.js +0 -1
  61. package/dist-ui/assets/StartPage-JBVzYXce.js +0 -1
  62. package/dist-ui/assets/Tools-CDl6irG1.js +0 -4
  63. package/dist-ui/assets/index-CTvq_isK.js +0 -16
@@ -0,0 +1,1049 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { isIP } from "node:net";
4
+ import { homedir } from "node:os";
5
+ import { join, resolve, sep } from "node:path";
6
+ import { z } from "zod";
7
+ import { SecretStore, expandPath, readRegistry } from "hmcp-core";
8
+ import { GuardInstallError, adoptRevert, backupPath, connectClient, detectClients, guardStatus, importCandidates, installGuard, outdatedLaunch, loadGatewayConfig, restartHintFor, uninstallGuard } from "hmcp-gateway";
9
+ import { HttpError, route, unprocessable } from "../http.js";
10
+ import { APPS } from "../model/apps.js";
11
+ import { appServersFor, connectionState, targetFor } from "../model/app-servers.js";
12
+ import { allNotes, backupStamp, deleteNote, noteMatches, readNote, safeToDelete, toolboxDigests, unchangedSinceMade, writeNote } from "../model/app-connect-note.js";
13
+ import { adoptToolboxId, asHttp, bringIn, connectedToolbox, otherAppsUsing } from "../model/bring-in.js";
14
+ import { egressChangesFor, readGatewayFile } from "../model/gateway-config.js";
15
+ import { deleteImportRecord, readImportRecord, readLiveImportRecord, upstreamDigest } from "../model/import-record.js";
16
+ import { removeNewToolbox } from "../model/new-toolbox.js";
17
+ import { removeProvisional, saveProvisional } from "../model/provisional-tools.js";
18
+ import { loadServer } from "../model/server.js";
19
+ import { toolboxLabel } from "../model/toolbox-label.js";
20
+ import { LABELS, gatewayAudit, launchOf, parse, pathDirsFromEnv, projectDirOf, record, recordRefresh, withoutSameFile } from "./connect.js";
21
+ import { undoImport } from "./connect-import.js";
22
+ import { DEFAULT_GATEWAY_ID, DEFAULT_GATEWAY_LABEL, secretUsage } from "./servers-add.js";
23
+ const APP_IDS = APPS.map((a) => a.id);
24
+ const REGISTRY_ID = /^[a-z0-9][a-z0-9_-]{0,63}$/;
25
+ const AppBody = z
26
+ .object({
27
+ app: z.enum(APP_IDS),
28
+ /** Claude Code only: also turn on the guard, which records Claude Code's own tools. */
29
+ guard: z.boolean().optional(),
30
+ /** The toolbox the page showed, to confirm putting the app's servers into one that has servers of its own. */
31
+ toolbox: z.string().regex(REGISTRY_ID).optional(),
32
+ // Used only when a toolbox has to be made. The same limits as POST /gateways.
33
+ name: z.string().regex(/^[a-z0-9][a-z0-9_-]{0,63}$/, "a name is lower-case letters, digits, dashes and underscores").optional(),
34
+ label: z.string().min(1).max(200).optional(),
35
+ /** Where Claude Code's one-project servers are looked for. Default: the console's own folder. Nothing in it is written. */
36
+ projectDir: z.string().min(1).optional(),
37
+ confirm: z.literal(true)
38
+ })
39
+ .strict();
40
+ const UndoBody = z.object({ app: z.enum(APP_IDS), projectDir: z.string().min(1).optional(), confirm: z.literal(true) }).strict();
41
+ /* ------------------------------------------------------------- helpers */
42
+ /** Where the older "Undo connection" button is, named the same way on the page and here. */
43
+ export const OLDER_UNDO = `"Undo connection" under Advanced in Connect your AI app`;
44
+ /** Whether a toolbox is only watching or protecting, as the picker says it. Null when it can't be read. */
45
+ function modeOf(entry) {
46
+ try {
47
+ return loadServer(entry).policy.enforcement === "enforce" ? "protecting" : "watching";
48
+ }
49
+ catch {
50
+ return null;
51
+ }
52
+ }
53
+ /** The process names an app runs as, for the "quit it first" hint. Apps not listed are not checked. */
54
+ const PROCESS_NAMES = {
55
+ "claude-desktop": ["Claude"],
56
+ cursor: ["Cursor"],
57
+ codex: ["ChatGPT", "codex"],
58
+ windsurf: ["Windsurf"]
59
+ };
60
+ /** `pgrep -x`: advice only, so any failure is "can't tell". */
61
+ export function pgrepRunning(app) {
62
+ const names = PROCESS_NAMES[app.id];
63
+ if (!names || process.platform === "win32")
64
+ return Promise.resolve(null);
65
+ const one = (name) => new Promise((done) => {
66
+ execFile("pgrep", ["-x", name], { timeout: 2_000, windowsHide: true }, (err) => {
67
+ if (!err)
68
+ return done(true);
69
+ // pgrep exits 1 for "no such process"; anything else (not installed, timed out) is "can't tell".
70
+ done(err.code === 1 ? false : null);
71
+ });
72
+ });
73
+ return Promise.all(names.map(one)).then((r) => (r.includes(true) ? true : r.includes(null) ? null : false));
74
+ }
75
+ /**
76
+ * The toolbox an app that isn't connected yet would go into: the only one
77
+ * there is, else the first one made in the console (under ~/.hmcp/gateways).
78
+ * Null when there is none of either, and then one is made.
79
+ */
80
+ function defaultToolbox(registryPath) {
81
+ const gateways = readRegistry(registryPath).servers.filter((s) => s.kind === "gateway");
82
+ if (gateways.length === 1)
83
+ return gateways[0];
84
+ const made = resolve(homedir(), ".hmcp", "gateways") + sep;
85
+ return gateways.find((s) => resolve(expandPath(s.config_path)).startsWith(made)) ?? null;
86
+ }
87
+ /** The server names in a toolbox, for the page to show before anything goes into it. */
88
+ function toolboxServers(entry) {
89
+ try {
90
+ return loadGatewayConfig(resolve(expandPath(entry.config_path))).config.upstreams.map((u) => u.name);
91
+ }
92
+ catch {
93
+ return [];
94
+ }
95
+ }
96
+ /**
97
+ * A toolbox one click may put this app into without asking: one a one-click
98
+ * connect made (by a note that still describes a real connection), in which
99
+ * every server is either this app's own -- from this app's matching note, as
100
+ * it was brought in -- or one this app already has itself, so connecting
101
+ * hands it nothing new. A toolbox holding another app's servers is asked
102
+ * about, like any other.
103
+ */
104
+ function oneClickToolboxFor(registryPath, entry, app, cwd) {
105
+ const home = homedir();
106
+ const configPath = resolve(expandPath(entry.config_path));
107
+ // A note left by a connection undone some other way (`adopt --revert` at a terminal, say) never counts.
108
+ const live = allNotes(registryPath).filter((n) => {
109
+ const scope = APPS.find((a) => a.id === n.app)?.scope;
110
+ return scope !== undefined && scope === n.scope && noteMatches(n, targetFor(scope, cwd, home));
111
+ });
112
+ if (!live.some((n) => n.created_toolbox?.id === entry.id && resolve(n.created_toolbox.configPath) === configPath))
113
+ return false;
114
+ let upstreams;
115
+ try {
116
+ upstreams = loadGatewayConfig(configPath).config.upstreams;
117
+ }
118
+ catch {
119
+ return false;
120
+ }
121
+ const own = live
122
+ .filter((n) => n.app === app.id && n.gateway_id === entry.id)
123
+ .flatMap((n) => n.items.filter((i) => i.added && i.digest !== undefined));
124
+ let alreadyHas;
125
+ try {
126
+ const { candidates } = importCandidates({ scope: app.scope, cwd, home, gatewayConfigPath: configPath, secrets: new SecretStore() });
127
+ alreadyHas = new Set(candidates.flatMap((c) => (c.inToolbox !== undefined ? [c.inToolbox] : [])));
128
+ }
129
+ catch {
130
+ return false;
131
+ }
132
+ return upstreams.every((u) => alreadyHas.has(u.name) || own.some((i) => i.upstream === u.name && i.digest === upstreamDigest(u)));
133
+ }
134
+ /** A name for a new toolbox whose folder and id are both free: "main", then "main-2", ... */
135
+ function freeToolboxName(registryPath) {
136
+ const taken = new Set(readRegistry(registryPath).servers.map((s) => s.id));
137
+ for (let n = 1; n <= 50; n++) {
138
+ const name = n === 1 ? DEFAULT_GATEWAY_ID : `${DEFAULT_GATEWAY_ID}-${n}`;
139
+ const dir = join(homedir(), ".hmcp", "gateways", name);
140
+ if (!taken.has(name) && !existsSync(join(dir, "gateway.yaml")) && !existsSync(join(dir, "policy.yaml")))
141
+ return name;
142
+ }
143
+ // Every one taken: the toolbox plan refuses it, in words.
144
+ return DEFAULT_GATEWAY_ID;
145
+ }
146
+ /** A DNS name of at least two labels: no wildcard, no `?`, nothing a pattern could match more than once. */
147
+ const PLAIN_DNS = /^[a-z0-9-]+(\.[a-z0-9-]+)+\.?$/i;
148
+ /**
149
+ * The allow-list entry (`host` or `host:port`) for a server reached over
150
+ * HTTPS at a plain public DNS name, or null for anything else: another
151
+ * protocol, a wildcard or odd host (`*.example.com`, also when written
152
+ * `%2a`), a bare IPv4 or IPv6 address, localhost, a `.local` name, or one the
153
+ * app's settings place on the local network.
154
+ */
155
+ export function plainHttpsEntry(upstream, needsLocalHttp = false) {
156
+ if (upstream.transport !== "http")
157
+ return null;
158
+ let url;
159
+ try {
160
+ url = new URL(upstream.url);
161
+ }
162
+ catch {
163
+ return null;
164
+ }
165
+ if (url.protocol !== "https:")
166
+ return null;
167
+ const host = url.hostname;
168
+ if (!PLAIN_DNS.test(host))
169
+ return null;
170
+ const bare = host.toLowerCase().replace(/\.$/, "");
171
+ if (isIP(bare) !== 0 || bare === "localhost" || bare.endsWith(".localhost") || bare.endsWith(".local"))
172
+ return null;
173
+ const changes = egressChangesFor(upstream, { localNetwork: needsLocalHttp });
174
+ if (changes.some((c) => c.kind === "egress-local-network" || c.kind === "egress-plain-http"))
175
+ return null;
176
+ const allow = changes.find((c) => c.kind === "egress-allow");
177
+ return allow && allow.kind === "egress-allow" ? allow.host : null;
178
+ }
179
+ /** The one loosening a click may carry: that entry on the allow-list, and the POST its protocol needs. */
180
+ export function ownHttpsAddress(line, upstream, server = { needsLocalHttp: false }) {
181
+ const entry = plainHttpsEntry(upstream, server.needsLocalHttp);
182
+ if (entry === null)
183
+ return false;
184
+ return line === "Your toolbox may send POST requests" || line === `Your toolbox may connect to ${entry}`;
185
+ }
186
+ /**
187
+ * What a click may accept for this toolbox. One that already lets servers
188
+ * reach the local network (`block_private_ips: false`) accepts no new
189
+ * address at all: a plain-looking name such as `nas.lan` may lead to a
190
+ * private address there, and nothing about the name can tell.
191
+ */
192
+ function holdFor(toolbox) {
193
+ if (toolbox && toolbox.server.policy.egress.block_private_ips === false) {
194
+ return {
195
+ accept: () => false,
196
+ why: "It needs your OK first: this toolbox already lets servers reach your local network, so a new web address can't be checked to be a public one."
197
+ };
198
+ }
199
+ return { accept: ownHttpsAddress };
200
+ }
201
+ const MAY_NEED_OK = "It may need your OK: the console couldn't tell ahead of time whether bringing it in would let more through.";
202
+ const keyOf = (source, key) => `${source}:${key}`;
203
+ /**
204
+ * What one click would decide for each server, worked out the way the click
205
+ * works it out (`bringIn` stopped before anything starts) against the toolbox
206
+ * it would use. Whether a server then answers its test can't be known ahead.
207
+ */
208
+ async function previewFor(options, app, cwd, chosen, entryName) {
209
+ const out = new Map();
210
+ const home = homedir();
211
+ let toolbox;
212
+ let configPath;
213
+ if (chosen) {
214
+ try {
215
+ configPath = resolve(expandPath(chosen.config_path));
216
+ toolbox = { target: targetFor(app.scope, cwd, home), entry: chosen, server: loadServer(chosen), configPath, entryName: entryName ?? "hmcp", home };
217
+ }
218
+ catch {
219
+ return out;
220
+ }
221
+ }
222
+ else {
223
+ toolbox = { new: { name: freeToolboxName(options.registryPath) } };
224
+ }
225
+ let candidates;
226
+ try {
227
+ candidates = importCandidates({
228
+ scope: app.scope,
229
+ cwd,
230
+ home,
231
+ ...(configPath ? { gatewayConfigPath: configPath, entryName: entryName ?? "hmcp" } : {}),
232
+ secrets: new SecretStore()
233
+ }).candidates;
234
+ }
235
+ catch {
236
+ return out;
237
+ }
238
+ const wanted = candidates.filter((c) => c.importable && !(c.source === "extension" && c.enabled === false));
239
+ if (wanted.length === 0)
240
+ return out;
241
+ try {
242
+ const dry = await bringIn({
243
+ options,
244
+ scope: app.scope,
245
+ cwd,
246
+ names: wanted.filter((c) => c.source === "config").map((c) => c.key),
247
+ extensions: wanted.filter((c) => c.source === "extension").map((c) => c.key),
248
+ toolbox,
249
+ actor: "preview",
250
+ hold: holdFor("new" in toolbox ? null : toolbox),
251
+ dryRun: true
252
+ });
253
+ for (const h of dry.held)
254
+ out.set(keyOf(h.source, h.key), { auto: false, kind: "needs-ok", why: h.why });
255
+ if (dry.warning)
256
+ for (const c of wanted)
257
+ if (!out.has(keyOf(c.source, c.key)))
258
+ out.set(keyOf(c.source, c.key), { auto: false, kind: "needs-ok", why: MAY_NEED_OK, maybe: true });
259
+ for (const c of wanted)
260
+ if (!out.has(keyOf(c.source, c.key)))
261
+ out.set(keyOf(c.source, c.key), { auto: true });
262
+ }
263
+ catch {
264
+ for (const c of wanted)
265
+ out.set(keyOf(c.source, c.key), { auto: false, kind: "needs-ok", why: MAY_NEED_OK, maybe: true });
266
+ }
267
+ return out;
268
+ }
269
+ /** How one server the app has is treated by one click, as the picker shows it before anything runs. */
270
+ function plannedFor(s, preview) {
271
+ if (!s.importable)
272
+ return { auto: false, kind: "cant-move", why: s.reason ?? "It can't be brought in." };
273
+ if (s.source === "extension" && s.enabled === false) {
274
+ return { auto: false, kind: "off", why: "It is switched off in Claude Desktop, so it is left as it is." };
275
+ }
276
+ return preview.get(keyOf(s.source, s.source === "extension" ? (s.extensionId ?? s.name) : s.name)) ?? { auto: false, kind: "needs-ok", why: MAY_NEED_OK, maybe: true };
277
+ }
278
+ /** Claude Code's servers for one project only, which stay where they are. */
279
+ function projectOnly(app, cwd, registryPath) {
280
+ if (app.id !== "claude-code")
281
+ return [];
282
+ const scopes = withoutSameFile(detectClients({ cwd }).filter((c) => c.scope === "local" || c.scope === "project")).map((c) => c.scope);
283
+ return scopes.flatMap((scope) => appServersFor(scope, cwd, registryPath).servers.map((s) => ({
284
+ ...s,
285
+ scope,
286
+ auto: false,
287
+ kind: "project-only",
288
+ why: `It is set for one project only (${cwd}), so it stays in Claude Code. Bring it in from Advanced if you want it in every project.`
289
+ })));
290
+ }
291
+ /** What stays out of the activity log after connecting, in plain words. */
292
+ function notRecordedFor(app, guardOn, left) {
293
+ const out = [];
294
+ if (app.id === "claude-code") {
295
+ if (!guardOn) {
296
+ out.push("Claude Code's own tools: reading and editing files, running commands, opening web pages (turn on recording Claude Code's own actions to record them)");
297
+ }
298
+ }
299
+ else if (app.id === "claude-desktop") {
300
+ out.push("Claude Desktop's own built-in tools");
301
+ }
302
+ else if (app.id === "codex") {
303
+ out.push("Codex's and the ChatGPT app's own built-in tools");
304
+ }
305
+ else {
306
+ out.push(`${app.name}'s own built-in tools`);
307
+ }
308
+ if (app.id === "claude-desktop" || app.id === "claude-code") {
309
+ out.push("Connectors (add-ons) you added on claude.ai: they run in your Claude account, not on this computer");
310
+ }
311
+ if (app.id === "codex")
312
+ out.push("Connectors added to your ChatGPT account: they run in OpenAI's cloud, not on this computer");
313
+ for (const l of left)
314
+ out.push(`"${l.name}", which stays in ${app.name}`);
315
+ return out;
316
+ }
317
+ /** Apps whose servers live in a company's cloud, which a toolbox on this computer can't sit in front of. */
318
+ const CLOUD = [
319
+ {
320
+ label: "Claude on claude.ai",
321
+ note: "Connectors (add-ons) you added on claude.ai live in your Claude account, not on this computer, so they can't be connected from here."
322
+ },
323
+ {
324
+ label: "ChatGPT on chatgpt.com",
325
+ note: "ChatGPT on chatgpt.com, and connectors added to your ChatGPT account, live in OpenAI's cloud. They need a public web address " +
326
+ "with sign-in, which a toolbox on this computer isn't."
327
+ },
328
+ { label: "Gemini on the web", note: "Gemini's web app runs in Google's cloud, so it can't reach a toolbox on this computer." }
329
+ ];
330
+ async function pathDirsOf(deps) {
331
+ let dirs = [];
332
+ try {
333
+ dirs = (await deps.pathDirs?.()) ?? [];
334
+ }
335
+ catch {
336
+ // The machine check failing is no reason to refuse; the console's own PATH stands in.
337
+ }
338
+ return dirs.length > 0 ? dirs : pathDirsFromEnv();
339
+ }
340
+ function appFor(id) {
341
+ return APPS.find((a) => a.id === id);
342
+ }
343
+ /** A 409 that says which toolbox the page should show and confirm. */
344
+ function chooseToolbox(message, entry) {
345
+ return new HttpError(409, "conflict", message, {
346
+ needs: "toolbox",
347
+ toolbox: entry ? { id: entry.id, label: toolboxLabel(entry), servers: toolboxServers(entry) } : null
348
+ });
349
+ }
350
+ /**
351
+ * A refusal, with what could not be put back added to it. Its words must not
352
+ * say nothing changed while the app is still connected.
353
+ */
354
+ function withProblems(err, problems) {
355
+ if (problems.length === 0)
356
+ return err;
357
+ const base = err instanceof HttpError ? err : unprocessable(err.message ?? String(err));
358
+ const message = `${base.message.replace(/nothing was changed/gi, "the servers were left as they were")} Also: ${problems.join("; ")}.`;
359
+ return new HttpError(base.status, base.code, message, base.detail);
360
+ }
361
+ /* -------------------------------------------------------------- routes */
362
+ export function connectAppRoutes(options, deps = {}) {
363
+ const guardHome = () => options.home ?? homedir();
364
+ return [
365
+ /** Every app this build can connect, what each has, and what one click would do with it. Writes nothing. */
366
+ route("GET", "/api/v1/connect/apps", async (ctx) => {
367
+ const cwd = projectDirOf(ctx.query.get("projectDir"));
368
+ const home = homedir();
369
+ const reports = detectClients({ cwd });
370
+ const fallback = defaultToolbox(options.registryPath);
371
+ const rows = readRegistry(options.registryPath).servers;
372
+ const apps = [];
373
+ // One app after another: each preview reads the same files, and none of them is slow.
374
+ for (const app of APPS) {
375
+ const report = reports.find((r) => r.scope === app.scope);
376
+ const info = appServersFor(app.scope, cwd, options.registryPath);
377
+ const attached = info.attachedTo ? rows.find((s) => s.id === info.attachedTo.gatewayId) : undefined;
378
+ const chosen = attached ?? (info.connection === null ? fallback : null);
379
+ let running = null;
380
+ try {
381
+ running = deps.running ? await deps.running(app) : null;
382
+ }
383
+ catch {
384
+ running = null;
385
+ }
386
+ const preview = await previewFor(options, app, cwd, chosen, info.attachedTo?.entryName ?? null);
387
+ // One-click Undo, offered on the card after a reload: a note from a click that still describes this connection.
388
+ const note = readNote(options.registryPath, app.id);
389
+ const undoable = info.connection === "console" && !!note && noteMatches(note, targetFor(app.scope, cwd, home));
390
+ // Connected, but its entry starts an older copy of the toolbox than this one: said before the click. Reads only.
391
+ const outdated = info.connection === "console" && attached && info.attachedTo
392
+ ? outdatedLaunch({
393
+ scope: app.scope,
394
+ cwd,
395
+ home,
396
+ gatewayConfigPath: resolve(expandPath(attached.config_path)),
397
+ entryName: info.attachedTo.entryName,
398
+ pathDirs: pathDirsFromEnv(),
399
+ ...launchOf(options)
400
+ })
401
+ : null;
402
+ apps.push({
403
+ id: app.id,
404
+ label: app.name,
405
+ scope: app.scope,
406
+ scopeLabel: app.label,
407
+ // Windsurf's folder outlives it (it is Devin Desktop now): only a settings file says it is in use.
408
+ installed: app.id === "windsurf" ? report.exists : report.installed,
409
+ connected: info.connection === "console",
410
+ connection: info.connection,
411
+ undoable,
412
+ outdated,
413
+ toolbox: chosen
414
+ ? {
415
+ id: chosen.id,
416
+ label: toolboxLabel(chosen),
417
+ servers: toolboxServers(chosen),
418
+ // Watching or protecting: what recording Claude Code's own actions would then do.
419
+ mode: modeOf(chosen),
420
+ // Send its id back as `toolbox` to confirm: it has servers the person may not want this app to have.
421
+ needsConfirm: !attached && !oneClickToolboxFor(options.registryPath, chosen, app, cwd)
422
+ }
423
+ : null,
424
+ running,
425
+ error: report.error,
426
+ servers: [...info.servers.map((s) => ({ ...s, scope: app.scope, ...plannedFor(s, preview) })), ...projectOnly(app, cwd, options.registryPath)]
427
+ });
428
+ }
429
+ return {
430
+ toolbox: fallback ? { id: fallback.id, label: toolboxLabel(fallback), servers: toolboxServers(fallback) } : null,
431
+ apps,
432
+ cloud: CLOUD
433
+ };
434
+ }),
435
+ route("POST", "/api/v1/connect/app", async (ctx) => {
436
+ const body = parse(AppBody, ctx.body);
437
+ const app = appFor(body.app);
438
+ if (body.guard === true && app.id !== "claude-code") {
439
+ throw unprocessable("Recording Claude Code's own actions only works with Claude Code, so it can only be turned on with Claude Code.");
440
+ }
441
+ const scope = app.scope;
442
+ const cwd = projectDirOf(body.projectDir);
443
+ const home = homedir();
444
+ const target = targetFor(scope, cwd, home);
445
+ const state = connectionState(target, options.registryPath, { cwd, home });
446
+ if (state.kind === "adopt") {
447
+ throw unprocessable(`${app.name} was connected the older way, which already moved its servers into its toolbox. Use ${OLDER_UNDO}, then connect it again here.`);
448
+ }
449
+ if (state.kind === "entry-missing" || state.kind === "toolbox-missing") {
450
+ throw unprocessable(`${app.name} has a connection from this console that no longer works (${state.kind === "entry-missing" ? "its toolbox entry is gone from its settings" : "its toolbox is no longer in the console"}). ` +
451
+ `Use ${OLDER_UNDO}, then connect it again here.`);
452
+ }
453
+ // An earlier note counts only while it still describes this very connection.
454
+ const written = readNote(options.registryPath, app.id);
455
+ const before = written && noteMatches(written, target) ? written : undefined;
456
+ const alreadyConnected = state.kind === "console";
457
+ const pathDirs = await pathDirsOf(deps);
458
+ const warnings = [];
459
+ const problems = [];
460
+ /* the toolbox: the one it's connected to, one the person confirmed, a one-click one, or a new one */
461
+ let connected = null;
462
+ let attachedHere = false;
463
+ let updated = null;
464
+ if (alreadyConnected) {
465
+ connected = connectedToolbox(options, scope, cwd);
466
+ if (body.toolbox !== undefined && body.toolbox !== connected.entry.id) {
467
+ throw chooseToolbox(`${app.name} is already connected to ${toolboxLabel(connected.entry)}, not the toolbox you chose. Check again.`, connected.entry);
468
+ }
469
+ // Its toolbox found by what it runs, under a new id: its records are pointed at that id first.
470
+ adoptToolboxId(options.registryPath, connected);
471
+ // Its entry may start an older copy of the toolbox (an upgrade since): pointed at this one, nothing else changed.
472
+ const at = { scope, cwd, home, gatewayConfigPath: connected.configPath, entryName: connected.entryName, pathDirs, ...launchOf(options) };
473
+ // Why it was left alone is said only when the card offered the update, not on every click.
474
+ const offered = outdatedLaunch(at) !== null;
475
+ try {
476
+ const again = await connectClient({ ...at, registryId: connected.entry.id, refresh: true });
477
+ updated = again.refreshed;
478
+ if (again.leftAsIs && offered)
479
+ warnings.push(again.leftAsIs);
480
+ const w = recordRefresh(connected.configPath, ctx.actor, scope, again, connected.entry.id);
481
+ if (w)
482
+ warnings.push(w);
483
+ }
484
+ catch (err) {
485
+ warnings.push(`${app.name} still starts the copy of your toolbox it started before, because updating it failed: ${err.message}`);
486
+ }
487
+ }
488
+ else {
489
+ const existing = defaultToolbox(options.registryPath);
490
+ if (!existing && body.toolbox !== undefined) {
491
+ throw chooseToolbox("The toolbox you chose is no longer in the console, so nothing was changed. Check again.", null);
492
+ }
493
+ if (existing) {
494
+ if (body.toolbox !== undefined && body.toolbox !== existing.id) {
495
+ throw chooseToolbox(`${app.name} would go into ${toolboxLabel(existing)}, not the toolbox you chose, so nothing was changed. Check again.`, existing);
496
+ }
497
+ if (body.toolbox === undefined && !oneClickToolboxFor(options.registryPath, existing, app, cwd)) {
498
+ const servers = toolboxServers(existing);
499
+ throw chooseToolbox(`${app.name}'s servers would go into ${toolboxLabel(existing)}, which already has servers of its own` +
500
+ (servers.length > 0 ? ` (${servers.join(", ")})` : "") +
501
+ `, and ${app.name} would be able to use them too. Nothing was changed. Choose that toolbox on the page to confirm.`, existing);
502
+ }
503
+ const configPath = resolve(expandPath(existing.config_path));
504
+ let attached;
505
+ try {
506
+ attached = await connectClient({ scope, cwd, home, gatewayConfigPath: configPath, pathDirs, registryId: existing.id, ...launchOf(options) });
507
+ }
508
+ catch (err) {
509
+ asHttp(err);
510
+ }
511
+ if (attached.alreadyConnected) {
512
+ throw unprocessable(`${app.name} already has an entry ("${attached.entryName}") running ${toolboxLabel(existing)}, made outside this console, so there is no connection here to bring servers into. ` +
513
+ `Remove that entry from its settings, then connect again.`);
514
+ }
515
+ attachedHere = true;
516
+ const warning = record(gatewayAudit(configPath, ctx.actor), {
517
+ tool: "(connect)",
518
+ effect: null,
519
+ decision: "allow",
520
+ rule_id: "connect.attach",
521
+ reason: `${LABELS[scope]} connected to this gateway via the console by ${ctx.actor}, as "${attached.entryName}" in ${attached.configPath}`,
522
+ outcome: "completed",
523
+ args_redacted: { scope, client_config: attached.configPath, entry: attached.entryName, registry_id: existing.id }
524
+ });
525
+ if (warning)
526
+ warnings.push(warning);
527
+ try {
528
+ connected = connectedToolbox(options, scope, cwd);
529
+ }
530
+ catch (err) {
531
+ await undoAttach(options, app, cwd, home, problems);
532
+ throw withProblems(err, problems);
533
+ }
534
+ }
535
+ }
536
+ // The one-click note that made this toolbox, if any, and whether its files are still as it left them.
537
+ const creator = connected ? allNotes(options.registryPath).find((n) => n.created_toolbox?.id === connected.entry.id) : undefined;
538
+ const creatorUnchanged = creator?.created_toolbox ? unchangedSinceMade(creator.created_toolbox) : false;
539
+ // Set once the servers have moved: from then on nothing is undone here, and nothing after it throws.
540
+ let committed = false;
541
+ try {
542
+ /* what the app has, and what one click does with each */
543
+ let candidates = [];
544
+ let malformed = [];
545
+ try {
546
+ ({ candidates, malformed } = importCandidates({
547
+ scope,
548
+ cwd,
549
+ home,
550
+ ...(connected ? { gatewayConfigPath: connected.configPath, entryName: connected.entryName } : {}),
551
+ secrets: new SecretStore()
552
+ }));
553
+ }
554
+ catch (err) {
555
+ asHttp(err);
556
+ }
557
+ const left = [];
558
+ const names = [];
559
+ const extensions = [];
560
+ for (const c of candidates) {
561
+ if (!c.importable)
562
+ left.push({ name: c.name, kind: "cant-move", why: c.reason ?? "It can't be brought in." });
563
+ else if (c.source === "extension" && c.enabled === false) {
564
+ left.push({ name: c.name, kind: "off", why: "It is switched off in Claude Desktop, so it is left as it is." });
565
+ }
566
+ else
567
+ (c.source === "config" ? names : extensions).push(c.key);
568
+ }
569
+ for (const m of malformed)
570
+ left.push({ name: m.name, kind: "cant-move", why: `Its entry in ${app.name}'s settings can't be read: ${m.message}` });
571
+ for (const s of projectOnly(app, cwd, options.registryPath))
572
+ left.push({ name: s.name, kind: s.kind, why: s.why });
573
+ if (!connected && names.length === 0 && extensions.length === 0) {
574
+ return { status: "needs-server", app: app.id, left };
575
+ }
576
+ const result = names.length + extensions.length > 0
577
+ ? await bringIn({
578
+ options,
579
+ scope,
580
+ cwd,
581
+ names,
582
+ extensions,
583
+ toolbox: connected ?? { new: { name: body.name ?? freeToolboxName(options.registryPath), label: body.label ?? DEFAULT_GATEWAY_LABEL } },
584
+ actor: ctx.actor,
585
+ pathDirs,
586
+ hold: holdFor(connected)
587
+ })
588
+ : null;
589
+ committed = true;
590
+ for (const f of result?.failures ?? [])
591
+ left.push({ name: f.name, kind: "failed", why: f.message });
592
+ for (const h of result?.held ?? [])
593
+ left.push({ name: h.name, kind: "needs-ok", why: h.why });
594
+ // A new toolbox is never made empty: none of the servers connected, and nothing was written.
595
+ const toolbox = result?.toolbox ??
596
+ (connected
597
+ ? { id: connected.entry.id, label: toolboxLabel(connected.entry), configPath: connected.configPath, created: false, entryName: connected.entryName }
598
+ : null);
599
+ if (!toolbox)
600
+ return { status: "needs-server", app: app.id, left };
601
+ if (result?.warning)
602
+ warnings.push(result.warning);
603
+ try {
604
+ saveProvisional(options.registryPath, toolbox.id, result?.probed ?? []);
605
+ }
606
+ catch (err) {
607
+ warnings.push(`The tools couldn't be noted for the console to show before the toolbox runs (${err.message}).`);
608
+ }
609
+ const imported = (result?.imported ?? []).map((i) => ({ name: i.name, upstream: i.upstream, tools: i.tools }));
610
+ const takenOut = (result?.takenOut ?? []).map((t) => ({ name: t.name, upstream: t.upstream }));
611
+ /* the HTTPS addresses the click put on the allow-list, said back so the person sees them */
612
+ let allowedHosts = [];
613
+ try {
614
+ const now = loadGatewayConfig(toolbox.configPath).config.upstreams;
615
+ allowedHosts = [
616
+ ...new Set(imported.flatMap((i) => {
617
+ const u = now.find((x) => x.name === i.upstream);
618
+ const entry = u ? plainHttpsEntry(u) : null;
619
+ return entry ? [entry] : [];
620
+ }))
621
+ ];
622
+ }
623
+ catch {
624
+ /* the toolbox's file can't be read now; the activity log still has them */
625
+ }
626
+ /* the guard, for Claude Code, if asked */
627
+ // Carried only from a note that still matches, for this same toolbox.
628
+ const carry = before && before.gateway_id === toolbox.id ? before : undefined;
629
+ let guard = carry?.guard && resolve(carry.guard.config_path) === resolve(toolbox.configPath) ? carry.guard : null;
630
+ if (body.guard === true) {
631
+ const where = { scope: "user", home: guardHome() };
632
+ try {
633
+ const status = guardStatus(where);
634
+ if (status.installed && status.configPath !== null && resolve(status.configPath) !== resolve(toolbox.configPath)) {
635
+ warnings.push("Claude Code's own actions are already recorded by another toolbox, so that was left as it is.");
636
+ }
637
+ else {
638
+ const installed = installGuard({
639
+ ...where,
640
+ configPath: toolbox.configPath,
641
+ entryName: toolbox.entryName,
642
+ ...(options.guardCliPath ? { local: true, cliPath: options.guardCliPath } : {})
643
+ });
644
+ if (installed.changed) {
645
+ guard = { settings_path: installed.settingsPath, config_path: resolve(toolbox.configPath) };
646
+ const w = record(gatewayAudit(toolbox.configPath, ctx.actor), {
647
+ tool: "(guard)",
648
+ effect: null,
649
+ decision: "allow",
650
+ rule_id: "guard.install",
651
+ reason: `recording Claude Code's own actions was turned on by ${ctx.actor} in the console, while connecting Claude Code: hooks added to ${installed.settingsPath}`,
652
+ outcome: "completed",
653
+ args_redacted: { scope: "user", settings: installed.settingsPath, server_id: toolbox.id }
654
+ });
655
+ if (w)
656
+ warnings.push(w);
657
+ }
658
+ else if (guard === null) {
659
+ // Already on, exactly so, before this: not this connect's to turn off.
660
+ warnings.push("Claude Code's own actions were already recorded by this toolbox, so Undo will leave that on.");
661
+ }
662
+ }
663
+ }
664
+ catch (err) {
665
+ const why = err instanceof GuardInstallError ? err.message : `it was refused (${err.message})`;
666
+ warnings.push(`Claude Code is connected, but recording Claude Code's own actions couldn't be turned on: ${why}`);
667
+ }
668
+ }
669
+ // Whether Claude Code's own tools are recorded now, by this connect's guard or one already on for this toolbox.
670
+ const guardNow = (() => {
671
+ if (app.id !== "claude-code")
672
+ return null;
673
+ try {
674
+ const s = guardStatus({ scope: "user", home: guardHome() });
675
+ return s.installed && s.configPath !== null && resolve(s.configPath) === resolve(toolbox.configPath) ? s.settingsPath : null;
676
+ }
677
+ catch {
678
+ return null;
679
+ }
680
+ })();
681
+ /* the note Undo needs: this click's own servers, tied to this connection */
682
+ const asked = new Set([...names.map((n) => keyOf("config", n)), ...extensions.map((e) => keyOf("extension", e))]);
683
+ const moved = new Set([...(result?.imported ?? []), ...(result?.takenOut ?? [])].map((x) => keyOf(x.source, x.upstream)));
684
+ const recordNow = readImportRecord(options.registryPath, target);
685
+ const mine = (recordNow && recordNow.gateway_id === toolbox.id ? recordNow.items : [])
686
+ .filter((i) => asked.has(keyOf(i.source, i.key)) && moved.has(keyOf(i.source, i.upstream)))
687
+ .map((i) => ({ key: i.key, source: i.source, upstream: i.upstream, added: i.added, ...(i.digest !== undefined ? { digest: i.digest } : {}) }));
688
+ // As in the import record: a copy only taken out again doesn't replace the item that added it.
689
+ const earlierItems = carry?.items ?? [];
690
+ const sameItem = (a, b) => a.key === b.key && a.source === b.source;
691
+ const freshItems = mine.filter((m) => !(m.added === false && earlierItems.some((i) => sameItem(i, m) && i.added && i.upstream === m.upstream)));
692
+ const items = [...earlierItems.filter((i) => !freshItems.some((m) => sameItem(i, m))), ...freshItems];
693
+ const refreshed = (c) => ({ ...c, digests: toolboxDigests(c.configPath, c.policyPath) });
694
+ let createdToolbox = null;
695
+ if (result?.made)
696
+ createdToolbox = refreshed({ ...result.made, files: [...result.made.files], digests: { gateway: "-", policy: "-" } });
697
+ else if (carry?.created_toolbox)
698
+ createdToolbox = creatorUnchanged && creator?.app === app.id ? refreshed(carry.created_toolbox) : carry.created_toolbox;
699
+ // Another app's one-click made this toolbox: its note learns what this click wrote, if nobody changed the files meanwhile.
700
+ if (creator && creator.app !== app.id && creatorUnchanged && creator.created_toolbox) {
701
+ try {
702
+ writeNote(options.registryPath, { ...creator, created_toolbox: refreshed(creator.created_toolbox) });
703
+ }
704
+ catch {
705
+ /* that note then keeps its toolbox on Undo, which is the safe way round */
706
+ }
707
+ }
708
+ const stamp = backupStamp(target);
709
+ // One-click Undo needs both the app's backup and this note; without either, it isn't offered.
710
+ let undoable = stamp !== null;
711
+ if (stamp) {
712
+ try {
713
+ writeNote(options.registryPath, {
714
+ version: 2,
715
+ app: app.id,
716
+ scope,
717
+ config_path: target.path,
718
+ gateway_id: toolbox.id,
719
+ backup: stamp,
720
+ // Its connection is this click's, or an earlier click's that is still the one in place.
721
+ connected_here: attachedHere || toolbox.created || (carry !== undefined && alreadyConnected && carry.connected_here),
722
+ created_toolbox: createdToolbox,
723
+ guard,
724
+ items,
725
+ connected_at: carry?.connected_at ?? new Date().toISOString()
726
+ });
727
+ }
728
+ catch (err) {
729
+ undoable = false;
730
+ warnings.push(`Connected, but the note Undo needs couldn't be saved (${err.message}); ${OLDER_UNDO} still works.`);
731
+ }
732
+ }
733
+ else {
734
+ warnings.push(`Connected, but ${app.name}'s undo record couldn't be read, so one-click Undo won't be offered; ${OLDER_UNDO} still works.`);
735
+ }
736
+ const w = record(gatewayAudit(toolbox.configPath, ctx.actor), {
737
+ tool: "(connect)",
738
+ effect: null,
739
+ decision: "allow",
740
+ rule_id: "connect.app",
741
+ reason: `${app.name} connected in one click via the console by ${ctx.actor}: ${imported.length} server(s) brought in, ` +
742
+ `${takenOut.length} taken out of the app as already in the toolbox, ${left.length} left in the app` +
743
+ (toolbox.created ? `; toolbox "${toolbox.id}" made for it` : "") +
744
+ (allowedHosts.length > 0 ? `; web addresses allowed: ${allowedHosts.join(", ")}` : ""),
745
+ outcome: "completed",
746
+ args_redacted: {
747
+ app: app.id,
748
+ scope,
749
+ client_config: target.path,
750
+ registry_id: toolbox.id,
751
+ // This click connected the app (rather than finding it connected already).
752
+ connected_here: attachedHere || toolbox.created,
753
+ toolbox_created: toolbox.created,
754
+ imported: imported.map((i) => i.upstream),
755
+ left: left.map((l) => ({ name: l.name, kind: l.kind })),
756
+ allowed_hosts: allowedHosts,
757
+ guard: guard !== null
758
+ }
759
+ });
760
+ if (w)
761
+ warnings.push(w);
762
+ return {
763
+ status: "connected",
764
+ app: app.id,
765
+ toolbox: { id: toolbox.id, label: toolbox.label, created: toolbox.created },
766
+ configPath: target.path,
767
+ backupPath: backupPath(target),
768
+ alreadyConnected,
769
+ refreshed: updated,
770
+ imported,
771
+ takenOut,
772
+ left,
773
+ allowedHosts,
774
+ // What the servers brought in now offer, as tested.
775
+ toolCount: imported.reduce((n, i) => n + i.tools, 0),
776
+ extensionsToSwitchOff: result?.extensionsToSwitchOff ?? [],
777
+ guard: guardNow !== null ? { settingsPath: guardNow } : null,
778
+ notRecorded: notRecordedFor(app, guardNow !== null, left),
779
+ restartHint: result?.restartHint ?? restartHintFor(target, process.platform),
780
+ otherApps: result?.otherApps ?? otherAppsUsing(toolbox.configPath, target, cwd, home),
781
+ undoable,
782
+ warning: warnings.length > 0 ? warnings.join(" ") : null
783
+ };
784
+ }
785
+ catch (err) {
786
+ // A connection made a moment ago for this click goes again, so a refusal leaves the app as it was.
787
+ if (attachedHere && !committed)
788
+ await undoAttach(options, app, cwd, home, problems);
789
+ throw withProblems(err, problems);
790
+ }
791
+ }),
792
+ /**
793
+ * Undo one click, and only what it did: the app gets back the servers
794
+ * this click moved and loses the toolbox's entry if this click connected
795
+ * it; the toolbox loses what this click brought in, and is deleted only
796
+ * when this made it, it is exactly as one-click left it, and no other app
797
+ * or guard runs it; and the guard goes only if this turned it on and it
798
+ * still checks this toolbox.
799
+ */
800
+ route("POST", "/api/v1/connect/app/undo", async (ctx) => {
801
+ const body = parse(UndoBody, ctx.body);
802
+ const app = appFor(body.app);
803
+ const rec = readNote(options.registryPath, app.id);
804
+ if (!rec)
805
+ throw unprocessable(`There is nothing to undo: ${app.name} wasn't connected with one click here.`);
806
+ const scope = app.scope;
807
+ const cwd = projectDirOf(body.projectDir);
808
+ const home = homedir();
809
+ const target = targetFor(scope, cwd, home);
810
+ const notes = [];
811
+ const warnings = [];
812
+ const row = readRegistry(options.registryPath).servers.find((s) => s.id === rec.gateway_id && s.kind === "gateway");
813
+ const configPath = row ? resolve(expandPath(row.config_path)) : null;
814
+ // Opened first: a toolbox deleted below keeps its log, and the record goes beside what it then decided.
815
+ const log = configPath ? gatewayAudit(configPath, ctx.actor) : null;
816
+ const state = connectionState(target, options.registryPath, { cwd, home });
817
+ const stillConnected = noteMatches(rec, target) && state.kind === "console" && state.attached?.gatewayId === rec.gateway_id;
818
+ if (!stillConnected || !configPath) {
819
+ /* the connection was undone or remade some other way: only the guard and this note are left */
820
+ const guardRemoved = removeGuardIfOurs(guardHome(), rec.guard, notes, warnings);
821
+ deleteNote(options.registryPath, app.id);
822
+ return {
823
+ app: app.id,
824
+ restored: [],
825
+ removed: [],
826
+ keptInToolbox: [],
827
+ keysDeleted: [],
828
+ toolboxDeleted: false,
829
+ disconnected: false,
830
+ guardRemoved,
831
+ restartHint: restartHintFor(target, process.platform),
832
+ note: [`${app.name} is no longer connected the way one click connected it, so there was nothing else to put back.`, ...notes].join(" "),
833
+ warning: warnings.length > 0 ? warnings.join(" ") : null
834
+ };
835
+ }
836
+ const mineKeys = new Set(rec.items.map((i) => keyOf(i.source, i.key)));
837
+ const isMine = (i) => mineKeys.has(keyOf(i.source, i.key));
838
+ const imported = readLiveImportRecord(options.registryPath, target);
839
+ const items = imported && imported.gateway_id === rec.gateway_id ? imported.items.filter(isMine) : [];
840
+ const others = otherAppsUsing(configPath, target, cwd, home);
841
+ const file = readGatewayFile(configPath);
842
+ const ours = (u) => items.some((i) => i.added && i.upstream === u.name && i.digest !== undefined && i.digest === upstreamDigest(u));
843
+ const removable = file.config.upstreams.filter(ours).map((u) => u.name);
844
+ /* whether the toolbox this made can go: every reason it can't is said */
845
+ const created = rec.created_toolbox;
846
+ let keepBecause = null;
847
+ if (created) {
848
+ if (!rec.connected_here)
849
+ keepBecause = `${app.name} was connected to it before this`;
850
+ else if (others.length > 0)
851
+ keepBecause = `${others.join(", ")} also run${others.length === 1 ? "s" : ""} it`;
852
+ else if (!file.config.upstreams.every(ours))
853
+ keepBecause = "other servers were added to it since";
854
+ else if (!unchangedSinceMade(created))
855
+ keepBecause = "its settings (gateway.yaml or policy.yaml) were changed since it was made";
856
+ else if (!safeToDelete(created, row))
857
+ keepBecause = "the note of which files to remove doesn't match this toolbox's own files";
858
+ }
859
+ const deleting = created !== null && keepBecause === null;
860
+ let restored = [];
861
+ let removed = [];
862
+ let keptInToolbox = [];
863
+ let keysDeleted = [];
864
+ if (deleting) {
865
+ restored = (await revertApp(options, app, cwd, home)).restored;
866
+ deleteImportRecord(options.registryPath, target);
867
+ }
868
+ else {
869
+ if (items.length > 0) {
870
+ if (others.length > 0) {
871
+ keptInToolbox = removable;
872
+ notes.push(`${others.join(", ")} also run${others.length === 1 ? "s" : ""} this toolbox, so the servers brought in stay in it too.`);
873
+ }
874
+ else if (removable.length > 0 && removable.length >= file.config.upstreams.length) {
875
+ keptInToolbox = removable;
876
+ notes.push("Taking the servers out would leave the toolbox with none, so they stay in it too.");
877
+ }
878
+ else {
879
+ const undone = await undoImport(options, scope, cwd, ctx.actor, isMine);
880
+ restored.push(...undone.restored);
881
+ removed = undone.removed;
882
+ keptInToolbox = undone.keptInToolbox;
883
+ keysDeleted = undone.keysDeleted;
884
+ if (undone.note)
885
+ notes.push(undone.note);
886
+ if (undone.warning)
887
+ warnings.push(undone.warning);
888
+ }
889
+ }
890
+ if (rec.connected_here) {
891
+ restored.push(...(await revertApp(options, app, cwd, home)).restored);
892
+ deleteImportRecord(options.registryPath, target);
893
+ }
894
+ else if (keptInToolbox.length > 0) {
895
+ notes.push(`${app.name} was connected before this, so it stays connected; use ${OLDER_UNDO} to give it its servers back.`);
896
+ }
897
+ if (keepBecause)
898
+ notes.push(`The toolbox made for ${app.name} is kept, because ${keepBecause}.`);
899
+ }
900
+ /* the guard, if this turned it on and it still checks this toolbox: before the toolbox goes, since its hook reads it */
901
+ const guardRemoved = removeGuardIfOurs(guardHome(), rec.guard, notes, warnings);
902
+ let toolboxDeleted = false;
903
+ if (deleting && guardUses(configPath, guardHome(), cwd)) {
904
+ notes.push("The toolbox is kept, because it still records Claude Code's own actions.");
905
+ }
906
+ else if (deleting) {
907
+ try {
908
+ removeNewToolbox({ ...created, entry: row }, options.registryPath);
909
+ toolboxDeleted = true;
910
+ }
911
+ catch (err) {
912
+ warnings.push(`The toolbox could not be removed (${err.message}); remove it from its page.`);
913
+ }
914
+ if (toolboxDeleted) {
915
+ keysDeleted = deleteUnusedKeys(options, items.flatMap((i) => i.keys_created));
916
+ removeProvisional(options.registryPath, rec.gateway_id);
917
+ }
918
+ }
919
+ if (!toolboxDeleted && removed.length > 0)
920
+ removeProvisional(options.registryPath, rec.gateway_id, removed);
921
+ const w = record(log, {
922
+ tool: "(connect)",
923
+ effect: null,
924
+ decision: "allow",
925
+ rule_id: "connect.app.undo",
926
+ reason: `connecting ${app.name} in one click undone via the console by ${ctx.actor}: ${restored.length} server(s) put back in ${target.path}` +
927
+ (toolboxDeleted ? `; toolbox "${rec.gateway_id}" removed` : removed.length > 0 ? `; ${removed.length} removed from this gateway` : "") +
928
+ (guardRemoved ? "; recording Claude Code's own actions turned off" : ""),
929
+ outcome: "completed",
930
+ args_redacted: {
931
+ app: app.id,
932
+ scope,
933
+ client_config: target.path,
934
+ registry_id: rec.gateway_id,
935
+ restored,
936
+ removed: toolboxDeleted ? file.config.upstreams.map((u) => u.name) : removed,
937
+ kept_in_toolbox: keptInToolbox,
938
+ toolbox_removed: toolboxDeleted,
939
+ toolbox_kept_because: keepBecause,
940
+ disconnected: rec.connected_here,
941
+ secrets_deleted: keysDeleted,
942
+ guard_removed: guardRemoved
943
+ }
944
+ });
945
+ if (w)
946
+ warnings.push(w);
947
+ deleteNote(options.registryPath, app.id);
948
+ return {
949
+ app: app.id,
950
+ restored,
951
+ removed,
952
+ keptInToolbox,
953
+ keysDeleted,
954
+ toolboxDeleted,
955
+ disconnected: rec.connected_here,
956
+ guardRemoved,
957
+ restartHint: restartHintFor(target, process.platform),
958
+ note: notes.length > 0 ? notes.join(" ") : null,
959
+ warning: warnings.length > 0 ? warnings.join(" ") : null
960
+ };
961
+ })
962
+ ];
963
+ }
964
+ /** The app's settings back as they were before the connection, and its undo record gone. */
965
+ async function revertApp(options, app, cwd, home) {
966
+ try {
967
+ const result = await adoptRevert({ scope: app.scope, cwd, home, registry: options.registryPath });
968
+ return { restored: [...result.restored] };
969
+ }
970
+ catch (err) {
971
+ if (err instanceof HttpError)
972
+ throw err;
973
+ throw unprocessable(`${app.name}'s settings could not be put back: ${err.message}`);
974
+ }
975
+ }
976
+ /** A connection made for a click that was then refused, taken away again. A failure is added to `problems`, for the refusal to carry. */
977
+ async function undoAttach(options, app, cwd, home, problems) {
978
+ try {
979
+ await adoptRevert({ scope: app.scope, cwd, home, registry: options.registryPath });
980
+ }
981
+ catch (err) {
982
+ problems.push(`${app.name} is still connected to the toolbox, because disconnecting it again failed (${err.message}); use ${OLDER_UNDO}`);
983
+ }
984
+ }
985
+ /** Whether a Claude Code guard install checks calls against this toolbox. Can't tell: yes, so nothing it needs is deleted. */
986
+ function guardUses(configPath, home, cwd) {
987
+ const uses = (s) => s.installed && s.configPath !== null && resolve(s.configPath) === configPath;
988
+ try {
989
+ if (uses(guardStatus({ scope: "user", home })))
990
+ return true;
991
+ }
992
+ catch {
993
+ return true;
994
+ }
995
+ try {
996
+ return uses(guardStatus({ scope: "project", home, projectDir: cwd }));
997
+ }
998
+ catch {
999
+ return false;
1000
+ }
1001
+ }
1002
+ /**
1003
+ * Turns off the guard this connect turned on, only while it is still that
1004
+ * install: the same settings file, checking calls against the same toolbox.
1005
+ * One pointed at another toolbox since is someone's later choice, and stays.
1006
+ */
1007
+ function removeGuardIfOurs(home, guard, notes, warnings) {
1008
+ if (!guard)
1009
+ return false;
1010
+ let status;
1011
+ try {
1012
+ status = guardStatus({ scope: "user", home });
1013
+ }
1014
+ catch (err) {
1015
+ warnings.push(`Whether Claude Code's own actions are still recorded couldn't be read (${err.message}), so that was left as it is.`);
1016
+ return false;
1017
+ }
1018
+ if (!status.installed)
1019
+ return false;
1020
+ if (status.configPath === null || resolve(status.configPath) !== resolve(guard.config_path) || resolve(status.settingsPath) !== resolve(guard.settings_path)) {
1021
+ notes.push("Claude Code's own actions are now recorded by another toolbox, so that was left on.");
1022
+ return false;
1023
+ }
1024
+ try {
1025
+ return uninstallGuard({ scope: "user", home }).removed > 0;
1026
+ }
1027
+ catch (err) {
1028
+ warnings.push(`Recording Claude Code's own actions could not be turned off (${err.message}); turn it off on the Connections page.`);
1029
+ return false;
1030
+ }
1031
+ }
1032
+ /** Keys the connect made, once nothing uses them. */
1033
+ function deleteUnusedKeys(options, names) {
1034
+ const usage = secretUsage(options);
1035
+ const store = new SecretStore();
1036
+ const deleted = [];
1037
+ for (const name of names) {
1038
+ if ((usage.get(name) ?? []).length > 0)
1039
+ continue;
1040
+ try {
1041
+ if (store.delete(name))
1042
+ deleted.push(name);
1043
+ }
1044
+ catch {
1045
+ /* kept; it is named by nothing and harmless */
1046
+ }
1047
+ }
1048
+ return deleted;
1049
+ }