@yawlabs/mcp 1.0.1 → 1.0.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.
@@ -1,2167 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/auto-upgrade.ts
4
- import { spawn as spawn3 } from "child_process";
5
- import { createHash } from "crypto";
6
- import {
7
- closeSync,
8
- openSync,
9
- readFileSync as readFileSync3,
10
- realpathSync as realpathSync2,
11
- renameSync,
12
- statSync as statSync2,
13
- unlinkSync,
14
- writeFileSync,
15
- writeSync
16
- } from "fs";
17
- import { tmpdir } from "os";
18
- import { dirname as dirname2, join as join4, sep as sep2 } from "path";
19
-
20
- // src/internal-secret-env.ts
21
- var INTERNAL_SECRET_ENV_KEYS = /* @__PURE__ */ new Set([
22
- "YAW_MCP_TOKEN",
23
- "YAW_MCP_VAULT_PASSPHRASE",
24
- "YAW_MCP_VAULT_PASSPHRASE_NEW"
25
- ]);
26
- function scrubInternalSecretsFromProcessEnv() {
27
- for (const key of Object.keys(process.env)) {
28
- if (INTERNAL_SECRET_ENV_KEYS.has(key.toUpperCase())) delete process.env[key];
29
- }
30
- }
31
- function stripInternalSecretsFromEnv(env) {
32
- const out = {};
33
- for (const [key, value] of Object.entries(env)) {
34
- if (INTERNAL_SECRET_ENV_KEYS.has(key.toUpperCase())) continue;
35
- out[key] = value;
36
- }
37
- return out;
38
- }
39
-
40
- // src/logger.ts
41
- var LOG_LEVELS = { debug: 0, info: 1, warn: 2, error: 3 };
42
- function minLevel() {
43
- return LOG_LEVELS[process.env.LOG_LEVEL?.toLowerCase()] ?? LOG_LEVELS.info;
44
- }
45
- function guardStderrErrors() {
46
- try {
47
- if (process.stderr.listenerCount("error") === 0) {
48
- process.stderr.on("error", () => {
49
- });
50
- }
51
- } catch {
52
- }
53
- }
54
- var surface = "server";
55
- function setLogSurface(next) {
56
- surface = next;
57
- }
58
- function logLevelRequested() {
59
- const raw = process.env.LOG_LEVEL?.trim().toLowerCase();
60
- return raw !== void 0 && raw in LOG_LEVELS;
61
- }
62
- function renderData(data) {
63
- if (data === void 0) return "";
64
- try {
65
- const parts = Object.entries(data).map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`);
66
- return parts.length > 0 ? ` (${parts.join("; ")})` : "";
67
- } catch {
68
- return " (details omitted)";
69
- }
70
- }
71
- function log(level, msg, data) {
72
- if (LOG_LEVELS[level] < minLevel()) return;
73
- guardStderrErrors();
74
- if (surface === "cli" && !logLevelRequested()) {
75
- if (LOG_LEVELS[level] < LOG_LEVELS.warn) return;
76
- try {
77
- process.stderr.write(`yaw-mcp: ${level === "warn" ? "warning" : "error"}: ${msg}${renderData(data)}
78
- `);
79
- } catch {
80
- }
81
- return;
82
- }
83
- const ts = (/* @__PURE__ */ new Date()).toISOString();
84
- let entry;
85
- try {
86
- entry = JSON.stringify({ ...data, level, msg, ts });
87
- } catch {
88
- entry = JSON.stringify({ level, msg, ts, dataOmitted: true });
89
- }
90
- try {
91
- process.stderr.write(`${entry}
92
- `);
93
- } catch {
94
- }
95
- }
96
- var brokenStreams = /* @__PURE__ */ new WeakSet();
97
- var guardedStreams = /* @__PURE__ */ new WeakSet();
98
- function createStreamWriter(stream) {
99
- if (!guardedStreams.has(stream)) {
100
- guardedStreams.add(stream);
101
- try {
102
- stream.on("error", () => {
103
- brokenStreams.add(stream);
104
- });
105
- } catch {
106
- }
107
- }
108
- return (s) => {
109
- if (brokenStreams.has(stream)) return;
110
- try {
111
- stream.write(s);
112
- } catch {
113
- brokenStreams.add(stream);
114
- }
115
- };
116
- }
117
-
118
- // src/upgrade-cmd.ts
119
- import { spawn as spawn2 } from "child_process";
120
- import { readFileSync as readFileSync2, realpathSync } from "fs";
121
- import { join as join3 } from "path";
122
-
123
- // src/oam-spawn.ts
124
- import { spawn } from "child_process";
125
- import { accessSync, constants, existsSync, readdirSync, readFileSync, statSync } from "fs";
126
- import { homedir as homedir3 } from "os";
127
- import { dirname, isAbsolute as isAbsolute2, join as join2, sep } from "path";
128
- import { fileURLToPath } from "url";
129
-
130
- // src/install-targets.ts
131
- import { homedir } from "os";
132
- import { isAbsolute, join, resolve } from "path";
133
- var CURRENT_OS = process.platform === "darwin" ? "macos" : process.platform === "win32" ? "windows" : "linux";
134
- var INSTALL_TARGETS = [
135
- {
136
- clientId: "claude-code",
137
- label: "Claude Code",
138
- jsonShape: "mcpServers",
139
- availableOn: ["macos", "linux", "windows"],
140
- scopes: [
141
- {
142
- scope: "user",
143
- label: "User (global)",
144
- description: "Private to this machine; applies to every project.",
145
- requiresProjectDir: false
146
- },
147
- {
148
- scope: "project",
149
- label: "Project",
150
- description: "Commit to share with your team.",
151
- requiresProjectDir: true
152
- },
153
- {
154
- scope: "local",
155
- label: "Local",
156
- description: "Per-project override; typically gitignored.",
157
- requiresProjectDir: true
158
- }
159
- ]
160
- },
161
- {
162
- clientId: "claude-desktop",
163
- label: "Claude Desktop",
164
- jsonShape: "mcpServers",
165
- availableOn: ["macos", "windows"],
166
- // ASCII `--`, not an em-dash: install prints this verbatim (`Note: ...`),
167
- // and Claude Desktop is a Windows client -- on a console whose codepage is
168
- // not UTF-8 the em-dash rendered as mojibake in the line the user reads.
169
- notes: "Claude Desktop reads one file per OS -- no project scope. Restart the app after editing.",
170
- scopes: [
171
- {
172
- scope: "user",
173
- label: "User",
174
- description: "The only config file Claude Desktop reads.",
175
- requiresProjectDir: false
176
- }
177
- ]
178
- },
179
- {
180
- clientId: "cursor",
181
- label: "Cursor",
182
- jsonShape: "mcpServers",
183
- availableOn: ["macos", "linux", "windows"],
184
- scopes: [
185
- {
186
- scope: "user",
187
- label: "User (global)",
188
- description: "Private to this machine; applies to every Cursor project.",
189
- requiresProjectDir: false
190
- },
191
- {
192
- scope: "project",
193
- label: "Project",
194
- description: "Commit to share with your team.",
195
- requiresProjectDir: true
196
- }
197
- ]
198
- },
199
- {
200
- clientId: "vscode",
201
- label: "VS Code",
202
- jsonShape: "servers",
203
- availableOn: ["macos", "linux", "windows"],
204
- notes: "VS Code uses `servers` (not `mcpServers`) as the top-level key in mcp.json -- the user-profile file and .vscode/mcp.json share that shape. The user file covers the DEFAULT profile only; a custom profile keeps its own copy under Code/User/profiles/<id>/mcp.json. Needs VS Code 1.102 or newer, before which user-level MCP lived under the `mcp` key in settings.json.",
205
- scopes: [
206
- // User FIRST: enumerateProbeSlots walks this array in order, so it
207
- // decides --list and doctor row order, and every other multi-scope
208
- // client lists user before project.
209
- {
210
- scope: "user",
211
- label: "User (global)",
212
- description: "Private to this machine; applies to every VS Code workspace.",
213
- requiresProjectDir: false
214
- },
215
- {
216
- scope: "project",
217
- label: "Workspace",
218
- description: "Per-project config; commit to share.",
219
- requiresProjectDir: true
220
- }
221
- ]
222
- },
223
- // APPENDED, never inserted: autoDetectClient returns the first usable probe
224
- // slot in array order and documents Claude-Code-first as an invariant, so an
225
- // insert would silently change which client `try` picks for existing users.
226
- {
227
- clientId: "windsurf",
228
- label: "Windsurf",
229
- jsonShape: "mcpServers",
230
- availableOn: ["macos", "linux", "windows"],
231
- notes: "Windsurf reads ~/.codeium/windsurf/mcp_config.json and does not create it on first launch. If the server does not appear, open Cascade -> MCP servers -> Manage plugins -> View raw config and check it is the file above.",
232
- scopes: [
233
- {
234
- scope: "user",
235
- label: "User (global)",
236
- description: "The only config file Windsurf reads; it has no workspace scope.",
237
- requiresProjectDir: false
238
- }
239
- ]
240
- },
241
- {
242
- clientId: "gemini-cli",
243
- label: "Gemini CLI",
244
- jsonShape: "mcpServers",
245
- availableOn: ["macos", "linux", "windows"],
246
- notes: "Gemini CLI merges ~/.gemini/settings.json with <project>/.gemini/settings.json, project winning. `mcpServers` is a top-level key, distinct from the sibling `mcp` object that holds discovery knobs.",
247
- scopes: [
248
- {
249
- scope: "user",
250
- label: "User (global)",
251
- description: "Private to this machine; applies to every project.",
252
- requiresProjectDir: false
253
- },
254
- {
255
- scope: "project",
256
- label: "Project",
257
- description: "Commit to share with your team; wins over the user file.",
258
- requiresProjectDir: true
259
- }
260
- ]
261
- }
262
- ];
263
- function resolveAppDataDir(opts) {
264
- if (opts.appData !== void 0 && opts.appData.length > 0) return opts.appData;
265
- if (opts.home !== void 0) return join(opts.home, "AppData", "Roaming");
266
- const env = opts.env ?? process.env;
267
- const fromEnv = env.APPDATA;
268
- return fromEnv && fromEnv.length > 0 ? fromEnv : join(homedir(), "AppData", "Roaming");
269
- }
270
- function resolveInstallPath(opts) {
271
- const home = opts.home ?? homedir();
272
- const appData = opts.appData && opts.appData.length > 0 ? opts.appData : join(home, "AppData", "Roaming");
273
- const { clientId, scope, os, projectDir, claudeConfigDir } = opts;
274
- const target = INSTALL_TARGETS.find((t) => t.clientId === clientId);
275
- if (!target) throw new Error(`Unknown client: ${clientId}`);
276
- const scopeSpec = target.scopes.find((s) => s.scope === scope);
277
- if (!scopeSpec) throw new Error(`Client ${clientId} does not support scope ${scope}`);
278
- if (!target.availableOn.includes(os)) {
279
- throw new Error(`${target.label} is not available on ${os}`);
280
- }
281
- if (scopeSpec.requiresProjectDir && !projectDir) {
282
- throw new Error(`Scope ${scope} for ${clientId} requires a project directory`);
283
- }
284
- const absoluteProjectDir = projectDir && !isAbsolute(projectDir) ? resolve(projectDir) : projectDir;
285
- const p = pathFor(clientId, scope, os, {
286
- home,
287
- appData,
288
- projectDir: absoluteProjectDir ?? "",
289
- claudeConfigDir: claudeConfigDir && claudeConfigDir.length > 0 ? claudeConfigDir : void 0
290
- });
291
- return p;
292
- }
293
- function claudeCodeProjectKey(projectDir) {
294
- return /^(?:[A-Za-z]:[\\/]|\\\\)/.test(projectDir) ? projectDir.replace(/\\/g, "/") : projectDir;
295
- }
296
- function pathFor(client, scope, os, base) {
297
- const { home, appData, projectDir, claudeConfigDir } = base;
298
- const sep3 = os === "windows" ? "\\" : "/";
299
- const joinPath = (...parts) => parts.join(sep3);
300
- if (client === "claude-code") {
301
- if (scope === "user") {
302
- if (claudeConfigDir) {
303
- const absolute = join(claudeConfigDir, ".claude.json");
304
- return { absolute, display: absolute, containerPath: ["mcpServers"] };
305
- }
306
- const display = os === "windows" ? "%USERPROFILE%\\.claude.json" : "~/.claude.json";
307
- return { absolute: join(home, ".claude.json"), display, containerPath: ["mcpServers"] };
308
- }
309
- if (scope === "project") {
310
- return {
311
- absolute: join(projectDir, ".mcp.json"),
312
- display: joinPath("<project folder>", ".mcp.json"),
313
- containerPath: ["mcpServers"]
314
- };
315
- }
316
- const projectKey = claudeCodeProjectKey(projectDir);
317
- if (claudeConfigDir) {
318
- const absolute = join(claudeConfigDir, ".claude.json");
319
- return { absolute, display: absolute, containerPath: ["projects", projectKey, "mcpServers"] };
320
- }
321
- return {
322
- absolute: join(home, ".claude.json"),
323
- display: os === "windows" ? "%USERPROFILE%\\.claude.json" : "~/.claude.json",
324
- containerPath: ["projects", projectKey, "mcpServers"]
325
- };
326
- }
327
- if (client === "claude-desktop") {
328
- if (os === "macos") {
329
- return {
330
- absolute: join(home, "Library", "Application Support", "Claude", "claude_desktop_config.json"),
331
- display: "~/Library/Application Support/Claude/claude_desktop_config.json",
332
- containerPath: ["mcpServers"]
333
- };
334
- }
335
- if (os === "windows") {
336
- return {
337
- absolute: join(appData, "Claude", "claude_desktop_config.json"),
338
- display: "%APPDATA%\\Claude\\claude_desktop_config.json",
339
- containerPath: ["mcpServers"]
340
- };
341
- }
342
- throw new Error("Claude Desktop is not available on Linux");
343
- }
344
- if (client === "cursor") {
345
- if (scope === "user") {
346
- const display = os === "windows" ? "%USERPROFILE%\\.cursor\\mcp.json" : "~/.cursor/mcp.json";
347
- return { absolute: join(home, ".cursor", "mcp.json"), display, containerPath: ["mcpServers"] };
348
- }
349
- return {
350
- absolute: join(projectDir, ".cursor", "mcp.json"),
351
- display: joinPath("<project folder>", ".cursor", "mcp.json"),
352
- containerPath: ["mcpServers"]
353
- };
354
- }
355
- if (client === "vscode") {
356
- if (scope === "user") {
357
- if (os === "windows") {
358
- return {
359
- absolute: join(appData, "Code", "User", "mcp.json"),
360
- display: "%APPDATA%\\Code\\User\\mcp.json",
361
- containerPath: ["servers"]
362
- };
363
- }
364
- if (os === "macos") {
365
- return {
366
- absolute: join(home, "Library", "Application Support", "Code", "User", "mcp.json"),
367
- display: "~/Library/Application Support/Code/User/mcp.json",
368
- containerPath: ["servers"]
369
- };
370
- }
371
- return {
372
- absolute: join(home, ".config", "Code", "User", "mcp.json"),
373
- display: "~/.config/Code/User/mcp.json",
374
- containerPath: ["servers"]
375
- };
376
- }
377
- return {
378
- absolute: join(projectDir, ".vscode", "mcp.json"),
379
- display: joinPath("<project folder>", ".vscode", "mcp.json"),
380
- containerPath: ["servers"]
381
- };
382
- }
383
- if (client === "windsurf") {
384
- const display = os === "windows" ? "%USERPROFILE%\\.codeium\\windsurf\\mcp_config.json" : "~/.codeium/windsurf/mcp_config.json";
385
- return {
386
- absolute: join(home, ".codeium", "windsurf", "mcp_config.json"),
387
- display,
388
- containerPath: ["mcpServers"]
389
- };
390
- }
391
- if (client === "gemini-cli") {
392
- if (scope === "user") {
393
- const display = os === "windows" ? "%USERPROFILE%\\.gemini\\settings.json" : "~/.gemini/settings.json";
394
- return { absolute: join(home, ".gemini", "settings.json"), display, containerPath: ["mcpServers"] };
395
- }
396
- return {
397
- absolute: join(projectDir, ".gemini", "settings.json"),
398
- display: joinPath("<project folder>", ".gemini", "settings.json"),
399
- containerPath: ["mcpServers"]
400
- };
401
- }
402
- throw new Error(`Unhandled client: ${client}`);
403
- }
404
- var CMD_METACHARS = /[&|<>^()]/g;
405
- var HAS_CMD_METACHAR = /[&|<>^()]/;
406
- var KNOWN_CMD_SHIM_LAUNCHERS = /* @__PURE__ */ new Set(["npx", "npm", "pnpm", "yarn", "bunx"]);
407
- var KNOWN_DIRECT_BINARIES = /* @__PURE__ */ new Set([
408
- "node",
409
- "deno",
410
- "bun",
411
- "python",
412
- "python3",
413
- "py",
414
- "uv",
415
- "uvx",
416
- "pipx",
417
- "ruby",
418
- "php",
419
- "docker",
420
- "dotnet",
421
- "java",
422
- "go"
423
- ]);
424
- function isCmdShimLauncher(command) {
425
- const base = command.replace(/^.*[\\/]/, "").toLowerCase();
426
- if (/\.(?:cmd|bat)$/.test(base)) return true;
427
- if (/\.(?:exe|com)$/.test(base)) return false;
428
- const stem = base.replace(/\.[^.]*$/, "");
429
- if (KNOWN_CMD_SHIM_LAUNCHERS.has(stem)) return true;
430
- if (KNOWN_DIRECT_BINARIES.has(stem)) return false;
431
- return true;
432
- }
433
- function escapeCmdArg(arg, opts) {
434
- if (arg.includes('"')) {
435
- if (HAS_CMD_METACHAR.test(arg)) {
436
- throw new Error(
437
- `Cannot safely encode an argument that contains BOTH a double-quote and a cmd.exe metacharacter (& | < > ^ ( )) for the Windows cmd /c launcher: ${arg} -- passing it through cmd.exe risks a command injection at client-spawn time. Rework the server's args to drop one of the two.`
438
- );
439
- }
440
- return arg;
441
- }
442
- if (/[ \t]/.test(arg)) return arg;
443
- const caret = opts.shim ? "^^^" : "^";
444
- return arg.replace(CMD_METACHARS, (m) => caret + m);
445
- }
446
- function buildLaunchEntry(opts) {
447
- if (opts.upstream) {
448
- const { command, args, env } = opts.upstream;
449
- if (opts.os === "windows") {
450
- if (/[ \t]/.test(command)) {
451
- throw new Error(
452
- `Cannot safely encode a launcher command that contains whitespace for the Windows cmd /c launcher: ${command} -- cmd.exe strips the outer quotes when the line carries another quoted token, so the client's spawn fails with "'...' is not recognized". Point the server at a whitespace-free launcher (a bare npx/uvx resolved on PATH, or a short path).`
453
- );
454
- }
455
- const shim = isCmdShimLauncher(command);
456
- const wrapped = {
457
- command: "cmd",
458
- args: ["/c", escapeCmdArg(command, { shim: false }), ...args.map((a) => escapeCmdArg(a, { shim }))]
459
- };
460
- if (env && Object.keys(env).length > 0) wrapped.env = { ...env };
461
- return wrapped;
462
- }
463
- const entry = { command, args: [...args] };
464
- if (env && Object.keys(env).length > 0) entry.env = { ...env };
465
- return entry;
466
- }
467
- const pkg = opts.pkg ?? "@yawlabs/mcp@latest";
468
- if (opts.oamBinPath && isAbsolute(opts.oamBinPath) && opts.oamEntry && !opts.pkg) {
469
- return { command: opts.oamBinPath, args: ["run", "--no-check", opts.oamEntry] };
470
- }
471
- return opts.os === "windows" ? { command: "cmd", args: ["/c", "npx", "-y", pkg] } : { command: "npx", args: ["-y", pkg] };
472
- }
473
- function isProjectLocalEntry(entryPath, cwd) {
474
- const norm = (p) => p.replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
475
- const entry = norm(entryPath);
476
- const here = norm(cwd);
477
- const idx = entry.indexOf("/node_modules/");
478
- if (idx <= 0) return false;
479
- const root = entry.slice(0, idx);
480
- return here === root || here.startsWith(`${root}/`);
481
- }
482
- var ENTRY_NAME = "mcp";
483
- var LEGACY_ENTRY_NAMES = ["mcp.hosting", "mcph", "yaw-mcp"];
484
- function findLegacyEntry(container) {
485
- return LEGACY_ENTRY_NAMES.find((n) => n in container) ?? null;
486
- }
487
- var CLAUDE_CODE_ALLOW_PATTERN = "mcp__mcp__*";
488
- function resolveClaudeCodeSettingsPath(scope, opts) {
489
- const { home, projectDir, claudeConfigDir } = opts;
490
- const cfgDir = claudeConfigDir && claudeConfigDir.length > 0 ? claudeConfigDir : null;
491
- if (scope === "user") return cfgDir ? join(cfgDir, "settings.json") : join(home, ".claude", "settings.json");
492
- if (scope === "project" && projectDir) return join(projectDir, ".claude", "settings.json");
493
- if (scope === "local" && projectDir) return join(projectDir, ".claude", "settings.local.json");
494
- return null;
495
- }
496
-
497
- // src/paths.ts
498
- import { realpath, stat } from "fs/promises";
499
- import { homedir as homedir2 } from "os";
500
- import path from "path";
501
- function cacheDir() {
502
- if (process.platform === "win32") {
503
- const localAppData = process.env.LOCALAPPDATA;
504
- const base = localAppData && localAppData.length > 0 ? localAppData : path.join(homedir2(), "AppData", "Local");
505
- return path.join(base, "yaw-mcp", "Cache");
506
- }
507
- if (process.platform === "darwin") {
508
- return path.join(homedir2(), "Library", "Caches", "yaw-mcp");
509
- }
510
- const xdg = process.env.XDG_CACHE_HOME;
511
- return path.join(xdg && xdg.length > 0 ? xdg : path.join(homedir2(), ".cache"), "yaw-mcp");
512
- }
513
- var CONFIG_DIRNAME = ".yaw-mcp";
514
- var SIDECARS_DIRNAME = "sidecars";
515
- function sidecarsRoot(home = homedir2()) {
516
- return path.join(userConfigDir(home), SIDECARS_DIRNAME);
517
- }
518
- function sidecarsNodeModules(home = homedir2()) {
519
- return path.join(sidecarsRoot(home), "node_modules");
520
- }
521
- function userConfigDir(home = homedir2()) {
522
- return path.join(home, CONFIG_DIRNAME);
523
- }
524
- function normalizeForCompare(p) {
525
- return process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p;
526
- }
527
- async function realpathOrSelf(p) {
528
- try {
529
- return await realpath(p);
530
- } catch {
531
- return p;
532
- }
533
- }
534
- function isUnderHome(dir, homeResolved) {
535
- const dirKey = normalizeForCompare(dir);
536
- const homeKey = normalizeForCompare(homeResolved);
537
- if (dirKey === homeKey) return false;
538
- const rel = path.relative(homeKey, dirKey);
539
- if (rel === "" || path.isAbsolute(rel)) return false;
540
- return rel !== ".." && !rel.startsWith(`..${path.sep}`);
541
- }
542
- var ALLOW_UNOWNED_ENV = "YAW_MCP_ALLOW_UNOWNED_PROJECT_DIRS";
543
- var warnedUntrustedDirs = /* @__PURE__ */ new Set();
544
- function ownedByCurrentUser(st, env) {
545
- const geteuid = process.geteuid;
546
- if (typeof geteuid !== "function") return env[ALLOW_UNOWNED_ENV] === "1";
547
- return typeof st.uid === "number" && st.uid === geteuid.call(process);
548
- }
549
- async function findProjectConfigDir(start, home = homedir2(), env = process.env) {
550
- const homeFallback = home && home.length > 0 ? home : homedir2();
551
- const homeResolved = path.resolve(await realpathOrSelf(path.resolve(homeFallback)));
552
- let dir = path.resolve(await realpathOrSelf(path.resolve(start)));
553
- const userConfigKey = normalizeForCompare(await realpathOrSelf(path.join(homeResolved, CONFIG_DIRNAME)));
554
- const boundedByHome = isUnderHome(dir, homeResolved) || normalizeForCompare(dir) === normalizeForCompare(homeResolved);
555
- let prev = "";
556
- while (dir !== prev) {
557
- if (boundedByHome && !isUnderHome(dir, homeResolved)) return null;
558
- const candidate = path.join(dir, CONFIG_DIRNAME);
559
- try {
560
- const st = await stat(candidate);
561
- if (!st.isDirectory()) {
562
- log("debug", "Skipping a .yaw-mcp that exists but is not a directory", { candidate });
563
- } else if (normalizeForCompare(await realpathOrSelf(candidate)) === userConfigKey) {
564
- log("debug", "Skipping a .yaw-mcp/ that resolves to the user-global config dir", { candidate });
565
- } else if (boundedByHome || ownedByCurrentUser(st, env)) {
566
- return candidate;
567
- } else {
568
- if (!warnedUntrustedDirs.has(candidate)) {
569
- warnedUntrustedDirs.add(candidate);
570
- log("warn", "Skipping an untrusted .yaw-mcp/ dir outside $HOME", {
571
- candidate,
572
- hint: `owned by another user, or ownership is unverifiable on this platform (set ${ALLOW_UNOWNED_ENV}=1 to trust it)`
573
- });
574
- }
575
- }
576
- } catch {
577
- }
578
- prev = dir;
579
- dir = path.dirname(dir);
580
- }
581
- return null;
582
- }
583
- var GUIDE_FILENAME = "YAW-MCP.md";
584
- function guidePath(configDir) {
585
- return path.join(configDir, GUIDE_FILENAME);
586
- }
587
-
588
- // src/oam-spawn.ts
589
- function packageName(spec) {
590
- const start = spec.startsWith("@") ? 1 : 0;
591
- const at = spec.indexOf("@", start);
592
- return at === -1 ? spec : spec.slice(0, at);
593
- }
594
- function specSuffix(spec) {
595
- const start = spec.startsWith("@") ? 1 : 0;
596
- const at = spec.indexOf("@", start);
597
- return at === -1 ? null : spec.slice(at + 1);
598
- }
599
- var EXACT_VERSION = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
600
- function specConstraint(spec) {
601
- const suffix = specSuffix(spec);
602
- if (suffix === null || suffix === "") return { kind: "any" };
603
- if (EXACT_VERSION.test(suffix)) return { kind: "exact", version: suffix };
604
- const versionish = /^[v=<>^~*\d]/.test(suffix) || suffix.includes("||");
605
- return versionish ? { kind: "range", raw: suffix } : { kind: "any" };
606
- }
607
- function isRegistrySpec(spec) {
608
- if (spec.includes(":") || /^[./~\\]/.test(spec)) return false;
609
- const m = /^(?:@([^/]+)\/)?([^./_][^/]*)$/.exec(packageName(spec));
610
- if (!m) return false;
611
- const [, scope, name] = m;
612
- return (scope === void 0 || encodeURIComponent(scope) === scope) && encodeURIComponent(name) === name;
613
- }
614
- function npxSpecIndex(args) {
615
- return args.findIndex((a) => a !== "-y" && a !== "--yes");
616
- }
617
- function npxSpec(args) {
618
- const idx = npxSpecIndex(args);
619
- if (idx === -1) return null;
620
- const spec = args[idx];
621
- return spec.startsWith("-") ? null : spec;
622
- }
623
- var MIN_OAM_VERSION = "0.13.1";
624
- var OAM_INSTALL_SH = "curl -fsSL https://oamjs.org/install.sh | sh";
625
- var OAM_INSTALL_PS1 = "irm https://oamjs.org/install.ps1 | iex";
626
- function oamInstallCommand(os) {
627
- return os === "windows" ? OAM_INSTALL_PS1 : OAM_INSTALL_SH;
628
- }
629
- function oamPublishesBinaryFor(platform, arch) {
630
- if (platform === "win32" || platform === "darwin") return arch === "x64" || arch === "arm64";
631
- if (platform === "linux") return arch === "x64";
632
- return false;
633
- }
634
- function oamPublishesBinaryForThisMachine() {
635
- return oamPublishesBinaryFor(process.platform, process.arch);
636
- }
637
- function oamNoBinaryReason() {
638
- return `no published oam binary for ${process.platform}-${process.arch} yet -- build from source at https://oamjs.org`;
639
- }
640
- function oamInstallAdvice(os) {
641
- if (os === CURRENT_OS && !oamPublishesBinaryForThisMachine()) return oamNoBinaryReason();
642
- return oamInstallCommand(os);
643
- }
644
- function oamHeapOomHint(stderr) {
645
- if (!stderr.includes("OAM-RT-OOM")) return null;
646
- return `The oam-hosted child hit its V8 heap cap (oam defaults to 4 GiB). Raise it with OAM_MAX_HEAP_MB=<mb> in this server's env, or set "runtime": "node" for this server in bundles.json.`;
647
- }
648
- var warnedOamUnavailable = false;
649
- function oamFailureLabel(failure) {
650
- if (failure === "timeout") return "`oam --version` did not answer in time";
651
- if (failure === "exit") return "`oam --version` exited non-zero";
652
- return "the binary could not be executed";
653
- }
654
- var oamProbeCache;
655
- function parseOamVersion(out) {
656
- const m = /\d+\.\d+\.\d+(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?/.exec(out);
657
- return m ? m[0] : null;
658
- }
659
- function parseSemver(s) {
660
- const m = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-.]+))?/.exec(s);
661
- if (!m) return null;
662
- const pre = m[4] === void 0 ? [] : m[4].split(".").map((id) => /^\d+$/.test(id) ? Number(id) : id);
663
- return { release: [Number(m[1]), Number(m[2]), Number(m[3])], pre };
664
- }
665
- function comparePre(a, b) {
666
- if (a.length === 0 || b.length === 0) {
667
- if (a.length === b.length) return 0;
668
- return a.length === 0 ? 1 : -1;
669
- }
670
- for (let i = 0; i < Math.min(a.length, b.length); i++) {
671
- const x = a[i];
672
- const y = b[i];
673
- if (x === y) continue;
674
- if (typeof x === "number" && typeof y === "number") return x < y ? -1 : 1;
675
- if (typeof x === "number") return -1;
676
- if (typeof y === "number") return 1;
677
- return x < y ? -1 : 1;
678
- }
679
- if (a.length === b.length) return 0;
680
- return a.length < b.length ? -1 : 1;
681
- }
682
- function compareSemver(a, b) {
683
- for (let i = 0; i < 3; i++) {
684
- if (a.release[i] !== b.release[i]) return a.release[i] < b.release[i] ? -1 : 1;
685
- }
686
- return comparePre(a.pre, b.pre);
687
- }
688
- function compareVersions(a, b) {
689
- const pa = parseSemver(a);
690
- const pb = parseSemver(b);
691
- if (!pa || !pb) return 0;
692
- return compareSemver(pa, pb);
693
- }
694
- function satisfiesExactPin(declared, want) {
695
- if (declared === null) return false;
696
- const d = parseSemver(declared);
697
- const w = parseSemver(want);
698
- if (d && w) return compareSemver(d, w) === 0;
699
- return declared === want;
700
- }
701
- function winNormalize(p, platform = process.platform) {
702
- return platform === "win32" ? p.replace(/\//g, "\\") : p;
703
- }
704
- function isExecutableFile(candidate, platform) {
705
- try {
706
- if (!statSync(candidate).isFile()) return false;
707
- if (platform !== "win32") accessSync(candidate, constants.X_OK);
708
- return true;
709
- } catch {
710
- return false;
711
- }
712
- }
713
- function resolveBinAbsolute(bin, env = process.env, platform = process.platform) {
714
- if (isAbsolute2(bin)) return isExecutableFile(bin, platform) ? winNormalize(bin, platform) : null;
715
- if (bin.includes("/") || platform === "win32" && bin.includes("\\")) return null;
716
- const pathVar = env.PATH ?? env.Path ?? env.path ?? "";
717
- if (!pathVar) return null;
718
- const dirs = pathVar.split(platform === "win32" ? ";" : ":").filter(Boolean);
719
- const pathext = (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
720
- const carriesExt = pathext.some((e) => bin.toLowerCase().endsWith(e.toLowerCase()));
721
- const exts = platform === "win32" ? carriesExt ? ["", ...pathext] : pathext : [""];
722
- for (const dir of dirs) {
723
- const clean = dir.replace(/^"|"$/g, "");
724
- for (const ext of exts) {
725
- const candidate = join2(clean, bin + ext);
726
- if (!isAbsolute2(candidate)) continue;
727
- if (isExecutableFile(candidate, platform)) return winNormalize(candidate, platform);
728
- }
729
- }
730
- return null;
731
- }
732
- function classifyProbeFailure(err) {
733
- const code = err?.code;
734
- if (code === "ETIMEDOUT") return "timeout";
735
- if (code === "EOAMEXIT") return "exit";
736
- return "spawn";
737
- }
738
- var OAM_PROBE_TIMEOUT_MS = 3e3;
739
- var OAM_PROBE_KILL_SIGNAL = "SIGKILL";
740
- var OAM_PROBE_MAX_OUTPUT = 8 * 1024;
741
- var VERSION_CARRY = 32;
742
- function createProbeCollector(max = OAM_PROBE_MAX_OUTPUT) {
743
- let head = "";
744
- let carry = "";
745
- let found = null;
746
- let pending = null;
747
- return {
748
- push(chunk) {
749
- if (found !== null) return;
750
- const scan = carry + chunk;
751
- const hit = parseOamVersion(scan);
752
- if (hit !== null) {
753
- if (scan.endsWith(hit)) pending = hit;
754
- else found = hit;
755
- }
756
- carry = scan.slice(-VERSION_CARRY);
757
- if (head.length >= max) return;
758
- head += chunk.slice(0, max - head.length);
759
- },
760
- /** The version if one appeared anywhere, else the capped head (which
761
- * parses to null either way, so the caller's contract is unchanged).
762
- * Called after the stream closes, so a still-pending match is final: no
763
- * further chunk can extend it. */
764
- result() {
765
- return found ?? pending ?? head;
766
- },
767
- /** Test hook: bytes actually retained. */
768
- retainedLength() {
769
- return head.length;
770
- }
771
- };
772
- }
773
- function spawnVersionProbe(bin) {
774
- return new Promise((resolve2, reject) => {
775
- let settled = false;
776
- let timer;
777
- const settle = (fn) => {
778
- if (settled) return;
779
- settled = true;
780
- if (timer) clearTimeout(timer);
781
- fn();
782
- };
783
- let child;
784
- try {
785
- child = spawn(bin, ["--version"], {
786
- stdio: ["ignore", "pipe", "ignore"],
787
- windowsHide: process.platform === "win32",
788
- // oam is a binary yaw-mcp did not write; README promises the vault
789
- // passphrase is stripped from every child yaw-mcp starts, and this
790
- // probe was one of two spawns that still inherited process.env whole.
791
- env: stripInternalSecretsFromEnv(process.env)
792
- });
793
- } catch (err) {
794
- reject(err);
795
- return;
796
- }
797
- const collector = createProbeCollector();
798
- child.stdout?.setEncoding("utf8");
799
- child.stdout?.on("error", () => {
800
- });
801
- child.stdout?.on("data", (chunk) => collector.push(chunk));
802
- child.on("error", (err) => settle(() => reject(err)));
803
- child.on(
804
- "close",
805
- (code, signal) => settle(() => {
806
- if (code === 0) {
807
- resolve2(collector.result());
808
- return;
809
- }
810
- const err = new Error(`oam exited ${code ?? signal}`);
811
- err.code = "EOAMEXIT";
812
- reject(err);
813
- })
814
- );
815
- timer = setTimeout(() => {
816
- settle(() => {
817
- try {
818
- child.kill(OAM_PROBE_KILL_SIGNAL);
819
- } catch {
820
- }
821
- try {
822
- child.stdout?.destroy();
823
- child.unref();
824
- } catch {
825
- }
826
- const err = new Error(`oam --version exceeded ${OAM_PROBE_TIMEOUT_MS}ms`);
827
- err.code = "ETIMEDOUT";
828
- reject(err);
829
- });
830
- }, OAM_PROBE_TIMEOUT_MS);
831
- timer.unref?.();
832
- });
833
- }
834
- var oamProbeInFlight;
835
- var oamProbeGeneration = 0;
836
- async function probeOam(run = spawnVersionProbe) {
837
- if (oamProbeCache !== void 0) return oamProbeCache;
838
- if (oamProbeInFlight !== void 0) return oamProbeInFlight;
839
- const generation = oamProbeGeneration;
840
- oamProbeInFlight = probeOamUncached(run, generation).finally(() => {
841
- if (generation === oamProbeGeneration) oamProbeInFlight = void 0;
842
- });
843
- return oamProbeInFlight;
844
- }
845
- async function probeOamUncached(run, generation) {
846
- const explicit = Boolean(process.env.OAM_BIN);
847
- const bin = winNormalize(process.env.OAM_BIN || (process.platform === "win32" ? "oam.exe" : "oam"));
848
- const publish = (probe) => {
849
- if (generation === oamProbeGeneration) oamProbeCache = probe;
850
- return probe;
851
- };
852
- try {
853
- const version = parseOamVersion(await run(bin));
854
- if (version !== null && compareVersions(version, MIN_OAM_VERSION) < 0) {
855
- log("warn", "oam is installed but below the minimum supported version; falling back to node", {
856
- // The full token, prerelease suffix included: a build reporting
857
- // "0.8.3-rc.1" against a 0.8.3 floor lands here deliberately (semver
858
- // ranks a prerelease below its release), and naming it as "0.8.3" would
859
- // make this line look like a comparator bug.
860
- oamVersion: version,
861
- minVersion: MIN_OAM_VERSION,
862
- // The floor tracks the latest release, so below-min always means out
863
- // of date, and oam updates itself in place.
864
- updateWith: "oam self-update",
865
- // ...but updating alone changes nothing here. oamProbeCache is written
866
- // once per process and only ever cleared by a test hook, so every
867
- // opted-in server keeps landing on node until the broker restarts --
868
- // and an MCP broker under a desktop client lives for days. Without this
869
- // the user runs the update, sees no further log line, and reads a
870
- // working fix as a fix that did not work. The timeout and generic
871
- // failure warns say "for this process" for the same reason.
872
- thenRestart: "restart yaw-mcp; this probe is cached for the process lifetime"
873
- });
874
- return publish({ bin: null, binPath: null, version, belowMin: true, failure: null, failureDetail: null });
875
- }
876
- if (version === null) {
877
- log("debug", "oam --version printed no parsable version; the minimum-version gate did not run for this binary", {
878
- bin,
879
- minVersion: MIN_OAM_VERSION
880
- });
881
- }
882
- return publish({
883
- bin,
884
- // Resolved once, alongside the probe that proved the name spawns, so the
885
- // install path never has to re-derive it (or spawn `where`/`which`).
886
- binPath: resolveBinAbsolute(bin),
887
- version,
888
- belowMin: false,
889
- failure: null,
890
- failureDetail: null
891
- });
892
- } catch (err) {
893
- const code = err?.code;
894
- const absent = code === "ENOENT" && !explicit;
895
- if (code === "ETIMEDOUT") {
896
- log("warn", "oam did not respond to --version in time; falling back to node for this process", {
897
- timeoutMs: OAM_PROBE_TIMEOUT_MS,
898
- bin
899
- });
900
- } else if (code !== "ENOENT") {
901
- log("warn", "oam --version failed; falling back to node for this process", {
902
- bin,
903
- error: err instanceof Error ? err.message : String(err)
904
- });
905
- } else if (explicit) {
906
- log("warn", "OAM_BIN points at a path that does not exist; falling back to node for this process", {
907
- bin,
908
- error: err instanceof Error ? err.message : String(err)
909
- });
910
- }
911
- return publish({
912
- bin: null,
913
- binPath: null,
914
- version: null,
915
- belowMin: false,
916
- failure: absent ? null : classifyProbeFailure(err),
917
- failureDetail: absent ? null : err instanceof Error ? err.message : String(err)
918
- });
919
- }
920
- }
921
- var WIN_EXE_EXT = /\.(?:exe|cmd|bat)$/i;
922
- function nodeLaunchKind(command) {
923
- const base = (command.split(/[\\/]/).pop() ?? command).replace(WIN_EXE_EXT, "").toLowerCase();
924
- if (base === "node") return "node";
925
- if (base === "npx") return "npx";
926
- return null;
927
- }
928
- var TS_ENTRY_RE = /\.[mc]?ts$/i;
929
- function rewriteForOam(command, args, deps) {
930
- const bin = deps.oamBin;
931
- if (!bin) return { command, args };
932
- const toOam = (entry, rest) => {
933
- const flags = TS_ENTRY_RE.test(entry) ? ["--no-check"] : [];
934
- return {
935
- command: bin,
936
- args: rest.length > 0 ? ["run", ...flags, entry, "--", ...rest] : ["run", ...flags, entry]
937
- };
938
- };
939
- const kind = nodeLaunchKind(command);
940
- if (kind === "node") {
941
- const [entry, ...rest] = args;
942
- if (!entry) return { command, args };
943
- if (entry.startsWith("-")) return { command, args };
944
- return toOam(entry, rest);
945
- }
946
- if (kind === "npx") {
947
- const specIdx = npxSpecIndex(args);
948
- const spec = specIdx === -1 ? void 0 : args[specIdx];
949
- if (!spec) return { command, args };
950
- if (spec.startsWith("-")) {
951
- log("debug", "npx launch carries flags yaw-mcp does not parse; staying on npx instead of oam", {
952
- flag: spec,
953
- argc: args.length
954
- });
955
- return { command, args };
956
- }
957
- if (!isRegistrySpec(spec)) {
958
- log("debug", "npx spec is a git/path target, not a registry package; staying on npx instead of oam", { spec });
959
- return { command, args };
960
- }
961
- const pkg = packageName(spec);
962
- const constraint = specConstraint(spec);
963
- if (constraint.kind === "range") {
964
- log("debug", "npx spec constrains the version with a range yaw-mcp cannot evaluate; staying on npx", {
965
- package: pkg,
966
- range: constraint.raw
967
- });
968
- return { command, args };
969
- }
970
- const wantVersion = constraint.kind === "exact" ? constraint.version : null;
971
- const entry = deps.resolveEntry(pkg, wantVersion);
972
- if (!entry) {
973
- if (wantVersion !== null) {
974
- log("debug", "no on-disk copy declares the pinned version; staying on npx so the pin is honoured", {
975
- package: pkg,
976
- version: wantVersion
977
- });
978
- } else {
979
- log("debug", "npx package has no on-disk entry; staying on npx instead of oam", { package: pkg });
980
- }
981
- return { command, args };
982
- }
983
- return toOam(entry, args.slice(specIdx + 1));
984
- }
985
- return { command, args };
986
- }
987
- var NPX_CACHE_MARKER = `${sep}_npx${sep}`;
988
- function npxHashNodeModules(npxRoot) {
989
- try {
990
- return readdirSync(npxRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => join2(npxRoot, e.name, "node_modules"));
991
- } catch {
992
- return [];
993
- }
994
- }
995
- function npxCacheNodeModules(fromUrl = import.meta.url) {
996
- let here;
997
- try {
998
- here = fileURLToPath(fromUrl);
999
- } catch {
1000
- return [];
1001
- }
1002
- const idx = here.indexOf(NPX_CACHE_MARKER);
1003
- if (idx === -1) return [];
1004
- const npxRoot = here.slice(0, idx + NPX_CACHE_MARKER.length - sep.length);
1005
- return npxHashNodeModules(npxRoot);
1006
- }
1007
- function npmrcValue(raw) {
1008
- const v = raw.trim();
1009
- const quoted = v.length > 1 && (v.startsWith('"') && v.endsWith('"') || v.startsWith("'") && v.endsWith("'"));
1010
- if (quoted) {
1011
- if (v.startsWith('"')) {
1012
- try {
1013
- return JSON.parse(v);
1014
- } catch {
1015
- return v.slice(1, -1);
1016
- }
1017
- }
1018
- return v.slice(1, -1);
1019
- }
1020
- let out = "";
1021
- let esc = false;
1022
- for (const c of v) {
1023
- if (esc) {
1024
- out += ";#\\".includes(c) ? c : `\\${c}`;
1025
- esc = false;
1026
- continue;
1027
- }
1028
- if (c === ";" || c === "#") break;
1029
- if (c === "\\") {
1030
- esc = true;
1031
- continue;
1032
- }
1033
- out += c;
1034
- }
1035
- if (esc) out += "\\";
1036
- return out.trim();
1037
- }
1038
- function npmrcCache(file) {
1039
- let text;
1040
- try {
1041
- text = readFileSync(file, "utf8");
1042
- } catch {
1043
- return null;
1044
- }
1045
- let last = null;
1046
- for (const line of text.split(/\r?\n/)) {
1047
- const m = /^\s*cache\s*=(.*)$/.exec(line);
1048
- if (!m) continue;
1049
- const value = expandNpmrcEnv(npmrcValue(m[1]));
1050
- if (!value) continue;
1051
- last = value.startsWith("~/") ? join2(homedir3(), value.slice(2)) : value;
1052
- }
1053
- return last;
1054
- }
1055
- function expandNpmrcEnv(value, env = process.env) {
1056
- return value.replace(/(\\*)\$\{([^${}]+)\}/g, (orig, esc, name) => {
1057
- if (esc.length % 2 === 1) return orig.slice((esc.length + 1) / 2);
1058
- const val = env[name];
1059
- return esc.slice(esc.length / 2) + (val === void 0 ? `\${${name}}` : val);
1060
- });
1061
- }
1062
- var npmCacheDirCache = /* @__PURE__ */ new Map();
1063
- function npmCacheDir(fromUrl = import.meta.url) {
1064
- const cached = npmCacheDirCache.get(fromUrl);
1065
- if (cached !== void 0) return cached;
1066
- const resolved = resolveNpmCacheDir(fromUrl);
1067
- npmCacheDirCache.set(fromUrl, resolved);
1068
- return resolved;
1069
- }
1070
- function resolveNpmCacheDir(fromUrl) {
1071
- const envKey = Object.keys(process.env).find((k) => /^npm_config_cache$/i.test(k));
1072
- const fromEnv = envKey === void 0 ? void 0 : process.env[envKey];
1073
- if (fromEnv) return fromEnv;
1074
- const candidates = [join2(homedir3(), ".npmrc")];
1075
- for (const nodeModules of ownNodeModules(fromUrl)) {
1076
- candidates.push(
1077
- join2(dirname(nodeModules), "etc", "npmrc"),
1078
- // <prefix>/node_modules (Windows)
1079
- join2(dirname(dirname(nodeModules)), "etc", "npmrc"),
1080
- // <prefix>/lib/node_modules (POSIX)
1081
- join2(nodeModules, "npm", "npmrc")
1082
- // builtin, beside npm itself
1083
- );
1084
- }
1085
- const nodeDir = dirname(process.execPath);
1086
- candidates.push(
1087
- join2(nodeDir, "node_modules", "npm", "npmrc"),
1088
- // Windows layout
1089
- join2(nodeDir, "..", "lib", "node_modules", "npm", "npmrc")
1090
- // POSIX layout
1091
- );
1092
- for (const file of candidates) {
1093
- const cache = npmrcCache(file);
1094
- if (cache) return cache;
1095
- }
1096
- const fallback = process.platform === "win32" ? process.env.LOCALAPPDATA && join2(process.env.LOCALAPPDATA, "npm-cache") : join2(homedir3(), ".npm");
1097
- return fallback && existsSync(fallback) ? fallback : null;
1098
- }
1099
- function npmCacheNpxNodeModules(cacheDir2) {
1100
- if (!cacheDir2) return [];
1101
- return npxHashNodeModules(join2(cacheDir2, "_npx"));
1102
- }
1103
- function ownNodeModules(fromUrl = import.meta.url) {
1104
- let here;
1105
- try {
1106
- here = fileURLToPath(fromUrl);
1107
- } catch {
1108
- return [];
1109
- }
1110
- const seg = `${sep}node_modules${sep}`;
1111
- const idx = here.lastIndexOf(seg);
1112
- if (idx === -1) return [];
1113
- return [here.slice(0, idx + seg.length - sep.length)];
1114
- }
1115
- function packageEntry(pkgDir, pkg) {
1116
- const pjPath = join2(pkgDir, "package.json");
1117
- if (!existsSync(pjPath)) return null;
1118
- let parsed;
1119
- try {
1120
- parsed = JSON.parse(readFileSync(pjPath, "utf8"));
1121
- } catch {
1122
- return null;
1123
- }
1124
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
1125
- const j = parsed;
1126
- let rel;
1127
- if (typeof j.bin === "string") {
1128
- rel = j.bin;
1129
- } else if (j.bin && typeof j.bin === "object") {
1130
- const bins = j.bin;
1131
- const own = (key) => typeof key === "string" && Object.hasOwn(bins, key) ? bins[key] : void 0;
1132
- const unscoped = pkg.slice(pkg.lastIndexOf("/") + 1);
1133
- rel = own(unscoped) ?? own(j.name) ?? Object.values(bins)[0];
1134
- }
1135
- if (!rel && typeof j.main === "string") rel = j.main;
1136
- if (typeof rel !== "string" || rel.length === 0) return null;
1137
- const entry = isAbsolute2(rel) ? rel : join2(pkgDir, rel);
1138
- if (!existsSync(entry)) return null;
1139
- return {
1140
- entry,
1141
- version: typeof j.version === "string" ? j.version : null
1142
- };
1143
- }
1144
- function resolveNpmEntry(pkg, fromUrl = import.meta.url, npmCache = npmCacheDir(fromUrl), managedRoot = sidecarsNodeModules(), wantVersion = null) {
1145
- const parts = pkg.split("/");
1146
- const own = ownNodeModules(fromUrl);
1147
- const ownCache = own.filter((nodeModules) => nodeModules.includes(NPX_CACHE_MARKER));
1148
- const ownDurable = own.filter((nodeModules) => !nodeModules.includes(NPX_CACHE_MARKER));
1149
- const durable = [
1150
- ...managedRoot ? [{ nodeModules: managedRoot, source: "managed" }] : [],
1151
- // Only the copies that are genuinely durable take part in the take-outright
1152
- // loop. A sidecar sitting in the broker's OWN _npx hash dir is a cache copy
1153
- // like any other, so it belongs in the highest-version scan below -- taking
1154
- // it outright let an old build in our own hash dir beat a NEWER copy in a
1155
- // sibling cache dir, which is the opposite of the rule that scan exists to
1156
- // enforce. (Only the ranking was wrong: the replaced branch already keyed
1157
- // `source` off NPX_CACHE_MARKER, so an own `_npx` copy was tagged
1158
- // "npx-cache" and did get the `npx -y <pkg>@latest` refresh advice.)
1159
- ...ownDurable.map((nodeModules) => ({ nodeModules, source: "durable" }))
1160
- ];
1161
- for (const { nodeModules, source } of durable) {
1162
- const hit = packageEntry(join2(nodeModules, ...parts), pkg);
1163
- if (!hit) continue;
1164
- if (wantVersion !== null && !satisfiesExactPin(hit.version, wantVersion)) continue;
1165
- notePinnedSidecar(pkg, hit.version, source, nodeModules);
1166
- return hit.entry;
1167
- }
1168
- const roots = /* @__PURE__ */ new Set([...ownCache, ...npxCacheNodeModules(fromUrl), ...npmCacheNpxNodeModules(npmCache)]);
1169
- let best = null;
1170
- let bestRoot = null;
1171
- let bestParsed = null;
1172
- for (const nodeModules of roots) {
1173
- const hit = packageEntry(join2(nodeModules, ...parts), pkg);
1174
- if (!hit) continue;
1175
- if (wantVersion !== null && !satisfiesExactPin(hit.version, wantVersion)) continue;
1176
- const parsed = hit.version === null ? null : parseSemver(hit.version);
1177
- const wins = best === null || parsed !== null && (bestParsed === null || compareSemver(parsed, bestParsed) > 0);
1178
- if (wins) {
1179
- best = hit;
1180
- bestRoot = nodeModules;
1181
- bestParsed = parsed;
1182
- }
1183
- }
1184
- if (best !== null && bestRoot !== null) notePinnedSidecar(pkg, best.version, "npx-cache", bestRoot);
1185
- return best?.entry ?? null;
1186
- }
1187
- var REFRESH_COMMAND = {
1188
- managed: () => "yaw-mcp sidecars install",
1189
- durable: (pkg) => `npm install ${pkg}@latest`,
1190
- // No trailing flag. `npx -y <pkg>@latest` re-resolves the tag and refreshes
1191
- // the cache tree BEFORE it execs the binary, which is all the refresh
1192
- // needs -- and stdio MCP servers ignore flags like `--help` and simply
1193
- // start, so tacking one on turns "runs briefly" into "hangs the terminal
1194
- // on a server waiting for stdin" (measured on
1195
- // @modelcontextprotocol/server-memory). `npm cache add` is no substitute:
1196
- // it only fills _cacache, never the _npx install tree this resolver reads.
1197
- // No inline `#` comment either: that is comment syntax only in sh and
1198
- // PowerShell -- cmd.exe hands `#` and everything after it to npx as literal
1199
- // argv for the spawned server, which arg-parsing servers fail on. The
1200
- // Ctrl-C guidance rides in REFRESH_NOTE instead, so the command itself is
1201
- // copy-paste safe in all three shells.
1202
- "npx-cache": (pkg) => `npx -y ${pkg}@latest`
1203
- };
1204
- var REFRESH_NOTE = {
1205
- "npx-cache": "then Ctrl-C -- the cache is refreshed before the server starts"
1206
- };
1207
- var pinnedReported = /* @__PURE__ */ new Set();
1208
- function notePinnedSidecar(pkg, version, source, from) {
1209
- if (pinnedReported.has(pkg)) return;
1210
- pinnedReported.add(pkg);
1211
- log(
1212
- source === "managed" ? "debug" : "info",
1213
- "hosting sidecar on oam from an on-disk copy; it will not self-update the way npx does",
1214
- {
1215
- package: pkg,
1216
- version: version ?? "unknown",
1217
- source,
1218
- // The node_modules the entry was actually resolved out of. refreshWith
1219
- // cannot name it -- a durable tree may be global or project-local, and
1220
- // the command differs -- so this is what makes the advice actionable
1221
- // rather than something to run in whatever cwd the user happens to be.
1222
- from,
1223
- refreshWith: REFRESH_COMMAND[source](pkg),
1224
- // Only npx-cache has one today; JSON.stringify drops the field entirely
1225
- // for the sources that do not, rather than printing "undefined".
1226
- refreshNote: REFRESH_NOTE[source]
1227
- }
1228
- );
1229
- }
1230
- function resolveStableNpmEntry(pkg, fromUrl = import.meta.url) {
1231
- for (const nodeModules of ownNodeModules(fromUrl)) {
1232
- if (nodeModules.includes(NPX_CACHE_MARKER)) continue;
1233
- const hit = packageEntry(join2(nodeModules, ...pkg.split("/")), pkg);
1234
- if (hit) return hit.entry;
1235
- }
1236
- return null;
1237
- }
1238
- async function resolveOamSpawn(command, args, optedIn = true) {
1239
- const probe = await probeOam();
1240
- if (optedIn && probe.bin === null && !probe.belowMin && !warnedOamUnavailable && nodeLaunchKind(command) !== null) {
1241
- warnedOamUnavailable = true;
1242
- if (probe.failure !== null) {
1243
- log("warn", "a server opted in to oam but oam is installed and unusable; running it on node instead", {
1244
- reason: oamFailureLabel(probe.failure),
1245
- // The raw error behind the label. It is the part a support ticket needs
1246
- // and the part the plain-English line deliberately does not carry.
1247
- detail: probe.failureDetail,
1248
- // No install commands: the install is already there. Pointing OAM_BIN
1249
- // at a working copy is the actionable move, and the probe is cached for
1250
- // the process lifetime, so repairing it needs a restart to take effect.
1251
- overrideWith: "OAM_BIN",
1252
- thenRestart: "restart yaw-mcp; this probe is cached for the process lifetime"
1253
- });
1254
- } else {
1255
- log("warn", "a server opted in to oam but oam is not installed; running it on node instead", {
1256
- // Both, not oamInstallCommand(CURRENT_OS): this is a structured log
1257
- // line read off a server's stderr, which is routinely a different
1258
- // machine from the one reading it. The rendered REPORTS (doctor,
1259
- // install) are the surfaces that know which platform they are about.
1260
- install: OAM_INSTALL_SH,
1261
- installWindows: OAM_INSTALL_PS1,
1262
- overrideWith: "OAM_BIN"
1263
- });
1264
- }
1265
- }
1266
- return rewriteForOam(command, args, {
1267
- oamBin: probe.bin,
1268
- // The three injectables (fromUrl, npmCache, managedRoot) keep their
1269
- // production defaults -- explicit `undefined` rather than a reorder,
1270
- // because they are positional and every test call site passes them.
1271
- resolveEntry: (pkg, wantVersion) => resolveNpmEntry(pkg, void 0, void 0, void 0, wantVersion)
1272
- });
1273
- }
1274
- function isOamCommand(command) {
1275
- const base = command.split(/[\\/]/).pop() ?? command;
1276
- return /^oam(\.exe)?$/i.test(base);
1277
- }
1278
- function isOamLaunch(command, args = []) {
1279
- if (isOamCommand(command)) return true;
1280
- const base = command.split(/[\\/]/).pop() ?? command;
1281
- if (/^cmd(\.exe)?$/i.test(base)) {
1282
- const first = args.find((a) => !/^\/[a-z]$/i.test(a));
1283
- return first !== void 0 && isOamCommand(first);
1284
- }
1285
- if (/^(sh|bash|zsh|dash)$/i.test(base)) {
1286
- const dashC = args.indexOf("-c");
1287
- const payload = dashC >= 0 ? args[dashC + 1] : args[0];
1288
- if (payload === void 0) return false;
1289
- const firstToken = payload.trim().split(/\s+/)[0]?.replace(/^["']|["']$/g, "");
1290
- return firstToken !== void 0 && firstToken.length > 0 && isOamCommand(firstToken);
1291
- }
1292
- return false;
1293
- }
1294
-
1295
- // src/upgrade-cmd.ts
1296
- var POSIX_GLOBAL_LIB_PREFIX = /^(?:[A-Za-z]:)?(?:\/usr(?:\/local)?|\/opt\/[^/]+)\/lib\/node_modules\/@yawlabs\/mcp\//;
1297
- var MANAGED_NODE_LIB_PREFIX = /\/(?:\.nvm\/versions\/node\/[^/]+|\.volta\/tools\/image\/node\/[^/]+|\.asdf\/installs\/nodejs\/[^/]+|(?:\.local\/share\/)?\.?fnm\/node-versions\/[^/]+\/installation|\.nodenv\/versions\/[^/]+|\.nvs\/[^/]+\/[^/]+\/[^/]+|n\/versions\/node\/[^/]+|\.local)\/lib\/node_modules\/@yawlabs\/mcp\//;
1298
- var UPGRADE_USAGE = `Usage: yaw-mcp upgrade [--run] [--json]
1299
-
1300
- Show (or execute) the command to upgrade @yawlabs/mcp to the latest version.
1301
-
1302
- --run Run the upgrade in place (global npm, pnpm, bun, and local npm
1303
- installs). No-op for npx installs -- they always fetch the latest.
1304
- --json Emit a machine-readable snapshot ({ current, latest, stale,
1305
- method, command, cwd }) instead of prose. "cwd" is the directory
1306
- "command" must run IN -- the package-tree root for a
1307
- local-node-modules install, null for every other method (the
1308
- command can run anywhere). Running a local install's command from
1309
- the wrong directory creates a stray package.json + node_modules
1310
- there instead of upgrading the tree.
1311
- NOTE: --json is a report-only snapshot; it never spawns an upgrade
1312
- even when combined with --run, and exits 1 whenever "stale" is
1313
- true. Use --run without --json to actually perform the upgrade.`;
1314
- function parseUpgradeArgs(argv) {
1315
- const opts = {};
1316
- for (const a of argv) {
1317
- if (a === "--run") opts.run = true;
1318
- else if (a === "--json") opts.json = true;
1319
- else if (a === "--help" || a === "-h") return { ok: false, error: UPGRADE_USAGE, help: true };
1320
- else return { ok: false, error: `yaw-mcp upgrade: unknown argument "${a}"
1321
-
1322
- ${UPGRADE_USAGE}` };
1323
- }
1324
- return { ok: true, options: opts };
1325
- }
1326
- function detectInstallMethod(argvPath, realpath2 = realpathSync, resolveWhen = ["unknown"]) {
1327
- if (!argvPath) return "unknown";
1328
- const literal = classifyEntrypoint(argvPath);
1329
- if (!resolveWhen.includes(literal)) return literal;
1330
- let resolved;
1331
- try {
1332
- resolved = realpath2(argvPath);
1333
- } catch {
1334
- return literal;
1335
- }
1336
- return resolved === argvPath ? literal : classifyEntrypoint(resolved);
1337
- }
1338
- function classifyEntrypoint(argvPath) {
1339
- const normalized = argvPath.replace(/\\/g, "/");
1340
- if (/\/_npx\/[0-9a-f]+\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "npx";
1341
- if (/\/app\.asar\.unpacked\//.test(normalized)) return "bundled-app";
1342
- if (/\/npm\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "global-npm";
1343
- if (POSIX_GLOBAL_LIB_PREFIX.test(normalized)) return "global-npm";
1344
- if (MANAGED_NODE_LIB_PREFIX.test(normalized)) return "global-npm";
1345
- if (/\/AppData\/Roaming\/npm\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "global-npm";
1346
- if (/\/bin\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "global-npm";
1347
- if (/\/pnpm\/global\/\d+\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "pnpm-global";
1348
- if (/\/\.bun\/install\/global\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "bun-global";
1349
- if (/\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "local-node-modules";
1350
- if (/\/(yaw-mcp|mcph|mcp)\/(dist|src)\//.test(normalized)) return "dev-checkout";
1351
- return "unknown";
1352
- }
1353
- function localInstallRoot(argvPath) {
1354
- if (!argvPath) return null;
1355
- const idx = argvPath.replace(/\\/g, "/").indexOf("/node_modules/");
1356
- return idx > 0 ? argvPath.slice(0, idx) : null;
1357
- }
1358
- function runningPackageDir(argvPath, realpath2 = realpathSync) {
1359
- if (!argvPath) return null;
1360
- const literal = packageDirOf(argvPath);
1361
- if (literal !== null) return literal;
1362
- try {
1363
- return packageDirOf(realpath2(argvPath));
1364
- } catch {
1365
- return null;
1366
- }
1367
- }
1368
- function packageDirOf(p) {
1369
- const marker = "/node_modules/@yawlabs/mcp/";
1370
- const idx = p.replace(/\\/g, "/").lastIndexOf(marker);
1371
- return idx === -1 ? null : p.slice(0, idx + marker.length - 1);
1372
- }
1373
- function defaultInstalledVersion(pkgDir) {
1374
- if (process.env.VITEST) return null;
1375
- try {
1376
- const parsed = JSON.parse(readFileSync2(join3(pkgDir, "package.json"), "utf8"));
1377
- return typeof parsed.version === "string" ? parsed.version : null;
1378
- } catch {
1379
- return null;
1380
- }
1381
- }
1382
- function killProcessTree(child, platform = process.platform, spawnImpl = spawn2) {
1383
- if (platform === "win32" && child.pid !== void 0) {
1384
- try {
1385
- spawnImpl("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" }).on("error", () => {
1386
- });
1387
- } catch {
1388
- }
1389
- }
1390
- child.kill();
1391
- }
1392
- async function npmGlobalPrefix(spawnImpl) {
1393
- if (process.env.VITEST && !spawnImpl) return null;
1394
- const spawnFn = spawnImpl ?? spawn2;
1395
- return new Promise((resolve2) => {
1396
- const child = spawnFn("npm", ["prefix", "-g"], {
1397
- shell: process.platform === "win32",
1398
- stdio: ["ignore", "pipe", "ignore"],
1399
- // Even a read-only `npm prefix -g` is an npm invocation: yaw-mcp's own
1400
- // secrets do not ride into it. See internal-secret-env.ts.
1401
- env: stripInternalSecretsFromEnv(process.env)
1402
- });
1403
- let out = "";
1404
- const timer = setTimeout(() => {
1405
- killProcessTree(child);
1406
- resolve2(null);
1407
- }, 3e3);
1408
- child.stdout?.on("data", (d) => {
1409
- out += String(d);
1410
- });
1411
- child.on("close", (code) => {
1412
- clearTimeout(timer);
1413
- resolve2(code === 0 && out.trim() ? out.trim() : null);
1414
- });
1415
- child.on("error", () => {
1416
- clearTimeout(timer);
1417
- resolve2(null);
1418
- });
1419
- });
1420
- }
1421
- function comparablePath(p) {
1422
- let real = p;
1423
- try {
1424
- real = realpathSync(p);
1425
- } catch {
1426
- }
1427
- const normalized = real.replace(/\\/g, "/");
1428
- return process.platform === "win32" ? normalized.toLowerCase() : normalized;
1429
- }
1430
- async function refineInstallMethod(method, argvPath, npmPrefix = npmGlobalPrefix) {
1431
- if (method !== "local-node-modules" && method !== "unknown") return method;
1432
- if (!argvPath) return method;
1433
- const prefix = await npmPrefix();
1434
- if (!prefix) return method;
1435
- const entry = comparablePath(argvPath);
1436
- const pfx = comparablePath(prefix);
1437
- if (entry.startsWith(`${pfx}/node_modules/`) || entry.startsWith(`${pfx}/lib/node_modules/`)) {
1438
- return "global-npm";
1439
- }
1440
- return method;
1441
- }
1442
- var UPGRADE_PACKAGE_SPEC = "@yawlabs/mcp@latest";
1443
- var UPGRADE_COMMANDS = {
1444
- "global-npm": { cmd: "npm", args: ["install", "-g", UPGRADE_PACKAGE_SPEC] },
1445
- "pnpm-global": { cmd: "pnpm", args: ["add", "-g", UPGRADE_PACKAGE_SPEC] },
1446
- "bun-global": { cmd: "bun", args: ["add", "-g", UPGRADE_PACKAGE_SPEC] },
1447
- "local-node-modules": { cmd: "npm", args: ["install", UPGRADE_PACKAGE_SPEC] },
1448
- npx: null,
1449
- "bundled-app": null,
1450
- "dev-checkout": null,
1451
- binary: null,
1452
- unknown: null
1453
- };
1454
- var GLOBAL_UPGRADE_METHODS = ["global-npm", "pnpm-global", "bun-global"];
1455
- function upgradeSpawnSpec(method, prefixArg = null) {
1456
- const base = UPGRADE_COMMANDS[method];
1457
- if (base === null) return null;
1458
- const args = [...base.args];
1459
- if (method === "global-npm" && prefixArg !== null) args.splice(args.length - 1, 0, "--prefix", prefixArg);
1460
- return { cmd: base.cmd, args };
1461
- }
1462
- function upgradeCommandLine(method) {
1463
- const spec = upgradeSpawnSpec(method);
1464
- return spec === null ? null : [spec.cmd, ...spec.args].join(" ");
1465
- }
1466
- var BINARY_RETIRED_HINT = `the standalone-binary track was retired in 0.70.3. Install from npm instead -- \`${upgradeCommandLine("global-npm")}\` -- then delete this executable.`;
1467
- function globalUpgradeCommandLineForTool(tool) {
1468
- const method = GLOBAL_UPGRADE_METHODS.find((m) => UPGRADE_COMMANDS[m]?.cmd === tool);
1469
- return method === void 0 ? null : upgradeCommandLine(method);
1470
- }
1471
- function buildUpgradePlan(input) {
1472
- const { current, latest, method } = input;
1473
- const stripV = (s) => s.startsWith("v") ? s.slice(1) : s;
1474
- const stale = latest !== null && current !== "dev" && compareVersions(stripV(current), stripV(latest)) < 0;
1475
- let command;
1476
- switch (method) {
1477
- case "npx":
1478
- command = null;
1479
- break;
1480
- case "bundled-app":
1481
- command = null;
1482
- break;
1483
- case "binary":
1484
- command = null;
1485
- break;
1486
- case "dev-checkout":
1487
- command = "git pull && npm run build";
1488
- break;
1489
- case "unknown":
1490
- command = upgradeCommandLine("global-npm");
1491
- break;
1492
- default:
1493
- command = upgradeCommandLine(method);
1494
- break;
1495
- }
1496
- return { current, latest, stale, method, command };
1497
- }
1498
- var REGISTRY_FETCH_TIMEOUT_MS = 3e3;
1499
- async function fetchLatestVersion(opts = {}) {
1500
- if (opts.override) {
1501
- try {
1502
- return await opts.override();
1503
- } catch {
1504
- return null;
1505
- }
1506
- }
1507
- const ac = new AbortController();
1508
- const timer = setTimeout(() => ac.abort(), opts.timeoutMs ?? REGISTRY_FETCH_TIMEOUT_MS);
1509
- try {
1510
- const res = await fetch("https://registry.npmjs.org/@yawlabs/mcp/latest", {
1511
- signal: ac.signal,
1512
- headers: { accept: "application/json" }
1513
- });
1514
- if (!res.ok) return null;
1515
- const body = await res.json();
1516
- return typeof body.version === "string" ? body.version : null;
1517
- } catch {
1518
- return null;
1519
- } finally {
1520
- clearTimeout(timer);
1521
- }
1522
- }
1523
- async function probeOamQuietly() {
1524
- const prev = process.env.LOG_LEVEL;
1525
- process.env.LOG_LEVEL = "error";
1526
- try {
1527
- return await probeOam();
1528
- } finally {
1529
- if (prev === void 0) delete process.env.LOG_LEVEL;
1530
- else process.env.LOG_LEVEL = prev;
1531
- }
1532
- }
1533
- async function oamFloorLines(probe) {
1534
- if (!probe && process.env.VITEST) return [];
1535
- try {
1536
- const oam = probe ? await probe() : await probeOamQuietly();
1537
- if (!oam.belowMin) return [];
1538
- return [
1539
- "",
1540
- `oam: v${oam.version ?? "unknown"} is installed but below the v${MIN_OAM_VERSION} floor yaw-mcp`,
1541
- " requires, so MCP sidecars run on node instead of oam. Update it:",
1542
- "",
1543
- " oam self-update"
1544
- ];
1545
- } catch {
1546
- return [];
1547
- }
1548
- }
1549
- async function defaultRunningPrefix(argvPath) {
1550
- if (process.env.VITEST) return null;
1551
- const { detectRunningInstallPrefix: detectRunningInstallPrefix2 } = await import("./auto-upgrade-WMCX5NYW.js");
1552
- return detectRunningInstallPrefix2(argvPath);
1553
- }
1554
- async function defaultSpawn(cmd, args, cwd) {
1555
- return new Promise((resolve2) => {
1556
- const child = spawn2(cmd, args, {
1557
- stdio: "inherit",
1558
- shell: process.platform === "win32",
1559
- cwd,
1560
- // yaw-mcp's own secrets stay out of the install: npm runs every
1561
- // dependency's pre/postinstall with this env, and a passphrase parked
1562
- // in yaw-mcp's env block (where README says to put it) must not reach
1563
- // them. See internal-secret-env.ts.
1564
- env: stripInternalSecretsFromEnv(process.env)
1565
- });
1566
- child.on("close", (code) => resolve2(typeof code === "number" ? code : 1));
1567
- child.on("error", () => resolve2(1));
1568
- });
1569
- }
1570
- async function detectSea() {
1571
- if (process.env.ELECTRON_RUN_AS_NODE) return false;
1572
- const exe = process.execPath.replace(/\\/g, "/").split("/").pop()?.toLowerCase() ?? "";
1573
- if (exe === "node" || exe === "node.exe") return false;
1574
- try {
1575
- const sea = await import("sea");
1576
- return typeof sea.isSea === "function" && sea.isSea() === true;
1577
- } catch {
1578
- return false;
1579
- }
1580
- }
1581
- async function runUpgrade(opts = {}) {
1582
- const write = opts.out ?? createStreamWriter(process.stdout);
1583
- const writeErr = opts.err ?? createStreamWriter(process.stderr);
1584
- const lines = [];
1585
- const print = (s = "") => {
1586
- lines.push(s);
1587
- write(`${s}
1588
- `);
1589
- };
1590
- const printErr = (s) => {
1591
- lines.push(s);
1592
- writeErr(`${s}
1593
- `);
1594
- };
1595
- const fetcher = opts.fetchLatest ?? fetchLatestVersion;
1596
- const current = opts.currentVersion ?? readCurrentVersion();
1597
- const argvPath = opts.argvPath ?? process.argv[1];
1598
- const sea = opts.isSea ? opts.isSea() : await detectSea();
1599
- const method = sea ? "binary" : await refineInstallMethod(detectInstallMethod(argvPath), argvPath, opts.npmPrefix);
1600
- let latest;
1601
- try {
1602
- latest = await fetcher();
1603
- } catch {
1604
- latest = null;
1605
- }
1606
- const plan = buildUpgradePlan({ current, latest, method });
1607
- let globalPrefixArg = null;
1608
- let suggestedCommand = plan.command;
1609
- if (method === "global-npm") {
1610
- const rawPrefix = await (opts.runningPrefix ?? defaultRunningPrefix)(argvPath);
1611
- if (rawPrefix !== null) {
1612
- const { quoteArgForDisplay: quoteArgForDisplay2, quoteShellArgIfNeeded: quoteShellArgIfNeeded2 } = await import("./auto-upgrade-WMCX5NYW.js");
1613
- const spawnForm = quoteShellArgIfNeeded2(rawPrefix, opts.platform);
1614
- const displayForm = quoteArgForDisplay2(rawPrefix, opts.platform);
1615
- if (spawnForm !== null && displayForm !== null) {
1616
- globalPrefixArg = spawnForm;
1617
- const spec2 = upgradeSpawnSpec("global-npm", displayForm);
1618
- suggestedCommand = spec2 === null ? null : [spec2.cmd, ...spec2.args].join(" ");
1619
- }
1620
- }
1621
- }
1622
- const installRoot = method === "local-node-modules" ? localInstallRoot(argvPath) : null;
1623
- if (opts.json) {
1624
- print(JSON.stringify({ ...plan, command: suggestedCommand, cwd: installRoot }, null, 2));
1625
- return { exitCode: plan.stale ? 1 : 0, lines };
1626
- }
1627
- if (latest === null) {
1628
- print("yaw-mcp upgrade: couldn't reach the npm registry (offline? firewall?).");
1629
- if (suggestedCommand) {
1630
- print("When you're back online, run:");
1631
- print("");
1632
- if (installRoot) {
1633
- print(`in ${installRoot}:`);
1634
- }
1635
- print(` ${suggestedCommand}`);
1636
- } else if (method === "bundled-app") {
1637
- print("This copy of yaw-mcp ships inside Yaw Terminal and updates with the app -- nothing to run.");
1638
- } else if (method === "binary") {
1639
- print(`yaw-mcp is a standalone binary; ${BINARY_RETIRED_HINT}`);
1640
- } else {
1641
- print("Your install uses `npx -y` -- just restart the MCP client when you're back online.");
1642
- }
1643
- for (const line of await oamFloorLines(opts.oamProbe)) print(line);
1644
- return { exitCode: 0, lines };
1645
- }
1646
- print(`Current: ${current}`);
1647
- print(`Latest: ${latest}`);
1648
- print(`Install: ${method}`);
1649
- for (const line of await oamFloorLines(opts.oamProbe)) print(line);
1650
- if (!plan.stale) {
1651
- print("");
1652
- print("OK: You're on the latest version -- nothing to do.");
1653
- return { exitCode: 0, lines };
1654
- }
1655
- print("");
1656
- if (method === "npx") {
1657
- print("Your install uses `npx -y` -- restart the MCP client and it will fetch the new version.");
1658
- return { exitCode: 0, lines };
1659
- }
1660
- if (method === "bundled-app") {
1661
- print("This copy of yaw-mcp ships inside Yaw Terminal and updates with the app --");
1662
- print("there is nothing to run here. Update Yaw Terminal to get the new version.");
1663
- return { exitCode: 0, lines };
1664
- }
1665
- if (method === "binary") {
1666
- const emit = opts.run ? printErr : print;
1667
- emit("yaw-mcp is running as a standalone binary -- manual upgrade required.");
1668
- emit(`There's no package manager to upgrade it, and \`--run\` can't automate this: ${BINARY_RETIRED_HINT}`);
1669
- return { exitCode: opts.run ? 2 : 1, lines };
1670
- }
1671
- const spec = upgradeSpawnSpec(method, globalPrefixArg);
1672
- const runSpec = spec === null ? null : method === "local-node-modules" ? installRoot !== null ? { ...spec, cwd: installRoot } : null : spec;
1673
- const commandLine = method === "global-npm" ? suggestedCommand : runSpec ? [runSpec.cmd, ...runSpec.args].join(" ") : plan.command;
1674
- if (!opts.run) {
1675
- if (runSpec) {
1676
- print("Run `yaw-mcp upgrade --run` to upgrade in place, or run it yourself:");
1677
- } else {
1678
- print("Manual upgrade required (--run can't safely automate this install method). Run it yourself:");
1679
- }
1680
- print("");
1681
- if (installRoot) {
1682
- print(`in ${installRoot}:`);
1683
- }
1684
- print(` ${commandLine}`);
1685
- return { exitCode: 1, lines };
1686
- }
1687
- if (!runSpec) {
1688
- printErr(
1689
- `yaw-mcp upgrade --run: a "${method}" install can't be upgraded automatically (manual upgrade required). Run it yourself:`
1690
- );
1691
- printErr("");
1692
- printErr(` ${commandLine}`);
1693
- return { exitCode: 2, lines };
1694
- }
1695
- const runner = opts.spawnImpl ?? defaultSpawn;
1696
- if (runSpec.cwd) {
1697
- print(`Running in ${runSpec.cwd}:`);
1698
- } else {
1699
- print("Running:");
1700
- }
1701
- print(` ${commandLine}`);
1702
- print("");
1703
- const code = await runner(runSpec.cmd, runSpec.args, runSpec.cwd);
1704
- if (code === 0) {
1705
- print("");
1706
- print(`OK: Upgraded @yawlabs/mcp to ${latest}`);
1707
- const pkgDir = runningPackageDir(argvPath);
1708
- const running = pkgDir === null ? null : await (opts.installedVersion ?? defaultInstalledVersion)(pkgDir);
1709
- const bare = (s) => s.startsWith("v") ? s.slice(1) : s;
1710
- if (running !== null && compareVersions(bare(running), bare(latest)) < 0) {
1711
- printErr("");
1712
- printErr(`WARNING: the copy this command ran from still reports ${running}, not ${latest}:`);
1713
- printErr(` ${pkgDir}`);
1714
- printErr(
1715
- "The install landed in a different tree, so your MCP client keeps spawning the old version until that tree is upgraded too (for a copy nested under another package's node_modules, upgrade the package that pins it)."
1716
- );
1717
- }
1718
- return { exitCode: 0, lines };
1719
- }
1720
- printErr(`yaw-mcp upgrade: ${runSpec.cmd} exited ${code}. Try running the command yourself:`);
1721
- printErr("");
1722
- if (installRoot) {
1723
- printErr(`in ${installRoot}:`);
1724
- }
1725
- printErr(` ${commandLine}`);
1726
- return { exitCode: 3, lines };
1727
- }
1728
- function readCurrentVersion() {
1729
- return true ? "1.0.1" : "dev";
1730
- }
1731
-
1732
- // src/auto-upgrade.ts
1733
- function quoteShellArgIfNeeded(arg, platform = process.platform) {
1734
- if (platform !== "win32") return arg;
1735
- if (/[\r\n\0"%]/.test(arg)) return null;
1736
- if (!/[\s&|<>^]/.test(arg)) return arg;
1737
- return `"${arg}"`;
1738
- }
1739
- function quoteArgForDisplay(arg, platform = process.platform) {
1740
- if (platform === "win32") return quoteShellArgIfNeeded(arg, platform);
1741
- if (/^[A-Za-z0-9_\-./+,:@=]+$/.test(arg)) return arg;
1742
- return `'${arg.replace(/'/g, "'\\''")}'`;
1743
- }
1744
- function detectRunningInstallPrefix(argvPath) {
1745
- if (!argvPath) return null;
1746
- let resolved;
1747
- try {
1748
- resolved = realpathSync2(argvPath);
1749
- } catch {
1750
- return null;
1751
- }
1752
- const dir = dirname2(resolved);
1753
- const idx = dir.lastIndexOf(`${sep2}node_modules${sep2}`);
1754
- if (idx === -1) return null;
1755
- const candidate = dir.slice(0, idx);
1756
- if (candidate.endsWith(`${sep2}lib`)) return candidate.slice(0, -`${sep2}lib`.length);
1757
- return candidate;
1758
- }
1759
- async function compareWithNpmPrefix(detected, probe = npmGlobalPrefix) {
1760
- const npmPrefix = await probe();
1761
- if (!npmPrefix?.trim()) return;
1762
- if (comparablePath(npmPrefix.trim()) === comparablePath(detected)) return;
1763
- log(
1764
- "warn",
1765
- "yaw-mcp self-upgrade: running prefix differs from `npm prefix -g`; installing into the running prefix so the upgrade lands in the tree the client spawned from",
1766
- { running: detected, npmPrefix }
1767
- );
1768
- }
1769
- var UPGRADE_LOCK_NAME = ".yaw-mcp-upgrade.lock";
1770
- var UPGRADE_LOCK_STALE_MS = 10 * 60 * 1e3;
1771
- var UPGRADE_LOCK_FUTURE_SKEW_MS = 5 * 1e3;
1772
- function lockHolderAlive(lockPath) {
1773
- let pid;
1774
- try {
1775
- pid = Number.parseInt(readFileSync3(lockPath, "utf8").trim(), 10);
1776
- } catch {
1777
- return true;
1778
- }
1779
- if (!Number.isInteger(pid) || pid <= 0) return true;
1780
- if (pid === process.pid) return true;
1781
- try {
1782
- process.kill(pid, 0);
1783
- return true;
1784
- } catch (err) {
1785
- return err.code !== "ESRCH";
1786
- }
1787
- }
1788
- function acquireUpgradeLock(dir, lockName = UPGRADE_LOCK_NAME, opts = {}) {
1789
- const lockPath = join4(dir, lockName);
1790
- const holderAlive = (path2) => opts.probeHolder ? lockHolderAlive(path2) : true;
1791
- const mine = String(process.pid);
1792
- const take = () => {
1793
- try {
1794
- const fd = openSync(lockPath, "wx");
1795
- try {
1796
- writeSync(fd, `${mine}
1797
- `);
1798
- } finally {
1799
- closeSync(fd);
1800
- }
1801
- let released = false;
1802
- return () => {
1803
- if (released) return;
1804
- released = true;
1805
- try {
1806
- if (readFileSync3(lockPath, "utf8").trim() !== mine) return;
1807
- unlinkSync(lockPath);
1808
- } catch {
1809
- }
1810
- };
1811
- } catch (err) {
1812
- if (err.code === "EEXIST") return void 0;
1813
- return () => {
1814
- };
1815
- }
1816
- };
1817
- const first = take();
1818
- if (first !== void 0) return first;
1819
- const isLive = (ageMs2) => ageMs2 > -UPGRADE_LOCK_FUTURE_SKEW_MS && ageMs2 < UPGRADE_LOCK_STALE_MS;
1820
- let ageMs;
1821
- try {
1822
- ageMs = Date.now() - statSync2(lockPath).mtimeMs;
1823
- } catch {
1824
- ageMs = UPGRADE_LOCK_STALE_MS;
1825
- }
1826
- if (isLive(ageMs) && holderAlive(lockPath)) return null;
1827
- const stolenPath = `${lockPath}.stale-${process.pid}`;
1828
- try {
1829
- renameSync(lockPath, stolenPath);
1830
- } catch (err) {
1831
- if (err.code !== "ENOENT") return null;
1832
- const retry = take();
1833
- return retry === void 0 ? null : retry;
1834
- }
1835
- let stoleLive = false;
1836
- try {
1837
- stoleLive = isLive(Date.now() - statSync2(stolenPath).mtimeMs) && holderAlive(stolenPath);
1838
- } catch {
1839
- }
1840
- if (stoleLive) {
1841
- try {
1842
- const holder = readFileSync3(stolenPath, "utf8");
1843
- const fd = openSync(lockPath, "wx");
1844
- try {
1845
- writeSync(fd, holder);
1846
- } finally {
1847
- closeSync(fd);
1848
- }
1849
- } catch {
1850
- }
1851
- try {
1852
- unlinkSync(stolenPath);
1853
- } catch {
1854
- }
1855
- return null;
1856
- }
1857
- try {
1858
- unlinkSync(stolenPath);
1859
- } catch {
1860
- }
1861
- const second = take();
1862
- return second === void 0 ? null : second;
1863
- }
1864
- function defaultAcquireLock(dir, lockName) {
1865
- if (process.env.VITEST) return () => {
1866
- };
1867
- return acquireUpgradeLock(dir, lockName);
1868
- }
1869
- var UPGRADE_CHECK_INTERVAL_MS = 60 * 60 * 1e3;
1870
- var UPGRADE_ATTEMPT_COOLDOWN_MS = 6 * 60 * 60 * 1e3;
1871
- function readMemo(path2) {
1872
- let parsed;
1873
- try {
1874
- parsed = JSON.parse(readFileSync3(path2, "utf8"));
1875
- } catch {
1876
- return null;
1877
- }
1878
- if (typeof parsed !== "object" || parsed === null) return null;
1879
- const memo = parsed;
1880
- if (typeof memo.at !== "number") return null;
1881
- const ageMs = Date.now() - memo.at;
1882
- return ageMs < -UPGRADE_LOCK_FUTURE_SKEW_MS ? null : { ageMs, memo };
1883
- }
1884
- function writeMemo(path2, fields) {
1885
- try {
1886
- writeFileSync(path2, `${JSON.stringify({ at: Date.now(), ...fields })}
1887
- `);
1888
- } catch {
1889
- }
1890
- }
1891
- function checkMemoPath() {
1892
- return join4(tmpdir(), `.yaw-mcp-upgrade-check-${process.getuid?.() ?? "win"}.json`);
1893
- }
1894
- function readCheckMemo(path2) {
1895
- const read = readMemo(path2);
1896
- if (read === null || read.ageMs >= UPGRADE_CHECK_INTERVAL_MS) return null;
1897
- const latest = read.memo.latest;
1898
- if (latest !== null && typeof latest !== "string") return null;
1899
- return { latest };
1900
- }
1901
- function writeCheckMemo(path2, latest) {
1902
- writeMemo(path2, { latest });
1903
- }
1904
- function attemptMemoPath(dir, lockName) {
1905
- return join4(dir, `${lockName}.attempt`);
1906
- }
1907
- function attemptMemoFallbackPath(dir, lockName, fallbackDir) {
1908
- const scope = createHash("sha256").update(`${dir}\0${lockName}`).digest("hex").slice(0, 16);
1909
- return join4(fallbackDir, `.yaw-mcp-upgrade-attempt-${process.getuid?.() ?? "win"}-${scope}.json`);
1910
- }
1911
- function defaultCheckedRecently() {
1912
- if (process.env.VITEST) return null;
1913
- return readCheckMemo(checkMemoPath());
1914
- }
1915
- function defaultRecordCheck(latest) {
1916
- if (process.env.VITEST) return;
1917
- writeCheckMemo(checkMemoPath(), latest);
1918
- }
1919
- function defaultAttemptedRecently(dir, lockName, version) {
1920
- if (process.env.VITEST) return false;
1921
- return attemptedRecentlyAt(dir, lockName, version);
1922
- }
1923
- function defaultRecordAttempt(dir, lockName, version) {
1924
- if (process.env.VITEST) return;
1925
- recordAttemptAt(dir, lockName, version);
1926
- }
1927
- function attemptedRecentlyAt(dir, lockName, version, fallbackDir = tmpdir()) {
1928
- const recent = (read) => read !== null && read.memo.version === version && read.ageMs < UPGRADE_ATTEMPT_COOLDOWN_MS;
1929
- if (recent(readMemo(attemptMemoPath(dir, lockName)))) return true;
1930
- return recent(readMemo(attemptMemoFallbackPath(dir, lockName, fallbackDir)));
1931
- }
1932
- function recordAttemptAt(dir, lockName, version, fallbackDir = tmpdir()) {
1933
- const primary = attemptMemoPath(dir, lockName);
1934
- try {
1935
- writeFileSync(primary, `${JSON.stringify({ at: Date.now(), version })}
1936
- `);
1937
- return;
1938
- } catch {
1939
- }
1940
- writeMemo(attemptMemoFallbackPath(dir, lockName, fallbackDir), { version });
1941
- }
1942
- function defaultSpawn2(cmd, args, onDone = () => {
1943
- }) {
1944
- let errorFired = false;
1945
- let released = false;
1946
- const finish = () => {
1947
- if (released) return;
1948
- released = true;
1949
- onDone();
1950
- };
1951
- const correctiveCmd = globalUpgradeCommandLineForTool(cmd);
1952
- const child = spawn3(cmd, args, {
1953
- stdio: "ignore",
1954
- // yaw-mcp's own secrets stay out of the install. npm runs every
1955
- // dependency's pre/postinstall with this env, and README tells the user to
1956
- // put YAW_MCP_VAULT_PASSPHRASE in yaw-mcp's env block precisely because
1957
- // "yaw-mcp strips its own secrets from every child env" -- a promise the
1958
- // upstream spawn kept and this one, spawning with the full inherited
1959
- // process.env, silently did not: a compromised transitive dependency's
1960
- // install script plus ~/.yaw-mcp/secrets.json was the whole vault.
1961
- env: stripInternalSecretsFromEnv(process.env),
1962
- // Not detached, so the install shares yaw-mcp's process group and an MCP
1963
- // client that tears down the whole tree takes it with it. Two things this
1964
- // does NOT buy (the file header lists both as known gaps): on POSIX a
1965
- // plain parent exit does not kill it, and if it IS killed mid-install the
1966
- // result is not guaranteed intact -- npm reify removes the existing
1967
- // package dir before moving the new one in, and nothing here repairs a
1968
- // partial install on the next startup.
1969
- detached: false,
1970
- shell: process.platform === "win32"
1971
- });
1972
- child.on("close", (code) => {
1973
- finish();
1974
- if (errorFired) return;
1975
- if (code === 0) {
1976
- log("info", "yaw-mcp self-upgrade complete; the next client restart will run the new version");
1977
- } else {
1978
- const hint = cmd === "npm" ? " (often EACCES on a sudo-installed global -- run with the right permissions)" : "";
1979
- const manual = correctiveCmd === null ? "Set" : `Run \`${correctiveCmd}\` manually, or set`;
1980
- log(
1981
- "warn",
1982
- `yaw-mcp self-upgrade: ${cmd} exited non-zero${hint}. ${manual} YAW_MCP_AUTO_UPGRADE=0 to silence this.`,
1983
- { code }
1984
- );
1985
- }
1986
- });
1987
- child.on("error", (err) => {
1988
- errorFired = true;
1989
- finish();
1990
- log("warn", `yaw-mcp self-upgrade: ${cmd} spawn failed`, { error: err?.message });
1991
- });
1992
- }
1993
- async function maybeAutoUpgrade(deps = {}) {
1994
- const optOut = process.env.YAW_MCP_AUTO_UPGRADE;
1995
- if (optOut === "0" || optOut?.toLowerCase() === "false") return;
1996
- const current = deps.currentVersion ?? (true ? "1.0.1" : "dev");
1997
- if (current === "dev") return;
1998
- const argvPath = deps.argvPath ?? process.argv[1];
1999
- const method = (deps.isSeaImpl ? await deps.isSeaImpl() : await detectSea()) ? "binary" : detectInstallMethod(argvPath, realpathSync2, ["unknown", "local-node-modules"]);
2000
- const cached = (deps.checkedRecentlyImpl ?? defaultCheckedRecently)();
2001
- let latest;
2002
- if (cached !== null) {
2003
- latest = cached.latest;
2004
- } else {
2005
- latest = await (deps.fetchLatestImpl ?? fetchLatestVersion)();
2006
- (deps.recordCheckImpl ?? defaultRecordCheck)(latest);
2007
- }
2008
- if (latest === null) return;
2009
- const plan = buildUpgradePlan({ current, latest, method });
2010
- if (!plan.stale) return;
2011
- const rawPrefix = method === "global-npm" ? detectRunningInstallPrefix(argvPath) : null;
2012
- const quotedPrefix = rawPrefix === null ? null : quoteShellArgIfNeeded(rawPrefix);
2013
- const globalSpec = GLOBAL_UPGRADE_METHODS.includes(method) ? upgradeSpawnSpec(method, quotedPrefix) : null;
2014
- if (globalSpec) {
2015
- const lockDir = rawPrefix ?? tmpdir();
2016
- const lockName = rawPrefix === null ? `.yaw-mcp-upgrade-${globalSpec.cmd}-${process.getuid?.() ?? "win"}.lock` : UPGRADE_LOCK_NAME;
2017
- if ((deps.attemptedRecentlyImpl ?? defaultAttemptedRecently)(lockDir, lockName, latest)) {
2018
- log("info", "yaw-mcp self-upgrade: this upgrade was already attempted recently; not retrying yet", {
2019
- current,
2020
- latest,
2021
- tool: globalSpec.cmd,
2022
- lockDir
2023
- });
2024
- return;
2025
- }
2026
- const releaseLock = (deps.acquireLockImpl ?? defaultAcquireLock)(lockDir, lockName);
2027
- if (releaseLock === null) {
2028
- log("info", "yaw-mcp self-upgrade: another process is already upgrading this install; skipping this one", {
2029
- current,
2030
- latest,
2031
- tool: globalSpec.cmd,
2032
- lockDir
2033
- });
2034
- return;
2035
- }
2036
- log("info", "yaw-mcp is out of date; upgrading the global install in the background", {
2037
- current,
2038
- latest,
2039
- tool: globalSpec.cmd,
2040
- // The RAW prefix, not the shell-quoted argv form -- a log field is read
2041
- // by a human, and stray quotes read as part of the path. Omitted when
2042
- // quoting failed, because then no `--prefix` was passed at all and npm
2043
- // resolves its own prefix.
2044
- prefix: quotedPrefix === null ? void 0 : rawPrefix ?? void 0
2045
- });
2046
- if (method === "global-npm" && rawPrefix !== null && quotedPrefix !== null) {
2047
- compareWithNpmPrefix(rawPrefix, deps.npmPrefixImpl).catch(() => {
2048
- });
2049
- }
2050
- (deps.recordAttemptImpl ?? defaultRecordAttempt)(lockDir, lockName, latest);
2051
- try {
2052
- (deps.spawnImpl ?? defaultSpawn2)(globalSpec.cmd, globalSpec.args, releaseLock);
2053
- } catch (err) {
2054
- releaseLock();
2055
- log("warn", `yaw-mcp self-upgrade: could not start ${globalSpec.cmd}`, {
2056
- error: err instanceof Error ? err.message : String(err)
2057
- });
2058
- }
2059
- return;
2060
- }
2061
- if (method === "bundled-app") {
2062
- log("info", "yaw-mcp (bundled with Yaw Terminal) is behind npm; it updates with the app", { current, latest });
2063
- return;
2064
- }
2065
- if (method === "binary") {
2066
- log(
2067
- "info",
2068
- "yaw-mcp (standalone binary) is behind npm; the binary track was retired -- npm install -g @yawlabs/mcp@latest, then delete the old executable",
2069
- { current, latest }
2070
- );
2071
- return;
2072
- }
2073
- if (method === "npx") {
2074
- log("info", "yaw-mcp is out of date; restart your MCP client to pick up the latest version", {
2075
- current,
2076
- latest,
2077
- method
2078
- });
2079
- } else if (method === "local-node-modules") {
2080
- log(
2081
- "info",
2082
- "yaw-mcp is out of date; run `yaw-mcp upgrade --run` to update this install (a restart re-runs the version pinned in your project's node_modules)",
2083
- {
2084
- current,
2085
- latest,
2086
- method
2087
- }
2088
- );
2089
- } else {
2090
- log(
2091
- "info",
2092
- "yaw-mcp is out of date; run `yaw-mcp upgrade` for the command that updates this install (`--run` can't automate this install method)",
2093
- {
2094
- current,
2095
- latest,
2096
- method
2097
- }
2098
- );
2099
- }
2100
- }
2101
-
2102
- export {
2103
- INTERNAL_SECRET_ENV_KEYS,
2104
- scrubInternalSecretsFromProcessEnv,
2105
- stripInternalSecretsFromEnv,
2106
- setLogSurface,
2107
- log,
2108
- createStreamWriter,
2109
- cacheDir,
2110
- CONFIG_DIRNAME,
2111
- sidecarsRoot,
2112
- sidecarsNodeModules,
2113
- userConfigDir,
2114
- normalizeForCompare,
2115
- realpathOrSelf,
2116
- isUnderHome,
2117
- ALLOW_UNOWNED_ENV,
2118
- findProjectConfigDir,
2119
- guidePath,
2120
- CURRENT_OS,
2121
- INSTALL_TARGETS,
2122
- resolveAppDataDir,
2123
- resolveInstallPath,
2124
- buildLaunchEntry,
2125
- isProjectLocalEntry,
2126
- ENTRY_NAME,
2127
- LEGACY_ENTRY_NAMES,
2128
- findLegacyEntry,
2129
- CLAUDE_CODE_ALLOW_PATTERN,
2130
- resolveClaudeCodeSettingsPath,
2131
- packageName,
2132
- specConstraint,
2133
- isRegistrySpec,
2134
- npxSpecIndex,
2135
- npxSpec,
2136
- MIN_OAM_VERSION,
2137
- oamInstallCommand,
2138
- oamPublishesBinaryForThisMachine,
2139
- oamNoBinaryReason,
2140
- oamInstallAdvice,
2141
- oamHeapOomHint,
2142
- oamFailureLabel,
2143
- compareVersions,
2144
- probeOam,
2145
- nodeLaunchKind,
2146
- resolveStableNpmEntry,
2147
- resolveOamSpawn,
2148
- isOamCommand,
2149
- isOamLaunch,
2150
- parseUpgradeArgs,
2151
- detectInstallMethod,
2152
- refineInstallMethod,
2153
- BINARY_RETIRED_HINT,
2154
- buildUpgradePlan,
2155
- fetchLatestVersion,
2156
- detectSea,
2157
- runUpgrade,
2158
- quoteShellArgIfNeeded,
2159
- quoteArgForDisplay,
2160
- detectRunningInstallPrefix,
2161
- acquireUpgradeLock,
2162
- readCheckMemo,
2163
- writeCheckMemo,
2164
- attemptedRecentlyAt,
2165
- recordAttemptAt,
2166
- maybeAutoUpgrade
2167
- };