hmcp-web 0.0.1 → 0.2.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 (94) hide show
  1. package/LICENSE +77 -0
  2. package/README.md +49 -2
  3. package/THIRD-PARTY-NOTICES.md +110 -0
  4. package/bin/hmcp-web.js +20 -0
  5. package/dist/api.d.ts +22 -0
  6. package/dist/api.js +1458 -0
  7. package/dist/cli.d.ts +2 -0
  8. package/dist/cli.js +40 -0
  9. package/dist/contracts/onboarding.d.ts +233 -0
  10. package/dist/contracts/onboarding.js +1 -0
  11. package/dist/http.d.ts +72 -0
  12. package/dist/http.js +319 -0
  13. package/dist/index.d.ts +7 -0
  14. package/dist/index.js +7 -0
  15. package/dist/model/app-servers.d.ts +85 -0
  16. package/dist/model/app-servers.js +109 -0
  17. package/dist/model/console-settings.d.ts +37 -0
  18. package/dist/model/console-settings.js +74 -0
  19. package/dist/model/doctor.d.ts +68 -0
  20. package/dist/model/doctor.js +254 -0
  21. package/dist/model/fs-browse.d.ts +9 -0
  22. package/dist/model/fs-browse.js +184 -0
  23. package/dist/model/gateway-config.d.ts +287 -0
  24. package/dist/model/gateway-config.js +760 -0
  25. package/dist/model/import-record.d.ts +80 -0
  26. package/dist/model/import-record.js +179 -0
  27. package/dist/model/metrics.d.ts +65 -0
  28. package/dist/model/metrics.js +213 -0
  29. package/dist/model/oauth-flows.d.ts +60 -0
  30. package/dist/model/oauth-flows.js +79 -0
  31. package/dist/model/pipeline.d.ts +58 -0
  32. package/dist/model/pipeline.js +84 -0
  33. package/dist/model/probe.d.ts +155 -0
  34. package/dist/model/probe.js +385 -0
  35. package/dist/model/process.d.ts +100 -0
  36. package/dist/model/process.js +278 -0
  37. package/dist/model/protection.d.ts +378 -0
  38. package/dist/model/protection.js +470 -0
  39. package/dist/model/registry-cache.d.ts +59 -0
  40. package/dist/model/registry-cache.js +238 -0
  41. package/dist/model/scan.d.ts +48 -0
  42. package/dist/model/scan.js +59 -0
  43. package/dist/model/server.d.ts +127 -0
  44. package/dist/model/server.js +243 -0
  45. package/dist/model/tools.d.ts +61 -0
  46. package/dist/model/tools.js +72 -0
  47. package/dist/routes/catalog.d.ts +8 -0
  48. package/dist/routes/catalog.js +47 -0
  49. package/dist/routes/connect-import.d.ts +9 -0
  50. package/dist/routes/connect-import.js +594 -0
  51. package/dist/routes/connect.d.ts +50 -0
  52. package/dist/routes/connect.js +691 -0
  53. package/dist/routes/github.d.ts +97 -0
  54. package/dist/routes/github.js +587 -0
  55. package/dist/routes/guard.d.ts +3 -0
  56. package/dist/routes/guard.js +166 -0
  57. package/dist/routes/oauth.d.ts +55 -0
  58. package/dist/routes/oauth.js +406 -0
  59. package/dist/routes/policy.d.ts +34 -0
  60. package/dist/routes/policy.js +513 -0
  61. package/dist/routes/runtime.d.ts +12 -0
  62. package/dist/routes/runtime.js +921 -0
  63. package/dist/routes/servers-add.d.ts +32 -0
  64. package/dist/routes/servers-add.js +1091 -0
  65. package/dist/routes/system.d.ts +4 -0
  66. package/dist/routes/system.js +13 -0
  67. package/dist/start.d.ts +56 -0
  68. package/dist/start.js +164 -0
  69. package/dist-ui/assets/Activity-CZ78RyRO.js +1 -0
  70. package/dist-ui/assets/Approvals-DPIlNZsv.js +1 -0
  71. package/dist-ui/assets/AttachApp-DjSeWCbS.js +5 -0
  72. package/dist-ui/assets/Connections-qcA96lXh.js +2 -0
  73. package/dist-ui/assets/Gallery-DB_OO7Vw.js +17 -0
  74. package/dist-ui/assets/PreApprovals-C4cKajcK.js +1 -0
  75. package/dist-ui/assets/Protection-B8h-5YAb.js +1 -0
  76. package/dist-ui/assets/Safety-BQqHyYdo.js +1 -0
  77. package/dist-ui/assets/Settings-Cx50zZSt.js +1 -0
  78. package/dist-ui/assets/StartPage-CdX-v7ej.js +1 -0
  79. package/dist-ui/assets/Suggestions-CRo5UOTT.js +1 -0
  80. package/dist-ui/assets/Tools-xo39lPKB.js +4 -0
  81. package/dist-ui/assets/index-DttDjRpu.js +16 -0
  82. package/dist-ui/assets/index-QeJyD5z2.css +2 -0
  83. package/dist-ui/assets/kit-DRVm92_t.js +4 -0
  84. package/dist-ui/brand/logo-256.png +0 -0
  85. package/dist-ui/brand/logo-512.png +0 -0
  86. package/dist-ui/brand/logo.svg +6 -0
  87. package/dist-ui/brand/mark.svg +5 -0
  88. package/dist-ui/fonts/OFL.txt +99 -0
  89. package/dist-ui/fonts/README.md +21 -0
  90. package/dist-ui/fonts/jetbrainsmono-latin.woff2 +0 -0
  91. package/dist-ui/fonts/manrope-latin.woff2 +0 -0
  92. package/dist-ui/index.html +51 -0
  93. package/package.json +69 -6
  94. package/bin/notice.js +0 -7
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export * from "./api.js";
2
+ export * from "./http.js";
3
+ export * from "./model/server.js";
4
+ export * from "./model/protection.js";
5
+ export * from "./model/pipeline.js";
6
+ export * from "./model/tools.js";
7
+ export * from "./start.js";
@@ -0,0 +1,85 @@
1
+ import { type ImportCandidate, type Scope, type ScopeTarget } from "hmcp-gateway";
2
+ /**
3
+ * What an AI app has, for the Connections page: the servers in its own
4
+ * settings (and, for Claude Desktop, its extensions), whether each could come
5
+ * into the toolbox it is connected to, and what an earlier "Bring in
6
+ * servers" brought.
7
+ *
8
+ * Names only, ever. The app's file holds each server's command line, address
9
+ * and keys; none of that is in what this returns, only what a person needs to
10
+ * recognise a server and decide.
11
+ */
12
+ /** The toolbox an app was connected to from the console, when it was. */
13
+ export interface AttachedTo {
14
+ readonly gatewayId: string;
15
+ readonly entryName: string;
16
+ readonly configPath: string;
17
+ }
18
+ export interface AppServer {
19
+ /** The entry's name in the app, or the extension's display name. */
20
+ readonly name: string;
21
+ readonly transport: "stdio" | "http" | "sse";
22
+ readonly source: "config" | "extension";
23
+ readonly importable: boolean;
24
+ readonly reason?: string;
25
+ /** The toolbox already has a server that runs the same program or reaches the same address. */
26
+ readonly inToolbox?: string;
27
+ /** The name it would have in the toolbox. */
28
+ readonly upstreamName?: string;
29
+ /** The settings (env or header names) whose values would go into the locked keys. */
30
+ readonly keysLocked: readonly string[];
31
+ /** Its address is on this computer or the local network, which needs confirming. */
32
+ readonly needsLocalHttp: boolean;
33
+ readonly extensionId?: string;
34
+ /** Extensions only: switched on in Claude. */
35
+ readonly enabled?: boolean;
36
+ }
37
+ /**
38
+ * How this app is connected, so its card can say what to do: from the console
39
+ * and still running the toolbox; the older way (adopt); from the console but
40
+ * with the toolbox's entry gone from the app; or to a toolbox no longer in
41
+ * the console's list. Null when the console did not connect it.
42
+ */
43
+ export type ConnectionKind = "console" | "adopt" | "entry-missing" | "toolbox-missing";
44
+ export interface AppServersInfo {
45
+ readonly attachedTo: {
46
+ readonly gatewayId: string;
47
+ readonly entryName: string;
48
+ } | null;
49
+ readonly connection: ConnectionKind | null;
50
+ readonly servers: readonly AppServer[];
51
+ readonly imported: readonly {
52
+ readonly name: string;
53
+ readonly upstream: string;
54
+ readonly source: "config" | "extension";
55
+ }[];
56
+ readonly canUndoImport: boolean;
57
+ }
58
+ export declare function targetFor(scope: Scope, cwd: string, home?: string): ScopeTarget;
59
+ /**
60
+ * The toolbox this app was connected to with "Connect" in the console: its
61
+ * undo record generated no files (adopt's would have) and names a toolbox
62
+ * still in the console's list. The record must be this scope's own --
63
+ * Claude Code's `user` and `local` share one file -- and the app's settings
64
+ * here must still run that toolbox: `local`'s record is shared by every
65
+ * project, and an entry deleted by hand leaves the record behind.
66
+ */
67
+ export declare function attachedTo(target: ScopeTarget, registryPath: string, at: {
68
+ cwd: string;
69
+ home: string;
70
+ }): AttachedTo | null;
71
+ /** Which `ConnectionKind` this app's connection is, with the toolbox when it is one servers can be brought into. */
72
+ export declare function connectionState(target: ScopeTarget, registryPath: string, at: {
73
+ cwd: string;
74
+ home: string;
75
+ }): {
76
+ kind: ConnectionKind | null;
77
+ attached: AttachedTo | null;
78
+ };
79
+ /** One candidate as the browser may see it. */
80
+ export declare function appServer(c: ImportCandidate): AppServer;
81
+ /**
82
+ * Everything the Connections page shows about one app's own servers. A file
83
+ * that can't be read gives an empty list: the app's row already says why.
84
+ */
85
+ export declare function appServersFor(scope: Scope, cwd: string, registryPath: string): AppServersInfo;
@@ -0,0 +1,109 @@
1
+ import { homedir } from "node:os";
2
+ import { resolve } from "node:path";
3
+ import { SecretStore, expandPath, readRegistry } from "hmcp-core";
4
+ import { importCandidates, readBackup, runsToolbox, scopeTargets } from "hmcp-gateway";
5
+ import { readLiveImportRecord } from "./import-record.js";
6
+ export function targetFor(scope, cwd, home = homedir()) {
7
+ return scopeTargets({ cwd, home }).find((t) => t.scope === scope);
8
+ }
9
+ /**
10
+ * The toolbox this app was connected to with "Connect" in the console: its
11
+ * undo record generated no files (adopt's would have) and names a toolbox
12
+ * still in the console's list. The record must be this scope's own --
13
+ * Claude Code's `user` and `local` share one file -- and the app's settings
14
+ * here must still run that toolbox: `local`'s record is shared by every
15
+ * project, and an entry deleted by hand leaves the record behind.
16
+ */
17
+ export function attachedTo(target, registryPath, at) {
18
+ const state = connectionState(target, registryPath, at);
19
+ return state.kind === "console" ? state.attached : null;
20
+ }
21
+ /** Which `ConnectionKind` this app's connection is, with the toolbox when it is one servers can be brought into. */
22
+ export function connectionState(target, registryPath, at) {
23
+ let backup;
24
+ try {
25
+ backup = readBackup(target);
26
+ }
27
+ catch {
28
+ return { kind: null, attached: null };
29
+ }
30
+ if (!backup || backup.scope !== target.scope)
31
+ return { kind: null, attached: null };
32
+ if (backup.generated.length > 0)
33
+ return { kind: "adopt", attached: null };
34
+ let row;
35
+ try {
36
+ row = backup.registry_id ? readRegistry(registryPath).servers.find((s) => s.id === backup.registry_id && s.kind === "gateway") : undefined;
37
+ }
38
+ catch {
39
+ row = undefined;
40
+ }
41
+ if (!row)
42
+ return { kind: "toolbox-missing", attached: null };
43
+ const configPath = resolve(expandPath(row.config_path));
44
+ if (!runsToolbox({ scope: target.scope, cwd: at.cwd, home: at.home }, backup.gateway_entry_name, configPath)) {
45
+ return { kind: "entry-missing", attached: null };
46
+ }
47
+ return { kind: "console", attached: { gatewayId: row.id, entryName: backup.gateway_entry_name, configPath } };
48
+ }
49
+ /** One candidate as the browser may see it. */
50
+ export function appServer(c) {
51
+ return {
52
+ name: c.name,
53
+ transport: c.transport,
54
+ source: c.source,
55
+ importable: c.importable,
56
+ ...(c.reason !== undefined ? { reason: c.reason } : {}),
57
+ ...(c.inToolbox !== undefined ? { inToolbox: c.inToolbox } : {}),
58
+ ...(c.upstreamName !== undefined ? { upstreamName: c.upstreamName } : {}),
59
+ keysLocked: [...c.keySettings],
60
+ needsLocalHttp: c.needsLocalHttp,
61
+ ...(c.source === "extension" ? { extensionId: c.key, enabled: c.enabled ?? true } : {})
62
+ };
63
+ }
64
+ /**
65
+ * Everything the Connections page shows about one app's own servers. A file
66
+ * that can't be read gives an empty list: the app's row already says why.
67
+ */
68
+ export function appServersFor(scope, cwd, registryPath) {
69
+ const home = homedir();
70
+ const target = targetFor(scope, cwd, home);
71
+ const state = connectionState(target, registryPath, { cwd, home });
72
+ const attached = state.attached;
73
+ let candidates = [];
74
+ try {
75
+ candidates = importCandidates({
76
+ scope,
77
+ cwd,
78
+ home,
79
+ // Read only, to tell whether the toolbox's copy of a server uses the same key as the app's.
80
+ secrets: new SecretStore(),
81
+ ...(attached ? { gatewayConfigPath: attached.configPath, entryName: attached.entryName } : {})
82
+ }).candidates;
83
+ }
84
+ catch {
85
+ // A toolbox whose files don't load still has an app whose servers can be listed.
86
+ try {
87
+ candidates = importCandidates({ scope, cwd, home, ...(attached ? { entryName: attached.entryName } : {}) }).candidates;
88
+ }
89
+ catch {
90
+ candidates = [];
91
+ }
92
+ }
93
+ let record;
94
+ try {
95
+ // Read whether or not the app is connected now: a record left by a connection undone elsewhere is tidied away here.
96
+ record = readLiveImportRecord(registryPath, target);
97
+ }
98
+ catch {
99
+ record = undefined;
100
+ }
101
+ const items = record && record.gateway_id === attached?.gatewayId ? record.items : [];
102
+ return {
103
+ attachedTo: attached ? { gatewayId: attached.gatewayId, entryName: attached.entryName } : null,
104
+ connection: state.kind,
105
+ servers: candidates.map(appServer),
106
+ imported: items.map((i) => ({ name: i.name, upstream: i.upstream, source: i.source })),
107
+ canUndoImport: items.length > 0
108
+ };
109
+ }
@@ -0,0 +1,37 @@
1
+ import { z } from "zod";
2
+ import type { ConsoleSettings } from "../contracts/onboarding.js";
3
+ /** What PUT accepts: any part of the settings; the rest stays as it is. */
4
+ export declare const SettingsPatchSchema: z.ZodObject<{
5
+ version: z.ZodOptional<z.ZodLiteral<1>>;
6
+ onboarding: z.ZodOptional<z.ZodObject<{
7
+ step: z.ZodOptional<z.ZodEnum<{
8
+ server: "server";
9
+ done: "done";
10
+ welcome: "welcome";
11
+ computer: "computer";
12
+ app: "app";
13
+ try: "try";
14
+ protect: "protect";
15
+ }>>;
16
+ done: z.ZodOptional<z.ZodArray<z.ZodEnum<{
17
+ server: "server";
18
+ done: "done";
19
+ welcome: "welcome";
20
+ computer: "computer";
21
+ app: "app";
22
+ try: "try";
23
+ protect: "protect";
24
+ }>>>;
25
+ dismissed: z.ZodOptional<z.ZodBoolean>;
26
+ }, z.core.$strict>>;
27
+ registry: z.ZodOptional<z.ZodObject<{
28
+ enabled: z.ZodOptional<z.ZodBoolean>;
29
+ }, z.core.$strict>>;
30
+ }, z.core.$strict>;
31
+ export type SettingsPatch = z.infer<typeof SettingsPatchSchema>;
32
+ export declare function defaultConsoleSettings(): ConsoleSettings;
33
+ export declare function consoleSettingsPath(): string;
34
+ export declare function readConsoleSettings(path?: string): ConsoleSettings;
35
+ export declare function writeConsoleSettings(patch: unknown, path?: string): ConsoleSettings;
36
+ /** For the registry routes (workstream D): is the public server list switched on? */
37
+ export declare function registryEnabled(): boolean;
@@ -0,0 +1,74 @@
1
+ import { mkdirSync, readFileSync } from "node:fs";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { z } from "zod";
5
+ import { writeAtomically } from "hmcp-core";
6
+ import { unprocessable } from "../http.js";
7
+ /**
8
+ * The console's own settings, `~/.hmcp/console.json`: where the start page
9
+ * got to, and whether the public server list is used.
10
+ *
11
+ * Separate from every gateway's files on purpose: none of this changes what
12
+ * a gateway lets through, so none of it needs a digest, an acknowledgement or
13
+ * an audit record. A file that is missing or broken reads as the defaults
14
+ * rather than failing the page -- losing your place in the welcome steps is
15
+ * not worth an error screen.
16
+ */
17
+ const STEPS = ["welcome", "computer", "server", "app", "try", "protect", "done"];
18
+ const Step = z.enum(STEPS);
19
+ const SettingsSchema = z
20
+ .object({
21
+ version: z.literal(1),
22
+ onboarding: z.object({ step: Step, done: z.array(Step), dismissed: z.boolean() }).strict(),
23
+ registry: z.object({ enabled: z.boolean() }).strict()
24
+ })
25
+ .strict();
26
+ /** What PUT accepts: any part of the settings; the rest stays as it is. */
27
+ export const SettingsPatchSchema = z
28
+ .object({
29
+ version: z.literal(1).optional(),
30
+ onboarding: z
31
+ .object({ step: Step.optional(), done: z.array(Step).optional(), dismissed: z.boolean().optional() })
32
+ .strict()
33
+ .optional(),
34
+ registry: z.object({ enabled: z.boolean().optional() }).strict().optional()
35
+ })
36
+ .strict();
37
+ export function defaultConsoleSettings() {
38
+ return { version: 1, onboarding: { step: "welcome", done: [], dismissed: false }, registry: { enabled: true } };
39
+ }
40
+ export function consoleSettingsPath() {
41
+ return process.env["HMCP_CONSOLE_SETTINGS"] || join(homedir(), ".hmcp", "console.json");
42
+ }
43
+ export function readConsoleSettings(path = consoleSettingsPath()) {
44
+ try {
45
+ const parsed = SettingsSchema.safeParse(JSON.parse(readFileSync(path, "utf8")));
46
+ return parsed.success ? parsed.data : defaultConsoleSettings();
47
+ }
48
+ catch {
49
+ return defaultConsoleSettings();
50
+ }
51
+ }
52
+ export function writeConsoleSettings(patch, path = consoleSettingsPath()) {
53
+ const parsed = SettingsPatchSchema.safeParse(patch ?? {});
54
+ if (!parsed.success) {
55
+ throw unprocessable(`these settings are not valid: ${parsed.error.issues.map((i) => `${i.path.join(".") || "(body)"}: ${i.message}`).join("; ")}`);
56
+ }
57
+ const current = readConsoleSettings(path);
58
+ const next = {
59
+ version: 1,
60
+ onboarding: {
61
+ step: parsed.data.onboarding?.step ?? current.onboarding.step,
62
+ done: [...new Set(parsed.data.onboarding?.done ?? current.onboarding.done)],
63
+ dismissed: parsed.data.onboarding?.dismissed ?? current.onboarding.dismissed
64
+ },
65
+ registry: { enabled: parsed.data.registry?.enabled ?? current.registry.enabled }
66
+ };
67
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
68
+ writeAtomically(path, `${JSON.stringify(next, null, 2)}\n`);
69
+ return next;
70
+ }
71
+ /** For the registry routes (workstream D): is the public server list switched on? */
72
+ export function registryEnabled() {
73
+ return readConsoleSettings().registry.enabled;
74
+ }
@@ -0,0 +1,68 @@
1
+ import type { DoctorResponse, RuntimeCheck } from "../contracts/onboarding.js";
2
+ /**
3
+ * The machine check: which of the programs MCP servers are started with are
4
+ * installed here, where, and which version.
5
+ *
6
+ * Two reasons it is more than `which`:
7
+ *
8
+ * - An AI app started from the Dock or the Start menu does not get the PATH a
9
+ * terminal has. Claude Desktop on macOS sees roughly /usr/bin:/bin, so `npx`
10
+ * from Homebrew or nvm is "not found" there even though it works in a
11
+ * terminal. So this also looks in the places installers put things, and the
12
+ * answer carries absolute paths -- saved commands use them, and the app's
13
+ * entry is given `pathDirs` as its PATH.
14
+ * - "Docker is installed" and "Docker is running" are different problems with
15
+ * different fixes, so `docker info` is asked as well as `--version`.
16
+ *
17
+ * Nothing here runs through a shell: lookups are done in JS and programs are
18
+ * started with execFile.
19
+ */
20
+ export type CheckId = RuntimeCheck["id"];
21
+ export interface DoctorEnvironment {
22
+ readonly platform: NodeJS.Platform;
23
+ readonly arch: string;
24
+ readonly env: NodeJS.ProcessEnv;
25
+ readonly home: string;
26
+ /** Runs a program and gives its stdout; rejects on failure or timeout. Swapped in tests. */
27
+ readonly run: (file: string, args: string[], timeoutMs: number) => Promise<string>;
28
+ /** Replaces the folders searched. Tests only, so the answer does not depend on this computer. */
29
+ readonly dirs?: readonly string[];
30
+ }
31
+ export declare function hostEnvironment(): DoctorEnvironment;
32
+ /** The folders a system puts on every program's PATH. */
33
+ export declare function systemDefaultDirs(platform: NodeJS.Platform, env?: NodeJS.ProcessEnv): string[];
34
+ /**
35
+ * Places installers put programs that a GUI app's PATH does not include.
36
+ * Searched after PATH, so what a terminal would run still wins.
37
+ */
38
+ export declare function extraDirs(platform: NodeJS.Platform, home: string, env: NodeJS.ProcessEnv): string[];
39
+ /** PATH first, then the extra places, then the system defaults, without repeats. */
40
+ export declare function searchDirs(environment: Pick<DoctorEnvironment, "platform" | "env" | "home">): string[];
41
+ /**
42
+ * A pure-JS `which`. On Windows each PATHEXT extension is tried, because
43
+ * `npx` there is `npx.cmd`.
44
+ */
45
+ export declare function findOnPath(name: string, dirs: readonly string[], platform: NodeJS.Platform, env?: NodeJS.ProcessEnv): string | null;
46
+ /** "v22.19.0", "uv 0.5.1 (abc 2024-..)", "Docker version 27.3.1, build ..." -> the number. */
47
+ export declare function parseVersion(output: string): string | null;
48
+ /** Runs the whole check. Use `doctor()` from a route; this is uncached. */
49
+ export declare function runDoctor(environment?: DoctorEnvironment): Promise<DoctorResponse>;
50
+ /**
51
+ * The check, cached for a minute: the start page, Test it and install all ask,
52
+ * and a `docker info` against a stopped daemon takes the whole timeout.
53
+ * `fresh` is the "Check again" button, after someone installed something.
54
+ */
55
+ export declare function doctor(options?: {
56
+ fresh?: boolean;
57
+ now?: number;
58
+ }): Promise<DoctorResponse>;
59
+ /** For tests. */
60
+ export declare function clearDoctorCache(): void;
61
+ /**
62
+ * Absolute paths keyed by program name, for `materializeDraft`'s
63
+ * `commandPaths` ("npx" -> "/opt/homebrew/bin/npx"). `python3` and `python`
64
+ * both map to whichever was found.
65
+ */
66
+ export declare function commandPathsFrom(result: DoctorResponse): Record<string, string>;
67
+ /** The folders an AI app's entry should have on PATH (for connectRoutes' `deps.pathDirs`). */
68
+ export declare function doctorPathDirs(): Promise<string[]>;
@@ -0,0 +1,254 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readdirSync, statSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { delimiter as hostDelimiter, join, dirname } from "node:path";
5
+ /** What is looked for, in order. `python` tries python3 first. */
6
+ const PROGRAMS = [
7
+ { id: "node", names: ["node"] },
8
+ { id: "npx", names: ["npx"] },
9
+ { id: "uv", names: ["uv"] },
10
+ { id: "uvx", names: ["uvx"] },
11
+ { id: "docker", names: ["docker"] },
12
+ { id: "python", names: ["python3", "python"] },
13
+ { id: "git", names: ["git"] }
14
+ ];
15
+ const VERSION_TIMEOUT_MS = 3_000;
16
+ const CACHE_MS = 60_000;
17
+ function defaultRun(platform) {
18
+ return (file, args, timeoutMs) => new Promise((resolvePromise, reject) => {
19
+ /*
20
+ * On Windows a .cmd or .bat (npx.cmd) cannot be started by execFile
21
+ * without a shell any more (Node refuses since the 2024 fix for
22
+ * argument injection). cmd.exe is named explicitly with the path as one
23
+ * argument instead of turning the shell on for everything.
24
+ */
25
+ const viaCmd = platform === "win32" && /\.(cmd|bat)$/i.test(file);
26
+ const [exe, argv] = viaCmd ? ["cmd.exe", ["/d", "/s", "/c", file, ...args]] : [file, args];
27
+ execFile(exe, argv, { timeout: timeoutMs, windowsHide: true, encoding: "utf8" }, (err, stdout, stderr) => {
28
+ if (err)
29
+ reject(err);
30
+ else
31
+ resolvePromise(`${stdout}${stdout ? "" : stderr}`);
32
+ });
33
+ });
34
+ }
35
+ export function hostEnvironment() {
36
+ return {
37
+ platform: process.platform,
38
+ arch: process.arch,
39
+ env: process.env,
40
+ home: homedir(),
41
+ run: defaultRun(process.platform)
42
+ };
43
+ }
44
+ function pathDelimiter(platform) {
45
+ return platform === "win32" ? ";" : platform === process.platform ? hostDelimiter : ":";
46
+ }
47
+ function joinFor(platform, ...parts) {
48
+ return platform === "win32" ? parts.join("\\").replace(/\\+/g, "\\") : join(...parts);
49
+ }
50
+ /** The folders a system puts on every program's PATH. */
51
+ export function systemDefaultDirs(platform, env = {}) {
52
+ if (platform === "win32") {
53
+ const root = env["SystemRoot"] ?? env["windir"] ?? "C:\\Windows";
54
+ return [`${root}\\System32`, root];
55
+ }
56
+ return ["/usr/bin", "/bin", "/usr/sbin", "/sbin"];
57
+ }
58
+ /** The newest nvm-installed node's bin folder, or the one nvm says is current. */
59
+ function nvmBin(home, env) {
60
+ if (env["NVM_BIN"])
61
+ return [env["NVM_BIN"]];
62
+ const versions = join(env["NVM_DIR"] ?? join(home, ".nvm"), "versions", "node");
63
+ try {
64
+ const found = readdirSync(versions)
65
+ .filter((v) => /^v\d+\.\d+\.\d+$/.test(v))
66
+ .sort((a, b) => {
67
+ const pa = a.slice(1).split(".").map(Number);
68
+ const pb = b.slice(1).split(".").map(Number);
69
+ for (let i = 0; i < 3; i++)
70
+ if (pa[i] !== pb[i])
71
+ return pb[i] - pa[i];
72
+ return 0;
73
+ });
74
+ return found.length > 0 ? [join(versions, found[0], "bin")] : [];
75
+ }
76
+ catch {
77
+ return [];
78
+ }
79
+ }
80
+ /**
81
+ * Places installers put programs that a GUI app's PATH does not include.
82
+ * Searched after PATH, so what a terminal would run still wins.
83
+ */
84
+ export function extraDirs(platform, home, env) {
85
+ if (platform === "win32") {
86
+ const pf = env["ProgramFiles"] ?? "C:\\Program Files";
87
+ const appData = env["APPDATA"] ?? joinFor(platform, home, "AppData", "Roaming");
88
+ const local = env["LOCALAPPDATA"] ?? joinFor(platform, home, "AppData", "Local");
89
+ return [
90
+ joinFor(platform, pf, "nodejs"),
91
+ joinFor(platform, appData, "npm"),
92
+ joinFor(platform, home, ".local", "bin"),
93
+ joinFor(platform, home, ".cargo", "bin"),
94
+ joinFor(platform, local, "Volta", "bin"),
95
+ joinFor(platform, pf, "Docker", "Docker", "resources", "bin"),
96
+ joinFor(platform, pf, "Git", "cmd")
97
+ ];
98
+ }
99
+ return [
100
+ "/opt/homebrew/bin",
101
+ "/usr/local/bin",
102
+ join(home, ".local", "bin"),
103
+ join(home, ".cargo", "bin"),
104
+ ...nvmBin(home, env),
105
+ join(env["VOLTA_HOME"] ?? join(home, ".volta"), "bin"),
106
+ ...(platform === "darwin" ? ["/Applications/Docker.app/Contents/Resources/bin"] : [])
107
+ ];
108
+ }
109
+ /** PATH first, then the extra places, then the system defaults, without repeats. */
110
+ export function searchDirs(environment) {
111
+ const { platform, env, home } = environment;
112
+ const pathVar = env["PATH"] ?? env["Path"] ?? "";
113
+ const fromPath = pathVar.split(pathDelimiter(platform)).filter((d) => d.length > 0);
114
+ const seen = new Set();
115
+ const out = [];
116
+ for (const dir of [...fromPath, ...extraDirs(platform, home, env), ...systemDefaultDirs(platform, env)]) {
117
+ const key = platform === "win32" ? dir.toLowerCase() : dir;
118
+ if (seen.has(key))
119
+ continue;
120
+ seen.add(key);
121
+ out.push(dir);
122
+ }
123
+ return out;
124
+ }
125
+ function isExecutableFile(path, platform) {
126
+ try {
127
+ const st = statSync(path);
128
+ if (!st.isFile())
129
+ return false;
130
+ return platform === "win32" ? true : (st.mode & 0o111) !== 0;
131
+ }
132
+ catch {
133
+ return false;
134
+ }
135
+ }
136
+ /**
137
+ * A pure-JS `which`. On Windows each PATHEXT extension is tried, because
138
+ * `npx` there is `npx.cmd`.
139
+ */
140
+ export function findOnPath(name, dirs, platform, env = {}) {
141
+ const exts = platform === "win32"
142
+ ? (env["PATHEXT"] ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean).map((e) => e.toLowerCase())
143
+ : [""];
144
+ for (const dir of dirs) {
145
+ for (const ext of exts) {
146
+ const candidate = join(dir, name + ext);
147
+ if (isExecutableFile(candidate, platform))
148
+ return candidate;
149
+ }
150
+ }
151
+ return null;
152
+ }
153
+ /** "v22.19.0", "uv 0.5.1 (abc 2024-..)", "Docker version 27.3.1, build ..." -> the number. */
154
+ export function parseVersion(output) {
155
+ const line = output.split(/\r?\n/).find((l) => l.trim().length > 0) ?? "";
156
+ const match = /(\d+\.\d+(?:\.\d+)?)/.exec(line);
157
+ return match ? match[1] : null;
158
+ }
159
+ async function check(environment, id, names, dirs) {
160
+ let path = null;
161
+ for (const name of names) {
162
+ path = findOnPath(name, dirs, environment.platform, environment.env);
163
+ if (path)
164
+ break;
165
+ }
166
+ if (!path)
167
+ return { id, found: false, path: null, version: null };
168
+ let version = null;
169
+ let problem;
170
+ try {
171
+ version = parseVersion(await environment.run(path, ["--version"], VERSION_TIMEOUT_MS));
172
+ }
173
+ catch (err) {
174
+ problem = `found at ${path}, but it did not answer when asked its version (${err.message.split("\n")[0]})`;
175
+ }
176
+ const out = { id, found: true, path, version, ...(problem ? { problem } : {}) };
177
+ if (id === "docker") {
178
+ try {
179
+ await environment.run(path, ["info", "--format", "{{.ServerVersion}}"], VERSION_TIMEOUT_MS);
180
+ out.running = true;
181
+ }
182
+ catch {
183
+ out.running = false;
184
+ out.problem ??= "Docker is installed but not running. Open Docker Desktop and wait until it says it is running.";
185
+ }
186
+ }
187
+ return out;
188
+ }
189
+ /** Runs the whole check. Use `doctor()` from a route; this is uncached. */
190
+ export async function runDoctor(environment = hostEnvironment()) {
191
+ const dirs = environment.dirs ?? searchDirs(environment);
192
+ const checks = await Promise.all(PROGRAMS.map((p) => check(environment, p.id, p.names, dirs)));
193
+ const found = checks.filter((c) => c.found && c.path).map((c) => dirnameFor(environment.platform, c.path));
194
+ const seen = new Set();
195
+ const pathDirs = [];
196
+ for (const dir of [...found, ...systemDefaultDirs(environment.platform, environment.env)]) {
197
+ const key = environment.platform === "win32" ? dir.toLowerCase() : dir;
198
+ if (seen.has(key))
199
+ continue;
200
+ seen.add(key);
201
+ pathDirs.push(dir);
202
+ }
203
+ return { platform: environment.platform, arch: environment.arch, checks, pathDirs };
204
+ }
205
+ function dirnameFor(platform, path) {
206
+ if (platform !== "win32")
207
+ return dirname(path);
208
+ const i = path.lastIndexOf("\\");
209
+ return i > 0 ? path.slice(0, i) : path;
210
+ }
211
+ let cached = null;
212
+ /**
213
+ * The check, cached for a minute: the start page, Test it and install all ask,
214
+ * and a `docker info` against a stopped daemon takes the whole timeout.
215
+ * `fresh` is the "Check again" button, after someone installed something.
216
+ */
217
+ export function doctor(options = {}) {
218
+ const now = options.now ?? Date.now();
219
+ if (!options.fresh && cached && now - cached.at < CACHE_MS)
220
+ return cached.result;
221
+ const result = runDoctor();
222
+ cached = { at: now, result };
223
+ // A failed run is not kept, so the next ask tries again.
224
+ result.catch(() => {
225
+ if (cached?.result === result)
226
+ cached = null;
227
+ });
228
+ return result;
229
+ }
230
+ /** For tests. */
231
+ export function clearDoctorCache() {
232
+ cached = null;
233
+ }
234
+ /**
235
+ * Absolute paths keyed by program name, for `materializeDraft`'s
236
+ * `commandPaths` ("npx" -> "/opt/homebrew/bin/npx"). `python3` and `python`
237
+ * both map to whichever was found.
238
+ */
239
+ export function commandPathsFrom(result) {
240
+ const out = {};
241
+ for (const c of result.checks) {
242
+ if (!c.found || !c.path)
243
+ continue;
244
+ out[c.id] = c.path;
245
+ if (c.id === "python") {
246
+ out["python3"] = c.path;
247
+ }
248
+ }
249
+ return out;
250
+ }
251
+ /** The folders an AI app's entry should have on PATH (for connectRoutes' `deps.pathDirs`). */
252
+ export async function doctorPathDirs() {
253
+ return (await doctor()).pathDirs;
254
+ }
@@ -0,0 +1,9 @@
1
+ import type { DirListing } from "../contracts/onboarding.js";
2
+ /** Plain words when choosing this folder gives a server more than anyone means to. */
3
+ export declare function folderWarning(path: string, home: string, platform?: NodeJS.Platform): string | undefined;
4
+ export declare function shortcuts(home: string, platform?: NodeJS.Platform): DirListing["shortcuts"];
5
+ /** One folder's sub-folders. `raw` empty means the home folder. */
6
+ export declare function listDirs(raw: string | null, options?: {
7
+ home?: string;
8
+ platform?: NodeJS.Platform;
9
+ }): DirListing;