@yawlabs/mcp 0.73.2 → 0.74.1

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.
package/dist/index.js CHANGED
@@ -54,6 +54,15 @@ async function mkdirpWithMode(dir, dirMode) {
54
54
  }
55
55
  }
56
56
 
57
+ // src/json-key.ts
58
+ function setJsonKey(target, key, value) {
59
+ if (key === "__proto__") {
60
+ Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true });
61
+ return;
62
+ }
63
+ target[key] = value;
64
+ }
65
+
57
66
  // src/jsonc.ts
58
67
  import { applyEdits, modify } from "jsonc-parser";
59
68
  function stripJsoncComments(src) {
@@ -198,6 +207,13 @@ function cacheDir() {
198
207
  return path2.join(xdg && xdg.length > 0 ? xdg : path2.join(homedir(), ".cache"), "yaw-mcp");
199
208
  }
200
209
  var CONFIG_DIRNAME = ".yaw-mcp";
210
+ var SIDECARS_DIRNAME = "sidecars";
211
+ function sidecarsRoot(home = homedir()) {
212
+ return path2.join(userConfigDir(home), SIDECARS_DIRNAME);
213
+ }
214
+ function sidecarsNodeModules(home = homedir()) {
215
+ return path2.join(sidecarsRoot(home), "node_modules");
216
+ }
201
217
  function userConfigDir(home = homedir()) {
202
218
  return path2.join(home, CONFIG_DIRNAME);
203
219
  }
@@ -277,7 +293,7 @@ async function readGradesCache(home = homedir2()) {
277
293
  const out = {};
278
294
  for (const [ns, entry] of Object.entries(parsed)) {
279
295
  const validated = validateEntry(entry);
280
- if (validated) out[ns] = validated;
296
+ if (validated) setJsonKey(out, ns, validated);
281
297
  }
282
298
  return out;
283
299
  }
@@ -396,11 +412,11 @@ async function readTrustStore(home = homedir3()) {
396
412
  log("warn", "Dropping trust entry with a missing or malformed sha256", { path: path7, key });
397
413
  continue;
398
414
  }
399
- entries[key] = {
415
+ setJsonKey(entries, key, {
400
416
  path: typeof v.path === "string" && v.path.length > 0 ? v.path : key,
401
417
  sha256: v.sha256,
402
418
  grantedAt: typeof v.grantedAt === "string" ? v.grantedAt : ""
403
- };
419
+ });
404
420
  }
405
421
  return { version, entries, malformed: false, malformedReason: null, malformedKind: null, errorCode: null };
406
422
  }
@@ -1234,6 +1250,15 @@ var SUBCOMMAND_SPEC = [
1234
1250
  flags: ["--force", "--yes", "--help"]
1235
1251
  },
1236
1252
  { name: "list", description: "List the servers yaw-mcp loads locally", flags: ["--json", "--help"] },
1253
+ // Positional is the literal subcommand, not a placeholder -- `install` is
1254
+ // the only verb, and requiring it keeps room for later ones (list, prune)
1255
+ // without a bare `yaw-mcp sidecars` having ever meant something else.
1256
+ {
1257
+ name: "sidecars",
1258
+ description: "Install configured MCP servers into a managed directory",
1259
+ positional: [["install"]],
1260
+ flags: ["--json", "--help"]
1261
+ },
1237
1262
  // Consent gate for a project-local .yaw-mcp/bundles.json. Flags mirror
1238
1263
  // parseTrustArgs in src/trust-cmd.ts -- keep them in sync.
1239
1264
  {
@@ -2005,10 +2030,10 @@ function profileAllows(profile, namespace) {
2005
2030
  }
2006
2031
 
2007
2032
  // src/doctor-cmd.ts
2008
- import { existsSync as existsSync6, readFileSync as readFileSync2 } from "fs";
2033
+ import { existsSync as existsSync7, readFileSync as readFileSync3 } from "fs";
2009
2034
  import { readFile as readFile9 } from "fs/promises";
2010
- import { homedir as homedir10 } from "os";
2011
- import { join as join9 } from "path";
2035
+ import { homedir as homedir12 } from "os";
2036
+ import { isAbsolute as isAbsolute4, join as join10 } from "path";
2012
2037
 
2013
2038
  // src/cli-shadows.ts
2014
2039
  var EMPTY = [];
@@ -2173,16 +2198,18 @@ function formatShadowLine(server) {
2173
2198
  }
2174
2199
 
2175
2200
  // src/oam-spawn.ts
2176
- import { execFileSync } from "child_process";
2201
+ import { spawn as spawn2 } from "child_process";
2177
2202
  import { existsSync as existsSync3, readdirSync, readFileSync } from "fs";
2178
- import { isAbsolute as isAbsolute2, join as join6, sep } from "path";
2203
+ import { homedir as homedir7 } from "os";
2204
+ import { dirname as dirname2, isAbsolute as isAbsolute2, join as join6, sep } from "path";
2179
2205
  import { fileURLToPath } from "url";
2180
2206
  function packageName(spec) {
2181
2207
  const start = spec.startsWith("@") ? 1 : 0;
2182
2208
  const at = spec.indexOf("@", start);
2183
2209
  return at === -1 ? spec : spec.slice(0, at);
2184
2210
  }
2185
- var MIN_OAM_VERSION = "0.6.0";
2211
+ var MIN_OAM_VERSION = "0.8.2";
2212
+ var warnedOamMissing = false;
2186
2213
  var oamProbeCache;
2187
2214
  function parseOamVersion(out) {
2188
2215
  const m = /(\d+\.\d+\.\d+)/.exec(out);
@@ -2204,27 +2231,128 @@ function compareVersions(a, b) {
2204
2231
  function winNormalize(p, platform = process.platform) {
2205
2232
  return platform === "win32" ? p.replace(/\//g, "\\") : p;
2206
2233
  }
2207
- function probeOam(run = (bin) => execFileSync(bin, ["--version"], { stdio: ["ignore", "pipe", "ignore"], encoding: "utf8" })) {
2234
+ var OAM_PROBE_TIMEOUT_MS = 3e3;
2235
+ var OAM_PROBE_KILL_SIGNAL = "SIGKILL";
2236
+ var OAM_PROBE_MAX_OUTPUT = 8 * 1024;
2237
+ var VERSION_CARRY = 32;
2238
+ function createProbeCollector(max = OAM_PROBE_MAX_OUTPUT) {
2239
+ let head = "";
2240
+ let carry = "";
2241
+ let found = null;
2242
+ return {
2243
+ push(chunk) {
2244
+ if (found !== null) return;
2245
+ found = parseOamVersion(carry + chunk);
2246
+ carry = (carry + chunk).slice(-VERSION_CARRY);
2247
+ if (head.length >= max) return;
2248
+ head += chunk.slice(0, max - head.length);
2249
+ },
2250
+ /** The version if one appeared anywhere, else the capped head (which
2251
+ * parses to null either way, so the caller's contract is unchanged). */
2252
+ result() {
2253
+ return found ?? head;
2254
+ },
2255
+ /** Test hook: bytes actually retained. */
2256
+ retainedLength() {
2257
+ return head.length;
2258
+ }
2259
+ };
2260
+ }
2261
+ function spawnVersionProbe(bin) {
2262
+ return new Promise((resolve8, reject) => {
2263
+ let settled = false;
2264
+ let timer;
2265
+ const settle = (fn) => {
2266
+ if (settled) return;
2267
+ settled = true;
2268
+ if (timer) clearTimeout(timer);
2269
+ fn();
2270
+ };
2271
+ let child;
2272
+ try {
2273
+ child = spawn2(bin, ["--version"], {
2274
+ stdio: ["ignore", "pipe", "ignore"],
2275
+ windowsHide: process.platform === "win32"
2276
+ });
2277
+ } catch (err) {
2278
+ reject(err);
2279
+ return;
2280
+ }
2281
+ const collector = createProbeCollector();
2282
+ child.stdout?.setEncoding("utf8");
2283
+ child.stdout?.on("error", () => {
2284
+ });
2285
+ child.stdout?.on("data", (chunk) => collector.push(chunk));
2286
+ child.on("error", (err) => settle(() => reject(err)));
2287
+ child.on(
2288
+ "close",
2289
+ (code, signal) => settle(() => code === 0 ? resolve8(collector.result()) : reject(new Error(`oam exited ${code ?? signal}`)))
2290
+ );
2291
+ timer = setTimeout(() => {
2292
+ settle(() => {
2293
+ try {
2294
+ child.kill(OAM_PROBE_KILL_SIGNAL);
2295
+ } catch {
2296
+ }
2297
+ try {
2298
+ child.stdout?.destroy();
2299
+ child.unref();
2300
+ } catch {
2301
+ }
2302
+ const err = new Error(`oam --version exceeded ${OAM_PROBE_TIMEOUT_MS}ms`);
2303
+ err.code = "ETIMEDOUT";
2304
+ reject(err);
2305
+ });
2306
+ }, OAM_PROBE_TIMEOUT_MS);
2307
+ timer.unref?.();
2308
+ });
2309
+ }
2310
+ var oamProbeInFlight;
2311
+ var oamProbeGeneration = 0;
2312
+ async function probeOam(run = spawnVersionProbe) {
2313
+ if (oamProbeCache !== void 0) return oamProbeCache;
2314
+ if (oamProbeInFlight !== void 0) return oamProbeInFlight;
2315
+ const generation = oamProbeGeneration;
2316
+ oamProbeInFlight = probeOamUncached(run, generation).finally(() => {
2317
+ if (generation === oamProbeGeneration) oamProbeInFlight = void 0;
2318
+ });
2319
+ return oamProbeInFlight;
2320
+ }
2321
+ async function probeOamUncached(run, generation) {
2208
2322
  if (oamProbeCache !== void 0) return oamProbeCache;
2209
2323
  const bin = winNormalize(process.env.OAM_BIN || (process.platform === "win32" ? "oam.exe" : "oam"));
2324
+ const publish = (probe) => {
2325
+ if (generation === oamProbeGeneration) oamProbeCache = probe;
2326
+ return probe;
2327
+ };
2210
2328
  try {
2211
- const version = parseOamVersion(run(bin));
2329
+ const version = parseOamVersion(await run(bin));
2212
2330
  if (version !== null && compareVersions(version, MIN_OAM_VERSION) < 0) {
2213
2331
  log("warn", "oam is installed but below the minimum supported version; falling back to node", {
2214
2332
  oamVersion: version,
2215
- minVersion: MIN_OAM_VERSION
2333
+ minVersion: MIN_OAM_VERSION,
2334
+ // The floor tracks the latest release, so below-min always means out
2335
+ // of date, and oam updates itself in place.
2336
+ updateWith: "oam self-update"
2216
2337
  });
2217
- oamProbeCache = { bin: null, version, belowMin: true };
2218
- } else {
2219
- oamProbeCache = { bin, version, belowMin: false };
2338
+ return publish({ bin: null, version, belowMin: true });
2220
2339
  }
2221
- } catch {
2222
- oamProbeCache = { bin: null, version: null, belowMin: false };
2340
+ return publish({ bin, version, belowMin: false });
2341
+ } catch (err) {
2342
+ const code = err?.code;
2343
+ if (code === "ETIMEDOUT") {
2344
+ log("warn", "oam did not respond to --version in time; falling back to node for this process", {
2345
+ timeoutMs: OAM_PROBE_TIMEOUT_MS,
2346
+ bin
2347
+ });
2348
+ } else if (code !== "ENOENT") {
2349
+ log("warn", "oam --version failed; falling back to node for this process", {
2350
+ bin,
2351
+ error: err instanceof Error ? err.message : String(err)
2352
+ });
2353
+ }
2354
+ return publish({ bin: null, version: null, belowMin: false });
2223
2355
  }
2224
- return oamProbeCache;
2225
- }
2226
- function oamBin() {
2227
- return probeOam().bin;
2228
2356
  }
2229
2357
  function rewriteForOam(command, args, deps) {
2230
2358
  const bin = deps.oamBin;
@@ -2277,6 +2405,57 @@ function npxCacheNodeModules(fromUrl = import.meta.url) {
2277
2405
  return [];
2278
2406
  }
2279
2407
  }
2408
+ function npmrcCache(file) {
2409
+ let text;
2410
+ try {
2411
+ text = readFileSync(file, "utf8");
2412
+ } catch {
2413
+ return null;
2414
+ }
2415
+ for (const line of text.split(/\r?\n/)) {
2416
+ const m = /^\s*cache\s*=\s*(.+?)\s*$/.exec(line);
2417
+ if (m && !/^\s*[;#]/.test(line)) return m[1].replace(/^["']|["']$/g, "");
2418
+ }
2419
+ return null;
2420
+ }
2421
+ var npmCacheDirCache = /* @__PURE__ */ new Map();
2422
+ function npmCacheDir(fromUrl = import.meta.url) {
2423
+ const cached = npmCacheDirCache.get(fromUrl);
2424
+ if (cached !== void 0) return cached;
2425
+ const resolved = resolveNpmCacheDir(fromUrl);
2426
+ npmCacheDirCache.set(fromUrl, resolved);
2427
+ return resolved;
2428
+ }
2429
+ function resolveNpmCacheDir(fromUrl) {
2430
+ const fromEnv = process.env.npm_config_cache;
2431
+ if (fromEnv) return fromEnv;
2432
+ const candidates = [join6(homedir7(), ".npmrc")];
2433
+ for (const nodeModules of ownNodeModules(fromUrl)) {
2434
+ candidates.push(join6(dirname2(nodeModules), "etc", "npmrc"), join6(nodeModules, "npm", "npmrc"));
2435
+ }
2436
+ const nodeDir = dirname2(process.execPath);
2437
+ candidates.push(
2438
+ join6(nodeDir, "node_modules", "npm", "npmrc"),
2439
+ // Windows layout
2440
+ join6(nodeDir, "..", "lib", "node_modules", "npm", "npmrc")
2441
+ // POSIX layout
2442
+ );
2443
+ for (const file of candidates) {
2444
+ const cache = npmrcCache(file);
2445
+ if (cache) return cache;
2446
+ }
2447
+ const fallback = process.platform === "win32" ? process.env.LOCALAPPDATA && join6(process.env.LOCALAPPDATA, "npm-cache") : join6(homedir7(), ".npm");
2448
+ return fallback && existsSync3(fallback) ? fallback : null;
2449
+ }
2450
+ function npmCacheNpxNodeModules(cacheDir2) {
2451
+ if (!cacheDir2) return [];
2452
+ const npxRoot = join6(cacheDir2, "_npx");
2453
+ try {
2454
+ return readdirSync(npxRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => join6(npxRoot, e.name, "node_modules"));
2455
+ } catch {
2456
+ return [];
2457
+ }
2458
+ }
2280
2459
  function ownNodeModules(fromUrl = import.meta.url) {
2281
2460
  let here;
2282
2461
  try {
@@ -2307,22 +2486,83 @@ function packageEntry(pkgDir, pkg) {
2307
2486
  }
2308
2487
  if (!rel && typeof j.main === "string") rel = j.main;
2309
2488
  if (!rel) return null;
2310
- return isAbsolute2(rel) ? rel : join6(pkgDir, rel);
2489
+ return {
2490
+ entry: isAbsolute2(rel) ? rel : join6(pkgDir, rel),
2491
+ version: typeof j.version === "string" ? j.version : null
2492
+ };
2311
2493
  }
2312
- function resolveNpmEntry(pkg, fromUrl = import.meta.url) {
2494
+ function resolveNpmEntry(pkg, fromUrl = import.meta.url, npmCache = npmCacheDir(fromUrl), managedRoot = sidecarsNodeModules()) {
2313
2495
  const parts = pkg.split("/");
2314
- for (const nodeModules of [...ownNodeModules(fromUrl), ...npxCacheNodeModules(fromUrl)]) {
2315
- const entry = packageEntry(join6(nodeModules, ...parts), pkg);
2316
- if (entry) return entry;
2496
+ for (const nodeModules of [...managedRoot ? [managedRoot] : [], ...ownNodeModules(fromUrl)]) {
2497
+ const hit = packageEntry(join6(nodeModules, ...parts), pkg);
2498
+ if (hit) return hit.entry;
2499
+ }
2500
+ const roots = /* @__PURE__ */ new Set([...npxCacheNodeModules(fromUrl), ...npmCacheNpxNodeModules(npmCache)]);
2501
+ let best = null;
2502
+ for (const nodeModules of roots) {
2503
+ const hit = packageEntry(join6(nodeModules, ...parts), pkg);
2504
+ if (!hit) continue;
2505
+ if (best === null || hit.version !== null && (best.version === null || compareVersions(hit.version, best.version) > 0)) {
2506
+ best = hit;
2507
+ }
2508
+ }
2509
+ if (best !== null) notePinnedSidecar(pkg, best.version);
2510
+ return best?.entry ?? null;
2511
+ }
2512
+ var pinnedReported = /* @__PURE__ */ new Set();
2513
+ function notePinnedSidecar(pkg, version) {
2514
+ if (pinnedReported.has(pkg)) return;
2515
+ pinnedReported.add(pkg);
2516
+ log("info", "hosting sidecar on oam from an on-disk copy; it will not self-update the way npx does", {
2517
+ package: pkg,
2518
+ version: version ?? "unknown",
2519
+ refreshWith: `npx -y ${pkg}@latest --help`
2520
+ });
2521
+ }
2522
+ function resolveStableNpmEntry(pkg, fromUrl = import.meta.url) {
2523
+ const npxMarker = `${sep}_npx${sep}`;
2524
+ for (const nodeModules of ownNodeModules(fromUrl)) {
2525
+ if (nodeModules.includes(npxMarker)) continue;
2526
+ const hit = packageEntry(join6(nodeModules, ...pkg.split("/")), pkg);
2527
+ if (hit) return hit.entry;
2317
2528
  }
2318
2529
  return null;
2319
2530
  }
2320
- function resolveOamSpawn(command, args) {
2531
+ async function resolveOamSpawn(command, args, optedIn = true) {
2532
+ const probe = await probeOam();
2533
+ if (optedIn && probe.bin === null && !probe.belowMin && !warnedOamMissing) {
2534
+ warnedOamMissing = true;
2535
+ log("warn", "a server opted in to oam but oam is not installed; running it on node instead", {
2536
+ install: "curl -fsSL https://oamjs.org/install.sh | sh",
2537
+ installWindows: "irm https://oamjs.org/install.ps1 | iex",
2538
+ overrideWith: "OAM_BIN"
2539
+ });
2540
+ }
2321
2541
  return rewriteForOam(command, args, {
2322
- oamBin: oamBin(),
2542
+ oamBin: probe.bin,
2323
2543
  resolveEntry: (pkg) => resolveNpmEntry(pkg)
2324
2544
  });
2325
2545
  }
2546
+ function isOamCommand(command) {
2547
+ const base = command.split(/[\\/]/).pop() ?? command;
2548
+ return /^oam(\.exe)?$/i.test(base);
2549
+ }
2550
+ function isOamLaunch(command, args = []) {
2551
+ if (isOamCommand(command)) return true;
2552
+ const base = command.split(/[\\/]/).pop() ?? command;
2553
+ if (/^cmd(\.exe)?$/i.test(base)) {
2554
+ const first = args.find((a) => !/^\/[a-z]$/i.test(a));
2555
+ return first !== void 0 && isOamCommand(first);
2556
+ }
2557
+ if (/^(sh|bash|zsh|dash)$/i.test(base)) {
2558
+ const dashC = args.indexOf("-c");
2559
+ const payload = dashC >= 0 ? args[dashC + 1] : args[0];
2560
+ if (payload === void 0) return false;
2561
+ const firstToken = payload.trim().split(/\s+/)[0]?.replace(/^["']|["']$/g, "");
2562
+ return firstToken !== void 0 && firstToken.length > 0 && isOamCommand(firstToken);
2563
+ }
2564
+ return false;
2565
+ }
2326
2566
 
2327
2567
  // src/default-runtime.ts
2328
2568
  var bundlesDefaultCache;
@@ -2361,11 +2601,11 @@ function describeServerRuntime(server, configDefault, probe) {
2361
2601
  if (server.runtime === "node") {
2362
2602
  return { runtime: "node", code: "per-server-node", reason: 'per-server runtime:"node"' };
2363
2603
  }
2364
- const wantsOam = server.runtime === "oam" || server.runtime === void 0 && configDefault === "oam";
2604
+ const wantsOam = server.runtime === "oam" || server.runtime === void 0 && configDefault !== "node";
2365
2605
  if (!wantsOam) {
2366
- return { runtime: "node", code: "default-node", reason: "default (no oam opt-in)" };
2606
+ return { runtime: "node", code: "default-node", reason: 'config default runtime:"node"' };
2367
2607
  }
2368
- const via = server.runtime === "oam" ? 'per-server runtime:"oam"' : 'default runtime "oam"';
2608
+ const via = server.runtime === "oam" ? 'per-server runtime:"oam"' : configDefault === "oam" ? 'default runtime "oam"' : "oam is the default when installed";
2369
2609
  if (server.command !== "node" && server.command !== "npx") {
2370
2610
  return { runtime: "node", code: "not-node-command", reason: `${via}, but command is not node/npx` };
2371
2611
  }
@@ -2474,7 +2714,7 @@ function renderActiveServersSection(activeServers) {
2474
2714
  }
2475
2715
 
2476
2716
  // src/install-targets.ts
2477
- import { homedir as homedir7 } from "os";
2717
+ import { homedir as homedir8 } from "os";
2478
2718
  import { isAbsolute as isAbsolute3, join as join7, resolve as resolve4 } from "path";
2479
2719
  var CURRENT_OS = process.platform === "darwin" ? "macos" : process.platform === "win32" ? "windows" : "linux";
2480
2720
  var INSTALL_TARGETS = [
@@ -2556,7 +2796,7 @@ var INSTALL_TARGETS = [
2556
2796
  }
2557
2797
  ];
2558
2798
  function resolveInstallPath(opts) {
2559
- const home = opts.home ?? homedir7();
2799
+ const home = opts.home ?? homedir8();
2560
2800
  const appData = opts.appData ?? process.env.APPDATA ?? join7(home, "AppData", "Roaming");
2561
2801
  const { clientId, scope, os, projectDir, claudeConfigDir } = opts;
2562
2802
  const target = INSTALL_TARGETS.find((t) => t.clientId === clientId);
@@ -2658,6 +2898,9 @@ function buildLaunchEntry(opts) {
2658
2898
  return entry;
2659
2899
  }
2660
2900
  const pkg = opts.pkg ?? "@yawlabs/mcp@latest";
2901
+ if (opts.oamBin && opts.oamEntry && !opts.pkg) {
2902
+ return { command: opts.oamBin, args: ["run", "--no-check", opts.oamEntry] };
2903
+ }
2661
2904
  return opts.os === "windows" ? { command: "cmd", args: ["/c", "npx", "-y", pkg] } : { command: "npx", args: ["-y", pkg] };
2662
2905
  }
2663
2906
  var ENTRY_NAME = "mcp";
@@ -2749,7 +2992,7 @@ function sanitizeLearning(input) {
2749
2992
  if (typeof u.succeeded !== "number" || !Number.isFinite(u.succeeded) || u.succeeded < 0) continue;
2750
2993
  if (typeof u.lastUsedAt !== "number" || !Number.isFinite(u.lastUsedAt) || u.lastUsedAt < 0) continue;
2751
2994
  const succeeded = Math.min(u.succeeded, u.dispatched);
2752
- out[k] = { dispatched: u.dispatched, succeeded, lastUsedAt: u.lastUsedAt };
2995
+ setJsonKey(out, k, { dispatched: u.dispatched, succeeded, lastUsedAt: u.lastUsedAt });
2753
2996
  }
2754
2997
  return out;
2755
2998
  }
@@ -2802,11 +3045,231 @@ function errorMessage(err) {
2802
3045
  return err instanceof Error ? err.message : String(err);
2803
3046
  }
2804
3047
 
3048
+ // src/sidecars-cmd.ts
3049
+ import { spawn as spawn3 } from "child_process";
3050
+ import { existsSync as existsSync4, mkdirSync, readFileSync as readFileSync2 } from "fs";
3051
+ import { homedir as homedir9 } from "os";
3052
+ import { join as join8 } from "path";
3053
+ function isRegistrySpec(spec) {
3054
+ if (spec.includes(":") || /^[./~\\]/.test(spec)) return false;
3055
+ return /^(@[^/@\s]+\/)?[^./_@\s][^/@\s]*$/.test(packageName(spec));
3056
+ }
3057
+ function collectSidecarSpecs(servers) {
3058
+ const byPkg = /* @__PURE__ */ new Map();
3059
+ for (const s of servers) {
3060
+ if (s.type !== "local" || s.command !== "npx") continue;
3061
+ const positional = (s.args ?? []).filter((a) => a !== "-y" && a !== "--yes");
3062
+ const spec = positional[0];
3063
+ if (spec === void 0 || spec.startsWith("-")) continue;
3064
+ if (!isRegistrySpec(spec)) continue;
3065
+ const pkg = packageName(spec);
3066
+ if (!pkg) continue;
3067
+ const existing = byPkg.get(pkg);
3068
+ if (existing) {
3069
+ if (s.namespace && !existing.namespaces.includes(s.namespace)) existing.namespaces.push(s.namespace);
3070
+ if (spec !== existing.spec && !existing.conflicting.includes(spec)) existing.conflicting.push(spec);
3071
+ continue;
3072
+ }
3073
+ byPkg.set(pkg, { pkg, spec, namespaces: s.namespace ? [s.namespace] : [], conflicting: [] });
3074
+ }
3075
+ return [...byPkg.values()];
3076
+ }
3077
+ function collectNonRegistrySpecs(servers) {
3078
+ const out = [];
3079
+ for (const s of servers) {
3080
+ if (s.type !== "local" || s.command !== "npx") continue;
3081
+ const spec = (s.args ?? []).filter((a) => a !== "-y" && a !== "--yes")[0];
3082
+ if (spec === void 0 || spec.startsWith("-") || isRegistrySpec(spec)) continue;
3083
+ out.push({ namespace: s.namespace ?? "(unnamed)", spec });
3084
+ }
3085
+ return out;
3086
+ }
3087
+ function sidecarsManifest(specs) {
3088
+ const dependencies = {};
3089
+ for (const { pkg, spec } of specs.slice().sort((a, b) => a.pkg.localeCompare(b.pkg))) {
3090
+ const range = spec.slice(pkg.length).replace(/^@/, "");
3091
+ dependencies[pkg] = range === "" ? "latest" : range;
3092
+ }
3093
+ return `${JSON.stringify(
3094
+ {
3095
+ name: "yaw-mcp-sidecars",
3096
+ version: "0.0.0",
3097
+ private: true,
3098
+ description: "MCP servers installed by `yaw-mcp sidecars install`. Managed file -- edits are overwritten.",
3099
+ dependencies
3100
+ },
3101
+ null,
3102
+ 2
3103
+ )}
3104
+ `;
3105
+ }
3106
+ function installedVersion(pkg, home = homedir9()) {
3107
+ const pj = join8(sidecarsNodeModules(home), ...pkg.split("/"), "package.json");
3108
+ try {
3109
+ const v = JSON.parse(readFileSync2(pj, "utf8")).version;
3110
+ return typeof v === "string" ? v : null;
3111
+ } catch {
3112
+ return null;
3113
+ }
3114
+ }
3115
+ function jsonDocument(root, over = {}) {
3116
+ const doc = {
3117
+ root,
3118
+ installed: [],
3119
+ reason: null,
3120
+ error: null,
3121
+ conflicts: [],
3122
+ skipped: [],
3123
+ ...over
3124
+ };
3125
+ return `${JSON.stringify(doc, null, 2)}
3126
+ `;
3127
+ }
3128
+ function defaultRunNpm(args, cwd) {
3129
+ return new Promise((resolve8) => {
3130
+ const isWindows = process.platform === "win32";
3131
+ const child = spawn3(isWindows ? "npm.cmd" : "npm", args, {
3132
+ cwd,
3133
+ // npm's own progress ("added 220 packages in 12s") goes to its STDOUT,
3134
+ // and inheriting that put it ahead of the JSON document under --json --
3135
+ // enough to make `yaw-mcp sidecars install --json | jq` fail outright.
3136
+ // Routing the child's stdout to fd 2 keeps the progress visible while
3137
+ // leaving OUR stdout carrying only the result, which is what a caller
3138
+ // parses. Unconditional rather than --json-only: progress belongs on
3139
+ // stderr in both modes, and a mode-dependent stdio is a second shape to
3140
+ // get wrong.
3141
+ stdio: ["ignore", 2, "inherit"],
3142
+ shell: isWindows
3143
+ });
3144
+ child.on("error", () => resolve8(-1));
3145
+ child.on("close", (code, signal) => resolve8(code ?? (signal ? -1 : 0)));
3146
+ });
3147
+ }
3148
+ var SIDECARS_USAGE = `Usage: yaw-mcp sidecars install [--json]
3149
+
3150
+ Install the MCP servers from your bundles.json into ~/.yaw-mcp/sidecars,
3151
+ so they run from one known version instead of whatever npm's npx cache
3152
+ happens to hold.
3153
+
3154
+ Worth running when servers are hosted on oam: oam runs the copy already on
3155
+ disk and cannot re-resolve "@latest" the way npx did, so without a managed
3156
+ install a server stays pinned at whatever was last fetched. Re-run this to
3157
+ move them forward.
3158
+
3159
+ Only npx-launched servers naming a registry package are installed. docker,
3160
+ uvx, and native commands are left alone, as are node launches that already
3161
+ name a file and npx launches pointing at a git or path target.`;
3162
+ function parseSidecarsArgs(argv) {
3163
+ let json = false;
3164
+ let sawInstall = false;
3165
+ for (const a of argv) {
3166
+ if (a === "--json") {
3167
+ json = true;
3168
+ } else if (a === "--help" || a === "-h") {
3169
+ return { ok: false, error: SIDECARS_USAGE, help: true };
3170
+ } else if (a === "install") {
3171
+ sawInstall = true;
3172
+ } else if (a.startsWith("-")) {
3173
+ return { ok: false, error: `yaw-mcp sidecars: unknown argument "${a}"
3174
+
3175
+ ${SIDECARS_USAGE}` };
3176
+ } else {
3177
+ return { ok: false, error: `yaw-mcp sidecars: unknown subcommand "${a}"
3178
+
3179
+ ${SIDECARS_USAGE}` };
3180
+ }
3181
+ }
3182
+ if (!sawInstall) return { ok: false, error: `yaw-mcp sidecars: expected "install"
3183
+
3184
+ ${SIDECARS_USAGE}` };
3185
+ return { ok: true, options: { json } };
3186
+ }
3187
+ async function runSidecarsInstall(opts = {}) {
3188
+ const home = opts.home ?? homedir9();
3189
+ const write = opts.out ?? ((s) => process.stdout.write(s));
3190
+ const lines = [];
3191
+ const print = (s = "") => {
3192
+ lines.push(s);
3193
+ if (!opts.json) write(`${s}
3194
+ `);
3195
+ };
3196
+ const bundles = await loadLocalBundles({ cwd: opts.cwd, home });
3197
+ const servers = bundles.config?.servers ?? [];
3198
+ const specs = collectSidecarSpecs(servers);
3199
+ const skipped = collectNonRegistrySpecs(servers);
3200
+ const root = sidecarsRoot(home);
3201
+ const conflicts = specs.filter((s) => s.conflicting.length > 0).map((s) => ({ pkg: s.pkg, used: s.spec, ignored: s.conflicting }));
3202
+ const printSkipped = () => {
3203
+ if (skipped.length === 0) return;
3204
+ print();
3205
+ for (const k of skipped) {
3206
+ print(` note: ${k.namespace} launches ${k.spec}, not a registry package; it keeps using npx`);
3207
+ }
3208
+ };
3209
+ if (specs.length === 0) {
3210
+ if (bundles.config === null) {
3211
+ print("No servers configured yet -- nothing to install.");
3212
+ print("Add one with `yaw-mcp add <slug>`, then run this again.");
3213
+ printSkipped();
3214
+ if (opts.json) write(jsonDocument(root, { reason: "no-config", skipped }));
3215
+ return { exitCode: 0, installed: [], lines };
3216
+ }
3217
+ if (skipped.length > 0) {
3218
+ print("Nothing to install -- every npx server points at a git or path target.");
3219
+ printSkipped();
3220
+ if (opts.json) write(jsonDocument(root, { reason: "only-non-registry-specs", skipped }));
3221
+ return { exitCode: 0, installed: [], lines };
3222
+ }
3223
+ print("No npx-launched servers in bundles.json -- nothing to install.");
3224
+ print("docker, uvx, and native commands run as configured; only npx servers are installed here.");
3225
+ if (opts.json) write(jsonDocument(root, { reason: "no-npx-servers", skipped }));
3226
+ return { exitCode: 0, installed: [], lines };
3227
+ }
3228
+ mkdirSync(root, { recursive: true });
3229
+ await atomicWriteFile(join8(root, "package.json"), sidecarsManifest(specs));
3230
+ print(`Installing ${specs.length} server package(s) into ${root}`);
3231
+ for (const s of specs) print(` ${s.spec}${s.namespaces.length ? ` (${s.namespaces.join(", ")})` : ""}`);
3232
+ printSkipped();
3233
+ if (conflicts.length > 0) {
3234
+ print();
3235
+ for (const c of conflicts) {
3236
+ print(` note: ${c.pkg} is also configured as ${c.ignored.join(", ")}; installing ${c.used}`);
3237
+ }
3238
+ }
3239
+ print();
3240
+ const runNpm = opts.runNpm ?? defaultRunNpm;
3241
+ const code = await runNpm(["install", "--no-audit", "--no-fund"], root);
3242
+ if (code !== 0) {
3243
+ print(`npm install failed (exit ${code}). Servers keep resolving from the npx cache.`);
3244
+ if (opts.json) write(jsonDocument(root, { error: `npm exited ${code}`, conflicts, skipped }));
3245
+ return { exitCode: 1, installed: [], lines };
3246
+ }
3247
+ const installed = specs.map((s) => ({
3248
+ pkg: s.pkg,
3249
+ version: installedVersion(s.pkg, home),
3250
+ namespaces: s.namespaces
3251
+ }));
3252
+ const missing = installed.filter((i) => i.version === null);
3253
+ print("Installed:");
3254
+ for (const i of installed) print(` ${i.pkg} ${i.version ?? "NOT FOUND"}`);
3255
+ if (missing.length > 0) {
3256
+ print();
3257
+ print(`${missing.length} package(s) did not land; those servers keep resolving from the npx cache.`);
3258
+ }
3259
+ print();
3260
+ print("These versions are now fixed. Re-run this command to move them forward.");
3261
+ if (opts.json) write(jsonDocument(root, { installed, conflicts, skipped }));
3262
+ return { exitCode: missing.length === installed.length ? 1 : 0, installed, lines };
3263
+ }
3264
+ function hasManagedSidecars(home = homedir9()) {
3265
+ return existsSync4(sidecarsNodeModules(home));
3266
+ }
3267
+
2805
3268
  // src/try-cmd.ts
2806
- import { existsSync as existsSync5 } from "fs";
3269
+ import { existsSync as existsSync6 } from "fs";
2807
3270
  import { chmod as chmod4, mkdir as mkdir3, readdir, readFile as readFile8, unlink as unlink2 } from "fs/promises";
2808
- import { homedir as homedir9 } from "os";
2809
- import { join as join8, resolve as resolve6 } from "path";
3271
+ import { homedir as homedir11 } from "os";
3272
+ import { join as join9, resolve as resolve6 } from "path";
2810
3273
 
2811
3274
  // src/catalog.ts
2812
3275
  var DEFAULT_CATALOG_URL = "https://yaw.sh/data/mcp-catalog.json";
@@ -2909,9 +3372,9 @@ async function resolveCatalogSlug(slug, opts = {}) {
2909
3372
  }
2910
3373
 
2911
3374
  // src/install-cmd.ts
2912
- import { existsSync as existsSync4 } from "fs";
3375
+ import { existsSync as existsSync5 } from "fs";
2913
3376
  import { readFile as readFile7 } from "fs/promises";
2914
- import { homedir as homedir8 } from "os";
3377
+ import { homedir as homedir10 } from "os";
2915
3378
  import { resolve as resolve5 } from "path";
2916
3379
  import { createInterface } from "readline/promises";
2917
3380
  import { Writable } from "stream";
@@ -2987,12 +3450,20 @@ ${USAGE}`);
2987
3450
  }
2988
3451
  log2(`Target: ${target.label} (${scope})`);
2989
3452
  log2(`File: ${resolved.absolute}`);
2990
- const newEntry = buildLaunchEntry({ os });
3453
+ const oamProbeResult = await (opts.oamProbe ?? probeOam)();
3454
+ const resolveEntry = opts.resolveOamEntry ?? resolveStableNpmEntry;
3455
+ const oamEntry = oamProbeResult.bin ? resolveEntry("@yawlabs/mcp") : null;
3456
+ const newEntry = buildLaunchEntry({ os, oamBin: oamProbeResult.bin, oamEntry });
3457
+ if (oamProbeResult.bin && oamEntry) {
3458
+ log2(`Runtime: will run on oam ${oamProbeResult.version ?? ""}`.trimEnd());
3459
+ } else if (oamProbeResult.bin) {
3460
+ log2("Runtime: node (oam found, but yaw-mcp is not durably installed -- `npm i -g @yawlabs/mcp` to host it on oam)");
3461
+ }
2991
3462
  const containerPath = resolved.containerPath;
2992
3463
  let existing = {};
2993
3464
  let existingHasEntry = false;
2994
3465
  let legacyEntry = null;
2995
- if (existsSync4(resolved.absolute)) {
3466
+ if (existsSync5(resolved.absolute)) {
2996
3467
  let raw;
2997
3468
  try {
2998
3469
  raw = await readFile7(resolved.absolute, "utf8");
@@ -3048,10 +3519,16 @@ ${USAGE}`);
3048
3519
  }
3049
3520
  log2(`Overwriting existing "${ENTRY_NAME}" entry.`);
3050
3521
  }
3051
- const merged = mergeClientConfig(existing, containerPath, newEntry);
3522
+ const previousEntry = readEntryAt(existing, containerPath, ENTRY_NAME);
3523
+ const previousEnv = previousEntry?.env;
3524
+ const entryToWrite = newEntry.env === void 0 && previousEnv && Object.keys(previousEnv).length > 0 ? { ...newEntry, env: previousEnv } : newEntry;
3525
+ if (entryToWrite !== newEntry) {
3526
+ log2(`Kept existing env on the ${ENTRY_NAME} entry: ${Object.keys(previousEnv ?? {}).join(", ")}`);
3527
+ }
3528
+ const merged = mergeClientConfig(existing, containerPath, entryToWrite);
3052
3529
  const clientJson = `${JSON.stringify(merged, null, 2)}
3053
3530
  `;
3054
- const home = opts.home ?? homedir8();
3531
+ const home = opts.home ?? homedir10();
3055
3532
  const settingsPatch = opts.clientId === "claude-code" ? await prepareClaudeCodeSettingsPatch({
3056
3533
  scope,
3057
3534
  home,
@@ -3119,7 +3596,7 @@ async function prepareClaudeCodeSettingsPatch(opts) {
3119
3596
  });
3120
3597
  if (!path7) return null;
3121
3598
  let existing = {};
3122
- if (existsSync4(path7)) {
3599
+ if (existsSync5(path7)) {
3123
3600
  try {
3124
3601
  const raw = await readFile7(path7, "utf8");
3125
3602
  if (raw.trim().length > 0) {
@@ -3181,6 +3658,17 @@ function readNested(root, containerPath) {
3181
3658
  }
3182
3659
  return cur;
3183
3660
  }
3661
+ function readEntryAt(existing, containerPath, entryName = ENTRY_NAME) {
3662
+ let node = existing;
3663
+ for (const key of containerPath) {
3664
+ if (typeof node !== "object" || node === null || Array.isArray(node)) return null;
3665
+ node = node[key];
3666
+ }
3667
+ if (typeof node !== "object" || node === null || Array.isArray(node)) return null;
3668
+ const entry = node[entryName];
3669
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return null;
3670
+ return entry;
3671
+ }
3184
3672
  function mergeClientConfig(existing, containerPath, entry, entryName = ENTRY_NAME) {
3185
3673
  if (containerPath.length === 0) throw new Error("mergeClientConfig: containerPath cannot be empty");
3186
3674
  const out = { ...existing };
@@ -3294,7 +3782,7 @@ async function runInstallList(opts, log2) {
3294
3782
  messages.push(s);
3295
3783
  log2(s);
3296
3784
  };
3297
- const home = opts.home ?? homedir8();
3785
+ const home = opts.home ?? homedir10();
3298
3786
  const cwd = opts.cwd ?? process.cwd();
3299
3787
  const os = opts.os ?? CURRENT_OS;
3300
3788
  const probes = await probeClientsAsync({ home, os, cwd, claudeConfigDir: opts.claudeConfigDir });
@@ -3582,11 +4070,11 @@ function parseDurationMs(s) {
3582
4070
  const factor = unit === "s" ? 1e3 : unit === "m" ? 6e4 : unit === "h" ? 36e5 : 864e5;
3583
4071
  return n * factor;
3584
4072
  }
3585
- function trialsDir(home = homedir9()) {
3586
- return join8(home, CONFIG_DIRNAME, TRIALS_DIRNAME);
4073
+ function trialsDir(home = homedir11()) {
4074
+ return join9(home, CONFIG_DIRNAME, TRIALS_DIRNAME);
3587
4075
  }
3588
- function trialMarkerPath(slug, home = homedir9()) {
3589
- return join8(trialsDir(home), `${slug}.json`);
4076
+ function trialMarkerPath(slug, home = homedir11()) {
4077
+ return join9(trialsDir(home), `${slug}.json`);
3590
4078
  }
3591
4079
  async function defaultFetchExplore(_baseUrl, slug) {
3592
4080
  const resolved = await resolveCatalogSlug(slug, { catalogUrl: process.env.YAW_MCP_CATALOG_URL });
@@ -3635,7 +4123,7 @@ async function runTry(opts) {
3635
4123
  return { exitCode: 2, written: [] };
3636
4124
  }
3637
4125
  const env = opts.env ?? process.env;
3638
- const home = opts.home ?? homedir9();
4126
+ const home = opts.home ?? homedir11();
3639
4127
  const cwd = opts.cwd ?? process.cwd();
3640
4128
  const os = opts.os ?? CURRENT_OS;
3641
4129
  const now = opts.now ? opts.now() : Date.now();
@@ -3713,7 +4201,7 @@ async function runTry(opts) {
3713
4201
  entryName,
3714
4202
  createdAt: now
3715
4203
  };
3716
- const clientPreExisted = existsSync5(resolved.absolute);
4204
+ const clientPreExisted = existsSync6(resolved.absolute);
3717
4205
  let rawClient = null;
3718
4206
  if (clientPreExisted) {
3719
4207
  try {
@@ -3815,10 +4303,10 @@ async function runTryCleanup(opts) {
3815
4303
  return { exitCode: 2, written: [] };
3816
4304
  }
3817
4305
  const env = opts.env ?? process.env;
3818
- const home = opts.home ?? homedir9();
4306
+ const home = opts.home ?? homedir11();
3819
4307
  const baseUrl = opts.baseUrl ?? env.YAW_MCP_BASE_URL ?? DEFAULT_BASE_URL;
3820
4308
  const markerPath = trialMarkerPath(slug, home);
3821
- if (!existsSync5(markerPath)) {
4309
+ if (!existsSync6(markerPath)) {
3822
4310
  print(`yaw-mcp try-cleanup: no trial marker for "${slug}" (nothing to do).`);
3823
4311
  return { exitCode: 0, written: [] };
3824
4312
  }
@@ -3835,7 +4323,7 @@ async function runTryCleanup(opts) {
3835
4323
  return { exitCode: 1, written: [] };
3836
4324
  }
3837
4325
  const written = [];
3838
- if (existsSync5(marker.clientPath)) {
4326
+ if (existsSync6(marker.clientPath)) {
3839
4327
  try {
3840
4328
  const raw = await readFile8(marker.clientPath, "utf8");
3841
4329
  if (raw.trim().length > 0) {
@@ -3876,11 +4364,11 @@ function formatTtl(ms) {
3876
4364
  return `${Math.round(clamped / 864e5)}d`;
3877
4365
  }
3878
4366
  async function scanTrials(opts = {}) {
3879
- const home = opts.home ?? homedir9();
4367
+ const home = opts.home ?? homedir11();
3880
4368
  const now = opts.now ? opts.now() : Date.now();
3881
4369
  const dir = trialsDir(home);
3882
4370
  const result = { live: [], expired: [], malformed: [] };
3883
- if (!existsSync5(dir)) return result;
4371
+ if (!existsSync6(dir)) return result;
3884
4372
  let entries;
3885
4373
  try {
3886
4374
  entries = await readdir(dir);
@@ -3889,7 +4377,7 @@ async function scanTrials(opts = {}) {
3889
4377
  }
3890
4378
  for (const filename of entries) {
3891
4379
  if (!filename.endsWith(".json")) continue;
3892
- const path7 = join8(dir, filename);
4380
+ const path7 = join9(dir, filename);
3893
4381
  try {
3894
4382
  const raw = await readFile8(path7, "utf8");
3895
4383
  const parsed = JSON.parse(raw);
@@ -3909,7 +4397,7 @@ async function scanTrials(opts = {}) {
3909
4397
  return result;
3910
4398
  }
3911
4399
  async function gcExpiredTrials(opts) {
3912
- const home = opts.home ?? homedir9();
4400
+ const home = opts.home ?? homedir11();
3913
4401
  const env = opts.env ?? process.env;
3914
4402
  const baseUrl = opts.baseUrl ?? env.YAW_MCP_BASE_URL ?? DEFAULT_BASE_URL;
3915
4403
  const postEvent = opts.postEvent ?? defaultPostEvent;
@@ -3919,7 +4407,7 @@ async function gcExpiredTrials(opts) {
3919
4407
  let failed = 0;
3920
4408
  for (const { marker, path: path7 } of scan.expired) {
3921
4409
  try {
3922
- if (existsSync5(marker.clientPath)) {
4410
+ if (existsSync6(marker.clientPath)) {
3923
4411
  const raw = await readFile8(marker.clientPath, "utf8");
3924
4412
  if (raw.trim().length > 0) {
3925
4413
  const parsed = parseJsonc(raw);
@@ -3947,7 +4435,7 @@ async function gcExpiredTrials(opts) {
3947
4435
  }
3948
4436
 
3949
4437
  // src/upgrade-cmd.ts
3950
- import { spawn as spawn2 } from "child_process";
4438
+ import { spawn as spawn4 } from "child_process";
3951
4439
  import { realpathSync } from "fs";
3952
4440
  var BINARY_DOWNLOAD_URL = "https://github.com/YawLabs/mcp/releases/latest";
3953
4441
  var UPGRADE_USAGE = `Usage: yaw-mcp upgrade [--run] [--json]
@@ -3996,7 +4484,7 @@ function localInstallRoot(argvPath) {
3996
4484
  async function defaultNpmPrefix() {
3997
4485
  if (process.env.VITEST) return null;
3998
4486
  return new Promise((resolve8) => {
3999
- const child = spawn2("npm", ["prefix", "-g"], {
4487
+ const child = spawn4("npm", ["prefix", "-g"], {
4000
4488
  shell: process.platform === "win32",
4001
4489
  stdio: ["ignore", "pipe", "ignore"]
4002
4490
  });
@@ -4134,7 +4622,7 @@ async function defaultFetchLatest() {
4134
4622
  }
4135
4623
  async function defaultSpawn(cmd, args, cwd) {
4136
4624
  return new Promise((resolve8) => {
4137
- const child = spawn2(cmd, args, { stdio: "inherit", shell: process.platform === "win32", cwd });
4625
+ const child = spawn4(cmd, args, { stdio: "inherit", shell: process.platform === "win32", cwd });
4138
4626
  child.on("close", (code) => resolve8(typeof code === "number" ? code : 1));
4139
4627
  child.on("error", () => resolve8(1));
4140
4628
  });
@@ -4265,7 +4753,7 @@ async function runUpgrade(opts = {}) {
4265
4753
  return { exitCode: 3, lines };
4266
4754
  }
4267
4755
  function readCurrentVersion() {
4268
- return true ? "0.73.2" : "dev";
4756
+ return true ? "0.74.1" : "dev";
4269
4757
  }
4270
4758
 
4271
4759
  // src/learning.ts
@@ -4482,7 +4970,7 @@ async function projectTrustWarning(opts) {
4482
4970
  }
4483
4971
  return untrustedProjectWarning(probe, { detail: true });
4484
4972
  }
4485
- var VERSION = true ? "0.73.2" : "dev";
4973
+ var VERSION = true ? "0.74.1" : "dev";
4486
4974
  function isPersistenceDisabled(env) {
4487
4975
  const raw = env.YAW_MCP_DISABLE_PERSISTENCE;
4488
4976
  return raw !== void 0 && raw !== "" && (raw === "1" || raw.toLowerCase() === "true");
@@ -4497,7 +4985,7 @@ async function runDoctor(opts = {}) {
4497
4985
  `);
4498
4986
  };
4499
4987
  const cwd = opts.cwd ?? process.cwd();
4500
- const home = opts.home ?? homedir10();
4988
+ const home = opts.home ?? homedir12();
4501
4989
  const os = opts.os ?? CURRENT_OS;
4502
4990
  const env = opts.env ?? process.env;
4503
4991
  print(`yaw-mcp doctor \u2014 ${(/* @__PURE__ */ new Date()).toISOString()}`);
@@ -4522,7 +5010,7 @@ async function runDoctor(opts = {}) {
4522
5010
  const oamStatus = await collectOamRuntimeStatus({ env, cwd, home, probeFn: opts.oamProbe ?? probeOam });
4523
5011
  renderOamRuntimeSection({ status: oamStatus, print });
4524
5012
  const persistenceDisabled = isPersistenceDisabled(env);
4525
- const stateFilePath = join9(userConfigDir(home), STATE_FILENAME);
5013
+ const stateFilePath = join10(userConfigDir(home), STATE_FILENAME);
4526
5014
  const statePeek = persistenceDisabled ? null : await peekStateFile(stateFilePath);
4527
5015
  const persistedState = statePeek?.kind === "ok" ? await loadState(stateFilePath) : null;
4528
5016
  renderStateSection({
@@ -4613,7 +5101,7 @@ async function runDoctorJson(opts) {
4613
5101
  const lines = [];
4614
5102
  const write = opts.out ?? ((s) => process.stdout.write(s));
4615
5103
  const cwd = opts.cwd ?? process.cwd();
4616
- const home = opts.home ?? homedir10();
5104
+ const home = opts.home ?? homedir12();
4617
5105
  const os = opts.os ?? CURRENT_OS;
4618
5106
  const env = opts.env ?? process.env;
4619
5107
  const timestamp = (/* @__PURE__ */ new Date()).toISOString();
@@ -4638,7 +5126,7 @@ async function runDoctorJson(opts) {
4638
5126
  envOverrides[name] = raw === void 0 || raw === "" ? null : raw;
4639
5127
  }
4640
5128
  const persistDisabled = isPersistenceDisabled(env);
4641
- const stateFilePath = join9(userConfigDir(home), STATE_FILENAME);
5129
+ const stateFilePath = join10(userConfigDir(home), STATE_FILENAME);
4642
5130
  const statePeek = persistDisabled ? null : await peekStateFile(stateFilePath);
4643
5131
  const stateUsable = statePeek !== null && (statePeek.kind === "ok" || statePeek.kind === "missing");
4644
5132
  const persisted = stateUsable ? await loadState(stateFilePath) : null;
@@ -4788,7 +5276,7 @@ function renderEnvSection(opts) {
4788
5276
  { name: "YAW_MCP_AUTO_LOAD", defaultHint: "auto-load inactive" },
4789
5277
  { name: "YAW_MCP_AUTO_ACTIVATE", defaultHint: "default on" },
4790
5278
  { name: "YAW_MCP_PRUNE_RESPONSES", defaultHint: "pruning active" },
4791
- { name: "YAW_MCP_DEFAULT_RUNTIME", defaultHint: "per-server opt-in only" }
5279
+ { name: "YAW_MCP_DEFAULT_RUNTIME", defaultHint: "oam when installed" }
4792
5280
  ];
4793
5281
  const widest = vars.reduce((m, v) => Math.max(m, v.name.length), 0);
4794
5282
  print("ENVIRONMENT (behavior overrides)");
@@ -4800,14 +5288,20 @@ function renderEnvSection(opts) {
4800
5288
  print("");
4801
5289
  }
4802
5290
  async function collectOamRuntimeStatus(opts) {
4803
- const probe = opts.probeFn();
5291
+ const probe = await opts.probeFn();
4804
5292
  const dflt = await describeDefaultRuntime({ env: opts.env, cwd: opts.cwd, home: opts.home });
4805
5293
  const bundles = await loadLocalBundles({ cwd: opts.cwd, home: opts.home }).catch(() => null);
4806
5294
  const servers = (bundles?.config?.servers ?? []).map((s) => ({
4807
5295
  namespace: s.namespace,
4808
5296
  info: describeServerRuntime(s, dflt.runtime, probe)
4809
5297
  }));
4810
- return { probe, dflt, servers };
5298
+ const specs = collectSidecarSpecs(bundles?.config?.servers ?? []);
5299
+ const anyManaged = hasManagedSidecars(opts.home);
5300
+ const managed = {
5301
+ root: sidecarsRoot(opts.home),
5302
+ packages: specs.map((s) => ({ pkg: s.pkg, version: anyManaged ? installedVersion(s.pkg, opts.home) : null }))
5303
+ };
5304
+ return { probe, dflt, servers, managed };
4811
5305
  }
4812
5306
  function renderOamRuntimeSection(opts) {
4813
5307
  const { status, print } = opts;
@@ -4815,12 +5309,16 @@ function renderOamRuntimeSection(opts) {
4815
5309
  print("OAM RUNTIME");
4816
5310
  if (probe.belowMin) {
4817
5311
  print(` binary: installed (v${probe.version}) \u2014 below min ${MIN_OAM_VERSION}; IGNORED, servers run on node`);
5312
+ print(" fix: oam self-update");
4818
5313
  } else if (probe.bin === null) {
4819
5314
  print(" binary: not installed \u2014 node/npx spawns are used directly");
4820
5315
  } else {
4821
5316
  print(` binary: ${probe.bin} (v${probe.version ?? "unknown"}, min ${MIN_OAM_VERSION})`);
4822
5317
  }
4823
- const dfltLabel = dflt.runtime !== null ? `${dflt.runtime} (${dflt.source === "env" ? "env YAW_MCP_DEFAULT_RUNTIME" : `bundles.json defaultRuntime @ ${dflt.path}`})` : '(not set \u2014 per-server runtime:"oam" opt-in only)';
5318
+ const rawOamVersion = process.versions.oam;
5319
+ const runningOam = typeof rawOamVersion === "string" && rawOamVersion.length > 0 ? rawOamVersion : null;
5320
+ print(` this process: ${runningOam ? `oam ${runningOam}` : `node ${process.version}`}`);
5321
+ const dfltLabel = dflt.runtime !== null ? `${dflt.runtime} (${dflt.source === "env" ? "env YAW_MCP_DEFAULT_RUNTIME" : `bundles.json defaultRuntime @ ${dflt.path}`})` : `(not set \u2014 oam when installed, currently ${probe.bin !== null ? "oam" : "node"})`;
4824
5322
  print(` default runtime: ${dfltLabel}`);
4825
5323
  if (servers.length > 0) {
4826
5324
  print(" servers (local bundles.json):");
@@ -4829,6 +5327,17 @@ function renderOamRuntimeSection(opts) {
4829
5327
  print(` ${s.namespace.padEnd(widest)} ${(s.info.runtime ?? "-").padEnd(4)} ${s.info.reason}`);
4830
5328
  }
4831
5329
  }
5330
+ const { managed } = status;
5331
+ if (managed.packages.length > 0) {
5332
+ const anyInstalled = managed.packages.some((p) => p.version !== null);
5333
+ print(` managed install: ${anyInstalled ? managed.root : "none \u2014 run `yaw-mcp sidecars install`"}`);
5334
+ if (anyInstalled) {
5335
+ const widest = managed.packages.reduce((m, p) => Math.max(m, p.pkg.length), 0);
5336
+ for (const p of managed.packages) {
5337
+ print(` ${p.pkg.padEnd(widest)} ${p.version ?? "not installed \u2014 resolves from the npx cache"}`);
5338
+ }
5339
+ }
5340
+ }
4832
5341
  print("");
4833
5342
  }
4834
5343
  function renderProjectGuideSection(opts) {
@@ -4960,14 +5469,26 @@ function renderClientStatus(c, installCmd) {
4960
5469
  if (c.hasMcpEntry && c.hasLegacyEntry) {
4961
5470
  return `OK \u2014 has "${ENTRY_NAME}" entry; legacy "${c.legacyEntryName}" entry also present \u2014 remove it to avoid running yaw-mcp twice`;
4962
5471
  }
4963
- if (c.hasMcpEntry) return `OK \u2014 has "${ENTRY_NAME}" entry`;
5472
+ if (c.launchCommandMissing) {
5473
+ return `has "${ENTRY_NAME}" entry, but its launch command does not exist: ${c.launchCommandMissing} \u2014 the client cannot start yaw-mcp; rerun \`${installCmd}\``;
5474
+ }
5475
+ if (c.hasMcpEntry) {
5476
+ return `OK \u2014 has "${ENTRY_NAME}" entry${c.launchRuntime === "oam" ? " (runs on oam)" : ""}`;
5477
+ }
4964
5478
  if (c.hasLegacyEntry) {
4965
5479
  return `legacy "${c.legacyEntryName}" entry present \u2014 run \`${installCmd}\` to migrate, then remove the legacy entry by hand`;
4966
5480
  }
4967
5481
  if (c.exists) return `present, no "${ENTRY_NAME}" entry \u2014 run \`${installCmd}\``;
4968
5482
  return `not configured \u2014 run \`${installCmd}\``;
4969
5483
  }
4970
- var MALFORMED = { hasMcpEntry: false, hasLegacyEntry: false, legacyEntryName: null, malformed: true };
5484
+ var MALFORMED = {
5485
+ hasMcpEntry: false,
5486
+ hasLegacyEntry: false,
5487
+ legacyEntryName: null,
5488
+ malformed: true,
5489
+ launchCommandMissing: null,
5490
+ launchRuntime: null
5491
+ };
4971
5492
  function* enumerateProbeSlots(opts) {
4972
5493
  for (const target of INSTALL_TARGETS) {
4973
5494
  if (!target.availableOn.includes(opts.os)) {
@@ -4978,6 +5499,8 @@ function* enumerateProbeSlots(opts) {
4978
5499
  path: "(n/a)",
4979
5500
  exists: false,
4980
5501
  hasMcpEntry: false,
5502
+ launchCommandMissing: null,
5503
+ launchRuntime: null,
4981
5504
  hasLegacyEntry: false,
4982
5505
  legacyEntryName: null,
4983
5506
  malformed: false,
@@ -5001,7 +5524,7 @@ function* enumerateProbeSlots(opts) {
5001
5524
  } catch {
5002
5525
  continue;
5003
5526
  }
5004
- const exists3 = existsSync6(resolved.absolute);
5527
+ const exists3 = existsSync7(resolved.absolute);
5005
5528
  yield {
5006
5529
  result: {
5007
5530
  clientId: target.clientId,
@@ -5009,6 +5532,8 @@ function* enumerateProbeSlots(opts) {
5009
5532
  path: resolved.absolute,
5010
5533
  exists: exists3,
5011
5534
  hasMcpEntry: false,
5535
+ launchCommandMissing: null,
5536
+ launchRuntime: null,
5012
5537
  hasLegacyEntry: false,
5013
5538
  legacyEntryName: null,
5014
5539
  malformed: false,
@@ -5024,7 +5549,7 @@ function probeClients(opts) {
5024
5549
  for (const { result, read } of enumerateProbeSlots(opts)) {
5025
5550
  if (read) {
5026
5551
  try {
5027
- Object.assign(result, classifyProbeContent(readFileSync2(read.path, "utf8"), read.containerPath));
5552
+ Object.assign(result, classifyProbeContent(readFileSync3(read.path, "utf8"), read.containerPath));
5028
5553
  } catch {
5029
5554
  Object.assign(result, MALFORMED);
5030
5555
  }
@@ -5042,28 +5567,69 @@ function walkContainer(root, path7) {
5042
5567
  if (typeof cur !== "object" || cur === null || Array.isArray(cur)) return null;
5043
5568
  return cur;
5044
5569
  }
5045
- function classifyProbeContent(raw, containerPath) {
5570
+ function classifyProbeContent(raw, containerPath, exists3 = existsSync7) {
5046
5571
  if (raw.trim().length === 0) {
5047
- return { hasMcpEntry: false, hasLegacyEntry: false, legacyEntryName: null, malformed: false };
5572
+ return {
5573
+ hasMcpEntry: false,
5574
+ hasLegacyEntry: false,
5575
+ legacyEntryName: null,
5576
+ malformed: false,
5577
+ launchCommandMissing: null,
5578
+ launchRuntime: null
5579
+ };
5048
5580
  }
5049
5581
  try {
5050
5582
  const parsed = parseJsonc(raw);
5051
5583
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
5052
- return { hasMcpEntry: false, hasLegacyEntry: false, legacyEntryName: null, malformed: true };
5584
+ return {
5585
+ hasMcpEntry: false,
5586
+ hasLegacyEntry: false,
5587
+ legacyEntryName: null,
5588
+ malformed: true,
5589
+ launchCommandMissing: null,
5590
+ launchRuntime: null
5591
+ };
5053
5592
  }
5054
5593
  const container = walkContainer(parsed, containerPath);
5055
5594
  if (!container) {
5056
- return { hasMcpEntry: false, hasLegacyEntry: false, legacyEntryName: null, malformed: false };
5595
+ return {
5596
+ hasMcpEntry: false,
5597
+ hasLegacyEntry: false,
5598
+ legacyEntryName: null,
5599
+ malformed: false,
5600
+ launchCommandMissing: null,
5601
+ launchRuntime: null
5602
+ };
5057
5603
  }
5058
5604
  const legacyEntryName = findLegacyEntry(container);
5605
+ const entry = container[ENTRY_NAME];
5606
+ let launchCommandMissing = null;
5607
+ let launchRuntime = null;
5608
+ if (typeof entry === "object" && entry !== null && !Array.isArray(entry)) {
5609
+ const command = entry.command;
5610
+ if (typeof command === "string") {
5611
+ if (isAbsolute4(command) && !exists3(command)) launchCommandMissing = command;
5612
+ const entryArgs = entry.args;
5613
+ launchRuntime = isOamLaunch(command, Array.isArray(entryArgs) ? entryArgs : []) ? "oam" : "node";
5614
+ }
5615
+ }
5059
5616
  return {
5060
5617
  hasMcpEntry: ENTRY_NAME in container,
5061
5618
  hasLegacyEntry: legacyEntryName !== null,
5062
5619
  legacyEntryName,
5063
- malformed: false
5620
+ malformed: false,
5621
+ launchCommandMissing,
5622
+ launchRuntime
5064
5623
  };
5065
5624
  } catch {
5066
- return { hasMcpEntry: false, hasLegacyEntry: false, legacyEntryName: null, malformed: true };
5625
+ return {
5626
+ hasMcpEntry: false,
5627
+ hasLegacyEntry: false,
5628
+ legacyEntryName: null,
5629
+ malformed: true,
5630
+ launchCommandMissing: null,
5631
+ launchRuntime: null
5632
+ };
5067
5633
  }
5068
5634
  }
5069
5635
  async function probeClientsAsync(opts) {
@@ -5129,9 +5695,9 @@ function scanShellHistoryForShadows(opts) {
5129
5695
  }
5130
5696
  function shellHistorySources(opts) {
5131
5697
  const sources = [];
5132
- sources.push({ path: join9(opts.home, ".bash_history"), extractCommand: (l) => l.trim() || null });
5698
+ sources.push({ path: join10(opts.home, ".bash_history"), extractCommand: (l) => l.trim() || null });
5133
5699
  sources.push({
5134
- path: join9(opts.home, ".zsh_history"),
5700
+ path: join10(opts.home, ".zsh_history"),
5135
5701
  // Zsh extended-history lines look like `: 1700000000:0;npm audit`.
5136
5702
  // Strip the metadata prefix so we get just the command.
5137
5703
  extractCommand: (l) => {
@@ -5147,7 +5713,7 @@ function shellHistorySources(opts) {
5147
5713
  const appData = opts.env.APPDATA;
5148
5714
  if (appData) {
5149
5715
  sources.push({
5150
- path: join9(appData, "Microsoft", "Windows", "PowerShell", "PSReadLine", "ConsoleHost_history.txt"),
5716
+ path: join10(appData, "Microsoft", "Windows", "PowerShell", "PSReadLine", "ConsoleHost_history.txt"),
5151
5717
  extractCommand: (l) => l.trim() || null
5152
5718
  });
5153
5719
  }
@@ -5155,7 +5721,7 @@ function shellHistorySources(opts) {
5155
5721
  }
5156
5722
  function readTailLines(path7, n) {
5157
5723
  try {
5158
- const raw = readFileSync2(path7, "utf8");
5724
+ const raw = readFileSync3(path7, "utf8");
5159
5725
  const all = raw.split(/\r?\n/);
5160
5726
  return all.length <= n ? all : all.slice(all.length - n);
5161
5727
  } catch {
@@ -5200,13 +5766,13 @@ function compareSemver(a, b) {
5200
5766
  }
5201
5767
 
5202
5768
  // src/foundry-cmd.ts
5203
- import { mkdirSync, readFileSync as readFileSync4, writeFileSync } from "fs";
5204
- import { homedir as homedir12 } from "os";
5769
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync } from "fs";
5770
+ import { homedir as homedir14 } from "os";
5205
5771
  import path5 from "path";
5206
5772
 
5207
5773
  // src/foundry.ts
5208
5774
  import { appendFile, mkdir as mkdir4, stat as stat3 } from "fs/promises";
5209
- import { homedir as homedir11 } from "os";
5775
+ import { homedir as homedir13 } from "os";
5210
5776
  import path4 from "path";
5211
5777
 
5212
5778
  // src/relevance.ts
@@ -5224,28 +5790,31 @@ function tokenize(text) {
5224
5790
  if (!text) return [];
5225
5791
  return text.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length >= MIN_TOKEN_LEN);
5226
5792
  }
5793
+ function emptyField() {
5794
+ return { len: 0, counts: /* @__PURE__ */ new Map() };
5795
+ }
5796
+ function addTokens(field, tokens) {
5797
+ for (const t of tokens) {
5798
+ field.counts.set(t, (field.counts.get(t) ?? 0) + 1);
5799
+ }
5800
+ field.len += tokens.length;
5801
+ return field;
5802
+ }
5227
5803
  function buildDocFields(server) {
5228
- const toolNameTokens = [];
5229
- const toolDescriptionTokens = [];
5804
+ const toolName = emptyField();
5805
+ const toolDescription = emptyField();
5230
5806
  for (const tool of server.tools) {
5231
- toolNameTokens.push(...tokenize(tool.name));
5232
- toolDescriptionTokens.push(...tokenize(tool.description));
5807
+ addTokens(toolName, tokenize(tool.name));
5808
+ addTokens(toolDescription, tokenize(tool.description));
5233
5809
  }
5234
5810
  return {
5235
- namespace: tokenize(server.namespace),
5236
- name: tokenize(server.name),
5237
- description: tokenize(server.description),
5238
- toolName: toolNameTokens,
5239
- toolDescription: toolDescriptionTokens
5811
+ namespace: addTokens(emptyField(), tokenize(server.namespace)),
5812
+ name: addTokens(emptyField(), tokenize(server.name)),
5813
+ description: addTokens(emptyField(), tokenize(server.description)),
5814
+ toolName,
5815
+ toolDescription
5240
5816
  };
5241
5817
  }
5242
- function termFreq(tokens, term) {
5243
- let count = 0;
5244
- for (const t of tokens) {
5245
- if (t === term) count++;
5246
- }
5247
- return count;
5248
- }
5249
5818
  function bm25Score(queryTerms, fields, avgFieldLen, idfValues) {
5250
5819
  let score = 0;
5251
5820
  const seen = /* @__PURE__ */ new Set();
@@ -5255,12 +5824,12 @@ function bm25Score(queryTerms, fields, avgFieldLen, idfValues) {
5255
5824
  const termIdf = idfValues.get(term);
5256
5825
  if (termIdf === void 0 || termIdf <= 0) continue;
5257
5826
  for (const [fieldName, weight] of Object.entries(FIELD_WEIGHTS)) {
5258
- const fieldTokens = fields[fieldName];
5259
- if (fieldTokens.length === 0) continue;
5260
- const tf = termFreq(fieldTokens, term);
5827
+ const field = fields[fieldName];
5828
+ if (field.len === 0) continue;
5829
+ const tf = field.counts.get(term) ?? 0;
5261
5830
  if (tf === 0) continue;
5262
5831
  const avg = avgFieldLen[fieldName] || 1;
5263
- const normLen = 1 - B + B * (fieldTokens.length / avg);
5832
+ const normLen = 1 - B + B * (field.len / avg);
5264
5833
  const numerator = tf * (K1 + 1);
5265
5834
  const denominator = tf + K1 * normLen;
5266
5835
  score += weight * termIdf * (numerator / denominator);
@@ -5268,27 +5837,67 @@ function bm25Score(queryTerms, fields, avgFieldLen, idfValues) {
5268
5837
  }
5269
5838
  return score;
5270
5839
  }
5271
- function rankServers(context, servers) {
5272
- const queryTerms = tokenize(context);
5273
- if (queryTerms.length === 0 || servers.length === 0) return [];
5274
- const docsWithFields = servers.map((s) => ({ server: s, fields: buildDocFields(s) }));
5275
- const N = docsWithFields.length;
5840
+ var MAX_CACHED_DOCS = 512;
5841
+ var docCache = /* @__PURE__ */ new Map();
5842
+ var MAX_CACHED_INDEXES = 4;
5843
+ var indexCache = /* @__PURE__ */ new Map();
5844
+ var indexBuilds = 0;
5845
+ var docBuilds = 0;
5846
+ function putBounded(cache, key, value, max) {
5847
+ if (cache.size >= max) {
5848
+ const oldest = cache.keys().next().value;
5849
+ if (oldest !== void 0) cache.delete(oldest);
5850
+ }
5851
+ cache.set(key, value);
5852
+ }
5853
+ function touch(cache, key, value) {
5854
+ cache.delete(key);
5855
+ cache.set(key, value);
5856
+ }
5857
+ var SEP = "\0";
5858
+ function esc(text) {
5859
+ return text.includes(SEP) ? text.replaceAll(SEP, SEP + SEP) : text;
5860
+ }
5861
+ function serverSignature(server) {
5862
+ let sig = `${esc(server.namespace)}${SEP}${esc(server.name)}${SEP}${esc(server.description ?? "")}`;
5863
+ for (const tool of server.tools) {
5864
+ sig += `${SEP}${esc(tool.name)}${SEP}${esc(tool.description ?? "")}`;
5865
+ }
5866
+ return sig;
5867
+ }
5868
+ function indexKeyFor(signatures) {
5869
+ let lens = "";
5870
+ for (const sig of signatures) lens += `${sig.length},`;
5871
+ return `${lens}|${signatures.join("")}`;
5872
+ }
5873
+ function docFieldsFor(signature, server) {
5874
+ const cached = docCache.get(signature);
5875
+ if (cached) {
5876
+ touch(docCache, signature, cached);
5877
+ return cached;
5878
+ }
5879
+ docBuilds++;
5880
+ const fields = buildDocFields(server);
5881
+ putBounded(docCache, signature, fields, MAX_CACHED_DOCS);
5882
+ return fields;
5883
+ }
5884
+ function buildIndex(servers, signatures) {
5885
+ indexBuilds++;
5886
+ const docs = servers.map((s, i) => ({ namespace: s.namespace, fields: docFieldsFor(signatures[i], s) }));
5887
+ const N = docs.length;
5276
5888
  const df = /* @__PURE__ */ new Map();
5277
- for (const { fields } of docsWithFields) {
5278
- const bag = /* @__PURE__ */ new Set([
5279
- ...fields.namespace,
5280
- ...fields.name,
5281
- ...fields.description,
5282
- ...fields.toolName,
5283
- ...fields.toolDescription
5284
- ]);
5889
+ for (const { fields } of docs) {
5890
+ const bag = /* @__PURE__ */ new Set();
5891
+ for (const fieldName of Object.keys(FIELD_WEIGHTS)) {
5892
+ for (const term of fields[fieldName].counts.keys()) bag.add(term);
5893
+ }
5285
5894
  for (const term of bag) {
5286
5895
  df.set(term, (df.get(term) ?? 0) + 1);
5287
5896
  }
5288
5897
  }
5289
- const idfValues = /* @__PURE__ */ new Map();
5898
+ const idf = /* @__PURE__ */ new Map();
5290
5899
  for (const [term, d] of df) {
5291
- idfValues.set(term, Math.log((N - d + 0.5) / (d + 0.5) + 1));
5900
+ idf.set(term, Math.log((N - d + 0.5) / (d + 0.5) + 1));
5292
5901
  }
5293
5902
  const totalLen = {
5294
5903
  namespace: 0,
@@ -5297,12 +5906,10 @@ function rankServers(context, servers) {
5297
5906
  toolName: 0,
5298
5907
  toolDescription: 0
5299
5908
  };
5300
- for (const { fields } of docsWithFields) {
5301
- totalLen.namespace += fields.namespace.length;
5302
- totalLen.name += fields.name.length;
5303
- totalLen.description += fields.description.length;
5304
- totalLen.toolName += fields.toolName.length;
5305
- totalLen.toolDescription += fields.toolDescription.length;
5909
+ for (const { fields } of docs) {
5910
+ for (const fieldName of Object.keys(FIELD_WEIGHTS)) {
5911
+ totalLen[fieldName] += fields[fieldName].len;
5912
+ }
5306
5913
  }
5307
5914
  const denom = Math.max(N, 1);
5308
5915
  const avgFieldLen = {
@@ -5312,11 +5919,14 @@ function rankServers(context, servers) {
5312
5919
  toolName: totalLen.toolName / denom,
5313
5920
  toolDescription: totalLen.toolDescription / denom
5314
5921
  };
5922
+ return { docs, idf, avgFieldLen };
5923
+ }
5924
+ function scoreAgainstIndex(queryTerms, index) {
5315
5925
  const results = [];
5316
- for (const { server, fields } of docsWithFields) {
5317
- const score = bm25Score(queryTerms, fields, avgFieldLen, idfValues);
5926
+ for (const { namespace, fields } of index.docs) {
5927
+ const score = bm25Score(queryTerms, fields, index.avgFieldLen, index.idf);
5318
5928
  if (score > 0) {
5319
- results.push({ namespace: server.namespace, score });
5929
+ results.push({ namespace, score });
5320
5930
  }
5321
5931
  }
5322
5932
  results.sort((a, b) => {
@@ -5325,6 +5935,20 @@ function rankServers(context, servers) {
5325
5935
  });
5326
5936
  return results;
5327
5937
  }
5938
+ function rankServers(context, servers) {
5939
+ const queryTerms = tokenize(context);
5940
+ if (queryTerms.length === 0 || servers.length === 0) return [];
5941
+ const signatures = servers.map(serverSignature);
5942
+ const indexKey = indexKeyFor(signatures);
5943
+ let index = indexCache.get(indexKey);
5944
+ if (index === void 0) {
5945
+ index = buildIndex(servers, signatures);
5946
+ putBounded(indexCache, indexKey, index, MAX_CACHED_INDEXES);
5947
+ } else {
5948
+ touch(indexCache, indexKey, index);
5949
+ }
5950
+ return scoreAgainstIndex(queryTerms, index);
5951
+ }
5328
5952
 
5329
5953
  // src/foundry.ts
5330
5954
  var SECRET_PREFIXES = ["sk_", "sk-", "tok_", "ghp_", "gho_", "xox", "pk_", "akia"];
@@ -5372,7 +5996,7 @@ function isFoundryEnabled() {
5372
5996
  }
5373
5997
  var MAX_FOUNDRY_BYTES = 5 * 1024 * 1024;
5374
5998
  var FOUNDRY_FILENAME = "foundry.jsonl";
5375
- async function appendFoundryTrace(trace, home = homedir11()) {
5999
+ async function appendFoundryTrace(trace, home = homedir13()) {
5376
6000
  try {
5377
6001
  if (!isFoundryEnabled()) return;
5378
6002
  const dir = userConfigDir(home);
@@ -5397,7 +6021,7 @@ async function appendFoundryTrace(trace, home = homedir11()) {
5397
6021
  }
5398
6022
 
5399
6023
  // src/foundry-corpus.ts
5400
- import { readFileSync as readFileSync3 } from "fs";
6024
+ import { readFileSync as readFileSync4 } from "fs";
5401
6025
  var FOUNDRY_CORPUS_VERSION = 1;
5402
6026
  var DEFAULT_CORPUS_CAP = 500;
5403
6027
  function parseTraceLines(text) {
@@ -5556,11 +6180,11 @@ async function runFoundryExport(opts) {
5556
6180
  writeErr(`${s}
5557
6181
  `);
5558
6182
  };
5559
- const home = opts.home ?? homedir12();
6183
+ const home = opts.home ?? homedir14();
5560
6184
  const harvestPath = path5.join(userConfigDir(home), FOUNDRY_FILENAME);
5561
6185
  const blob = opts.readTraces ? opts.readTraces() : (() => {
5562
6186
  try {
5563
- return readFileSync4(harvestPath, "utf8");
6187
+ return readFileSync5(harvestPath, "utf8");
5564
6188
  } catch {
5565
6189
  return null;
5566
6190
  }
@@ -5582,7 +6206,7 @@ async function runFoundryExport(opts) {
5582
6206
  );
5583
6207
  return { exitCode: 2, lines };
5584
6208
  }
5585
- mkdirSync(path5.dirname(path5.resolve(opts.out)), { recursive: true });
6209
+ mkdirSync2(path5.dirname(path5.resolve(opts.out)), { recursive: true });
5586
6210
  writeFileSync(opts.out, `${JSON.stringify(corpus, null, 2)}
5587
6211
  `, "utf8");
5588
6212
  const score = scoreCorpus(corpus);
@@ -5612,13 +6236,13 @@ async function runFoundryExport(opts) {
5612
6236
 
5613
6237
  // src/local-add-cmd.ts
5614
6238
  import { readFile as readFile11 } from "fs/promises";
5615
- import { homedir as homedir14 } from "os";
6239
+ import { homedir as homedir16 } from "os";
5616
6240
  import { createInterface as createInterface3 } from "readline/promises";
5617
6241
 
5618
6242
  // src/trust-cmd.ts
5619
6243
  import { readFile as readFile10 } from "fs/promises";
5620
- import { homedir as homedir13 } from "os";
5621
- import { isAbsolute as isAbsolute4, resolve as resolve7 } from "path";
6244
+ import { homedir as homedir15 } from "os";
6245
+ import { isAbsolute as isAbsolute5, resolve as resolve7 } from "path";
5622
6246
  import { createInterface as createInterface2 } from "readline/promises";
5623
6247
  var TRUST_USAGE = `Usage: yaw-mcp trust [--yes]
5624
6248
  yaw-mcp trust --list [--json]
@@ -5718,7 +6342,7 @@ async function runTrustGrant(opts) {
5718
6342
  `);
5719
6343
  const printErr = (s) => err(`${s}
5720
6344
  `);
5721
- const home = opts.home ?? homedir13();
6345
+ const home = opts.home ?? homedir15();
5722
6346
  const cwd = opts.cwd ?? process.cwd();
5723
6347
  const env = opts.env ?? process.env;
5724
6348
  const probe = await probeProjectTrust({ cwd, home, env });
@@ -5855,7 +6479,7 @@ function displayArg(s) {
5855
6479
  var SCRIPT_EXT_RE = /\.(?:js|mjs|cjs|ts|mts|cts|py|rb|sh|bash|zsh|pl|php|lua|jar|bat|cmd|ps1|exe)$/i;
5856
6480
  function inRepoTokens(s) {
5857
6481
  const hits = [];
5858
- const isLocalish = (t) => t.length > 0 && !/\s/.test(t) && !isAbsolute4(t) && !t.includes("://") && !t.startsWith("-");
6482
+ const isLocalish = (t) => t.length > 0 && !/\s/.test(t) && !isAbsolute5(t) && !t.includes("://") && !t.startsWith("-");
5859
6483
  const command = s.command ?? "";
5860
6484
  if (isLocalish(command) && (/^\.{1,2}[\\/]/.test(command) || /[\\/]/.test(command))) hits.push(command);
5861
6485
  for (const a of s.args ?? []) {
@@ -5902,7 +6526,7 @@ function unversionedRegistrySpec(s) {
5902
6526
  break;
5903
6527
  }
5904
6528
  if (spec === null || spec.length === 0) return null;
5905
- if (spec.includes("://") || isAbsolute4(spec) || /^\.{1,2}[\\/]/.test(spec)) return null;
6529
+ if (spec.includes("://") || isAbsolute5(spec) || /^\.{1,2}[\\/]/.test(spec)) return null;
5906
6530
  const body = spec.startsWith("@") ? spec.slice(1) : spec;
5907
6531
  const afterScope = body.includes("/") ? body.slice(body.indexOf("/") + 1) : body;
5908
6532
  if (afterScope.includes("@") || afterScope.includes("==")) return null;
@@ -5930,7 +6554,7 @@ async function runTrustList(opts) {
5930
6554
  const err = opts.err ?? ((s) => process.stderr.write(s));
5931
6555
  const print = (s = "") => out(`${s}
5932
6556
  `);
5933
- const home = opts.home ?? homedir13();
6557
+ const home = opts.home ?? homedir15();
5934
6558
  const store = await readTrustStore(home);
5935
6559
  if (store.malformed) {
5936
6560
  const fix = store.malformedKind === "io" ? "fix its permissions (do NOT delete it -- your approvals are still in there)" : "it is fixed or deleted";
@@ -5999,7 +6623,7 @@ async function runTrustRevoke(opts) {
5999
6623
  `);
6000
6624
  const printErr = (s) => err(`${s}
6001
6625
  `);
6002
- const home = opts.home ?? homedir13();
6626
+ const home = opts.home ?? homedir15();
6003
6627
  const cwd = opts.cwd ?? process.cwd();
6004
6628
  const env = opts.env ?? process.env;
6005
6629
  let target;
@@ -6138,7 +6762,7 @@ async function runAdd(opts) {
6138
6762
  return { exitCode: 2, written: [] };
6139
6763
  }
6140
6764
  const env = opts.env ?? process.env;
6141
- const home = opts.home ?? homedir14();
6765
+ const home = opts.home ?? homedir16();
6142
6766
  const cwd = opts.cwd ?? process.cwd();
6143
6767
  let server;
6144
6768
  try {
@@ -6334,7 +6958,7 @@ async function runRemove(opts) {
6334
6958
  printErr(`yaw-mcp remove: "${opts.target}" isn't a valid slug or namespace.`);
6335
6959
  return { exitCode: 2, written: [] };
6336
6960
  }
6337
- const home = opts.home ?? homedir14();
6961
+ const home = opts.home ?? homedir16();
6338
6962
  const cwd = opts.cwd ?? process.cwd();
6339
6963
  const derived = deriveNamespace(opts.target);
6340
6964
  const candidates = derived === opts.target ? [opts.target] : [opts.target, derived];
@@ -6414,7 +7038,7 @@ async function runList(opts) {
6414
7038
  `);
6415
7039
  const printErr = (s) => err(`${s}
6416
7040
  `);
6417
- const home = opts.home ?? homedir14();
7041
+ const home = opts.home ?? homedir16();
6418
7042
  const cwd = opts.cwd ?? process.cwd();
6419
7043
  const loaded = await loadLocalBundles({ home, cwd });
6420
7044
  const servers = loaded.config?.servers ?? [];
@@ -6456,8 +7080,8 @@ ${servers.length} server${servers.length === 1 ? "" : "s"} in ${loaded.path}`);
6456
7080
 
6457
7081
  // src/reset-learning-cmd.ts
6458
7082
  import { readFile as readFile12, unlink as unlink3 } from "fs/promises";
6459
- import { homedir as homedir15 } from "os";
6460
- import { join as join10 } from "path";
7083
+ import { homedir as homedir17 } from "os";
7084
+ import { join as join11 } from "path";
6461
7085
  var RESET_LEARNING_USAGE = `Usage: yaw-mcp reset-learning
6462
7086
 
6463
7087
  Delete ~/.yaw-mcp/state.json so cross-session learning starts fresh.
@@ -6478,7 +7102,7 @@ ${RESET_LEARNING_USAGE}`
6478
7102
  };
6479
7103
  }
6480
7104
  async function runResetLearning(opts = {}) {
6481
- const home = opts.home ?? homedir15();
7105
+ const home = opts.home ?? homedir17();
6482
7106
  const env = opts.env ?? process.env;
6483
7107
  const write = opts.out ?? ((s) => process.stdout.write(s));
6484
7108
  const writeErr = opts.err ?? ((s) => process.stderr.write(s));
@@ -6493,7 +7117,7 @@ async function runResetLearning(opts = {}) {
6493
7117
  writeErr(`${s}
6494
7118
  `);
6495
7119
  };
6496
- const filePath = join10(userConfigDir(home), STATE_FILENAME);
7120
+ const filePath = join11(userConfigDir(home), STATE_FILENAME);
6497
7121
  const raw = env.YAW_MCP_DISABLE_PERSISTENCE;
6498
7122
  const disabled = raw !== void 0 && raw !== "" && (raw === "1" || raw.toLowerCase() === "true");
6499
7123
  if (disabled) {
@@ -6548,20 +7172,20 @@ function isFileNotFound2(err) {
6548
7172
  }
6549
7173
 
6550
7174
  // src/secrets-cmd.ts
6551
- import { existsSync as existsSync8 } from "fs";
6552
- import { homedir as homedir18 } from "os";
7175
+ import { existsSync as existsSync9 } from "fs";
7176
+ import { homedir as homedir20 } from "os";
6553
7177
 
6554
7178
  // src/secrets-audit.ts
6555
- import { existsSync as existsSync7 } from "fs";
7179
+ import { existsSync as existsSync8 } from "fs";
6556
7180
  import { appendFile as appendFile2, chmod as chmod5, readFile as readFile13, stat as stat4 } from "fs/promises";
6557
- import { homedir as homedir16 } from "os";
6558
- import { join as join11 } from "path";
7181
+ import { homedir as homedir18 } from "os";
7182
+ import { join as join12 } from "path";
6559
7183
  var SECRETS_AUDIT_FILENAME = "secrets-audit.log";
6560
7184
  var AUDIT_TAIL_CAP = 5e3;
6561
- function auditLogPath(home = homedir16()) {
6562
- return join11(home, CONFIG_DIRNAME, SECRETS_AUDIT_FILENAME);
7185
+ function auditLogPath(home = homedir18()) {
7186
+ return join12(home, CONFIG_DIRNAME, SECRETS_AUDIT_FILENAME);
6563
7187
  }
6564
- async function appendAuditEvent(input, home = homedir16()) {
7188
+ async function appendAuditEvent(input, home = homedir18()) {
6565
7189
  try {
6566
7190
  const event = {
6567
7191
  ts: (/* @__PURE__ */ new Date()).toISOString(),
@@ -6572,7 +7196,7 @@ async function appendAuditEvent(input, home = homedir16()) {
6572
7196
  const path7 = auditLogPath(home);
6573
7197
  const line = `${JSON.stringify(event)}
6574
7198
  `;
6575
- if (!existsSync7(path7)) {
7199
+ if (!existsSync8(path7)) {
6576
7200
  await atomicWriteFile(path7, line, "utf8", 384, 448);
6577
7201
  } else {
6578
7202
  await appendFile2(path7, line, "utf8");
@@ -6595,9 +7219,9 @@ async function trimToTailCap(path7) {
6595
7219
  await atomicWriteFile(path7, `${kept.join("\n")}
6596
7220
  `, "utf8", 384);
6597
7221
  }
6598
- async function readAuditLog(filter = {}, home = homedir16()) {
7222
+ async function readAuditLog(filter = {}, home = homedir18()) {
6599
7223
  const path7 = auditLogPath(home);
6600
- if (!existsSync7(path7)) return [];
7224
+ if (!existsSync8(path7)) return [];
6601
7225
  let raw;
6602
7226
  try {
6603
7227
  raw = await readFile13(path7, "utf8");
@@ -6629,8 +7253,8 @@ function isAuditEvent(v) {
6629
7253
  // src/secrets-vault.ts
6630
7254
  import { createHmac, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
6631
7255
  import { chmod as chmod6, mkdir as mkdir5, readFile as readFile14 } from "fs/promises";
6632
- import { homedir as homedir17 } from "os";
6633
- import { dirname as dirname2, join as join12 } from "path";
7256
+ import { homedir as homedir19 } from "os";
7257
+ import { dirname as dirname3, join as join13 } from "path";
6634
7258
 
6635
7259
  // src/secrets-crypto.ts
6636
7260
  import { createCipheriv, createDecipheriv, randomBytes, scrypt as scryptCb } from "crypto";
@@ -6687,8 +7311,8 @@ function decryptEntry(entry, key) {
6687
7311
  var SECRETS_FILENAME = "secrets.json";
6688
7312
  var SECRETS_SCHEMA_VERSION = 1;
6689
7313
  var VAULT_CHECK_PLAINTEXT = "yaw-mcp-vault-v1";
6690
- function vaultPath(home = homedir17()) {
6691
- return join12(home, CONFIG_DIRNAME, SECRETS_FILENAME);
7314
+ function vaultPath(home = homedir19()) {
7315
+ return join13(home, CONFIG_DIRNAME, SECRETS_FILENAME);
6692
7316
  }
6693
7317
  function emptyVault() {
6694
7318
  return {
@@ -6749,7 +7373,7 @@ function isEncryptedEntry(v) {
6749
7373
  return typeof e.iv === "string" && typeof e.ciphertext === "string" && typeof e.authTag === "string";
6750
7374
  }
6751
7375
  async function saveVault(path7, vault) {
6752
- const dir = dirname2(path7);
7376
+ const dir = dirname3(path7);
6753
7377
  await mkdir5(dir, { recursive: true });
6754
7378
  if (process.platform !== "win32") {
6755
7379
  try {
@@ -7261,7 +7885,7 @@ async function runSecrets(opts, io = {
7261
7885
  out: (s) => process.stdout.write(s),
7262
7886
  err: (s) => process.stderr.write(s)
7263
7887
  }) {
7264
- const home = opts.home ?? homedir18();
7888
+ const home = opts.home ?? homedir20();
7265
7889
  const path7 = vaultPath(home);
7266
7890
  if (opts.action === "lock") {
7267
7891
  lock();
@@ -7281,7 +7905,7 @@ async function runSecrets(opts, io = {
7281
7905
  if (!loaded2.ok) return loaded2.result;
7282
7906
  const vault2 = loaded2.vault;
7283
7907
  const keys = vault2 ? listKeys(vault2) : [];
7284
- if (opts.json) io.out(`${JSON.stringify({ ok: true, vault: existsSync8(path7), keys }, null, 2)}
7908
+ if (opts.json) io.out(`${JSON.stringify({ ok: true, vault: existsSync9(path7), keys }, null, 2)}
7285
7909
  `);
7286
7910
  else if (!vault2) io.out(`No vault at ${path7}. Run \`yaw-mcp secrets set <name>\` to create one.
7287
7911
  `);
@@ -7334,7 +7958,7 @@ async function runSecrets(opts, io = {
7334
7958
  if (!confirmed) return abortedResult(io, opts.json, "set");
7335
7959
  }
7336
7960
  let vault = loaded.vault ?? newVault();
7337
- const isFresh = !existsSync8(path7);
7961
+ const isFresh = !existsSync9(path7);
7338
7962
  const creatingVault = opts.action === "set" && !vault.check && Object.keys(vault.entries).length === 0;
7339
7963
  const passphrase = await resolvePassphrase(opts, creatingVault);
7340
7964
  if (passphrase === CANCELLED) return cancelledResult(io, opts.json);
@@ -7452,7 +8076,7 @@ async function runSecrets(opts, io = {
7452
8076
  return { exitCode: 2 };
7453
8077
  }
7454
8078
  async function runSecretsRotate(opts, io) {
7455
- const home = opts.home ?? homedir18();
8079
+ const home = opts.home ?? homedir20();
7456
8080
  const path7 = vaultPath(home);
7457
8081
  const loaded = await safeLoadVault(path7, io, opts.json, "rotate");
7458
8082
  if (!loaded.ok) return loaded.result;
@@ -7524,7 +8148,7 @@ async function runSecretsRotate(opts, io) {
7524
8148
  return { exitCode: 0 };
7525
8149
  }
7526
8150
  async function runSecretsAudit(opts, io) {
7527
- const home = opts.home ?? homedir18();
8151
+ const home = opts.home ?? homedir20();
7528
8152
  let events;
7529
8153
  try {
7530
8154
  events = await readAuditLog(
@@ -7559,7 +8183,7 @@ async function runSecretsAudit(opts, io) {
7559
8183
  }
7560
8184
 
7561
8185
  // src/server.ts
7562
- import { homedir as homedir19 } from "os";
8186
+ import { homedir as homedir21 } from "os";
7563
8187
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
7564
8188
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7565
8189
  import {
@@ -7572,9 +8196,9 @@ import {
7572
8196
  } from "@modelcontextprotocol/sdk/types.js";
7573
8197
 
7574
8198
  // src/auto-upgrade.ts
7575
- import { spawn as spawn3 } from "child_process";
8199
+ import { spawn as spawn5 } from "child_process";
7576
8200
  import { realpathSync as realpathSync2 } from "fs";
7577
- import { dirname as dirname3, sep as sep2 } from "path";
8201
+ import { dirname as dirname4, sep as sep2 } from "path";
7578
8202
  function quoteShellArgIfNeeded(arg, platform = process.platform) {
7579
8203
  if (platform !== "win32") return arg;
7580
8204
  if (/[\r\n\0"%]/.test(arg)) return null;
@@ -7589,7 +8213,7 @@ function detectRunningInstallPrefix(argvPath) {
7589
8213
  } catch {
7590
8214
  return null;
7591
8215
  }
7592
- let dir = dirname3(resolved);
8216
+ let dir = dirname4(resolved);
7593
8217
  let prev = "";
7594
8218
  let safety = 24;
7595
8219
  while (dir !== prev && safety-- > 0) {
@@ -7600,13 +8224,13 @@ function detectRunningInstallPrefix(argvPath) {
7600
8224
  return candidate;
7601
8225
  }
7602
8226
  prev = dir;
7603
- dir = dirname3(dir);
8227
+ dir = dirname4(dir);
7604
8228
  }
7605
8229
  return null;
7606
8230
  }
7607
8231
  async function compareWithNpmPrefix(detected) {
7608
8232
  await new Promise((res) => {
7609
- const child = spawn3("npm", ["prefix", "-g"], {
8233
+ const child = spawn5("npm", ["prefix", "-g"], {
7610
8234
  stdio: ["ignore", "pipe", "ignore"],
7611
8235
  shell: process.platform === "win32"
7612
8236
  });
@@ -7650,7 +8274,7 @@ async function fetchLatestVersion2() {
7650
8274
  function defaultSpawn2(cmd, args) {
7651
8275
  let errorFired = false;
7652
8276
  const correctiveCmd = cmd === "npm" ? "npm install -g @yawlabs/mcp@latest" : cmd === "pnpm" ? "pnpm add -g @yawlabs/mcp@latest" : "bun add -g @yawlabs/mcp@latest";
7653
- const child = spawn3(cmd, args, {
8277
+ const child = spawn5(cmd, args, {
7654
8278
  stdio: "ignore",
7655
8279
  // Stay a child of this process (not detached) so it dies with yaw-mcp
7656
8280
  // if yaw-mcp exits mid-install -- a half-finished install is fine
@@ -7679,7 +8303,7 @@ function defaultSpawn2(cmd, args) {
7679
8303
  async function maybeAutoUpgrade(deps = {}) {
7680
8304
  const optOut = process.env.YAW_MCP_AUTO_UPGRADE;
7681
8305
  if (optOut === "0" || optOut?.toLowerCase() === "false") return;
7682
- const current = deps.currentVersion ?? (true ? "0.73.2" : "dev");
8306
+ const current = deps.currentVersion ?? (true ? "0.74.1" : "dev");
7683
8307
  if (current === "dev") return;
7684
8308
  const method = (deps.isSeaImpl ? await deps.isSeaImpl() : await detectSea()) ? "binary" : detectInstallMethod(deps.argvPath ?? process.argv[1]);
7685
8309
  const latest = await (deps.fetchLatestImpl ?? fetchLatestVersion2)();
@@ -8030,7 +8654,12 @@ function resolveArgs(args, bindings) {
8030
8654
  if (args !== null && typeof args === "object") {
8031
8655
  const out = {};
8032
8656
  for (const [k, v] of Object.entries(args)) {
8033
- out[k] = resolveArgs(v, bindings);
8657
+ const resolved = resolveArgs(v, bindings);
8658
+ if (k === "__proto__") {
8659
+ Object.defineProperty(out, k, { value: resolved, writable: true, enumerable: true, configurable: true });
8660
+ } else {
8661
+ out[k] = resolved;
8662
+ }
8034
8663
  }
8035
8664
  return out;
8036
8665
  }
@@ -8263,13 +8892,13 @@ function pushToolCall(history, record, limit = HISTORY_LIMIT) {
8263
8892
  }
8264
8893
 
8265
8894
  // src/install-nudge.ts
8266
- import { existsSync as existsSync9, mkdirSync as mkdirSync2, readFileSync as readFileSync5, writeFileSync as writeFileSync2 } from "fs";
8267
- import { dirname as dirname4, join as join13 } from "path";
8895
+ import { existsSync as existsSync10, mkdirSync as mkdirSync3, readFileSync as readFileSync6, writeFileSync as writeFileSync2 } from "fs";
8896
+ import { dirname as dirname5, join as join14 } from "path";
8268
8897
  var INSTALL_NUDGE_MIN_COUNT = 5;
8269
8898
  var INSTALL_NUDGE_COOLDOWN_MS = 7 * 24 * 60 * 60 * 1e3;
8270
8899
  var INSTALL_NUDGE_STATE_FILENAME = "install-nudge-state.json";
8271
8900
  function installNudgeStatePath(home) {
8272
- return join13(home, CONFIG_DIRNAME, INSTALL_NUDGE_STATE_FILENAME);
8901
+ return join14(home, CONFIG_DIRNAME, INSTALL_NUDGE_STATE_FILENAME);
8273
8902
  }
8274
8903
  function installNudgeEnabled(env, config) {
8275
8904
  if (env.YAW_MCP_INSTALL_NUDGE === "1") return true;
@@ -8278,9 +8907,9 @@ function installNudgeEnabled(env, config) {
8278
8907
  }
8279
8908
  function readState(home) {
8280
8909
  const path7 = installNudgeStatePath(home);
8281
- if (!existsSync9(path7)) return { nudges: [] };
8910
+ if (!existsSync10(path7)) return { nudges: [] };
8282
8911
  try {
8283
- const parsed = JSON.parse(readFileSync5(path7, "utf8"));
8912
+ const parsed = JSON.parse(readFileSync6(path7, "utf8"));
8284
8913
  if (!parsed || typeof parsed !== "object") return { nudges: [] };
8285
8914
  const raw = parsed.nudges;
8286
8915
  if (!Array.isArray(raw)) return { nudges: [] };
@@ -8308,7 +8937,7 @@ function recordNudge(cli, home, now = Date.now) {
8308
8937
  const kept = state.nudges.filter((n) => n.cli !== cli && at - n.nudgedAt < INSTALL_NUDGE_COOLDOWN_MS);
8309
8938
  kept.push({ cli, nudgedAt: at });
8310
8939
  const path7 = installNudgeStatePath(home);
8311
- mkdirSync2(dirname4(path7), { recursive: true });
8940
+ mkdirSync3(dirname5(path7), { recursive: true });
8312
8941
  writeFileSync2(path7, `${JSON.stringify({ nudges: kept }, null, 2)}
8313
8942
  `, "utf8");
8314
8943
  } catch (err) {
@@ -9046,7 +9675,11 @@ function pruneJson(value) {
9046
9675
  for (const [k, v] of Object.entries(value)) {
9047
9676
  const pv = pruneJson(v);
9048
9677
  if (pv !== void 0) {
9049
- out[k] = pv;
9678
+ if (k === "__proto__") {
9679
+ Object.defineProperty(out, k, { value: pv, writable: true, enumerable: true, configurable: true });
9680
+ } else {
9681
+ out[k] = pv;
9682
+ }
9050
9683
  kept++;
9051
9684
  }
9052
9685
  }
@@ -9547,7 +10180,7 @@ import {
9547
10180
  } from "@modelcontextprotocol/sdk/types.js";
9548
10181
 
9549
10182
  // src/uv-bootstrap.ts
9550
- import { spawn as spawn4 } from "child_process";
10183
+ import { spawn as spawn6 } from "child_process";
9551
10184
  import { createHash as createHash3 } from "crypto";
9552
10185
  import { createWriteStream } from "fs";
9553
10186
  import fs from "fs/promises";
@@ -9600,7 +10233,7 @@ async function onPath(cmd) {
9600
10233
  };
9601
10234
  let child;
9602
10235
  try {
9603
- child = spawn4(cmd, ["--version"], {
10236
+ child = spawn6(cmd, ["--version"], {
9604
10237
  stdio: "ignore",
9605
10238
  // Windows needs a shell for PATHEXT shim resolution (.cmd/.exe)
9606
10239
  // so `uv --version` finds uv.cmd without an ENOENT false-negative.
@@ -9696,7 +10329,7 @@ async function extractArchive(archivePath, destDir) {
9696
10329
  }
9697
10330
  function runCommand(cmd, args) {
9698
10331
  return new Promise((resolve8, reject) => {
9699
- const child = spawn4(cmd, args, {
10332
+ const child = spawn6(cmd, args, {
9700
10333
  stdio: ["ignore", "pipe", "pipe"],
9701
10334
  shell: false,
9702
10335
  windowsHide: process.platform === "win32"
@@ -9916,7 +10549,7 @@ async function connectToUpstream(config, onDisconnect, onListChanged) {
9916
10549
  }
9917
10550
  async function connectToUpstreamOnce(config, onDisconnect, onListChanged, attempt, disableOamRewrite) {
9918
10551
  const client = new Client(
9919
- { name: "yaw-mcp", version: true ? "0.73.2" : "dev" },
10552
+ { name: "yaw-mcp", version: true ? "0.74.1" : "dev" },
9920
10553
  { capabilities: {} }
9921
10554
  );
9922
10555
  let transport;
@@ -9932,12 +10565,14 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, attemp
9932
10565
  ...parentEnv
9933
10566
  } = process.env;
9934
10567
  let resolved = await resolveUvSpawn(config.command, config.args ?? []);
9935
- const effectiveRuntime = config.runtime ?? await defaultRuntime();
10568
+ const configured = config.runtime ?? await defaultRuntime();
10569
+ const optedIn = configured !== null;
10570
+ const effectiveRuntime = configured ?? "oam";
9936
10571
  if (effectiveRuntime === "oam" && !disableOamRewrite && !oamDowngradedNamespaces.has(config.namespace)) {
9937
- const rewritten = resolveOamSpawn(resolved.command, resolved.args);
10572
+ const rewritten = await resolveOamSpawn(resolved.command, resolved.args, optedIn);
9938
10573
  if (rewritten.command !== resolved.command) {
9939
10574
  attempt.oamRewritten = true;
9940
- attempt.oamVersion = probeOam().version;
10575
+ attempt.oamVersion = (await probeOam()).version;
9941
10576
  resolved = rewritten;
9942
10577
  }
9943
10578
  }
@@ -10326,7 +10961,7 @@ var ConnectServer = class _ConnectServer {
10326
10961
  // real process values; overridable so tests can point the scan at a
10327
10962
  // synthetic home + stubbed env without touching the developer's real
10328
10963
  // shell history or ~/.yaw-mcp/ state file.
10329
- nudgeHome = homedir19();
10964
+ nudgeHome = homedir21();
10330
10965
  nudgeEnv = process.env;
10331
10966
  // Loaded YAW-MCP.md guides (user-global + project-local). Null until
10332
10967
  // start() has run the loader; fail-open if either file is missing,
@@ -10432,7 +11067,7 @@ var ConnectServer = class _ConnectServer {
10432
11067
  static STATE_SAVE_DEBOUNCE_MS = 1e3;
10433
11068
  constructor() {
10434
11069
  this.server = new Server(
10435
- { name: "yaw-mcp", version: true ? "0.73.2" : "dev" },
11070
+ { name: "yaw-mcp", version: true ? "0.74.1" : "dev" },
10436
11071
  {
10437
11072
  capabilities: {
10438
11073
  tools: { listChanged: true },
@@ -10587,7 +11222,7 @@ var ConnectServer = class _ConnectServer {
10587
11222
  //
10588
11223
  // `home` is a parameter rather than a field so tests can point it at a
10589
11224
  // synthetic ~/.yaw-mcp without running the whole of start().
10590
- async hydrateComplianceGrades(home = homedir19()) {
11225
+ async hydrateComplianceGrades(home = homedir21()) {
10591
11226
  if (!this.config) return;
10592
11227
  const grades = await readGradesCache(home).catch(() => ({}));
10593
11228
  if (Object.keys(grades).length === 0) return;
@@ -11131,9 +11766,10 @@ var ConnectServer = class _ConnectServer {
11131
11766
  activeServers.map((s) => this.rankableFor(s))
11132
11767
  );
11133
11768
  for (const r of ranked) scores.set(r.namespace, r.score);
11769
+ const byNamespace = new Map(activeServers.map((s) => [s.namespace, s]));
11770
+ const matched = ranked.map((r) => byNamespace.get(r.namespace)).filter((s) => s !== void 0);
11134
11771
  const rankedSet = new Set(ranked.map((r) => r.namespace));
11135
11772
  const rest = activeServers.filter((s) => !rankedSet.has(s.namespace));
11136
- const matched = ranked.map((r) => activeServers.find((s) => s.namespace === r.namespace)).filter((s) => s !== void 0);
11137
11773
  sorted = [...matched, ...rest];
11138
11774
  } else {
11139
11775
  sorted = activeServers;
@@ -12425,6 +13061,7 @@ var KNOWN_SUBCOMMANDS = [
12425
13061
  "doctor",
12426
13062
  "reset-learning",
12427
13063
  "servers",
13064
+ "sidecars",
12428
13065
  "bundles",
12429
13066
  "completion",
12430
13067
  "upgrade",
@@ -12549,6 +13186,19 @@ if (subcommand === "compliance") {
12549
13186
  process.exit(2);
12550
13187
  }
12551
13188
  dispatch("servers", runServersCommand(parsed.options));
13189
+ } else if (subcommand === "sidecars") {
13190
+ const parsed = parseSidecarsArgs(process.argv.slice(3));
13191
+ if (!parsed.ok) {
13192
+ if (parsed.help) {
13193
+ process.stdout.write(`${parsed.error}
13194
+ `);
13195
+ process.exit(0);
13196
+ }
13197
+ process.stderr.write(`${parsed.error}
13198
+ `);
13199
+ process.exit(2);
13200
+ }
13201
+ dispatch("sidecars", runSidecarsInstall(parsed.options));
12552
13202
  } else if (subcommand === "bundles") {
12553
13203
  const parsed = parseBundlesArgs(process.argv.slice(3));
12554
13204
  if (!parsed.ok) {
@@ -12731,6 +13381,12 @@ if (subcommand === "compliance") {
12731
13381
  Maintenance:
12732
13382
  upgrade Show (or --run) the command that bumps
12733
13383
  @yawlabs/mcp to the latest version.
13384
+ sidecars install Install your servers into ~/.yaw-mcp/sidecars so
13385
+ they run from one known version. Worth doing when
13386
+ servers run on oam: it runs the copy already on
13387
+ disk and cannot re-resolve \`@latest\` the way npx
13388
+ did. Re-run to move them forward; \`doctor\` shows
13389
+ the version each one is on.
12734
13390
  reset-learning Clear cross-session learning history
12735
13391
  (~/.yaw-mcp/state.json).
12736
13392
  completion <shell> Print a shell completion script for bash, zsh,
@@ -12811,7 +13467,7 @@ if (subcommand === "compliance") {
12811
13467
  `);
12812
13468
  process.exitCode = 0;
12813
13469
  } else if (subcommand === "--version" || subcommand === "-V") {
12814
- process.stdout.write(`yaw-mcp ${true ? "0.73.2" : "dev"}
13470
+ process.stdout.write(`yaw-mcp ${true ? "0.74.1" : "dev"}
12815
13471
  `);
12816
13472
  process.exitCode = 0;
12817
13473
  } else if (subcommand && !subcommand.startsWith("-")) {