@yawlabs/mcp 0.79.1 → 0.80.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.
@@ -1,7 +1,77 @@
1
1
  #!/usr/bin/env node
2
+
3
+ // src/auto-upgrade.ts
4
+ import { spawn as spawn3 } from "child_process";
5
+ import { createHash } from "crypto";
2
6
  import {
3
- log
4
- } from "./chunk-3RRZQPA5.js";
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
+ function log(level, msg, data) {
55
+ if (LOG_LEVELS[level] < minLevel()) return;
56
+ guardStderrErrors();
57
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
58
+ let entry;
59
+ try {
60
+ entry = JSON.stringify({ ...data, level, msg, ts });
61
+ } catch {
62
+ entry = JSON.stringify({ level, msg, ts, dataOmitted: true });
63
+ }
64
+ try {
65
+ process.stderr.write(`${entry}
66
+ `);
67
+ } catch {
68
+ }
69
+ }
70
+
71
+ // src/upgrade-cmd.ts
72
+ import { spawn as spawn2 } from "child_process";
73
+ import { readFileSync as readFileSync2, realpathSync } from "fs";
74
+ import { join as join3 } from "path";
5
75
 
6
76
  // src/oam-spawn.ts
7
77
  import { spawn } from "child_process";
@@ -46,7 +116,10 @@ var INSTALL_TARGETS = [
46
116
  label: "Claude Desktop",
47
117
  jsonShape: "mcpServers",
48
118
  availableOn: ["macos", "windows"],
49
- notes: "Claude Desktop reads one file per OS \u2014 no project scope. Restart the app after editing.",
119
+ // ASCII `--`, not an em-dash: install prints this verbatim (`Note: ...`),
120
+ // and Claude Desktop is a Windows client -- on a console whose codepage is
121
+ // not UTF-8 the em-dash rendered as mojibake in the line the user reads.
122
+ notes: "Claude Desktop reads one file per OS -- no project scope. Restart the app after editing.",
50
123
  scopes: [
51
124
  {
52
125
  scope: "user",
@@ -92,9 +165,16 @@ var INSTALL_TARGETS = [
92
165
  ]
93
166
  }
94
167
  ];
168
+ function resolveAppDataDir(opts) {
169
+ if (opts.appData !== void 0 && opts.appData.length > 0) return opts.appData;
170
+ if (opts.home !== void 0) return join(opts.home, "AppData", "Roaming");
171
+ const env = opts.env ?? process.env;
172
+ const fromEnv = env.APPDATA;
173
+ return fromEnv && fromEnv.length > 0 ? fromEnv : join(homedir(), "AppData", "Roaming");
174
+ }
95
175
  function resolveInstallPath(opts) {
96
176
  const home = opts.home ?? homedir();
97
- const appData = opts.appData ?? process.env.APPDATA ?? join(home, "AppData", "Roaming");
177
+ const appData = opts.appData && opts.appData.length > 0 ? opts.appData : join(home, "AppData", "Roaming");
98
178
  const { clientId, scope, os, projectDir, claudeConfigDir } = opts;
99
179
  const target = INSTALL_TARGETS.find((t) => t.clientId === clientId);
100
180
  if (!target) throw new Error(`Unknown client: ${clientId}`);
@@ -120,8 +200,8 @@ function claudeCodeProjectKey(projectDir) {
120
200
  }
121
201
  function pathFor(client, scope, os, base) {
122
202
  const { home, appData, projectDir, claudeConfigDir } = base;
123
- const sep2 = os === "windows" ? "\\" : "/";
124
- const joinPath = (...parts) => parts.join(sep2);
203
+ const sep3 = os === "windows" ? "\\" : "/";
204
+ const joinPath = (...parts) => parts.join(sep3);
125
205
  if (client === "claude-code") {
126
206
  if (scope === "user") {
127
207
  if (claudeConfigDir) {
@@ -188,7 +268,7 @@ function pathFor(client, scope, os, base) {
188
268
  }
189
269
  var CMD_METACHARS = /[&|<>^()]/g;
190
270
  var HAS_CMD_METACHAR = /[&|<>^()]/;
191
- var KNOWN_CMD_SHIM_LAUNCHERS = /* @__PURE__ */ new Set(["npx", "uvx", "pipx", "npm", "pnpm", "yarn", "bunx"]);
271
+ var KNOWN_CMD_SHIM_LAUNCHERS = /* @__PURE__ */ new Set(["npx", "npm", "pnpm", "yarn", "bunx"]);
192
272
  var KNOWN_DIRECT_BINARIES = /* @__PURE__ */ new Set([
193
273
  "node",
194
274
  "deno",
@@ -196,6 +276,9 @@ var KNOWN_DIRECT_BINARIES = /* @__PURE__ */ new Set([
196
276
  "python",
197
277
  "python3",
198
278
  "py",
279
+ "uv",
280
+ "uvx",
281
+ "pipx",
199
282
  "ruby",
200
283
  "php",
201
284
  "docker",
@@ -229,6 +312,11 @@ function buildLaunchEntry(opts) {
229
312
  if (opts.upstream) {
230
313
  const { command, args, env } = opts.upstream;
231
314
  if (opts.os === "windows") {
315
+ if (/[ \t]/.test(command)) {
316
+ throw new Error(
317
+ `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).`
318
+ );
319
+ }
232
320
  const shim = isCmdShimLauncher(command);
233
321
  const wrapped = {
234
322
  command: "cmd",
@@ -272,7 +360,7 @@ function resolveClaudeCodeSettingsPath(scope, opts) {
272
360
  }
273
361
 
274
362
  // src/paths.ts
275
- import { access, realpath, stat } from "fs/promises";
363
+ import { realpath, stat } from "fs/promises";
276
364
  import { homedir as homedir2 } from "os";
277
365
  import path from "path";
278
366
  function cacheDir() {
@@ -318,18 +406,13 @@ function isUnderHome(dir, homeResolved) {
318
406
  }
319
407
  var ALLOW_UNOWNED_ENV = "YAW_MCP_ALLOW_UNOWNED_PROJECT_DIRS";
320
408
  var warnedUntrustedDirs = /* @__PURE__ */ new Set();
321
- async function ownedByCurrentUser(candidate) {
409
+ function ownedByCurrentUser(st, env) {
322
410
  const geteuid = process.geteuid;
323
- if (typeof geteuid !== "function") return process.env[ALLOW_UNOWNED_ENV] === "1";
324
- try {
325
- const st = await stat(candidate);
326
- return typeof st.uid === "number" && st.uid === geteuid.call(process);
327
- } catch {
328
- return false;
329
- }
411
+ if (typeof geteuid !== "function") return env[ALLOW_UNOWNED_ENV] === "1";
412
+ return typeof st.uid === "number" && st.uid === geteuid.call(process);
330
413
  }
331
- async function findProjectConfigDir(start, home = homedir2()) {
332
- const homeFallback = home && home.length > 0 ? home : process.env.USERPROFILE || homedir2();
414
+ async function findProjectConfigDir(start, home = homedir2(), env = process.env) {
415
+ const homeFallback = home && home.length > 0 ? home : homedir2();
333
416
  const homeResolved = path.resolve(await realpathOrSelf(path.resolve(homeFallback)));
334
417
  let dir = path.resolve(await realpathOrSelf(path.resolve(start)));
335
418
  const userConfigKey = normalizeForCompare(await realpathOrSelf(path.join(homeResolved, CONFIG_DIRNAME)));
@@ -339,10 +422,12 @@ async function findProjectConfigDir(start, home = homedir2()) {
339
422
  if (boundedByHome && !isUnderHome(dir, homeResolved)) return null;
340
423
  const candidate = path.join(dir, CONFIG_DIRNAME);
341
424
  try {
342
- await access(candidate);
343
- if (normalizeForCompare(await realpathOrSelf(candidate)) === userConfigKey) {
425
+ const st = await stat(candidate);
426
+ if (!st.isDirectory()) {
427
+ log("debug", "Skipping a .yaw-mcp that exists but is not a directory", { candidate });
428
+ } else if (normalizeForCompare(await realpathOrSelf(candidate)) === userConfigKey) {
344
429
  log("debug", "Skipping a .yaw-mcp/ that resolves to the user-global config dir", { candidate });
345
- } else if (boundedByHome || await ownedByCurrentUser(candidate)) {
430
+ } else if (boundedByHome || ownedByCurrentUser(st, env)) {
346
431
  return candidate;
347
432
  } else {
348
433
  if (!warnedUntrustedDirs.has(candidate)) {
@@ -386,7 +471,10 @@ function specConstraint(spec) {
386
471
  }
387
472
  function isRegistrySpec(spec) {
388
473
  if (spec.includes(":") || /^[./~\\]/.test(spec)) return false;
389
- return /^(@[^/@\s]+\/)?[^./_@\s][^/@\s]*$/.test(packageName(spec));
474
+ const m = /^(?:@([^/]+)\/)?([^./_][^/]*)$/.exec(packageName(spec));
475
+ if (!m) return false;
476
+ const [, scope, name] = m;
477
+ return (scope === void 0 || encodeURIComponent(scope) === scope) && encodeURIComponent(name) === name;
390
478
  }
391
479
  function npxSpecIndex(args) {
392
480
  return args.findIndex((a) => a !== "-y" && a !== "--yes");
@@ -397,7 +485,7 @@ function npxSpec(args) {
397
485
  const spec = args[idx];
398
486
  return spec.startsWith("-") ? null : spec;
399
487
  }
400
- var MIN_OAM_VERSION = "0.12.1";
488
+ var MIN_OAM_VERSION = "0.13.1";
401
489
  var OAM_INSTALL_SH = "curl -fsSL https://oamjs.org/install.sh | sh";
402
490
  var OAM_INSTALL_PS1 = "irm https://oamjs.org/install.ps1 | iex";
403
491
  function oamInstallCommand(os) {
@@ -561,7 +649,11 @@ function spawnVersionProbe(bin) {
561
649
  try {
562
650
  child = spawn(bin, ["--version"], {
563
651
  stdio: ["ignore", "pipe", "ignore"],
564
- windowsHide: process.platform === "win32"
652
+ windowsHide: process.platform === "win32",
653
+ // oam is a binary yaw-mcp did not write; README promises the vault
654
+ // passphrase is stripped from every child yaw-mcp starts, and this
655
+ // probe was one of two spawns that still inherited process.env whole.
656
+ env: stripInternalSecretsFromEnv(process.env)
565
657
  });
566
658
  } catch (err) {
567
659
  reject(err);
@@ -616,7 +708,7 @@ async function probeOam(run = spawnVersionProbe) {
616
708
  return oamProbeInFlight;
617
709
  }
618
710
  async function probeOamUncached(run, generation) {
619
- if (oamProbeCache !== void 0) return oamProbeCache;
711
+ const explicit = Boolean(process.env.OAM_BIN);
620
712
  const bin = winNormalize(process.env.OAM_BIN || (process.platform === "win32" ? "oam.exe" : "oam"));
621
713
  const publish = (probe) => {
622
714
  if (generation === oamProbeGeneration) oamProbeCache = probe;
@@ -664,6 +756,7 @@ async function probeOamUncached(run, generation) {
664
756
  });
665
757
  } catch (err) {
666
758
  const code = err?.code;
759
+ const absent = code === "ENOENT" && !explicit;
667
760
  if (code === "ETIMEDOUT") {
668
761
  log("warn", "oam did not respond to --version in time; falling back to node for this process", {
669
762
  timeoutMs: OAM_PROBE_TIMEOUT_MS,
@@ -674,24 +767,22 @@ async function probeOamUncached(run, generation) {
674
767
  bin,
675
768
  error: err instanceof Error ? err.message : String(err)
676
769
  });
770
+ } else if (explicit) {
771
+ log("warn", "OAM_BIN points at a path that does not exist; falling back to node for this process", {
772
+ bin,
773
+ error: err instanceof Error ? err.message : String(err)
774
+ });
677
775
  }
678
776
  return publish({
679
777
  bin: null,
680
778
  binPath: null,
681
779
  version: null,
682
780
  belowMin: false,
683
- failure: code === "ENOENT" ? null : classifyProbeFailure(err),
684
- failureDetail: code === "ENOENT" ? null : err instanceof Error ? err.message : String(err)
781
+ failure: absent ? null : classifyProbeFailure(err),
782
+ failureDetail: absent ? null : err instanceof Error ? err.message : String(err)
685
783
  });
686
784
  }
687
785
  }
688
- function resetOamBinCache() {
689
- warnedOamUnavailable = false;
690
- oamProbeCache = void 0;
691
- oamProbeInFlight = void 0;
692
- oamProbeGeneration++;
693
- pinnedReported.clear();
694
- }
695
786
  var WIN_EXE_EXT = /\.(?:exe|cmd|bat)$/i;
696
787
  function nodeLaunchKind(command) {
697
788
  const base = (command.split(/[\\/]/).pop() ?? command).replace(WIN_EXE_EXT, "").toLowerCase();
@@ -724,7 +815,7 @@ function rewriteForOam(command, args, deps) {
724
815
  if (spec.startsWith("-")) {
725
816
  log("debug", "npx launch carries flags yaw-mcp does not parse; staying on npx instead of oam", {
726
817
  flag: spec,
727
- args
818
+ argc: args.length
728
819
  });
729
820
  return { command, args };
730
821
  }
@@ -759,6 +850,13 @@ function rewriteForOam(command, args, deps) {
759
850
  return { command, args };
760
851
  }
761
852
  var NPX_CACHE_MARKER = `${sep}_npx${sep}`;
853
+ function npxHashNodeModules(npxRoot) {
854
+ try {
855
+ return readdirSync(npxRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => join2(npxRoot, e.name, "node_modules"));
856
+ } catch {
857
+ return [];
858
+ }
859
+ }
762
860
  function npxCacheNodeModules(fromUrl = import.meta.url) {
763
861
  let here;
764
862
  try {
@@ -769,11 +867,7 @@ function npxCacheNodeModules(fromUrl = import.meta.url) {
769
867
  const idx = here.indexOf(NPX_CACHE_MARKER);
770
868
  if (idx === -1) return [];
771
869
  const npxRoot = here.slice(0, idx + NPX_CACHE_MARKER.length - sep.length);
772
- try {
773
- return readdirSync(npxRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => join2(npxRoot, e.name, "node_modules"));
774
- } catch {
775
- return [];
776
- }
870
+ return npxHashNodeModules(npxRoot);
777
871
  }
778
872
  function npmrcValue(raw) {
779
873
  const v = raw.trim();
@@ -817,12 +911,19 @@ function npmrcCache(file) {
817
911
  for (const line of text.split(/\r?\n/)) {
818
912
  const m = /^\s*cache\s*=(.*)$/.exec(line);
819
913
  if (!m) continue;
820
- const value = npmrcValue(m[1]);
914
+ const value = expandNpmrcEnv(npmrcValue(m[1]));
821
915
  if (!value) continue;
822
916
  last = value.startsWith("~/") ? join2(homedir3(), value.slice(2)) : value;
823
917
  }
824
918
  return last;
825
919
  }
920
+ function expandNpmrcEnv(value, env = process.env) {
921
+ return value.replace(/(\\*)\$\{([^${}]+)\}/g, (orig, esc, name) => {
922
+ if (esc.length % 2 === 1) return orig.slice((esc.length + 1) / 2);
923
+ const val = env[name];
924
+ return esc.slice(esc.length / 2) + (val === void 0 ? `\${${name}}` : val);
925
+ });
926
+ }
826
927
  var npmCacheDirCache = /* @__PURE__ */ new Map();
827
928
  function npmCacheDir(fromUrl = import.meta.url) {
828
929
  const cached = npmCacheDirCache.get(fromUrl);
@@ -831,11 +932,9 @@ function npmCacheDir(fromUrl = import.meta.url) {
831
932
  npmCacheDirCache.set(fromUrl, resolved);
832
933
  return resolved;
833
934
  }
834
- function resetNpmCacheDir() {
835
- npmCacheDirCache.clear();
836
- }
837
935
  function resolveNpmCacheDir(fromUrl) {
838
- const fromEnv = process.env.npm_config_cache;
936
+ const envKey = Object.keys(process.env).find((k) => /^npm_config_cache$/i.test(k));
937
+ const fromEnv = envKey === void 0 ? void 0 : process.env[envKey];
839
938
  if (fromEnv) return fromEnv;
840
939
  const candidates = [join2(homedir3(), ".npmrc")];
841
940
  for (const nodeModules of ownNodeModules(fromUrl)) {
@@ -864,12 +963,7 @@ function resolveNpmCacheDir(fromUrl) {
864
963
  }
865
964
  function npmCacheNpxNodeModules(cacheDir2) {
866
965
  if (!cacheDir2) return [];
867
- const npxRoot = join2(cacheDir2, "_npx");
868
- try {
869
- return readdirSync(npxRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => join2(npxRoot, e.name, "node_modules"));
870
- } catch {
871
- return [];
872
- }
966
+ return npxHashNodeModules(join2(cacheDir2, "_npx"));
873
967
  }
874
968
  function ownNodeModules(fromUrl = import.meta.url) {
875
969
  let here;
@@ -886,21 +980,25 @@ function ownNodeModules(fromUrl = import.meta.url) {
886
980
  function packageEntry(pkgDir, pkg) {
887
981
  const pjPath = join2(pkgDir, "package.json");
888
982
  if (!existsSync(pjPath)) return null;
889
- let j;
983
+ let parsed;
890
984
  try {
891
- j = JSON.parse(readFileSync(pjPath, "utf8"));
985
+ parsed = JSON.parse(readFileSync(pjPath, "utf8"));
892
986
  } catch {
893
987
  return null;
894
988
  }
989
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
990
+ const j = parsed;
895
991
  let rel;
896
992
  if (typeof j.bin === "string") {
897
993
  rel = j.bin;
898
994
  } else if (j.bin && typeof j.bin === "object") {
995
+ const bins = j.bin;
996
+ const own = (key) => typeof key === "string" && Object.hasOwn(bins, key) ? bins[key] : void 0;
899
997
  const unscoped = pkg.slice(pkg.lastIndexOf("/") + 1);
900
- rel = j.bin[unscoped] ?? (j.name ? j.bin[j.name] : void 0) ?? Object.values(j.bin)[0];
998
+ rel = own(unscoped) ?? own(j.name) ?? Object.values(bins)[0];
901
999
  }
902
1000
  if (!rel && typeof j.main === "string") rel = j.main;
903
- if (!rel) return null;
1001
+ if (typeof rel !== "string" || rel.length === 0) return null;
904
1002
  const entry = isAbsolute2(rel) ? rel : join2(pkgDir, rel);
905
1003
  if (!existsSync(entry)) return null;
906
1004
  return {
@@ -972,9 +1070,6 @@ var REFRESH_NOTE = {
972
1070
  "npx-cache": "then Ctrl-C -- the cache is refreshed before the server starts"
973
1071
  };
974
1072
  var pinnedReported = /* @__PURE__ */ new Set();
975
- function resetPinnedSidecarLog() {
976
- pinnedReported.clear();
977
- }
978
1073
  function notePinnedSidecar(pkg, version, source, from) {
979
1074
  if (pinnedReported.has(pkg)) return;
980
1075
  pinnedReported.add(pkg);
@@ -1062,23 +1157,836 @@ function isOamLaunch(command, args = []) {
1062
1157
  return false;
1063
1158
  }
1064
1159
 
1160
+ // src/upgrade-cmd.ts
1161
+ var POSIX_GLOBAL_LIB_PREFIX = /^(?:[A-Za-z]:)?(?:\/usr(?:\/local)?|\/opt\/[^/]+)\/lib\/node_modules\/@yawlabs\/mcp\//;
1162
+ 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\//;
1163
+ var UPGRADE_USAGE = `Usage: yaw-mcp upgrade [--run] [--json]
1164
+
1165
+ Show (or execute) the command to upgrade @yawlabs/mcp to the latest version.
1166
+
1167
+ --run Run the upgrade in place (global npm, pnpm, bun, and local npm
1168
+ installs). No-op for npx installs -- they always fetch the latest.
1169
+ --json Emit a machine-readable snapshot ({ current, latest, stale,
1170
+ method, command, cwd }) instead of prose. "cwd" is the directory
1171
+ "command" must run IN -- the package-tree root for a
1172
+ local-node-modules install, null for every other method (the
1173
+ command can run anywhere). Running a local install's command from
1174
+ the wrong directory creates a stray package.json + node_modules
1175
+ there instead of upgrading the tree.
1176
+ NOTE: --json is a report-only snapshot; it never spawns an upgrade
1177
+ even when combined with --run, and exits 1 whenever "stale" is
1178
+ true. Use --run without --json to actually perform the upgrade.`;
1179
+ function parseUpgradeArgs(argv) {
1180
+ const opts = {};
1181
+ for (const a of argv) {
1182
+ if (a === "--run") opts.run = true;
1183
+ else if (a === "--json") opts.json = true;
1184
+ else if (a === "--help" || a === "-h") return { ok: false, error: UPGRADE_USAGE, help: true };
1185
+ else return { ok: false, error: `yaw-mcp upgrade: unknown argument "${a}"
1186
+
1187
+ ${UPGRADE_USAGE}` };
1188
+ }
1189
+ return { ok: true, options: opts };
1190
+ }
1191
+ function detectInstallMethod(argvPath, realpath2 = realpathSync, resolveWhen = ["unknown"]) {
1192
+ if (!argvPath) return "unknown";
1193
+ const literal = classifyEntrypoint(argvPath);
1194
+ if (!resolveWhen.includes(literal)) return literal;
1195
+ let resolved;
1196
+ try {
1197
+ resolved = realpath2(argvPath);
1198
+ } catch {
1199
+ return literal;
1200
+ }
1201
+ return resolved === argvPath ? literal : classifyEntrypoint(resolved);
1202
+ }
1203
+ function classifyEntrypoint(argvPath) {
1204
+ const normalized = argvPath.replace(/\\/g, "/");
1205
+ if (/\/_npx\/[0-9a-f]+\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "npx";
1206
+ if (/\/app\.asar\.unpacked\//.test(normalized)) return "bundled-app";
1207
+ if (/\/npm\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "global-npm";
1208
+ if (POSIX_GLOBAL_LIB_PREFIX.test(normalized)) return "global-npm";
1209
+ if (MANAGED_NODE_LIB_PREFIX.test(normalized)) return "global-npm";
1210
+ if (/\/AppData\/Roaming\/npm\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "global-npm";
1211
+ if (/\/bin\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "global-npm";
1212
+ if (/\/pnpm\/global\/\d+\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "pnpm-global";
1213
+ if (/\/\.bun\/install\/global\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "bun-global";
1214
+ if (/\/node_modules\/@yawlabs\/mcp\//.test(normalized)) return "local-node-modules";
1215
+ if (/\/(yaw-mcp|mcph|mcp)\/(dist|src)\//.test(normalized)) return "dev-checkout";
1216
+ return "unknown";
1217
+ }
1218
+ function localInstallRoot(argvPath) {
1219
+ if (!argvPath) return null;
1220
+ const idx = argvPath.replace(/\\/g, "/").indexOf("/node_modules/");
1221
+ return idx > 0 ? argvPath.slice(0, idx) : null;
1222
+ }
1223
+ function runningPackageDir(argvPath, realpath2 = realpathSync) {
1224
+ if (!argvPath) return null;
1225
+ const literal = packageDirOf(argvPath);
1226
+ if (literal !== null) return literal;
1227
+ try {
1228
+ return packageDirOf(realpath2(argvPath));
1229
+ } catch {
1230
+ return null;
1231
+ }
1232
+ }
1233
+ function packageDirOf(p) {
1234
+ const marker = "/node_modules/@yawlabs/mcp/";
1235
+ const idx = p.replace(/\\/g, "/").lastIndexOf(marker);
1236
+ return idx === -1 ? null : p.slice(0, idx + marker.length - 1);
1237
+ }
1238
+ function defaultInstalledVersion(pkgDir) {
1239
+ if (process.env.VITEST) return null;
1240
+ try {
1241
+ const parsed = JSON.parse(readFileSync2(join3(pkgDir, "package.json"), "utf8"));
1242
+ return typeof parsed.version === "string" ? parsed.version : null;
1243
+ } catch {
1244
+ return null;
1245
+ }
1246
+ }
1247
+ function killProcessTree(child, platform = process.platform, spawnImpl = spawn2) {
1248
+ if (platform === "win32" && child.pid !== void 0) {
1249
+ try {
1250
+ spawnImpl("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore" }).on("error", () => {
1251
+ });
1252
+ } catch {
1253
+ }
1254
+ }
1255
+ child.kill();
1256
+ }
1257
+ async function npmGlobalPrefix(spawnImpl) {
1258
+ if (process.env.VITEST && !spawnImpl) return null;
1259
+ const spawnFn = spawnImpl ?? spawn2;
1260
+ return new Promise((resolve2) => {
1261
+ const child = spawnFn("npm", ["prefix", "-g"], {
1262
+ shell: process.platform === "win32",
1263
+ stdio: ["ignore", "pipe", "ignore"],
1264
+ // Even a read-only `npm prefix -g` is an npm invocation: yaw-mcp's own
1265
+ // secrets do not ride into it. See internal-secret-env.ts.
1266
+ env: stripInternalSecretsFromEnv(process.env)
1267
+ });
1268
+ let out = "";
1269
+ const timer = setTimeout(() => {
1270
+ killProcessTree(child);
1271
+ resolve2(null);
1272
+ }, 3e3);
1273
+ child.stdout?.on("data", (d) => {
1274
+ out += String(d);
1275
+ });
1276
+ child.on("close", (code) => {
1277
+ clearTimeout(timer);
1278
+ resolve2(code === 0 && out.trim() ? out.trim() : null);
1279
+ });
1280
+ child.on("error", () => {
1281
+ clearTimeout(timer);
1282
+ resolve2(null);
1283
+ });
1284
+ });
1285
+ }
1286
+ function comparablePath(p) {
1287
+ let real = p;
1288
+ try {
1289
+ real = realpathSync(p);
1290
+ } catch {
1291
+ }
1292
+ const normalized = real.replace(/\\/g, "/");
1293
+ return process.platform === "win32" ? normalized.toLowerCase() : normalized;
1294
+ }
1295
+ async function refineInstallMethod(method, argvPath, npmPrefix = npmGlobalPrefix) {
1296
+ if (method !== "local-node-modules" && method !== "unknown") return method;
1297
+ if (!argvPath) return method;
1298
+ const prefix = await npmPrefix();
1299
+ if (!prefix) return method;
1300
+ const entry = comparablePath(argvPath);
1301
+ const pfx = comparablePath(prefix);
1302
+ if (entry.startsWith(`${pfx}/node_modules/`) || entry.startsWith(`${pfx}/lib/node_modules/`)) {
1303
+ return "global-npm";
1304
+ }
1305
+ return method;
1306
+ }
1307
+ var UPGRADE_PACKAGE_SPEC = "@yawlabs/mcp@latest";
1308
+ var UPGRADE_COMMANDS = {
1309
+ "global-npm": { cmd: "npm", args: ["install", "-g", UPGRADE_PACKAGE_SPEC] },
1310
+ "pnpm-global": { cmd: "pnpm", args: ["add", "-g", UPGRADE_PACKAGE_SPEC] },
1311
+ "bun-global": { cmd: "bun", args: ["add", "-g", UPGRADE_PACKAGE_SPEC] },
1312
+ "local-node-modules": { cmd: "npm", args: ["install", UPGRADE_PACKAGE_SPEC] },
1313
+ npx: null,
1314
+ "bundled-app": null,
1315
+ "dev-checkout": null,
1316
+ binary: null,
1317
+ unknown: null
1318
+ };
1319
+ var GLOBAL_UPGRADE_METHODS = ["global-npm", "pnpm-global", "bun-global"];
1320
+ function upgradeSpawnSpec(method, prefixArg = null) {
1321
+ const base = UPGRADE_COMMANDS[method];
1322
+ if (base === null) return null;
1323
+ const args = [...base.args];
1324
+ if (method === "global-npm" && prefixArg !== null) args.splice(args.length - 1, 0, "--prefix", prefixArg);
1325
+ return { cmd: base.cmd, args };
1326
+ }
1327
+ function upgradeCommandLine(method) {
1328
+ const spec = upgradeSpawnSpec(method);
1329
+ return spec === null ? null : [spec.cmd, ...spec.args].join(" ");
1330
+ }
1331
+ 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.`;
1332
+ function globalUpgradeCommandLineForTool(tool) {
1333
+ const method = GLOBAL_UPGRADE_METHODS.find((m) => UPGRADE_COMMANDS[m]?.cmd === tool);
1334
+ return method === void 0 ? null : upgradeCommandLine(method);
1335
+ }
1336
+ function buildUpgradePlan(input) {
1337
+ const { current, latest, method } = input;
1338
+ const stripV = (s) => s.startsWith("v") ? s.slice(1) : s;
1339
+ const stale = latest !== null && current !== "dev" && compareVersions(stripV(current), stripV(latest)) < 0;
1340
+ let command;
1341
+ switch (method) {
1342
+ case "npx":
1343
+ command = null;
1344
+ break;
1345
+ case "bundled-app":
1346
+ command = null;
1347
+ break;
1348
+ case "binary":
1349
+ command = null;
1350
+ break;
1351
+ case "dev-checkout":
1352
+ command = "git pull && npm run build";
1353
+ break;
1354
+ case "unknown":
1355
+ command = upgradeCommandLine("global-npm");
1356
+ break;
1357
+ default:
1358
+ command = upgradeCommandLine(method);
1359
+ break;
1360
+ }
1361
+ return { current, latest, stale, method, command };
1362
+ }
1363
+ var REGISTRY_FETCH_TIMEOUT_MS = 3e3;
1364
+ async function fetchLatestVersion(opts = {}) {
1365
+ if (opts.override) {
1366
+ try {
1367
+ return await opts.override();
1368
+ } catch {
1369
+ return null;
1370
+ }
1371
+ }
1372
+ const ac = new AbortController();
1373
+ const timer = setTimeout(() => ac.abort(), opts.timeoutMs ?? REGISTRY_FETCH_TIMEOUT_MS);
1374
+ try {
1375
+ const res = await fetch("https://registry.npmjs.org/@yawlabs/mcp/latest", {
1376
+ signal: ac.signal,
1377
+ headers: { accept: "application/json" }
1378
+ });
1379
+ if (!res.ok) return null;
1380
+ const body = await res.json();
1381
+ return typeof body.version === "string" ? body.version : null;
1382
+ } catch {
1383
+ return null;
1384
+ } finally {
1385
+ clearTimeout(timer);
1386
+ }
1387
+ }
1388
+ async function probeOamQuietly() {
1389
+ const prev = process.env.LOG_LEVEL;
1390
+ process.env.LOG_LEVEL = "error";
1391
+ try {
1392
+ return await probeOam();
1393
+ } finally {
1394
+ if (prev === void 0) delete process.env.LOG_LEVEL;
1395
+ else process.env.LOG_LEVEL = prev;
1396
+ }
1397
+ }
1398
+ async function oamFloorLines(probe) {
1399
+ if (!probe && process.env.VITEST) return [];
1400
+ try {
1401
+ const oam = probe ? await probe() : await probeOamQuietly();
1402
+ if (!oam.belowMin) return [];
1403
+ return [
1404
+ "",
1405
+ `oam: v${oam.version ?? "unknown"} is installed but below the v${MIN_OAM_VERSION} floor yaw-mcp`,
1406
+ " requires, so MCP sidecars run on node instead of oam. Update it:",
1407
+ "",
1408
+ " oam self-update"
1409
+ ];
1410
+ } catch {
1411
+ return [];
1412
+ }
1413
+ }
1414
+ async function defaultRunningPrefix(argvPath) {
1415
+ if (process.env.VITEST) return null;
1416
+ const { detectRunningInstallPrefix: detectRunningInstallPrefix2 } = await import("./auto-upgrade-OHFS4H24.js");
1417
+ return detectRunningInstallPrefix2(argvPath);
1418
+ }
1419
+ async function defaultSpawn(cmd, args, cwd) {
1420
+ return new Promise((resolve2) => {
1421
+ const child = spawn2(cmd, args, {
1422
+ stdio: "inherit",
1423
+ shell: process.platform === "win32",
1424
+ cwd,
1425
+ // yaw-mcp's own secrets stay out of the install: npm runs every
1426
+ // dependency's pre/postinstall with this env, and a passphrase parked
1427
+ // in yaw-mcp's env block (where README says to put it) must not reach
1428
+ // them. See internal-secret-env.ts.
1429
+ env: stripInternalSecretsFromEnv(process.env)
1430
+ });
1431
+ child.on("close", (code) => resolve2(typeof code === "number" ? code : 1));
1432
+ child.on("error", () => resolve2(1));
1433
+ });
1434
+ }
1435
+ async function detectSea() {
1436
+ if (process.env.ELECTRON_RUN_AS_NODE) return false;
1437
+ const exe = process.execPath.replace(/\\/g, "/").split("/").pop()?.toLowerCase() ?? "";
1438
+ if (exe === "node" || exe === "node.exe") return false;
1439
+ try {
1440
+ const sea = await import("sea");
1441
+ return typeof sea.isSea === "function" && sea.isSea() === true;
1442
+ } catch {
1443
+ return false;
1444
+ }
1445
+ }
1446
+ async function runUpgrade(opts = {}) {
1447
+ const write = opts.out ?? ((s) => process.stdout.write(s));
1448
+ const writeErr = opts.err ?? ((s) => process.stderr.write(s));
1449
+ const lines = [];
1450
+ const print = (s = "") => {
1451
+ lines.push(s);
1452
+ write(`${s}
1453
+ `);
1454
+ };
1455
+ const printErr = (s) => {
1456
+ lines.push(s);
1457
+ writeErr(`${s}
1458
+ `);
1459
+ };
1460
+ const fetcher = opts.fetchLatest ?? fetchLatestVersion;
1461
+ const current = opts.currentVersion ?? readCurrentVersion();
1462
+ const argvPath = opts.argvPath ?? process.argv[1];
1463
+ const sea = opts.isSea ? opts.isSea() : await detectSea();
1464
+ const method = sea ? "binary" : await refineInstallMethod(detectInstallMethod(argvPath), argvPath, opts.npmPrefix);
1465
+ let latest;
1466
+ try {
1467
+ latest = await fetcher();
1468
+ } catch {
1469
+ latest = null;
1470
+ }
1471
+ const plan = buildUpgradePlan({ current, latest, method });
1472
+ let globalPrefixArg = null;
1473
+ let suggestedCommand = plan.command;
1474
+ if (method === "global-npm") {
1475
+ const rawPrefix = await (opts.runningPrefix ?? defaultRunningPrefix)(argvPath);
1476
+ if (rawPrefix !== null) {
1477
+ const { quoteArgForDisplay: quoteArgForDisplay2, quoteShellArgIfNeeded: quoteShellArgIfNeeded2 } = await import("./auto-upgrade-OHFS4H24.js");
1478
+ const spawnForm = quoteShellArgIfNeeded2(rawPrefix, opts.platform);
1479
+ const displayForm = quoteArgForDisplay2(rawPrefix, opts.platform);
1480
+ if (spawnForm !== null && displayForm !== null) {
1481
+ globalPrefixArg = spawnForm;
1482
+ const spec2 = upgradeSpawnSpec("global-npm", displayForm);
1483
+ suggestedCommand = spec2 === null ? null : [spec2.cmd, ...spec2.args].join(" ");
1484
+ }
1485
+ }
1486
+ }
1487
+ const installRoot = method === "local-node-modules" ? localInstallRoot(argvPath) : null;
1488
+ if (opts.json) {
1489
+ print(JSON.stringify({ ...plan, command: suggestedCommand, cwd: installRoot }, null, 2));
1490
+ return { exitCode: plan.stale ? 1 : 0, lines };
1491
+ }
1492
+ if (latest === null) {
1493
+ print("yaw-mcp upgrade: couldn't reach the npm registry (offline? firewall?).");
1494
+ if (suggestedCommand) {
1495
+ print("When you're back online, run:");
1496
+ print("");
1497
+ if (installRoot) {
1498
+ print(`in ${installRoot}:`);
1499
+ }
1500
+ print(` ${suggestedCommand}`);
1501
+ } else if (method === "bundled-app") {
1502
+ print("This copy of yaw-mcp ships inside Yaw Terminal and updates with the app -- nothing to run.");
1503
+ } else if (method === "binary") {
1504
+ print(`yaw-mcp is a standalone binary; ${BINARY_RETIRED_HINT}`);
1505
+ } else {
1506
+ print("Your install uses `npx -y` -- just restart the MCP client when you're back online.");
1507
+ }
1508
+ for (const line of await oamFloorLines(opts.oamProbe)) print(line);
1509
+ return { exitCode: 0, lines };
1510
+ }
1511
+ print(`Current: ${current}`);
1512
+ print(`Latest: ${latest}`);
1513
+ print(`Install: ${method}`);
1514
+ for (const line of await oamFloorLines(opts.oamProbe)) print(line);
1515
+ if (!plan.stale) {
1516
+ print("");
1517
+ print("OK: You're on the latest version -- nothing to do.");
1518
+ return { exitCode: 0, lines };
1519
+ }
1520
+ print("");
1521
+ if (method === "npx") {
1522
+ print("Your install uses `npx -y` -- restart the MCP client and it will fetch the new version.");
1523
+ return { exitCode: 0, lines };
1524
+ }
1525
+ if (method === "bundled-app") {
1526
+ print("This copy of yaw-mcp ships inside Yaw Terminal and updates with the app --");
1527
+ print("there is nothing to run here. Update Yaw Terminal to get the new version.");
1528
+ return { exitCode: 0, lines };
1529
+ }
1530
+ if (method === "binary") {
1531
+ const emit = opts.run ? printErr : print;
1532
+ emit("yaw-mcp is running as a standalone binary -- manual upgrade required.");
1533
+ emit(`There's no package manager to upgrade it, and \`--run\` can't automate this: ${BINARY_RETIRED_HINT}`);
1534
+ return { exitCode: opts.run ? 2 : 1, lines };
1535
+ }
1536
+ const spec = upgradeSpawnSpec(method, globalPrefixArg);
1537
+ const runSpec = spec === null ? null : method === "local-node-modules" ? installRoot !== null ? { ...spec, cwd: installRoot } : null : spec;
1538
+ const commandLine = method === "global-npm" ? suggestedCommand : runSpec ? [runSpec.cmd, ...runSpec.args].join(" ") : plan.command;
1539
+ if (!opts.run) {
1540
+ if (runSpec) {
1541
+ print("Run `yaw-mcp upgrade --run` to upgrade in place, or run it yourself:");
1542
+ } else {
1543
+ print("Manual upgrade required (--run can't safely automate this install method). Run it yourself:");
1544
+ }
1545
+ print("");
1546
+ if (installRoot) {
1547
+ print(`in ${installRoot}:`);
1548
+ }
1549
+ print(` ${commandLine}`);
1550
+ return { exitCode: 1, lines };
1551
+ }
1552
+ if (!runSpec) {
1553
+ printErr(
1554
+ `yaw-mcp upgrade --run: a "${method}" install can't be upgraded automatically (manual upgrade required). Run it yourself:`
1555
+ );
1556
+ printErr("");
1557
+ printErr(` ${commandLine}`);
1558
+ return { exitCode: 2, lines };
1559
+ }
1560
+ const runner = opts.spawnImpl ?? defaultSpawn;
1561
+ if (runSpec.cwd) {
1562
+ print(`Running in ${runSpec.cwd}:`);
1563
+ } else {
1564
+ print("Running:");
1565
+ }
1566
+ print(` ${commandLine}`);
1567
+ print("");
1568
+ const code = await runner(runSpec.cmd, runSpec.args, runSpec.cwd);
1569
+ if (code === 0) {
1570
+ print("");
1571
+ print(`OK: Upgraded @yawlabs/mcp to ${latest}`);
1572
+ const pkgDir = runningPackageDir(argvPath);
1573
+ const running = pkgDir === null ? null : await (opts.installedVersion ?? defaultInstalledVersion)(pkgDir);
1574
+ const bare = (s) => s.startsWith("v") ? s.slice(1) : s;
1575
+ if (running !== null && compareVersions(bare(running), bare(latest)) < 0) {
1576
+ printErr("");
1577
+ printErr(`WARNING: the copy this command ran from still reports ${running}, not ${latest}:`);
1578
+ printErr(` ${pkgDir}`);
1579
+ printErr(
1580
+ "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)."
1581
+ );
1582
+ }
1583
+ return { exitCode: 0, lines };
1584
+ }
1585
+ printErr(`yaw-mcp upgrade: ${runSpec.cmd} exited ${code}. Try running the command yourself:`);
1586
+ printErr("");
1587
+ if (installRoot) {
1588
+ printErr(`in ${installRoot}:`);
1589
+ }
1590
+ printErr(` ${commandLine}`);
1591
+ return { exitCode: 3, lines };
1592
+ }
1593
+ function readCurrentVersion() {
1594
+ return true ? "0.80.0" : "dev";
1595
+ }
1596
+
1597
+ // src/auto-upgrade.ts
1598
+ function quoteShellArgIfNeeded(arg, platform = process.platform) {
1599
+ if (platform !== "win32") return arg;
1600
+ if (/[\r\n\0"%]/.test(arg)) return null;
1601
+ if (!/[\s&|<>^]/.test(arg)) return arg;
1602
+ return `"${arg}"`;
1603
+ }
1604
+ function quoteArgForDisplay(arg, platform = process.platform) {
1605
+ if (platform === "win32") return quoteShellArgIfNeeded(arg, platform);
1606
+ if (/^[A-Za-z0-9_\-./+,:@=]+$/.test(arg)) return arg;
1607
+ return `'${arg.replace(/'/g, "'\\''")}'`;
1608
+ }
1609
+ function detectRunningInstallPrefix(argvPath) {
1610
+ if (!argvPath) return null;
1611
+ let resolved;
1612
+ try {
1613
+ resolved = realpathSync2(argvPath);
1614
+ } catch {
1615
+ return null;
1616
+ }
1617
+ const dir = dirname2(resolved);
1618
+ const idx = dir.lastIndexOf(`${sep2}node_modules${sep2}`);
1619
+ if (idx === -1) return null;
1620
+ const candidate = dir.slice(0, idx);
1621
+ if (candidate.endsWith(`${sep2}lib`)) return candidate.slice(0, -`${sep2}lib`.length);
1622
+ return candidate;
1623
+ }
1624
+ async function compareWithNpmPrefix(detected, probe = npmGlobalPrefix) {
1625
+ const npmPrefix = await probe();
1626
+ if (!npmPrefix?.trim()) return;
1627
+ if (comparablePath(npmPrefix.trim()) === comparablePath(detected)) return;
1628
+ log(
1629
+ "warn",
1630
+ "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",
1631
+ { running: detected, npmPrefix }
1632
+ );
1633
+ }
1634
+ var UPGRADE_LOCK_NAME = ".yaw-mcp-upgrade.lock";
1635
+ var UPGRADE_LOCK_STALE_MS = 10 * 60 * 1e3;
1636
+ var UPGRADE_LOCK_FUTURE_SKEW_MS = 5 * 1e3;
1637
+ function lockHolderAlive(lockPath) {
1638
+ let pid;
1639
+ try {
1640
+ pid = Number.parseInt(readFileSync3(lockPath, "utf8").trim(), 10);
1641
+ } catch {
1642
+ return true;
1643
+ }
1644
+ if (!Number.isInteger(pid) || pid <= 0) return true;
1645
+ if (pid === process.pid) return true;
1646
+ try {
1647
+ process.kill(pid, 0);
1648
+ return true;
1649
+ } catch (err) {
1650
+ return err.code !== "ESRCH";
1651
+ }
1652
+ }
1653
+ function acquireUpgradeLock(dir, lockName = UPGRADE_LOCK_NAME, opts = {}) {
1654
+ const lockPath = join4(dir, lockName);
1655
+ const holderAlive = (path2) => opts.probeHolder ? lockHolderAlive(path2) : true;
1656
+ const mine = String(process.pid);
1657
+ const take = () => {
1658
+ try {
1659
+ const fd = openSync(lockPath, "wx");
1660
+ try {
1661
+ writeSync(fd, `${mine}
1662
+ `);
1663
+ } finally {
1664
+ closeSync(fd);
1665
+ }
1666
+ let released = false;
1667
+ return () => {
1668
+ if (released) return;
1669
+ released = true;
1670
+ try {
1671
+ if (readFileSync3(lockPath, "utf8").trim() !== mine) return;
1672
+ unlinkSync(lockPath);
1673
+ } catch {
1674
+ }
1675
+ };
1676
+ } catch (err) {
1677
+ if (err.code === "EEXIST") return void 0;
1678
+ return () => {
1679
+ };
1680
+ }
1681
+ };
1682
+ const first = take();
1683
+ if (first !== void 0) return first;
1684
+ const isLive = (ageMs2) => ageMs2 > -UPGRADE_LOCK_FUTURE_SKEW_MS && ageMs2 < UPGRADE_LOCK_STALE_MS;
1685
+ let ageMs;
1686
+ try {
1687
+ ageMs = Date.now() - statSync2(lockPath).mtimeMs;
1688
+ } catch {
1689
+ ageMs = UPGRADE_LOCK_STALE_MS;
1690
+ }
1691
+ if (isLive(ageMs) && holderAlive(lockPath)) return null;
1692
+ const stolenPath = `${lockPath}.stale-${process.pid}`;
1693
+ try {
1694
+ renameSync(lockPath, stolenPath);
1695
+ } catch (err) {
1696
+ if (err.code !== "ENOENT") return null;
1697
+ const retry = take();
1698
+ return retry === void 0 ? null : retry;
1699
+ }
1700
+ let stoleLive = false;
1701
+ try {
1702
+ stoleLive = isLive(Date.now() - statSync2(stolenPath).mtimeMs) && holderAlive(stolenPath);
1703
+ } catch {
1704
+ }
1705
+ if (stoleLive) {
1706
+ try {
1707
+ const holder = readFileSync3(stolenPath, "utf8");
1708
+ const fd = openSync(lockPath, "wx");
1709
+ try {
1710
+ writeSync(fd, holder);
1711
+ } finally {
1712
+ closeSync(fd);
1713
+ }
1714
+ } catch {
1715
+ }
1716
+ try {
1717
+ unlinkSync(stolenPath);
1718
+ } catch {
1719
+ }
1720
+ return null;
1721
+ }
1722
+ try {
1723
+ unlinkSync(stolenPath);
1724
+ } catch {
1725
+ }
1726
+ const second = take();
1727
+ return second === void 0 ? null : second;
1728
+ }
1729
+ function defaultAcquireLock(dir, lockName) {
1730
+ if (process.env.VITEST) return () => {
1731
+ };
1732
+ return acquireUpgradeLock(dir, lockName);
1733
+ }
1734
+ var UPGRADE_CHECK_INTERVAL_MS = 60 * 60 * 1e3;
1735
+ var UPGRADE_ATTEMPT_COOLDOWN_MS = 6 * 60 * 60 * 1e3;
1736
+ function readMemo(path2) {
1737
+ let parsed;
1738
+ try {
1739
+ parsed = JSON.parse(readFileSync3(path2, "utf8"));
1740
+ } catch {
1741
+ return null;
1742
+ }
1743
+ if (typeof parsed !== "object" || parsed === null) return null;
1744
+ const memo = parsed;
1745
+ if (typeof memo.at !== "number") return null;
1746
+ const ageMs = Date.now() - memo.at;
1747
+ return ageMs < -UPGRADE_LOCK_FUTURE_SKEW_MS ? null : { ageMs, memo };
1748
+ }
1749
+ function writeMemo(path2, fields) {
1750
+ try {
1751
+ writeFileSync(path2, `${JSON.stringify({ at: Date.now(), ...fields })}
1752
+ `);
1753
+ } catch {
1754
+ }
1755
+ }
1756
+ function checkMemoPath() {
1757
+ return join4(tmpdir(), `.yaw-mcp-upgrade-check-${process.getuid?.() ?? "win"}.json`);
1758
+ }
1759
+ function readCheckMemo(path2) {
1760
+ const read = readMemo(path2);
1761
+ if (read === null || read.ageMs >= UPGRADE_CHECK_INTERVAL_MS) return null;
1762
+ const latest = read.memo.latest;
1763
+ if (latest !== null && typeof latest !== "string") return null;
1764
+ return { latest };
1765
+ }
1766
+ function writeCheckMemo(path2, latest) {
1767
+ writeMemo(path2, { latest });
1768
+ }
1769
+ function attemptMemoPath(dir, lockName) {
1770
+ return join4(dir, `${lockName}.attempt`);
1771
+ }
1772
+ function attemptMemoFallbackPath(dir, lockName, fallbackDir) {
1773
+ const scope = createHash("sha256").update(`${dir}\0${lockName}`).digest("hex").slice(0, 16);
1774
+ return join4(fallbackDir, `.yaw-mcp-upgrade-attempt-${process.getuid?.() ?? "win"}-${scope}.json`);
1775
+ }
1776
+ function defaultCheckedRecently() {
1777
+ if (process.env.VITEST) return null;
1778
+ return readCheckMemo(checkMemoPath());
1779
+ }
1780
+ function defaultRecordCheck(latest) {
1781
+ if (process.env.VITEST) return;
1782
+ writeCheckMemo(checkMemoPath(), latest);
1783
+ }
1784
+ function defaultAttemptedRecently(dir, lockName, version) {
1785
+ if (process.env.VITEST) return false;
1786
+ return attemptedRecentlyAt(dir, lockName, version);
1787
+ }
1788
+ function defaultRecordAttempt(dir, lockName, version) {
1789
+ if (process.env.VITEST) return;
1790
+ recordAttemptAt(dir, lockName, version);
1791
+ }
1792
+ function attemptedRecentlyAt(dir, lockName, version, fallbackDir = tmpdir()) {
1793
+ const recent = (read) => read !== null && read.memo.version === version && read.ageMs < UPGRADE_ATTEMPT_COOLDOWN_MS;
1794
+ if (recent(readMemo(attemptMemoPath(dir, lockName)))) return true;
1795
+ return recent(readMemo(attemptMemoFallbackPath(dir, lockName, fallbackDir)));
1796
+ }
1797
+ function recordAttemptAt(dir, lockName, version, fallbackDir = tmpdir()) {
1798
+ const primary = attemptMemoPath(dir, lockName);
1799
+ try {
1800
+ writeFileSync(primary, `${JSON.stringify({ at: Date.now(), version })}
1801
+ `);
1802
+ return;
1803
+ } catch {
1804
+ }
1805
+ writeMemo(attemptMemoFallbackPath(dir, lockName, fallbackDir), { version });
1806
+ }
1807
+ function defaultSpawn2(cmd, args, onDone = () => {
1808
+ }) {
1809
+ let errorFired = false;
1810
+ let released = false;
1811
+ const finish = () => {
1812
+ if (released) return;
1813
+ released = true;
1814
+ onDone();
1815
+ };
1816
+ const correctiveCmd = globalUpgradeCommandLineForTool(cmd);
1817
+ const child = spawn3(cmd, args, {
1818
+ stdio: "ignore",
1819
+ // yaw-mcp's own secrets stay out of the install. npm runs every
1820
+ // dependency's pre/postinstall with this env, and README tells the user to
1821
+ // put YAW_MCP_VAULT_PASSPHRASE in yaw-mcp's env block precisely because
1822
+ // "yaw-mcp strips its own secrets from every child env" -- a promise the
1823
+ // upstream spawn kept and this one, spawning with the full inherited
1824
+ // process.env, silently did not: a compromised transitive dependency's
1825
+ // install script plus ~/.yaw-mcp/secrets.json was the whole vault.
1826
+ env: stripInternalSecretsFromEnv(process.env),
1827
+ // Not detached, so the install shares yaw-mcp's process group and an MCP
1828
+ // client that tears down the whole tree takes it with it. Two things this
1829
+ // does NOT buy (the file header lists both as known gaps): on POSIX a
1830
+ // plain parent exit does not kill it, and if it IS killed mid-install the
1831
+ // result is not guaranteed intact -- npm reify removes the existing
1832
+ // package dir before moving the new one in, and nothing here repairs a
1833
+ // partial install on the next startup.
1834
+ detached: false,
1835
+ shell: process.platform === "win32"
1836
+ });
1837
+ child.on("close", (code) => {
1838
+ finish();
1839
+ if (errorFired) return;
1840
+ if (code === 0) {
1841
+ log("info", "yaw-mcp self-upgrade complete; the next client restart will run the new version");
1842
+ } else {
1843
+ const hint = cmd === "npm" ? " (often EACCES on a sudo-installed global -- run with the right permissions)" : "";
1844
+ const manual = correctiveCmd === null ? "Set" : `Run \`${correctiveCmd}\` manually, or set`;
1845
+ log(
1846
+ "warn",
1847
+ `yaw-mcp self-upgrade: ${cmd} exited non-zero${hint}. ${manual} YAW_MCP_AUTO_UPGRADE=0 to silence this.`,
1848
+ { code }
1849
+ );
1850
+ }
1851
+ });
1852
+ child.on("error", (err) => {
1853
+ errorFired = true;
1854
+ finish();
1855
+ log("warn", `yaw-mcp self-upgrade: ${cmd} spawn failed`, { error: err?.message });
1856
+ });
1857
+ }
1858
+ async function maybeAutoUpgrade(deps = {}) {
1859
+ const optOut = process.env.YAW_MCP_AUTO_UPGRADE;
1860
+ if (optOut === "0" || optOut?.toLowerCase() === "false") return;
1861
+ const current = deps.currentVersion ?? (true ? "0.80.0" : "dev");
1862
+ if (current === "dev") return;
1863
+ const argvPath = deps.argvPath ?? process.argv[1];
1864
+ const method = (deps.isSeaImpl ? await deps.isSeaImpl() : await detectSea()) ? "binary" : detectInstallMethod(argvPath, realpathSync2, ["unknown", "local-node-modules"]);
1865
+ const cached = (deps.checkedRecentlyImpl ?? defaultCheckedRecently)();
1866
+ let latest;
1867
+ if (cached !== null) {
1868
+ latest = cached.latest;
1869
+ } else {
1870
+ latest = await (deps.fetchLatestImpl ?? fetchLatestVersion)();
1871
+ (deps.recordCheckImpl ?? defaultRecordCheck)(latest);
1872
+ }
1873
+ if (latest === null) return;
1874
+ const plan = buildUpgradePlan({ current, latest, method });
1875
+ if (!plan.stale) return;
1876
+ const rawPrefix = method === "global-npm" ? detectRunningInstallPrefix(argvPath) : null;
1877
+ const quotedPrefix = rawPrefix === null ? null : quoteShellArgIfNeeded(rawPrefix);
1878
+ const globalSpec = GLOBAL_UPGRADE_METHODS.includes(method) ? upgradeSpawnSpec(method, quotedPrefix) : null;
1879
+ if (globalSpec) {
1880
+ const lockDir = rawPrefix ?? tmpdir();
1881
+ const lockName = rawPrefix === null ? `.yaw-mcp-upgrade-${globalSpec.cmd}-${process.getuid?.() ?? "win"}.lock` : UPGRADE_LOCK_NAME;
1882
+ if ((deps.attemptedRecentlyImpl ?? defaultAttemptedRecently)(lockDir, lockName, latest)) {
1883
+ log("info", "yaw-mcp self-upgrade: this upgrade was already attempted recently; not retrying yet", {
1884
+ current,
1885
+ latest,
1886
+ tool: globalSpec.cmd,
1887
+ lockDir
1888
+ });
1889
+ return;
1890
+ }
1891
+ const releaseLock = (deps.acquireLockImpl ?? defaultAcquireLock)(lockDir, lockName);
1892
+ if (releaseLock === null) {
1893
+ log("info", "yaw-mcp self-upgrade: another process is already upgrading this install; skipping this one", {
1894
+ current,
1895
+ latest,
1896
+ tool: globalSpec.cmd,
1897
+ lockDir
1898
+ });
1899
+ return;
1900
+ }
1901
+ log("info", "yaw-mcp is out of date; upgrading the global install in the background", {
1902
+ current,
1903
+ latest,
1904
+ tool: globalSpec.cmd,
1905
+ // The RAW prefix, not the shell-quoted argv form -- a log field is read
1906
+ // by a human, and stray quotes read as part of the path. Omitted when
1907
+ // quoting failed, because then no `--prefix` was passed at all and npm
1908
+ // resolves its own prefix.
1909
+ prefix: quotedPrefix === null ? void 0 : rawPrefix ?? void 0
1910
+ });
1911
+ if (method === "global-npm" && rawPrefix !== null && quotedPrefix !== null) {
1912
+ compareWithNpmPrefix(rawPrefix, deps.npmPrefixImpl).catch(() => {
1913
+ });
1914
+ }
1915
+ (deps.recordAttemptImpl ?? defaultRecordAttempt)(lockDir, lockName, latest);
1916
+ try {
1917
+ (deps.spawnImpl ?? defaultSpawn2)(globalSpec.cmd, globalSpec.args, releaseLock);
1918
+ } catch (err) {
1919
+ releaseLock();
1920
+ log("warn", `yaw-mcp self-upgrade: could not start ${globalSpec.cmd}`, {
1921
+ error: err instanceof Error ? err.message : String(err)
1922
+ });
1923
+ }
1924
+ return;
1925
+ }
1926
+ if (method === "bundled-app") {
1927
+ log("info", "yaw-mcp (bundled with Yaw Terminal) is behind npm; it updates with the app", { current, latest });
1928
+ return;
1929
+ }
1930
+ if (method === "binary") {
1931
+ log(
1932
+ "info",
1933
+ "yaw-mcp (standalone binary) is behind npm; the binary track was retired -- npm install -g @yawlabs/mcp@latest, then delete the old executable",
1934
+ { current, latest }
1935
+ );
1936
+ return;
1937
+ }
1938
+ if (method === "npx") {
1939
+ log("info", "yaw-mcp is out of date; restart your MCP client to pick up the latest version", {
1940
+ current,
1941
+ latest,
1942
+ method
1943
+ });
1944
+ } else if (method === "local-node-modules") {
1945
+ log(
1946
+ "info",
1947
+ "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)",
1948
+ {
1949
+ current,
1950
+ latest,
1951
+ method
1952
+ }
1953
+ );
1954
+ } else {
1955
+ log(
1956
+ "info",
1957
+ "yaw-mcp is out of date; run `yaw-mcp upgrade` for the command that updates this install (`--run` can't automate this install method)",
1958
+ {
1959
+ current,
1960
+ latest,
1961
+ method
1962
+ }
1963
+ );
1964
+ }
1965
+ }
1966
+
1065
1967
  export {
1968
+ INTERNAL_SECRET_ENV_KEYS,
1969
+ scrubInternalSecretsFromProcessEnv,
1970
+ stripInternalSecretsFromEnv,
1971
+ log,
1066
1972
  cacheDir,
1067
1973
  CONFIG_DIRNAME,
1068
1974
  sidecarsRoot,
1069
1975
  sidecarsNodeModules,
1070
1976
  userConfigDir,
1977
+ normalizeForCompare,
1071
1978
  realpathOrSelf,
1072
1979
  isUnderHome,
1980
+ ALLOW_UNOWNED_ENV,
1073
1981
  findProjectConfigDir,
1074
1982
  guidePath,
1075
1983
  CURRENT_OS,
1076
1984
  INSTALL_TARGETS,
1985
+ resolveAppDataDir,
1077
1986
  resolveInstallPath,
1078
1987
  buildLaunchEntry,
1079
1988
  isProjectLocalEntry,
1080
1989
  ENTRY_NAME,
1081
- LEGACY_ENTRY_NAMES,
1082
1990
  findLegacyEntry,
1083
1991
  CLAUDE_CODE_ALLOW_PATTERN,
1084
1992
  resolveClaudeCodeSettingsPath,
@@ -1088,36 +1996,34 @@ export {
1088
1996
  npxSpecIndex,
1089
1997
  npxSpec,
1090
1998
  MIN_OAM_VERSION,
1091
- OAM_INSTALL_SH,
1092
- OAM_INSTALL_PS1,
1093
1999
  oamInstallCommand,
1094
- oamPublishesBinaryFor,
1095
2000
  oamPublishesBinaryForThisMachine,
1096
2001
  oamNoBinaryReason,
1097
2002
  oamInstallAdvice,
1098
2003
  oamHeapOomHint,
1099
2004
  oamFailureLabel,
1100
- parseOamVersion,
1101
2005
  compareVersions,
1102
- winNormalize,
1103
- resolveBinAbsolute,
1104
- OAM_PROBE_TIMEOUT_MS,
1105
- OAM_PROBE_KILL_SIGNAL,
1106
- OAM_PROBE_MAX_OUTPUT,
1107
- createProbeCollector,
1108
2006
  probeOam,
1109
- resetOamBinCache,
1110
2007
  nodeLaunchKind,
1111
- rewriteForOam,
1112
- npxCacheNodeModules,
1113
- npmCacheDir,
1114
- resetNpmCacheDir,
1115
- npmCacheNpxNodeModules,
1116
- ownNodeModules,
1117
- resolveNpmEntry,
1118
- resetPinnedSidecarLog,
1119
2008
  resolveStableNpmEntry,
1120
2009
  resolveOamSpawn,
1121
2010
  isOamCommand,
1122
- isOamLaunch
2011
+ isOamLaunch,
2012
+ parseUpgradeArgs,
2013
+ detectInstallMethod,
2014
+ refineInstallMethod,
2015
+ BINARY_RETIRED_HINT,
2016
+ buildUpgradePlan,
2017
+ fetchLatestVersion,
2018
+ detectSea,
2019
+ runUpgrade,
2020
+ quoteShellArgIfNeeded,
2021
+ quoteArgForDisplay,
2022
+ detectRunningInstallPrefix,
2023
+ acquireUpgradeLock,
2024
+ readCheckMemo,
2025
+ writeCheckMemo,
2026
+ attemptedRecentlyAt,
2027
+ recordAttemptAt,
2028
+ maybeAutoUpgrade
1123
2029
  };