hmcp-web 0.2.2 → 0.2.3

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 +6 -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 +755 -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 +1018 -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 +11 -0
  31. package/dist/routes/connect.js +28 -116
  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-BSf4lBm-.js +1 -0
  38. package/dist-ui/assets/Approvals-CDz3zYpl.js +1 -0
  39. package/dist-ui/assets/AttachApp-COr1547c.js +5 -0
  40. package/dist-ui/assets/Connections-ClW5R6ea.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-DYDKgSpr.js} +1 -1
  43. package/dist-ui/assets/Protection-DMtABpM7.js +1 -0
  44. package/dist-ui/assets/Safety-BLTF2fqV.js +1 -0
  45. package/dist-ui/assets/{Settings-CSyTOe8X.js → Settings-DZ4P3Us6.js} +1 -1
  46. package/dist-ui/assets/StartPage-Bke6mrv5.js +1 -0
  47. package/dist-ui/assets/{Suggestions-CaQ_ifWR.js → Suggestions-kAWUILyw.js} +1 -1
  48. package/dist-ui/assets/Tools-BdXSeKeL.js +4 -0
  49. package/dist-ui/assets/connect-app-words-CT8Fytzv.js +1 -0
  50. package/dist-ui/assets/index-Cm4wG2zz.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
package/dist/api.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type Route } from "./http.js";
2
+ import type { AppChoice } from "./model/apps.js";
2
3
  export interface ApiOptions {
3
4
  readonly registryPath: string;
4
5
  /**
@@ -18,5 +19,10 @@ export interface ApiOptions {
18
19
  * installer's own choice.
19
20
  */
20
21
  readonly guardCliPath?: string;
22
+ /**
23
+ * Whether an AI app looks open, for one-click connect's "quit it first"
24
+ * hint. Advice only. Unset: `pgrep`; a test always sets it.
25
+ */
26
+ readonly appRunning?: (app: AppChoice) => Promise<boolean | null>;
21
27
  }
22
28
  export declare function buildRoutes(options: ApiOptions): Route[];
package/dist/api.js CHANGED
@@ -1,12 +1,14 @@
1
1
  import { randomBytes } from "node:crypto";
2
2
  import { readFileSync } from "node:fs";
3
- import { AuditLog, applyExposureChange, TOOL_RULE_CLEAR, TOOL_RULE_REFUSED, TOOL_RULE_SET, TOOL_RULE_UPDATE, boundsOf, globMatch, clearToolRule, decide, parseToolRuleDraft, policyDigest, previewClearToolRule, previewToolRule, ruleToYaml, UNCLASSIFIED_POSTURE_RULE, UNCLASSIFIED_RULE, writeToolRule, writeUnclassifiedPosture, approvalViolations, MAX_GRANT_TTL_SECONDS, REMEMBER_DEFAULT_TTL_SECONDS, REMEMBER_DEFAULT_USES, RememberError, rememberOnApprove, NO_TENANT, grantBoundGaps, grantCoversTool, grantMatches, hasLooseListItems, isOlderRemembered, parseExposureChange, parseGrantDraft, queryAuditLog, readRegistry, runtimeStateIsLive, verifyAuditLog, writeRegistry } from "hmcp-core";
3
+ import { AuditLog, applyExposureChange, TOOL_RULE_CLEAR, TOOL_RULE_REFUSED, TOOL_RULE_SET, TOOL_RULE_UPDATE, boundsOf, globMatch, clearToolRule, decide, parseToolRuleDraft, policyDigest, previewClearToolRule, previewToolRule, ruleToYaml, UNCLASSIFIED_POSTURE_RULE, UNCLASSIFIED_RULE, writeToolRule, writeUnclassifiedPosture, approvalViolations, MAX_GRANT_TTL_SECONDS, REMEMBER_DEFAULT_TTL_SECONDS, REMEMBER_DEFAULT_USES, RememberError, rememberOnApprove, NO_TENANT, grantBoundGaps, grantCoversTool, grantMatches, hasLooseListItems, isOlderRemembered, parseExposureChange, parseGrantDraft, queryAuditLog, readRegistry, verifyAuditLog, writeRegistry } from "hmcp-core";
4
4
  import { badRequest, conflict, notFound, route, unprocessable } from "./http.js";
5
5
  import { buildProtection, effectiveReach, recentActivity, toolProtection } from "./model/protection.js";
6
6
  import { chooseTenant, knownTenants, loadServer, scopeFor, scopedFor, storeFor } from "./model/server.js";
7
7
  import { surfaceWritable, toolSurfaceFor } from "./model/tools.js";
8
8
  import { buildMetrics, isWindow } from "./model/metrics.js";
9
9
  import { buildScan } from "./model/scan.js";
10
+ import { serverDisplayNames } from "./model/server-names.js";
11
+ import { toolboxLabel } from "./model/toolbox-label.js";
10
12
  import { toSarif } from "hmcp-scanner";
11
13
  import { z } from "zod";
12
14
  import { ENFORCEMENT_PIPELINE } from "./model/pipeline.js";
@@ -15,6 +17,8 @@ import { runtimeRoutes } from "./routes/runtime.js";
15
17
  import { policyRoutes } from "./routes/policy.js";
16
18
  import { connectRoutes } from "./routes/connect.js";
17
19
  import { connectImportRoutes } from "./routes/connect-import.js";
20
+ import { connectAppRoutes, pgrepRunning } from "./routes/connect-app.js";
21
+ import { dropNotesForToolbox } from "./model/app-connect-note.js";
18
22
  import { doctorPathDirs } from "./model/doctor.js";
19
23
  import { serversAddRoutes } from "./routes/servers-add.js";
20
24
  import { catalogRoutes } from "./routes/catalog.js";
@@ -408,6 +412,7 @@ export function buildRoutes(options) {
408
412
  // Absolute folders of node, uv, docker... so an app with a minimal PATH finds them.
409
413
  ...connectRoutes(options, { pathDirs: doctorPathDirs }),
410
414
  ...connectImportRoutes(options),
415
+ ...connectAppRoutes(options, { pathDirs: doctorPathDirs, running: options.appRunning ?? pgrepRunning }),
411
416
  ...serversAddRoutes(options),
412
417
  ...catalogRoutes(options),
413
418
  ...oauthRoutes(options),
@@ -465,21 +470,24 @@ export function buildRoutes(options) {
465
470
  * the gateway's.
466
471
  */
467
472
  const choice = chooseTenant(server, null);
468
- const surface = toolSurfaceFor(server, choice.ok ? choice.tenant : NO_TENANT);
469
- const announced = storeFor(server).runtimeState(server.component);
473
+ const surface = toolSurfaceFor(server, choice.ok ? choice.tenant : NO_TENANT, options.registryPath);
470
474
  return {
471
475
  id: entry.id,
472
476
  kind: entry.kind,
473
- label: entry.label,
477
+ label: toolboxLabel(entry, server.gateway.config.name),
474
478
  ok: true,
475
479
  component: server.component,
476
480
  upstreams: server.gateway.config.upstreams.map((u) => u.name),
481
+ // The catalog's name for each server it recognises ("github" -> "GitHub"), for headings and sentences.
482
+ displayNames: serverDisplayNames(server.gateway.config.upstreams),
477
483
  /*
478
484
  * Null, not zero, when nothing has been published. A gateway that
479
485
  * has not reported is not a gateway serving no tools, and the two
480
486
  * used to be the same number here.
481
487
  */
482
488
  toolCount: surface.live ? surface.entries.length : null,
489
+ // What its servers offered when tested on the way in, until it runs: shown, never trusted for a switch.
490
+ provisionalToolCount: surface.provisional.length,
483
491
  surfaceLive: surface.live,
484
492
  surfaceStale: surface.stale,
485
493
  posture: server.policy.defaults.mode,
@@ -491,7 +499,10 @@ export function buildRoutes(options) {
491
499
  tenantScope: choice.ok ? choice.tenant : null,
492
500
  tenantRequired: !choice.ok,
493
501
  tenantHint: choice.ok ? null : choice.why,
494
- running: announced !== undefined && runtimeStateIsLive(announced),
502
+ // The shared judgement: any running process of it, never one that just exited.
503
+ running: storeFor(server).liveProcesses(server.component).length > 0,
504
+ // Shown as a muted line under the name, so the path is still there to check.
505
+ configPath: entry.config_path,
495
506
  auditPath: server.auditPath,
496
507
  storePath: server.storePath,
497
508
  tenantError: server.tenantError
@@ -500,7 +511,14 @@ export function buildRoutes(options) {
500
511
  catch (err) {
501
512
  // A broken entry is listed with its error. Failing the whole list
502
513
  // would hide every working server behind one bad path.
503
- return { id: entry.id, kind: entry.kind, label: entry.label, ok: false, error: err.message };
514
+ return {
515
+ id: entry.id,
516
+ kind: entry.kind,
517
+ label: toolboxLabel(entry),
518
+ ok: false,
519
+ configPath: entry.config_path,
520
+ error: err.message
521
+ };
504
522
  }
505
523
  })),
506
524
  route("POST", "/api/v1/servers", (ctx) => {
@@ -520,6 +538,13 @@ export function buildRoutes(options) {
520
538
  catch (err) {
521
539
  throw unprocessable(`that server could not be loaded: ${err.message}`);
522
540
  }
541
+ /*
542
+ * Left empty, the label is named after the toolbox itself. The console
543
+ * used to send the file path here, and every title then read as a path.
544
+ */
545
+ if (typeof entry.label !== "string" || !entry.label.trim()) {
546
+ entry.label = toolboxLabel({ ...entry, label: "" }, loaded.gateway.config.name);
547
+ }
523
548
  writeRegistry({ ...reg, servers: [...reg.servers, entry] }, options.registryPath);
524
549
  return { id, component: loaded.component };
525
550
  }),
@@ -534,6 +559,8 @@ export function buildRoutes(options) {
534
559
  await processes.stop(id);
535
560
  // Only the registry entry is removed; the referenced files are never touched.
536
561
  writeRegistry({ ...reg, servers: reg.servers.filter((s) => s.id !== id) }, options.registryPath);
562
+ // One-click notes about it go too: a later toolbox under this id is not the one they describe.
563
+ dropNotesForToolbox(options.registryPath, id);
537
564
  return { removed: id };
538
565
  }),
539
566
  /* tools and protection */
@@ -561,7 +588,7 @@ export function buildRoutes(options) {
561
588
  }),
562
589
  route("GET", "/api/v1/servers/:id/protection", (ctx) => {
563
590
  const { server, tenant, explicit } = scopedRequest(options, ctx.params["id"], ctx.query);
564
- return buildProtection(server, tenant, explicit);
591
+ return buildProtection(server, tenant, explicit, options.registryPath);
565
592
  }),
566
593
  route("GET", "/api/v1/servers/:id/tools", (ctx) => {
567
594
  const { server, tenant, explicit } = scopedRequest(options, ctx.params["id"], ctx.query);
@@ -1348,7 +1375,8 @@ export function buildRoutes(options) {
1348
1375
  */
1349
1376
  route("GET", "/api/v1/servers/:id/policy", (ctx) => {
1350
1377
  const { server } = scopedRequest(options, ctx.params["id"], ctx.query);
1351
- const announced = storeFor(server).runtimeState(server.component);
1378
+ // Only a running process's digest: a stopped one's would show as drift that nothing is enforcing.
1379
+ const announced = storeFor(server).liveRuntimeState(server.component);
1352
1380
  let text = null;
1353
1381
  let readError = null;
1354
1382
  try {
@@ -0,0 +1,114 @@
1
+ import { z } from "zod";
2
+ import { type RegistryEntry } from "hmcp-core";
3
+ import { type ScopeTarget } from "hmcp-gateway";
4
+ /**
5
+ * What one-click "Connect your AI app" did, so its Undo takes back exactly
6
+ * that: the toolbox only if this made it (and it is still as made), the
7
+ * app's connection only if this made it, the guard only if this turned it
8
+ * on, and only the servers this brought in.
9
+ *
10
+ * One file per app, beside the console's list. Names, paths and digests
11
+ * only; nothing in it is a secret.
12
+ *
13
+ * A note is believed only while it describes the connection that is really
14
+ * there: the app's own undo record must name the same toolbox, under the same
15
+ * entry name, made at the same moment. A connection undone and made again
16
+ * some other way leaves a note that no longer matches, and it is ignored.
17
+ */
18
+ declare const NoteItemSchema: z.ZodObject<{
19
+ key: z.ZodString;
20
+ source: z.ZodEnum<{
21
+ config: "config";
22
+ extension: "extension";
23
+ }>;
24
+ upstream: z.ZodString;
25
+ added: z.ZodBoolean;
26
+ digest: z.ZodOptional<z.ZodString>;
27
+ }, z.core.$strict>;
28
+ export type NoteItem = z.infer<typeof NoteItemSchema>;
29
+ declare const CreatedSchema: z.ZodObject<{
30
+ id: z.ZodString;
31
+ configPath: z.ZodString;
32
+ policyPath: z.ZodString;
33
+ dir: z.ZodString;
34
+ createdDir: z.ZodBoolean;
35
+ files: z.ZodArray<z.ZodString>;
36
+ digests: z.ZodObject<{
37
+ gateway: z.ZodString;
38
+ policy: z.ZodString;
39
+ }, z.core.$strict>;
40
+ }, z.core.$strict>;
41
+ export type CreatedToolbox = z.infer<typeof CreatedSchema>;
42
+ export declare const AppNoteSchema: z.ZodObject<{
43
+ version: z.ZodLiteral<2>;
44
+ app: z.ZodString;
45
+ scope: z.ZodString;
46
+ config_path: z.ZodString;
47
+ gateway_id: z.ZodString;
48
+ backup: z.ZodObject<{
49
+ entry_name: z.ZodString;
50
+ created_at: z.ZodString;
51
+ }, z.core.$strict>;
52
+ connected_here: z.ZodBoolean;
53
+ created_toolbox: z.ZodNullable<z.ZodObject<{
54
+ id: z.ZodString;
55
+ configPath: z.ZodString;
56
+ policyPath: z.ZodString;
57
+ dir: z.ZodString;
58
+ createdDir: z.ZodBoolean;
59
+ files: z.ZodArray<z.ZodString>;
60
+ digests: z.ZodObject<{
61
+ gateway: z.ZodString;
62
+ policy: z.ZodString;
63
+ }, z.core.$strict>;
64
+ }, z.core.$strict>>;
65
+ guard: z.ZodNullable<z.ZodObject<{
66
+ settings_path: z.ZodString;
67
+ config_path: z.ZodString;
68
+ }, z.core.$strict>>;
69
+ items: z.ZodArray<z.ZodObject<{
70
+ key: z.ZodString;
71
+ source: z.ZodEnum<{
72
+ config: "config";
73
+ extension: "extension";
74
+ }>;
75
+ upstream: z.ZodString;
76
+ added: z.ZodBoolean;
77
+ digest: z.ZodOptional<z.ZodString>;
78
+ }, z.core.$strict>>;
79
+ connected_at: z.ZodString;
80
+ }, z.core.$strict>;
81
+ export type AppNote = z.infer<typeof AppNoteSchema>;
82
+ export declare function notePath(registryPath: string, appId: string): string;
83
+ /** The note as written, or undefined when there is none or it can't be read. Not yet checked against the connection. */
84
+ export declare function readNote(registryPath: string, appId: string): AppNote | undefined;
85
+ export declare function allNotes(registryPath: string): AppNote[];
86
+ /** Atomic and 0600, like the console's other notes. */
87
+ export declare function writeNote(registryPath: string, note: AppNote): void;
88
+ export declare function deleteNote(registryPath: string, appId: string): void;
89
+ /** The app's undo record as a note records it, or null when there is none for this scope. */
90
+ export declare function backupStamp(target: ScopeTarget): AppNote["backup"] | null;
91
+ /** Whether a note still describes the connection that is really there. */
92
+ export declare function noteMatches(note: AppNote, target: ScopeTarget): boolean;
93
+ export declare function toolboxDigests(configPath: string, policyPath: string): CreatedToolbox["digests"];
94
+ /** Both files exactly as the note last left them. */
95
+ export declare function unchangedSinceMade(created: CreatedToolbox): boolean;
96
+ /**
97
+ * Whether the files a note says to delete are a console-made toolbox's own
98
+ * and nothing else: gateway.yaml and policy.yaml in one folder directly under
99
+ * ~/.hmcp/gateways (where a new toolbox is always made), and the toolbox the
100
+ * console's list has under that id. A note edited by hand can't point a
101
+ * delete anywhere else.
102
+ */
103
+ export declare function safeToDelete(created: CreatedToolbox, row: RegistryEntry | undefined): boolean;
104
+ /** "Undo connection" on the Connections page: that app's note goes, since its connection did. */
105
+ export declare function dropNotesForApp(registryPath: string, target: ScopeTarget): void;
106
+ /** A toolbox removed from the console: every note about it goes. */
107
+ export declare function dropNotesForToolbox(registryPath: string, gatewayId: string): void;
108
+ /**
109
+ * The guard turned off on its own page: no note may turn it off again later.
110
+ * Only that part of the note goes; the rest still describes a connection that
111
+ * is there.
112
+ */
113
+ export declare function dropGuardFromNotes(registryPath: string, settingsPath: string): void;
114
+ export {};
@@ -0,0 +1,199 @@
1
+ import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { z } from "zod";
5
+ import { expandPath, sha256 } from "hmcp-core";
6
+ import { readBackup } from "hmcp-gateway";
7
+ /**
8
+ * What one-click "Connect your AI app" did, so its Undo takes back exactly
9
+ * that: the toolbox only if this made it (and it is still as made), the
10
+ * app's connection only if this made it, the guard only if this turned it
11
+ * on, and only the servers this brought in.
12
+ *
13
+ * One file per app, beside the console's list. Names, paths and digests
14
+ * only; nothing in it is a secret.
15
+ *
16
+ * A note is believed only while it describes the connection that is really
17
+ * there: the app's own undo record must name the same toolbox, under the same
18
+ * entry name, made at the same moment. A connection undone and made again
19
+ * some other way leaves a note that no longer matches, and it is ignored.
20
+ */
21
+ const NoteItemSchema = z
22
+ .object({
23
+ key: z.string().min(1),
24
+ source: z.enum(["config", "extension"]),
25
+ upstream: z.string().min(1),
26
+ added: z.boolean(),
27
+ digest: z.string().optional()
28
+ })
29
+ .strict();
30
+ const CreatedSchema = z
31
+ .object({
32
+ id: z.string().min(1),
33
+ configPath: z.string().min(1),
34
+ policyPath: z.string().min(1),
35
+ dir: z.string().min(1),
36
+ createdDir: z.boolean(),
37
+ files: z.array(z.string()),
38
+ /** gateway.yaml and policy.yaml as this left them, so Undo can tell they were changed since. */
39
+ digests: z.object({ gateway: z.string().min(1), policy: z.string().min(1) }).strict()
40
+ })
41
+ .strict();
42
+ export const AppNoteSchema = z
43
+ .object({
44
+ version: z.literal(2),
45
+ app: z.string().min(1),
46
+ scope: z.string().min(1),
47
+ config_path: z.string().min(1),
48
+ gateway_id: z.string().min(1),
49
+ /** The app's undo record as it stood after connecting: what ties this note to that connection. */
50
+ backup: z.object({ entry_name: z.string().min(1), created_at: z.string().min(1) }).strict(),
51
+ connected_here: z.boolean(),
52
+ created_toolbox: CreatedSchema.nullable(),
53
+ /** The guard this turned on: where, and which toolbox it checks against. */
54
+ guard: z.object({ settings_path: z.string().min(1), config_path: z.string().min(1) }).strict().nullable(),
55
+ /** The servers this brought in or took out of the app, and nothing earlier. */
56
+ items: z.array(NoteItemSchema),
57
+ connected_at: z.string()
58
+ })
59
+ .strict();
60
+ function notesDir(registryPath) {
61
+ return join(dirname(registryPath), "connect-apps");
62
+ }
63
+ const APP_ID = /^[a-z0-9][a-z0-9-]{0,63}$/;
64
+ export function notePath(registryPath, appId) {
65
+ if (!APP_ID.test(appId))
66
+ throw new Error(`"${appId}" is not an app id`);
67
+ return join(notesDir(registryPath), `${appId}.json`);
68
+ }
69
+ /** The note as written, or undefined when there is none or it can't be read. Not yet checked against the connection. */
70
+ export function readNote(registryPath, appId) {
71
+ const path = notePath(registryPath, appId);
72
+ if (!existsSync(path))
73
+ return undefined;
74
+ try {
75
+ const parsed = AppNoteSchema.safeParse(JSON.parse(readFileSync(path, "utf8")));
76
+ return parsed.success && parsed.data.app === appId ? parsed.data : undefined;
77
+ }
78
+ catch {
79
+ return undefined;
80
+ }
81
+ }
82
+ export function allNotes(registryPath) {
83
+ const dir = notesDir(registryPath);
84
+ if (!existsSync(dir))
85
+ return [];
86
+ return readdirSync(dir)
87
+ .filter((f) => f.endsWith(".json"))
88
+ .map((f) => readNote(registryPath, f.slice(0, -".json".length)))
89
+ .filter((n) => n !== undefined);
90
+ }
91
+ /** Atomic and 0600, like the console's other notes. */
92
+ export function writeNote(registryPath, note) {
93
+ AppNoteSchema.parse(note);
94
+ const path = notePath(registryPath, note.app);
95
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
96
+ const tmp = join(dirname(path), `.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
97
+ writeFileSync(tmp, `${JSON.stringify(note, null, 2)}\n`, { encoding: "utf8", mode: 0o600 });
98
+ try {
99
+ chmodSync(tmp, 0o600);
100
+ }
101
+ catch {
102
+ /* best effort: Windows has no such modes */
103
+ }
104
+ renameSync(tmp, path);
105
+ }
106
+ export function deleteNote(registryPath, appId) {
107
+ const path = notePath(registryPath, appId);
108
+ if (existsSync(path))
109
+ unlinkSync(path);
110
+ }
111
+ /** The app's undo record as a note records it, or null when there is none for this scope. */
112
+ export function backupStamp(target) {
113
+ try {
114
+ const b = readBackup(target);
115
+ return b && b.scope === target.scope ? { entry_name: b.gateway_entry_name, created_at: b.created_at } : null;
116
+ }
117
+ catch {
118
+ return null;
119
+ }
120
+ }
121
+ /** Whether a note still describes the connection that is really there. */
122
+ export function noteMatches(note, target) {
123
+ if (note.scope !== target.scope || note.config_path !== target.path)
124
+ return false;
125
+ try {
126
+ const b = readBackup(target);
127
+ return (b !== undefined &&
128
+ b.scope === target.scope &&
129
+ b.registry_id === note.gateway_id &&
130
+ b.gateway_entry_name === note.backup.entry_name &&
131
+ b.created_at === note.backup.created_at);
132
+ }
133
+ catch {
134
+ return false;
135
+ }
136
+ }
137
+ /** A file's bytes as a digest; "missing" when it isn't there. */
138
+ function fileDigest(path) {
139
+ try {
140
+ return sha256(readFileSync(path, "utf8"));
141
+ }
142
+ catch {
143
+ return "missing";
144
+ }
145
+ }
146
+ export function toolboxDigests(configPath, policyPath) {
147
+ return { gateway: fileDigest(configPath), policy: fileDigest(policyPath) };
148
+ }
149
+ /** Both files exactly as the note last left them. */
150
+ export function unchangedSinceMade(created) {
151
+ const now = toolboxDigests(created.configPath, created.policyPath);
152
+ return now.gateway === created.digests.gateway && now.policy === created.digests.policy;
153
+ }
154
+ /**
155
+ * Whether the files a note says to delete are a console-made toolbox's own
156
+ * and nothing else: gateway.yaml and policy.yaml in one folder directly under
157
+ * ~/.hmcp/gateways (where a new toolbox is always made), and the toolbox the
158
+ * console's list has under that id. A note edited by hand can't point a
159
+ * delete anywhere else.
160
+ */
161
+ export function safeToDelete(created, row) {
162
+ const dir = resolve(created.dir);
163
+ const config = resolve(created.configPath);
164
+ const policy = resolve(created.policyPath);
165
+ const own = new Set([join(dir, "gateway.yaml"), join(dir, "policy.yaml")]);
166
+ return (row !== undefined &&
167
+ row.kind === "gateway" &&
168
+ row.id === created.id &&
169
+ resolve(expandPath(row.config_path)) === config &&
170
+ dirname(config) === dir &&
171
+ config === join(dir, "gateway.yaml") &&
172
+ policy === join(dir, "policy.yaml") &&
173
+ created.files.every((f) => own.has(resolve(f))) &&
174
+ dirname(dir) === resolve(homedir(), ".hmcp", "gateways"));
175
+ }
176
+ /* ------------------------------------------------- the other undo paths */
177
+ /** "Undo connection" on the Connections page: that app's note goes, since its connection did. */
178
+ export function dropNotesForApp(registryPath, target) {
179
+ for (const n of allNotes(registryPath))
180
+ if (n.scope === target.scope && n.config_path === target.path)
181
+ deleteNote(registryPath, n.app);
182
+ }
183
+ /** A toolbox removed from the console: every note about it goes. */
184
+ export function dropNotesForToolbox(registryPath, gatewayId) {
185
+ for (const n of allNotes(registryPath))
186
+ if (n.gateway_id === gatewayId)
187
+ deleteNote(registryPath, n.app);
188
+ }
189
+ /**
190
+ * The guard turned off on its own page: no note may turn it off again later.
191
+ * Only that part of the note goes; the rest still describes a connection that
192
+ * is there.
193
+ */
194
+ export function dropGuardFromNotes(registryPath, settingsPath) {
195
+ for (const n of allNotes(registryPath)) {
196
+ if (n.guard && resolve(n.guard.settings_path) === resolve(settingsPath))
197
+ writeNote(registryPath, { ...n, guard: null });
198
+ }
199
+ }
@@ -1,4 +1,5 @@
1
- import { type ImportCandidate, type Scope, type ScopeTarget } from "hmcp-gateway";
1
+ import { type RegistryEntry } from "hmcp-core";
2
+ import { type AdoptBackup, type ImportCandidate, type Scope, type ScopeTarget } from "hmcp-gateway";
2
3
  /**
3
4
  * What an AI app has, for the Connections page: the servers in its own
4
5
  * settings (and, for Claude Desktop, its extensions), whether each could come
@@ -14,6 +15,8 @@ export interface AttachedTo {
14
15
  readonly gatewayId: string;
15
16
  readonly entryName: string;
16
17
  readonly configPath: string;
18
+ /** The id the app's undo record still names, when the toolbox was found by what the app runs under a new one. */
19
+ readonly staleId?: string;
17
20
  }
18
21
  export interface AppServer {
19
22
  /** The entry's name in the app, or the extension's display name. */
@@ -68,6 +71,26 @@ export declare function attachedTo(target: ScopeTarget, registryPath: string, at
68
71
  cwd: string;
69
72
  home: string;
70
73
  }): AttachedTo | null;
74
+ /**
75
+ * The console's row for the toolbox an app's undo record names: the row with
76
+ * its `registry_id`, whatever kind it is, as before.
77
+ *
78
+ * When no row has that id any more -- a toolbox removed from the console and
79
+ * added again gets a new id, and older versions named rows differently -- the
80
+ * toolbox is still found by what the app really runs: the one toolbox row
81
+ * whose gateway.yaml the app's own entry (`gateway_entry_name`) starts with
82
+ * `-c`, given as a full path (one relative to the app's settings file says
83
+ * less about which file is meant). Strictly one: none, or two rows for the
84
+ * same file, finds nothing, and a record with no `registry_id` at all is left
85
+ * as it was.
86
+ *
87
+ * Reads the registry, so it throws when that can't be read.
88
+ */
89
+ export declare function recordedToolbox(backup: Pick<AdoptBackup, "registry_id" | "gateway_entry_name">, registryPath: string, at: {
90
+ scope: Scope;
91
+ cwd: string;
92
+ home: string;
93
+ }): RegistryEntry | undefined;
71
94
  /** Which `ConnectionKind` this app's connection is, with the toolbox when it is one servers can be brought into. */
72
95
  export declare function connectionState(target: ScopeTarget, registryPath: string, at: {
73
96
  cwd: string;
@@ -1,7 +1,7 @@
1
1
  import { homedir } from "node:os";
2
- import { resolve } from "node:path";
2
+ import { isAbsolute, resolve } from "node:path";
3
3
  import { SecretStore, expandPath, readRegistry } from "hmcp-core";
4
- import { importCandidates, readBackup, runsToolbox, scopeTargets } from "hmcp-gateway";
4
+ import { importCandidates, isRemote, parseServers, readBackup, readClientConfig, runsToolbox, scopeTargets } from "hmcp-gateway";
5
5
  import { readLiveImportRecord } from "./import-record.js";
6
6
  export function targetFor(scope, cwd, home = homedir()) {
7
7
  return scopeTargets({ cwd, home }).find((t) => t.scope === scope);
@@ -18,6 +18,44 @@ export function attachedTo(target, registryPath, at) {
18
18
  const state = connectionState(target, registryPath, at);
19
19
  return state.kind === "console" ? state.attached : null;
20
20
  }
21
+ /**
22
+ * The console's row for the toolbox an app's undo record names: the row with
23
+ * its `registry_id`, whatever kind it is, as before.
24
+ *
25
+ * When no row has that id any more -- a toolbox removed from the console and
26
+ * added again gets a new id, and older versions named rows differently -- the
27
+ * toolbox is still found by what the app really runs: the one toolbox row
28
+ * whose gateway.yaml the app's own entry (`gateway_entry_name`) starts with
29
+ * `-c`, given as a full path (one relative to the app's settings file says
30
+ * less about which file is meant). Strictly one: none, or two rows for the
31
+ * same file, finds nothing, and a record with no `registry_id` at all is left
32
+ * as it was.
33
+ *
34
+ * Reads the registry, so it throws when that can't be read.
35
+ */
36
+ export function recordedToolbox(backup, registryPath, at) {
37
+ if (!backup.registry_id)
38
+ return undefined;
39
+ const rows = readRegistry(registryPath).servers;
40
+ const byId = rows.find((s) => s.id === backup.registry_id);
41
+ if (byId)
42
+ return byId;
43
+ let value;
44
+ try {
45
+ const entry = parseServers(readClientConfig(at.scope, { cwd: at.cwd, home: at.home }).servers).servers.get(backup.gateway_entry_name);
46
+ if (entry && !isRemote(entry)) {
47
+ const i = entry.args.indexOf("-c");
48
+ value = i >= 0 ? entry.args[i + 1] : undefined;
49
+ }
50
+ }
51
+ catch {
52
+ return undefined;
53
+ }
54
+ if (value === undefined || !isAbsolute(value))
55
+ return undefined;
56
+ const running = rows.filter((s) => s.kind === "gateway" && runsToolbox({ scope: at.scope, cwd: at.cwd, home: at.home }, backup.gateway_entry_name, resolve(expandPath(s.config_path))));
57
+ return running.length === 1 ? running[0] : undefined;
58
+ }
21
59
  /** Which `ConnectionKind` this app's connection is, with the toolbox when it is one servers can be brought into. */
22
60
  export function connectionState(target, registryPath, at) {
23
61
  let backup;
@@ -33,18 +71,26 @@ export function connectionState(target, registryPath, at) {
33
71
  return { kind: "adopt", attached: null };
34
72
  let row;
35
73
  try {
36
- row = backup.registry_id ? readRegistry(registryPath).servers.find((s) => s.id === backup.registry_id && s.kind === "gateway") : undefined;
74
+ row = recordedToolbox(backup, registryPath, { scope: target.scope, cwd: at.cwd, home: at.home });
37
75
  }
38
76
  catch {
39
77
  row = undefined;
40
78
  }
41
- if (!row)
79
+ if (!row || row.kind !== "gateway")
42
80
  return { kind: "toolbox-missing", attached: null };
43
81
  const configPath = resolve(expandPath(row.config_path));
44
82
  if (!runsToolbox({ scope: target.scope, cwd: at.cwd, home: at.home }, backup.gateway_entry_name, configPath)) {
45
83
  return { kind: "entry-missing", attached: null };
46
84
  }
47
- return { kind: "console", attached: { gatewayId: row.id, entryName: backup.gateway_entry_name, configPath } };
85
+ return {
86
+ kind: "console",
87
+ attached: {
88
+ gatewayId: row.id,
89
+ entryName: backup.gateway_entry_name,
90
+ configPath,
91
+ ...(backup.registry_id !== undefined && backup.registry_id !== row.id ? { staleId: backup.registry_id } : {})
92
+ }
93
+ };
48
94
  }
49
95
  /** One candidate as the browser may see it. */
50
96
  export function appServer(c) {
@@ -98,7 +144,9 @@ export function appServersFor(scope, cwd, registryPath) {
98
144
  catch {
99
145
  record = undefined;
100
146
  }
101
- const items = record && record.gateway_id === attached?.gatewayId ? record.items : [];
147
+ // A record from before the toolbox's id changed names the old one, until a change here points it at the new one.
148
+ const ours = record !== undefined && attached !== null && (record.gateway_id === attached.gatewayId || record.gateway_id === attached.staleId);
149
+ const items = ours ? record.items : [];
102
150
  return {
103
151
  attachedTo: attached ? { gatewayId: attached.gatewayId, entryName: attached.entryName } : null,
104
152
  connection: state.kind,
@@ -0,0 +1,24 @@
1
+ import type { Scope } from "hmcp-gateway";
2
+ /**
3
+ * The AI apps the simple picker offers, each with the one place in its
4
+ * settings "Connect" uses unless the person picks another: the app's
5
+ * all-projects file where it has one, since a person choosing an app (not a
6
+ * project) means the app everywhere.
7
+ *
8
+ * Data only. The full list of places, project ones included, stays the
9
+ * connect routes' `LABELS`; this names a default per app and reuses those
10
+ * words for it.
11
+ */
12
+ export interface AppChoice {
13
+ /** Stable, for the page and for tests. */
14
+ readonly id: string;
15
+ /** The app as a person knows it. */
16
+ readonly name: string;
17
+ /** Where in its settings it is connected by default. */
18
+ readonly scope: Scope;
19
+ /** That place in the console's own words. */
20
+ readonly label: string;
21
+ }
22
+ export declare const APPS: readonly AppChoice[];
23
+ /** The app's default place, or undefined for an app this list doesn't have. */
24
+ export declare function defaultScopeFor(appId: string): Scope | undefined;
@@ -0,0 +1,18 @@
1
+ import { LABELS } from "../routes/connect.js";
2
+ const DEFAULTS = [
3
+ ["claude-desktop", "Claude Desktop", "claude-desktop"],
4
+ ["claude-code", "Claude Code", "user"],
5
+ ["cursor", "Cursor", "cursor-user"],
6
+ ["vscode", "VS Code", "vscode-user"],
7
+ ["codex", "Codex and ChatGPT desktop", "codex"],
8
+ ["copilot-cli", "GitHub Copilot CLI", "copilot-cli"],
9
+ ["antigravity", "Antigravity", "antigravity"],
10
+ ["devin", "Devin", "devin"],
11
+ ["junie", "Junie", "junie"],
12
+ ["windsurf", "Windsurf", "windsurf"]
13
+ ];
14
+ export const APPS = DEFAULTS.map(([id, name, scope]) => ({ id, name, scope, label: LABELS[scope] }));
15
+ /** The app's default place, or undefined for an app this list doesn't have. */
16
+ export function defaultScopeFor(appId) {
17
+ return APPS.find((a) => a.id === appId)?.scope;
18
+ }