@yawlabs/mcp 0.79.0 → 0.79.2

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
@@ -1,5 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
+ ALLOW_UNOWNED_ENV,
4
+ BINARY_RETIRED_HINT,
3
5
  CLAUDE_CODE_ALLOW_PATTERN,
4
6
  CONFIG_DIRNAME,
5
7
  CURRENT_OS,
@@ -7,9 +9,14 @@ import {
7
9
  INSTALL_TARGETS,
8
10
  LEGACY_ENTRY_NAMES,
9
11
  MIN_OAM_VERSION,
12
+ acquireUpgradeLock,
10
13
  buildLaunchEntry,
14
+ buildUpgradePlan,
11
15
  cacheDir,
12
16
  compareVersions,
17
+ detectInstallMethod,
18
+ detectSea,
19
+ fetchLatestVersion,
13
20
  findLegacyEntry,
14
21
  findProjectConfigDir,
15
22
  guidePath,
@@ -18,6 +25,8 @@ import {
18
25
  isProjectLocalEntry,
19
26
  isRegistrySpec,
20
27
  isUnderHome,
28
+ log,
29
+ maybeAutoUpgrade,
21
30
  nodeLaunchKind,
22
31
  npxSpec,
23
32
  npxSpecIndex,
@@ -28,37 +37,26 @@ import {
28
37
  oamNoBinaryReason,
29
38
  oamPublishesBinaryForThisMachine,
30
39
  packageName,
40
+ parseUpgradeArgs,
31
41
  probeOam,
32
42
  realpathOrSelf,
43
+ refineInstallMethod,
44
+ resolveAppDataDir,
33
45
  resolveClaudeCodeSettingsPath,
34
46
  resolveInstallPath,
35
47
  resolveOamSpawn,
36
48
  resolveStableNpmEntry,
49
+ runUpgrade,
37
50
  sidecarsNodeModules,
38
51
  sidecarsRoot,
39
52
  specConstraint,
40
53
  userConfigDir
41
- } from "./chunk-33LK4DLQ.js";
42
- import {
43
- BINARY_RETIRED_HINT,
44
- acquireUpgradeLock,
45
- buildUpgradePlan,
46
- detectInstallMethod,
47
- detectSea,
48
- fetchLatestVersion,
49
- maybeAutoUpgrade,
50
- parseUpgradeArgs,
51
- refineInstallMethod,
52
- runUpgrade
53
- } from "./chunk-YS4SD3RS.js";
54
- import {
55
- log
56
- } from "./chunk-3RRZQPA5.js";
54
+ } from "./chunk-ODSIFM3N.js";
57
55
 
58
56
  // src/audit-cmd.ts
59
57
  import { readFile as readFile6 } from "fs/promises";
60
58
  import { homedir as homedir6 } from "os";
61
- import { dirname as dirname2, join as join6 } from "path";
59
+ import { dirname as dirname3, join as join6 } from "path";
62
60
  import { fileURLToPath } from "url";
63
61
 
64
62
  // src/grades-cache.ts
@@ -134,13 +132,13 @@ async function mkdirpWithMode(dir, dirMode) {
134
132
  const toCreate = [];
135
133
  let cursor = resolved;
136
134
  while (true) {
137
- let exists3 = true;
135
+ let exists2 = true;
138
136
  try {
139
137
  await stat(cursor);
140
138
  } catch {
141
- exists3 = false;
139
+ exists2 = false;
142
140
  }
143
- if (exists3) break;
141
+ if (exists2) break;
144
142
  toCreate.unshift(cursor);
145
143
  const parent = path.dirname(cursor);
146
144
  if (parent === cursor) break;
@@ -263,8 +261,8 @@ var FORMATTING_OPTIONS = {
263
261
  eol: "\n"
264
262
  };
265
263
  function editJsoncEntry(src, containerPath, entryName, value) {
266
- if (containerPath.length === 0 && entryName === "") {
267
- throw new Error("editJsoncEntry: must specify at least one path segment");
264
+ if (entryName === "") {
265
+ throw new Error("editJsoncEntry: entryName must be a non-empty key");
268
266
  }
269
267
  const debommed = src.charCodeAt(0) === 65279 ? src.slice(1) : src;
270
268
  const targetPath = [...containerPath, entryName];
@@ -272,8 +270,8 @@ function editJsoncEntry(src, containerPath, entryName, value) {
272
270
  return applyEdits(debommed, edits);
273
271
  }
274
272
  function removeJsoncEntry(src, containerPath, entryName) {
275
- if (containerPath.length === 0 && entryName === "") {
276
- throw new Error("removeJsoncEntry: must specify at least one path segment");
273
+ if (entryName === "") {
274
+ throw new Error("removeJsoncEntry: entryName must be a non-empty key");
277
275
  }
278
276
  const debommed = src.charCodeAt(0) === 65279 ? src.slice(1) : src;
279
277
  const targetPath = [...containerPath, entryName];
@@ -326,7 +324,13 @@ async function readGradesCacheImpl(home, opts) {
326
324
  });
327
325
  return {};
328
326
  }
329
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return {};
327
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
328
+ log("warn", "grades.json is not a JSON object of namespace -> grade; ignoring", {
329
+ path: path6,
330
+ rootType: Array.isArray(parsed) ? "array" : parsed === null ? "null" : typeof parsed
331
+ });
332
+ return {};
333
+ }
330
334
  const out = {};
331
335
  for (const [ns, entry] of Object.entries(parsed)) {
332
336
  const validated = validateEntry(entry);
@@ -366,7 +370,7 @@ import { join as join3 } from "path";
366
370
  import { createHash } from "crypto";
367
371
  import { chmod as chmod2, readFile as readFile2 } from "fs/promises";
368
372
  import { homedir as homedir2 } from "os";
369
- import { join as join2, resolve } from "path";
373
+ import { basename, dirname, join as join2, resolve } from "path";
370
374
  var TRUST_FILENAME = "trusted.json";
371
375
  var TRUST_SCHEMA_VERSION = 1;
372
376
  var TRUST_BYPASS_ENV = "YAW_MCP_TRUST_PROJECT";
@@ -393,9 +397,9 @@ var TrustStoreUnreadableError = class extends Error {
393
397
  function trustStorePath(home = homedir2()) {
394
398
  return join2(userConfigDir(home), TRUST_FILENAME);
395
399
  }
396
- function normalizeTrustKey(p) {
400
+ function normalizeTrustKey(p, platform = process.platform) {
397
401
  const resolved = resolve(p);
398
- const caseInsensitiveFs = process.platform === "win32" || process.platform === "darwin";
402
+ const caseInsensitiveFs = platform === "win32" || platform === "darwin";
399
403
  return caseInsensitiveFs ? resolved.toLowerCase() : resolved;
400
404
  }
401
405
  function hashTrustContent(contents) {
@@ -415,7 +419,7 @@ function emptyStore(kind = null, reason = null, errorCode = null, version = TRUS
415
419
  errorCode
416
420
  };
417
421
  }
418
- async function readTrustStore(home = homedir2()) {
422
+ async function readTrustStore(home = homedir2(), platform = process.platform) {
419
423
  const path6 = trustStorePath(home);
420
424
  let raw;
421
425
  try {
@@ -444,6 +448,10 @@ async function readTrustStore(home = homedir2()) {
444
448
  return emptyStore("parse", `${path6} has a non-numeric "version" field; the store is corrupt`);
445
449
  }
446
450
  const version = typeof obj.version === "number" ? obj.version : TRUST_SCHEMA_VERSION;
451
+ if (!Number.isInteger(version) || version < 1) {
452
+ log("warn", "Trust store has an out-of-range version; nothing is trusted", { path: path6, version });
453
+ return emptyStore("parse", `${path6} has an invalid "version" (${version}); the store is corrupt`);
454
+ }
447
455
  if (version > TRUST_SCHEMA_VERSION) {
448
456
  log("warn", "Trust store was written by a newer yaw-mcp; nothing is trusted", { path: path6, version });
449
457
  return emptyStore(
@@ -468,7 +476,7 @@ async function readTrustStore(home = homedir2()) {
468
476
  log("warn", "Dropping trust entry with a missing or malformed sha256", { path: path6, key });
469
477
  continue;
470
478
  }
471
- setJsonKey(entries, normalizeTrustKey(key), {
479
+ setJsonKey(entries, normalizeTrustKey(key, platform), {
472
480
  path: typeof v.path === "string" && v.path.length > 0 ? v.path : key,
473
481
  sha256: v.sha256,
474
482
  grantedAt: typeof v.grantedAt === "string" ? v.grantedAt : ""
@@ -497,17 +505,18 @@ async function writeTrustStore(home, entries) {
497
505
  }
498
506
  async function grantTrust(path6, contents, opts = {}) {
499
507
  const home = opts.home ?? homedir2();
500
- const store = await readTrustStore(home);
508
+ const platform = opts.platform ?? process.platform;
509
+ const store = await readTrustStore(home, platform);
501
510
  refuseUnusableStore(home, store);
502
511
  const record = {
503
512
  path: resolve(path6),
504
513
  sha256: hashTrustContent(contents),
505
514
  grantedAt: new Date(opts.now ? opts.now() : Date.now()).toISOString()
506
515
  };
507
- const fresh = await readTrustStore(home);
516
+ const fresh = await readTrustStore(home, platform);
508
517
  refuseUnusableStore(home, fresh);
509
518
  const entries = fresh.malformed ? {} : { ...fresh.entries };
510
- entries[normalizeTrustKey(path6)] = record;
519
+ setJsonKey(entries, normalizeTrustKey(path6, platform), record);
511
520
  const storePath = await writeTrustStore(home, entries);
512
521
  log("info", "Granted project bundles.json trust", { path: record.path, sha256: record.sha256 });
513
522
  return { storePath, record, storeWasMalformed: store.malformed || fresh.malformed };
@@ -522,18 +531,27 @@ function refuseUnusableStore(home, store) {
522
531
  kind
523
532
  );
524
533
  }
534
+ async function revokeKeyCandidates(p, platform) {
535
+ const lexical = normalizeTrustKey(p, platform);
536
+ const resolved = resolve(p);
537
+ const physical = normalizeTrustKey(join2(await realpathOrSelf(dirname(resolved)), basename(resolved)), platform);
538
+ return physical === lexical ? [lexical] : [lexical, physical];
539
+ }
525
540
  async function revokeTrust(path6, opts = {}) {
526
541
  const home = opts.home ?? homedir2();
527
- const store = await readTrustStore(home);
542
+ const platform = opts.platform ?? process.platform;
543
+ const store = await readTrustStore(home, platform);
528
544
  const storePath = trustStorePath(home);
529
545
  if (store.malformed) return { storePath, removed: false, storeWasMalformed: true };
530
- const key = normalizeTrustKey(path6);
531
- if (!Object.hasOwn(store.entries, key)) return { storePath, removed: false, storeWasMalformed: false };
532
- const fresh = await readTrustStore(home);
546
+ const candidates = await revokeKeyCandidates(path6, platform);
547
+ const keys = candidates.filter((c) => Object.hasOwn(store.entries, c));
548
+ if (keys.length === 0) return { storePath, removed: false, storeWasMalformed: false };
549
+ const fresh = await readTrustStore(home, platform);
533
550
  if (fresh.malformed) return { storePath, removed: false, storeWasMalformed: true };
534
- if (!Object.hasOwn(fresh.entries, key)) return { storePath, removed: false, storeWasMalformed: false };
551
+ const present = keys.filter((k) => Object.hasOwn(fresh.entries, k));
552
+ if (present.length === 0) return { storePath, removed: false, storeWasMalformed: false };
535
553
  const entries = { ...fresh.entries };
536
- delete entries[key];
554
+ for (const k of present) delete entries[k];
537
555
  await writeTrustStore(home, entries);
538
556
  log("info", "Revoked project bundles.json trust", { path: resolve(path6) });
539
557
  return { storePath, removed: true, storeWasMalformed: false };
@@ -937,6 +955,12 @@ function resolveUpsertTarget(servers, entry) {
937
955
  launchChanged
938
956
  };
939
957
  }
958
+ function mergedUpsertEntry(servers, entry, target) {
959
+ if (target.idx < 0) return entry;
960
+ const written = mergeServerEntry(servers[target.idx] ?? {}, entry);
961
+ if (target.matchedByNamespace) return written;
962
+ return { ...written, namespace: target.namespace ?? written.namespace, id: target.id ?? written.id };
963
+ }
940
964
  async function previewUpsertUserBundle(entry, opts = {}) {
941
965
  const home = opts.home ?? homedir3();
942
966
  const file = await readRawUserBundles(home);
@@ -945,6 +969,7 @@ async function previewUpsertUserBundle(entry, opts = {}) {
945
969
  replaced: target.idx >= 0,
946
970
  refusal: target.refusal,
947
971
  namespace: target.namespace ?? entry.namespace,
972
+ entry: mergedUpsertEntry(file.servers, entry, target),
948
973
  launchChanged: target.launchChanged
949
974
  };
950
975
  }
@@ -954,19 +979,11 @@ async function doUpsertUserBundle(entry, opts) {
954
979
  const file = await readRawUserBundles(home);
955
980
  const target = resolveUpsertTarget(file.servers, entry);
956
981
  if (target.refusal) throw new Error(target.refusal);
957
- const { idx, matchedByNamespace } = target;
982
+ const idx = target.idx;
958
983
  const replaced = idx >= 0;
959
- let written = replaced ? mergeServerEntry(file.servers[idx] ?? {}, entry) : entry;
960
- if (replaced && !matchedByNamespace) {
961
- written = {
962
- ...written,
963
- namespace: target.namespace ?? written.namespace,
964
- id: target.id ?? written.id
965
- };
966
- }
984
+ const written = mergedUpsertEntry(file.servers, entry, target);
967
985
  if (replaced) file.servers[idx] = written;
968
986
  else file.servers.push(written);
969
- file.version = file.version ?? CURRENT_BUNDLES_SCHEMA_VERSION;
970
987
  await atomicWriteFile(path6, `${JSON.stringify(file, null, 2)}
971
988
  `, "utf8", 384, 448);
972
989
  if (process.platform !== "win32") {
@@ -993,7 +1010,6 @@ async function doRemoveUserBundle(namespace, opts) {
993
1010
  const before = file.servers.length;
994
1011
  file.servers = file.servers.filter((s) => s?.namespace !== namespace);
995
1012
  if (file.servers.length === before) return { path: path6, removed: false };
996
- file.version = file.version ?? CURRENT_BUNDLES_SCHEMA_VERSION;
997
1013
  await atomicWriteFile(path6, `${JSON.stringify(file, null, 2)}
998
1014
  `, "utf8", 384, 448);
999
1015
  if (process.platform !== "win32") {
@@ -1011,9 +1027,9 @@ async function findShadowingProjectBundles(cwd, home = homedir3(), env = process
1011
1027
 
1012
1028
  // src/secrets-vault.ts
1013
1029
  import { createHmac, randomBytes as randomBytes2, timingSafeEqual } from "crypto";
1014
- import { chmod as chmod4, mkdir as mkdir2, readFile as readFile4 } from "fs/promises";
1030
+ import { chmod as chmod4, readFile as readFile4 } from "fs/promises";
1015
1031
  import { homedir as homedir4 } from "os";
1016
- import { dirname, join as join4 } from "path";
1032
+ import { dirname as dirname2, join as join4 } from "path";
1017
1033
 
1018
1034
  // src/secrets-crypto.ts
1019
1035
  import { createCipheriv, createDecipheriv, randomBytes, scrypt as scryptCb } from "crypto";
@@ -1021,6 +1037,7 @@ var KEY_LEN = 32;
1021
1037
  var IV_LEN = 12;
1022
1038
  var SALT_LEN = 16;
1023
1039
  var DEFAULT_KDF = { N: 1 << 15, r: 8, p: 1 };
1040
+ var LEGACY_KDF = Object.freeze({ N: 1 << 15, r: 8, p: 1 });
1024
1041
  var MAX_KDF_N = 1 << 18;
1025
1042
  var MAX_KDF_R = 32;
1026
1043
  var MAX_KDF_P = 16;
@@ -1046,7 +1063,7 @@ function generateSalt() {
1046
1063
  function normalizePassphrase(passphrase) {
1047
1064
  return passphrase.normalize("NFC");
1048
1065
  }
1049
- async function deriveKey(passphrase, salt, params = DEFAULT_KDF, normalize = true) {
1066
+ async function deriveKey(passphrase, salt, params = LEGACY_KDF, normalize = true) {
1050
1067
  return scryptCallWithMaxmem(normalize ? normalizePassphrase(passphrase) : passphrase, salt, KEY_LEN, params);
1051
1068
  }
1052
1069
  async function scryptCallWithMaxmem(password, salt, keylen, params) {
@@ -1160,6 +1177,9 @@ async function loadVault(path6) {
1160
1177
  throw new VaultEntryCorruptError(name);
1161
1178
  }
1162
1179
  }
1180
+ if (obj.check !== void 0 && !isEncryptedEntry(obj.check)) {
1181
+ log("warn", "Vault verification token is malformed; ignoring it (the next write re-stamps it)", { path: path6 });
1182
+ }
1163
1183
  const check = isEncryptedEntry(obj.check) ? obj.check : void 0;
1164
1184
  return {
1165
1185
  version: typeof obj.version === "number" ? obj.version : LEGACY_SCHEMA_VERSION,
@@ -1175,17 +1195,13 @@ function isEncryptedEntry(v) {
1175
1195
  return typeof e.iv === "string" && typeof e.ciphertext === "string" && typeof e.authTag === "string";
1176
1196
  }
1177
1197
  async function saveVault(path6, vault) {
1178
- const dir = dirname(path6);
1179
- await mkdir2(dir, { recursive: true });
1198
+ await atomicWriteFile(path6, `${JSON.stringify(vault, null, 2)}
1199
+ `, "utf8", 384, 448);
1180
1200
  if (process.platform !== "win32") {
1181
1201
  try {
1182
- await chmod4(dir, 448);
1202
+ await chmod4(dirname2(path6), 448);
1183
1203
  } catch {
1184
1204
  }
1185
- }
1186
- await atomicWriteFile(path6, `${JSON.stringify(vault, null, 2)}
1187
- `, "utf8", 384, 448);
1188
- if (process.platform !== "win32") {
1189
1205
  try {
1190
1206
  await chmod4(path6, 384);
1191
1207
  } catch {
@@ -1211,7 +1227,7 @@ async function unlock(vault, passphrase) {
1211
1227
  return cachedKey;
1212
1228
  }
1213
1229
  const salt = Buffer.from(vault.salt, "base64");
1214
- const params = vault.kdf ?? DEFAULT_KDF;
1230
+ const params = vault.kdf ?? LEGACY_KDF;
1215
1231
  let key = await deriveKey(passphrase, salt, params);
1216
1232
  try {
1217
1233
  verifyKey(vault, key);
@@ -1292,7 +1308,7 @@ async function rotateVault(vault, oldKey, newPassphrase) {
1292
1308
  try {
1293
1309
  const entries = {};
1294
1310
  for (const [name, value] of plaintext) {
1295
- entries[name] = encryptEntry(value, newKey, name);
1311
+ setJsonKey(entries, name, encryptEntry(value, newKey, name));
1296
1312
  }
1297
1313
  return {
1298
1314
  version: SECRETS_SCHEMA_VERSION,
@@ -1320,6 +1336,7 @@ function setSecret(vault, key, name, value) {
1320
1336
  return ensureCheck(
1321
1337
  {
1322
1338
  ...vault,
1339
+ kdf: vault.kdf ?? { ...LEGACY_KDF },
1323
1340
  entries: {
1324
1341
  ...vault.entries,
1325
1342
  [name]: encryptEntry(value, key, name)
@@ -1371,6 +1388,16 @@ function resolveSecretRefs(env, vault, key) {
1371
1388
  }
1372
1389
  return { resolved, missing };
1373
1390
  }
1391
+ function collectSecretRefNames(env) {
1392
+ const names = /* @__PURE__ */ new Set();
1393
+ if (!env) return names;
1394
+ const re = new RegExp(SECRET_REF_RE.source, SECRET_REF_RE.flags);
1395
+ for (const v of Object.values(env)) {
1396
+ if (typeof v !== "string") continue;
1397
+ for (const m of v.matchAll(re)) if (m[1]) names.add(m[1]);
1398
+ }
1399
+ return names;
1400
+ }
1374
1401
  function hasSecretRefs(env) {
1375
1402
  if (!env) return false;
1376
1403
  for (const v of Object.values(env)) {
@@ -1397,6 +1424,7 @@ import {
1397
1424
  import { statSync } from "fs";
1398
1425
  var bundlesDefaultCache;
1399
1426
  var warnedInvalidEnv = false;
1427
+ var inflight = null;
1400
1428
  var degradedProbe = null;
1401
1429
  var DEGRADED_RECHECK_MS = 5e3;
1402
1430
  var warnedDegradedBundles = false;
@@ -1428,40 +1456,47 @@ async function defaultRuntime(opts = {}) {
1428
1456
  const fromEnv = readEnvChoice(process.env);
1429
1457
  if (fromEnv !== null) return fromEnv;
1430
1458
  if (bundlesDefaultCache === void 0) {
1431
- const now = opts.now ?? Date.now;
1432
- if (degradedProbe !== null && now() - degradedProbe.at < DEGRADED_RECHECK_MS && degradedProbe.files.every((f) => statSignature(f.path) === f.signature)) {
1433
- return null;
1434
- }
1435
- const bundles = await loadLocalBundles({ cwd: opts.cwd ?? process.cwd(), home: opts.home }).catch(() => null);
1436
- const degraded = bundles === null || bundles.config === null && bundles.path !== null;
1437
- const resolved = bundles?.defaultRuntime ?? null;
1438
- if (degraded && resolved === null) {
1439
- const path6 = bundles?.path ?? null;
1440
- const signature = path6 === null ? null : statSignature(path6);
1441
- if (path6 === null || signature === null) {
1442
- degradedProbe = null;
1443
- } else {
1444
- const watched = bundles?.consultedPaths?.length ? bundles.consultedPaths : [path6];
1445
- degradedProbe = {
1446
- files: watched.map((f) => ({ path: f, signature: statSignature(f) })),
1447
- at: now()
1448
- };
1449
- }
1450
- if (!warnedDegradedBundles) {
1451
- warnedDegradedBundles = true;
1452
- log(
1453
- "warn",
1454
- "bundles.json could not be read for the default runtime; using the fallback until the file changes",
1455
- { path: path6 ?? "(unknown)" }
1456
- );
1457
- }
1458
- return null;
1459
+ if (inflight === null) {
1460
+ inflight = resolveBundlesDefault(opts).finally(() => {
1461
+ inflight = null;
1462
+ });
1459
1463
  }
1460
- degradedProbe = null;
1461
- bundlesDefaultCache = resolved;
1464
+ return inflight;
1462
1465
  }
1463
1466
  return bundlesDefaultCache;
1464
1467
  }
1468
+ async function resolveBundlesDefault(opts) {
1469
+ const now = opts.now ?? Date.now;
1470
+ if (degradedProbe !== null && now() - degradedProbe.at < DEGRADED_RECHECK_MS && degradedProbe.files.every((f) => statSignature(f.path) === f.signature)) {
1471
+ return null;
1472
+ }
1473
+ const bundles = await loadLocalBundles({ cwd: opts.cwd ?? process.cwd(), home: opts.home }).catch(() => null);
1474
+ const degraded = bundles === null || bundles.config === null && bundles.path !== null;
1475
+ const resolved = bundles?.defaultRuntime ?? null;
1476
+ if (degraded && resolved === null) {
1477
+ const path6 = bundles?.path ?? null;
1478
+ const signature = path6 === null ? null : statSignature(path6);
1479
+ if (path6 === null || signature === null) {
1480
+ degradedProbe = null;
1481
+ } else {
1482
+ const watched = bundles?.consultedPaths?.length ? bundles.consultedPaths : [path6];
1483
+ degradedProbe = {
1484
+ files: watched.map((f) => ({ path: f, signature: statSignature(f) })),
1485
+ at: now()
1486
+ };
1487
+ }
1488
+ if (!warnedDegradedBundles) {
1489
+ warnedDegradedBundles = true;
1490
+ log("warn", "bundles.json could not be read for the default runtime; using the fallback until the file changes", {
1491
+ path: path6 ?? "(unknown)"
1492
+ });
1493
+ }
1494
+ return null;
1495
+ }
1496
+ degradedProbe = null;
1497
+ bundlesDefaultCache = resolved;
1498
+ return resolved;
1499
+ }
1465
1500
  function describeLaunchShape(command, args) {
1466
1501
  const kind = nodeLaunchKind(command);
1467
1502
  if (kind === "node") {
@@ -1549,6 +1584,7 @@ import { homedir as homedir5 } from "os";
1549
1584
  import { join as join5 } from "path";
1550
1585
  var SECRETS_AUDIT_FILENAME = "secrets-audit.log";
1551
1586
  var AUDIT_TAIL_CAP = 5e3;
1587
+ var AUDIT_TRIM_TO = AUDIT_TAIL_CAP - 500;
1552
1588
  function auditLogPath(home = homedir5()) {
1553
1589
  return join5(home, CONFIG_DIRNAME, SECRETS_AUDIT_FILENAME);
1554
1590
  }
@@ -1582,7 +1618,7 @@ async function trimToTailCap(path6) {
1582
1618
  const raw = await readFile5(path6, "utf8");
1583
1619
  const lines = raw.split("\n").filter((l) => l.length > 0);
1584
1620
  if (lines.length <= AUDIT_TAIL_CAP) return;
1585
- const kept = lines.slice(lines.length - AUDIT_TAIL_CAP);
1621
+ const kept = lines.slice(lines.length - AUDIT_TRIM_TO);
1586
1622
  await atomicWriteFile(path6, `${kept.join("\n")}
1587
1623
  `, "utf8", 384);
1588
1624
  }
@@ -1664,14 +1700,6 @@ function binName() {
1664
1700
  function archiveExt() {
1665
1701
  return process.platform === "win32" ? "zip" : "tar.gz";
1666
1702
  }
1667
- async function exists(p) {
1668
- try {
1669
- await fs.access(p);
1670
- return true;
1671
- } catch {
1672
- return false;
1673
- }
1674
- }
1675
1703
  async function onPath(cmd) {
1676
1704
  return new Promise((resolve8) => {
1677
1705
  let settled = false;
@@ -1882,7 +1910,8 @@ async function resolveUv() {
1882
1910
  }
1883
1911
  const installDir = path2.join(cacheDir(), "uv", UV_VERSION, target);
1884
1912
  const finalBin = path2.join(installDir, binName());
1885
- if (await exists(finalBin)) return finalBin;
1913
+ const cached = await fs.stat(finalBin).catch(() => null);
1914
+ if (cached?.isFile() && cached.size > 0) return finalBin;
1886
1915
  await fs.mkdir(installDir, { recursive: true });
1887
1916
  log("info", "Bootstrapping uv", { version: UV_VERSION, target, cache: installDir });
1888
1917
  const archiveName = `uv-${target}.${archiveExt()}`;
@@ -1996,12 +2025,14 @@ async function resolveServerEnv(env, namespace) {
1996
2025
  "missing"
1997
2026
  );
1998
2027
  }
1999
- const vault = await loadVault(vaultPath()).catch((err) => {
2000
- log("warn", "Failed to load vault for env resolution", {
2001
- error: err instanceof Error ? err.message : String(err)
2002
- });
2003
- return null;
2004
- });
2028
+ let vault;
2029
+ try {
2030
+ vault = await loadVault(vaultPath());
2031
+ } catch (err) {
2032
+ const msg = err instanceof Error ? err.message : String(err);
2033
+ log("warn", "Failed to load vault for env resolution", { error: msg });
2034
+ throw new Error(`vault unreadable: ${msg}`);
2035
+ }
2005
2036
  if (!vault) {
2006
2037
  throw new Error("vault locked: server env references ${secret:...} but no vault exists yet");
2007
2038
  }
@@ -2040,31 +2071,29 @@ async function recordResolveAudit(namespace, env, missing) {
2040
2071
  }
2041
2072
  return;
2042
2073
  }
2043
- for (const name of collectSecretNames(env)) {
2074
+ for (const name of collectSecretRefNames(env)) {
2044
2075
  await appendAuditEvent({ server: namespace, secret: name, event: "injected" });
2045
2076
  }
2046
2077
  }
2047
- function collectSecretNames(env) {
2048
- const names = /* @__PURE__ */ new Set();
2049
- const re = new RegExp(SECRET_REF_RE.source, SECRET_REF_RE.flags);
2050
- for (const v of Object.values(env)) {
2051
- if (typeof v !== "string") continue;
2052
- for (const m of v.matchAll(re)) names.add(m[1]);
2053
- }
2054
- return [...names];
2055
- }
2056
- var DEFAULT_CONNECT_TIMEOUT = (() => {
2057
- const env = process.env.MCP_CONNECT_TIMEOUT;
2058
- if (!env) return 15e3;
2059
- const n = Number.parseInt(env, 10);
2060
- return Number.isFinite(n) && n > 0 ? n : 15e3;
2061
- })();
2062
- var LIST_TIMEOUT = (() => {
2063
- const env = process.env.MCP_LIST_TIMEOUT;
2064
- if (!env) return 15e3;
2065
- const n = Number.parseInt(env, 10);
2066
- return Number.isFinite(n) && n > 0 ? n : 15e3;
2067
- })();
2078
+ var MAX_TIMEOUT_MS = 2147483647;
2079
+ function resolveTimeoutEnv(name, defaultMs) {
2080
+ const raw = process.env[name];
2081
+ if (raw === void 0) return defaultMs;
2082
+ const trimmed = raw.trim();
2083
+ if (trimmed === "") return defaultMs;
2084
+ if (/^\d+$/.test(trimmed)) {
2085
+ const n = Number.parseInt(trimmed, 10);
2086
+ if (n > 0 && n <= MAX_TIMEOUT_MS) return n;
2087
+ }
2088
+ log("warn", `${name} ignored: expected a whole number of milliseconds in 1..${MAX_TIMEOUT_MS}`, {
2089
+ value: raw,
2090
+ maxMs: MAX_TIMEOUT_MS,
2091
+ usingMs: defaultMs
2092
+ });
2093
+ return defaultMs;
2094
+ }
2095
+ var DEFAULT_CONNECT_TIMEOUT = resolveTimeoutEnv("MCP_CONNECT_TIMEOUT", 15e3);
2096
+ var LIST_TIMEOUT = resolveTimeoutEnv("MCP_LIST_TIMEOUT", 15e3);
2068
2097
  var STDERR_RING_CAP = 8 * 1024;
2069
2098
  var MAX_TOOLS_PER_SERVER = 1e3;
2070
2099
  var MAX_RESOURCES_PER_SERVER = 1e3;
@@ -2106,6 +2135,24 @@ function categorizeSpawnError(err) {
2106
2135
  if (/EACCES|permission denied/i.test(msg)) return "spawn_failure";
2107
2136
  return "unknown";
2108
2137
  }
2138
+ function remoteFailureDetail(err) {
2139
+ const parts = [];
2140
+ const code = err?.code;
2141
+ if (typeof code === "number" && code >= 100 && code <= 599) parts.push(`HTTP ${code}`);
2142
+ const cause = err instanceof Error ? err.cause : void 0;
2143
+ const message = cause instanceof Error ? cause.message : err instanceof Error ? err.message : String(err);
2144
+ if (message) parts.push(message);
2145
+ return parts.join(": ").replace(/\s+/g, " ").trim().slice(0, 200);
2146
+ }
2147
+ function withStderrTail(err, stderrRing, env) {
2148
+ if (!(err instanceof ActivationError) || err.stderrTail) return err;
2149
+ const trimmed = stderrRing.trim();
2150
+ if (trimmed.length === 0) return err;
2151
+ const safe = redactSecretsInOutput(trimmed, env);
2152
+ const oomHint = oamHeapOomHint(trimmed);
2153
+ const message = `${err.message}${oomHint ? ` ${oomHint}` : ""} stderr tail: ${safe.slice(-500)}`;
2154
+ return new ActivationError(message, err.category, safe, err.cause);
2155
+ }
2109
2156
  var oamDowngradedNamespaces = /* @__PURE__ */ new Set();
2110
2157
  async function connectToUpstream(config, onDisconnect, onListChanged, bridge) {
2111
2158
  const attempt = { oamRewriteApplied: false, oamVersion: null };
@@ -2162,7 +2209,7 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge
2162
2209
  if (downstreamCaps?.sampling) capabilities.sampling = downstreamCaps.sampling;
2163
2210
  if (downstreamCaps?.roots) capabilities.roots = {};
2164
2211
  const client = new Client(
2165
- { name: "yaw-mcp", version: true ? "0.79.0" : "dev" },
2212
+ { name: "yaw-mcp", version: true ? "0.79.2" : "dev" },
2166
2213
  { capabilities }
2167
2214
  );
2168
2215
  if (bridge && capabilities.elicitation) {
@@ -2186,6 +2233,7 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge
2186
2233
  let transport;
2187
2234
  let stderrRing = "";
2188
2235
  let resolvedServerEnv = {};
2236
+ let spawnedCommand = config.command;
2189
2237
  if (config.type === "local") {
2190
2238
  if (!config.command) {
2191
2239
  throw new Error("command is required for local servers");
@@ -2215,6 +2263,7 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge
2215
2263
  err
2216
2264
  );
2217
2265
  }
2266
+ spawnedCommand = resolved.command;
2218
2267
  const serverEnv = await resolveServerEnv(config.env ?? {}, config.namespace);
2219
2268
  resolvedServerEnv = serverEnv;
2220
2269
  const stdioTransport = new StdioClientTransport({
@@ -2245,14 +2294,28 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge
2245
2294
  { namespace: config.namespace }
2246
2295
  );
2247
2296
  }
2248
- const url = new URL(config.url);
2297
+ let url;
2298
+ try {
2299
+ url = new URL(config.url);
2300
+ } catch (err) {
2301
+ const message = err instanceof Error ? err.message : String(err);
2302
+ throw new ActivationError(
2303
+ withConfigPointer(`Server "${config.namespace}" has an invalid url "${config.url}": ${message}`, config),
2304
+ "unknown",
2305
+ void 0,
2306
+ err
2307
+ );
2308
+ }
2249
2309
  if (config.transport === "sse") {
2250
2310
  transport = new SSEClientTransport(url);
2251
2311
  } else {
2252
2312
  transport = new StreamableHTTPClientTransport(url);
2253
2313
  }
2254
2314
  }
2255
- const connectTimeoutMs = typeof config.connectTimeoutMs === "number" && config.connectTimeoutMs > 0 ? config.connectTimeoutMs : DEFAULT_CONNECT_TIMEOUT;
2315
+ const connectTimeoutMs = Math.min(
2316
+ typeof config.connectTimeoutMs === "number" && config.connectTimeoutMs > 0 ? config.connectTimeoutMs : DEFAULT_CONNECT_TIMEOUT,
2317
+ MAX_TIMEOUT_MS
2318
+ );
2256
2319
  let timedOut = false;
2257
2320
  let timer;
2258
2321
  const timeoutPromise = new Promise((_, reject) => {
@@ -2278,7 +2341,8 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge
2278
2341
  let message;
2279
2342
  if (config.type !== "local") {
2280
2343
  category = timedOut ? "init_timeout" : "protocol_error";
2281
- message = timedOut ? `Remote server at ${config.url} did not respond within ${connectTimeoutMs / 1e3}s. Verify the URL is reachable.` : `Remote server at ${config.url} refused the connection.`;
2344
+ const detail = timedOut ? "" : remoteFailureDetail(err);
2345
+ message = timedOut ? `Remote server at ${config.url} did not respond within ${connectTimeoutMs / 1e3}s. Verify the URL is reachable.` : `Remote server at ${config.url} refused the connection.${detail ? ` ${detail}` : ""}`;
2282
2346
  } else if (timedOut) {
2283
2347
  category = "init_timeout";
2284
2348
  message = `Server "${config.namespace}" started but didn't complete the MCP handshake within ${connectTimeoutMs / 1e3}s.${trimmedStderr ? ` stderr tail: ${redactSecretsInOutput(trimmedStderr, resolvedServerEnv).slice(-500)}` : ""}`;
@@ -2290,7 +2354,7 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge
2290
2354
  } else {
2291
2355
  category = categorizeSpawnError(err);
2292
2356
  if (category === "spawn_failure") {
2293
- message = `Command '${config.command}' is not on PATH or is not executable. Verify the runtime is installed (e.g. Node.js for npx, Python for uvx).`;
2357
+ message = `Command '${config.command}' is not on PATH or is not executable. Verify the runtime is installed (e.g. Node.js for npx, Python for uvx).${spawnedCommand && spawnedCommand !== config.command ? ` The binary that actually failed to spawn was '${spawnedCommand}'.` : ""}`;
2294
2358
  } else {
2295
2359
  message = err instanceof Error ? err.message : String(err);
2296
2360
  }
@@ -2299,7 +2363,12 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge
2299
2363
  const redactedTail = trimmedStderr ? redactSecretsInOutput(trimmedStderr, resolvedServerEnv) : void 0;
2300
2364
  throw new ActivationError(message, category, redactedTail, err);
2301
2365
  }
2302
- const runtimeFields = attempt.oamRewriteApplied ? disableOamRewrite ? { runtime: "node", downgradedFromOam: true } : { runtime: "oam", oamVersion: attempt.oamVersion } : {};
2366
+ let runtimeFields = {};
2367
+ if (attempt.oamRewriteApplied) {
2368
+ runtimeFields = disableOamRewrite ? { runtime: "node", downgradedFromOam: true } : { runtime: "oam", oamVersion: attempt.oamVersion };
2369
+ } else if (config.type === "local" && oamDowngradedNamespaces.has(config.namespace)) {
2370
+ runtimeFields = { runtime: "node", downgradedFromOam: true, oamPinned: true };
2371
+ }
2303
2372
  log("info", "Connected to upstream", {
2304
2373
  name: config.name,
2305
2374
  namespace: config.namespace,
@@ -2325,22 +2394,35 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge
2325
2394
  releaseChains = resolve8;
2326
2395
  });
2327
2396
  if (onListChanged) {
2328
- let toolsChain = chainsGate;
2329
- let resourcesChain = chainsGate;
2330
- let promptsChain = chainsGate;
2331
- client.setNotificationHandler(ToolListChangedNotificationSchema, () => {
2332
- toolsChain = toolsChain.then(async () => {
2397
+ const queueRefresh = (state, run2) => {
2398
+ if (state.outstanding >= 2) return state.chain;
2399
+ state.outstanding += 1;
2400
+ state.chain = state.chain.then(async () => {
2401
+ try {
2402
+ await run2();
2403
+ } finally {
2404
+ state.outstanding -= 1;
2405
+ }
2406
+ });
2407
+ return state.chain;
2408
+ };
2409
+ const toolsRefresh = { chain: chainsGate, outstanding: 0 };
2410
+ const resourcesRefresh = { chain: chainsGate, outstanding: 0 };
2411
+ const promptsRefresh = { chain: chainsGate, outstanding: 0 };
2412
+ client.setNotificationHandler(
2413
+ ToolListChangedNotificationSchema,
2414
+ () => queueRefresh(toolsRefresh, async () => {
2333
2415
  try {
2334
2416
  connection.tools = await fetchToolsFromUpstream(client, config.namespace);
2335
2417
  onListChanged(config.namespace);
2336
2418
  } catch (err) {
2337
2419
  log("warn", "Failed to refresh tools from upstream", { namespace: config.namespace, error: err.message });
2338
2420
  }
2339
- });
2340
- return toolsChain;
2341
- });
2342
- client.setNotificationHandler(ResourceListChangedNotificationSchema, () => {
2343
- resourcesChain = resourcesChain.then(async () => {
2421
+ })
2422
+ );
2423
+ client.setNotificationHandler(
2424
+ ResourceListChangedNotificationSchema,
2425
+ () => queueRefresh(resourcesRefresh, async () => {
2344
2426
  try {
2345
2427
  connection.resources = await fetchResourcesFromUpstream(client, config.namespace, { throwOnError: true });
2346
2428
  onListChanged(config.namespace);
@@ -2350,11 +2432,11 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge
2350
2432
  error: err.message
2351
2433
  });
2352
2434
  }
2353
- });
2354
- return resourcesChain;
2355
- });
2356
- client.setNotificationHandler(PromptListChangedNotificationSchema, () => {
2357
- promptsChain = promptsChain.then(async () => {
2435
+ })
2436
+ );
2437
+ client.setNotificationHandler(
2438
+ PromptListChangedNotificationSchema,
2439
+ () => queueRefresh(promptsRefresh, async () => {
2358
2440
  try {
2359
2441
  connection.prompts = await fetchPromptsFromUpstream(client, config.namespace, { throwOnError: true });
2360
2442
  onListChanged(config.namespace);
@@ -2364,11 +2446,10 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge
2364
2446
  error: err.message
2365
2447
  });
2366
2448
  }
2367
- });
2368
- return promptsChain;
2369
- });
2449
+ })
2450
+ );
2370
2451
  }
2371
- const tools = await fetchToolsFromUpstream(client, config.namespace);
2452
+ const tools = await fetchToolsFromUpstream(client, config.namespace, { allowMissingToolsCapability: true });
2372
2453
  const resources = await fetchResourcesFromUpstream(client, config.namespace);
2373
2454
  const prompts = await fetchPromptsFromUpstream(client, config.namespace);
2374
2455
  if (closedBeforeReady) {
@@ -2391,7 +2472,7 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge
2391
2472
  await client.close();
2392
2473
  } catch {
2393
2474
  }
2394
- throw err;
2475
+ throw withStderrTail(err, stderrRing, resolvedServerEnv);
2395
2476
  }
2396
2477
  }
2397
2478
  async function disconnectFromUpstream(connection) {
@@ -2411,8 +2492,17 @@ async function fetchAllPages(fetchPage, cap, context) {
2411
2492
  let cursor;
2412
2493
  for (let page = 0; page < MAX_LIST_PAGES; page++) {
2413
2494
  const { items, nextCursor } = await fetchPage(cursor);
2414
- all.push(...items);
2495
+ for (const item of items) all.push(item);
2415
2496
  if (nextCursor === void 0 || all.length > cap) return all;
2497
+ if (nextCursor.length === 0 || nextCursor === cursor) {
2498
+ log("warn", "Upstream repeated its pagination cursor; stopping pagination", {
2499
+ namespace: context.namespace,
2500
+ endpoint: context.endpoint,
2501
+ pagesFetched: page + 1,
2502
+ items: all.length
2503
+ });
2504
+ return all;
2505
+ }
2416
2506
  if (items.length === 0) {
2417
2507
  log("warn", "Upstream returned an empty page with a cursor; stopping pagination", {
2418
2508
  namespace: context.namespace,
@@ -2499,7 +2589,10 @@ async function fetchPromptsFromUpstream(client, namespace, opts = {}) {
2499
2589
  throw new Error(`"${namespace}" returned an error on prompts/list: ${message}`);
2500
2590
  }
2501
2591
  }
2502
- async function fetchToolsFromUpstream(client, namespace) {
2592
+ function isMethodNotFound(err) {
2593
+ return err?.code === -32601;
2594
+ }
2595
+ async function fetchToolsFromUpstream(client, namespace, opts = {}) {
2503
2596
  let all;
2504
2597
  try {
2505
2598
  all = await fetchAllPages(
@@ -2511,6 +2604,10 @@ async function fetchToolsFromUpstream(client, namespace) {
2511
2604
  { namespace, endpoint: "tools/list" }
2512
2605
  );
2513
2606
  } catch (err) {
2607
+ if (opts.allowMissingToolsCapability && isMethodNotFound(err)) {
2608
+ log("info", "Upstream does not implement tools/list; loading it as a zero-tool server", { namespace });
2609
+ return [];
2610
+ }
2514
2611
  const message = err instanceof Error ? err.message : String(err);
2515
2612
  throw new ActivationError(
2516
2613
  `"${namespace}" returned an error on tools/list: ${message}`,
@@ -2563,8 +2660,9 @@ var SECRET_FLAG_NAMES = /* @__PURE__ */ new Set([
2563
2660
  "--secret",
2564
2661
  "-p"
2565
2662
  ]);
2663
+ var SECRET_FLAG_RE = /^--?[a-z0-9_-]*(token|secret|passw|apikey|api[-_]?key|auth|cred|bearer)[a-z0-9_-]*$/i;
2566
2664
  function redactSecretArgs(args) {
2567
- const isSecretFlag = (s) => SECRET_FLAG_NAMES.has(s.toLowerCase());
2665
+ const isSecretFlag = (s) => SECRET_FLAG_NAMES.has(s.toLowerCase()) || SECRET_FLAG_RE.test(s);
2568
2666
  const out = [];
2569
2667
  for (let i = 0; i < args.length; i++) {
2570
2668
  const a = args[i] ?? "";
@@ -2635,13 +2733,13 @@ async function resolveComplianceSuiteVersion(fromUrl = import.meta.url) {
2635
2733
  } catch {
2636
2734
  return void 0;
2637
2735
  }
2638
- for (let dir = dirname2(here); ; dir = dirname2(dir)) {
2736
+ for (let dir = dirname3(here); ; dir = dirname3(dir)) {
2639
2737
  const pjPath = join6(dir, "node_modules", "@yawlabs", "mcp-compliance", "package.json");
2640
2738
  let raw;
2641
2739
  try {
2642
2740
  raw = await readFile6(pjPath, "utf8");
2643
2741
  } catch {
2644
- if (dirname2(dir) === dir) return void 0;
2742
+ if (dirname3(dir) === dir) return void 0;
2645
2743
  continue;
2646
2744
  }
2647
2745
  try {
@@ -2744,7 +2842,7 @@ async function runAudit(opts = {}) {
2744
2842
  report = await runner(target);
2745
2843
  } catch (err) {
2746
2844
  const msg = err instanceof Error ? err.message : String(err);
2747
- log("error", "audit: compliance suite failed", { namespace, error: msg });
2845
+ log("debug", "audit: compliance suite failed", { namespace, error: msg });
2748
2846
  printErr(`yaw-mcp audit: compliance suite failed for "${namespace}": ${msg}`);
2749
2847
  return { exitCode: 2, lines };
2750
2848
  }
@@ -2759,7 +2857,7 @@ async function runAudit(opts = {}) {
2759
2857
  );
2760
2858
  } catch (err) {
2761
2859
  cacheError = err instanceof Error ? err.message : String(err);
2762
- log("error", "audit: grade cache write failed", { namespace, error: cacheError });
2860
+ log("debug", "audit: grade cache write failed", { namespace, error: cacheError });
2763
2861
  }
2764
2862
  if (opts.json) {
2765
2863
  const payload = {
@@ -2767,6 +2865,12 @@ async function runAudit(opts = {}) {
2767
2865
  grade: report.grade,
2768
2866
  score: report.score,
2769
2867
  gradedAt,
2868
+ // The rubric that produced the letter. It is persisted to grades.json, so
2869
+ // a --json consumer that omitted it could not tell an "A" graded under an
2870
+ // older rubric from a current one -- the whole reason the field exists.
2871
+ // OMITTED rather than null when the runner reported none, matching the
2872
+ // cache entry (a pre-field entry simply has no key).
2873
+ ...report.suiteVersion !== void 0 ? { suiteVersion: report.suiteVersion } : {},
2770
2874
  cache: cachePath
2771
2875
  };
2772
2876
  if (cacheError !== null) payload.cacheError = cacheError;
@@ -2850,14 +2954,15 @@ function matchBundles(installedNamespaces) {
2850
2954
  function bundleActivateHint(bundle) {
2851
2955
  return `mcp_connect_activate({ servers: ${JSON.stringify(bundle.namespaces)} })`;
2852
2956
  }
2957
+ function comparePartialBundles(a, b) {
2958
+ if (a.missing.length !== b.missing.length) return a.missing.length - b.missing.length;
2959
+ if (a.have.length !== b.have.length) return b.have.length - a.have.length;
2960
+ return a.bundle.id.localeCompare(b.bundle.id);
2961
+ }
2853
2962
  function topPartialBundles(installedNamespaces, limit) {
2854
2963
  if (limit <= 0) return [];
2855
2964
  const { partial } = matchBundles(installedNamespaces);
2856
- return partial.slice().sort((a, b) => {
2857
- if (a.missing.length !== b.missing.length) return a.missing.length - b.missing.length;
2858
- if (a.have.length !== b.have.length) return b.have.length - a.have.length;
2859
- return a.bundle.id.localeCompare(b.bundle.id);
2860
- }).slice(0, limit);
2965
+ return partial.slice().sort(comparePartialBundles).slice(0, limit);
2861
2966
  }
2862
2967
 
2863
2968
  // src/config-loader.ts
@@ -2866,14 +2971,14 @@ import { homedir as homedir7 } from "os";
2866
2971
  import { join as join8, resolve as resolve3 } from "path";
2867
2972
 
2868
2973
  // src/migrate.ts
2869
- import { lstat as lstat2, mkdir as mkdir3, rename as rename2, stat as stat3 } from "fs/promises";
2870
- import { dirname as dirname3, join as join7, resolve as resolve2 } from "path";
2974
+ import { lstat as lstat2, mkdir as mkdir2, rename as rename2, stat as stat3 } from "fs/promises";
2975
+ import { dirname as dirname4, join as join7, resolve as resolve2 } from "path";
2871
2976
  var LEGACY_GLOBAL_FILENAME = ".yaw-mcp.json";
2872
2977
  var LEGACY_PROJECT_FILENAME = ".yaw-mcp.json";
2873
2978
  var LEGACY_LOCAL_FILENAME = ".yaw-mcp.local.json";
2874
2979
  var NEW_CONFIG_FILENAME = "config.json";
2875
2980
  var NEW_LOCAL_FILENAME = "config.local.json";
2876
- async function exists2(path6) {
2981
+ async function exists(path6) {
2877
2982
  try {
2878
2983
  await stat3(path6);
2879
2984
  return true;
@@ -2912,7 +3017,7 @@ async function migrateFile(legacy, target, scope) {
2912
3017
  }
2913
3018
  }
2914
3019
  }
2915
- if (await exists2(target)) {
3020
+ if (await exists(target)) {
2916
3021
  log("warn", "yaw-mcp config: legacy file exists alongside new location -- legacy is ignored", {
2917
3022
  scope,
2918
3023
  legacy,
@@ -2922,7 +3027,7 @@ async function migrateFile(legacy, target, scope) {
2922
3027
  return;
2923
3028
  }
2924
3029
  try {
2925
- await mkdir3(dirname3(target), { recursive: true });
3030
+ await mkdir2(dirname4(target), { recursive: true });
2926
3031
  await rename2(legacy, target);
2927
3032
  log("info", "yaw-mcp config: migrated legacy file into .yaw-mcp/ directory", {
2928
3033
  scope,
@@ -2944,7 +3049,7 @@ async function migrateLegacyConfigPaths(opts) {
2944
3049
  const newGlobal = join7(userConfigDir(home), NEW_CONFIG_FILENAME);
2945
3050
  await migrateFile(legacyGlobal, newGlobal, "global");
2946
3051
  const homeLocal = join7(home, LEGACY_LOCAL_FILENAME);
2947
- if (await exists2(homeLocal)) {
3052
+ if (await exists(homeLocal)) {
2948
3053
  log("warn", "yaw-mcp config: legacy machine-local file at $HOME has no new location -- leaving it in place", {
2949
3054
  scope: "local",
2950
3055
  legacy: homeLocal,
@@ -2970,9 +3075,9 @@ async function findLegacyProjectRoot(cwd, home) {
2970
3075
  if (!isUnderHome(dir, homeResolved)) return null;
2971
3076
  const legacyProject = join7(dir, LEGACY_PROJECT_FILENAME);
2972
3077
  const legacyLocal = join7(dir, LEGACY_LOCAL_FILENAME);
2973
- if (await exists2(legacyProject) || await exists2(legacyLocal)) return dir;
3078
+ if (await exists(legacyProject) || await exists(legacyLocal)) return dir;
2974
3079
  prev = dir;
2975
- dir = dirname3(dir);
3080
+ dir = dirname4(dir);
2976
3081
  }
2977
3082
  return null;
2978
3083
  }
@@ -2989,6 +3094,7 @@ var KNOWN_CONFIG_KEYS = /* @__PURE__ */ new Set([
2989
3094
  "blocked",
2990
3095
  "installNudge"
2991
3096
  ]);
3097
+ var CONFIG_SCHEMA_URL = "https://raw.githubusercontent.com/YawLabs/mcp/main/schemas/yaw-mcp.config.v1.json";
2992
3098
  function deprecatedKeyWarning(path6, keys) {
2993
3099
  const quoted = keys.map((k) => `'${k}'`).join(" and ");
2994
3100
  const isAre = keys.length > 1 ? "are" : "is";
@@ -2997,14 +3103,28 @@ function deprecatedKeyWarning(path6, keys) {
2997
3103
  return `${path6}: ${quoted} ${isAre} no longer used -- yaw-mcp is local-only and never contacts a hosted API. Delete ${them} from ${path6}.${revoke}`;
2998
3104
  }
2999
3105
  function filterStringArray(raw, field, path6, warnings) {
3000
- if (!Array.isArray(raw)) return void 0;
3001
- const strings = raw.filter((v) => typeof v === "string" && v.trim() !== "");
3106
+ if (!Array.isArray(raw)) {
3107
+ if (raw !== void 0) {
3108
+ warnings.push(
3109
+ `${path6}: '${field}' must be an array of namespace strings (found ${raw === null ? "null" : typeof raw}) -- ignored.`
3110
+ );
3111
+ }
3112
+ return void 0;
3113
+ }
3114
+ const strings = raw.map((v) => typeof v === "string" ? v.trim() : v).filter((v) => typeof v === "string" && v !== "");
3002
3115
  const dropped = raw.length - strings.length;
3003
3116
  if (dropped > 0) {
3004
3117
  warnings.push(
3005
3118
  `${path6}: '${field}' dropped ${dropped} non-string or empty ${dropped === 1 ? "entry" : "entries"} -- only non-empty string namespaces are honored.`
3006
3119
  );
3007
3120
  }
3121
+ for (const s of strings) {
3122
+ if (!NAMESPACE_RE.test(s)) {
3123
+ warnings.push(
3124
+ `${path6}: '${field}' entry '${s}' is not a valid namespace (a lowercase letter followed by [a-z0-9_]) -- it can never match an installed server.`
3125
+ );
3126
+ }
3127
+ }
3008
3128
  if (strings.length === 0 && raw.length > 0) return void 0;
3009
3129
  return strings;
3010
3130
  }
@@ -3055,12 +3175,17 @@ async function readConfigAt(path6, scope, warnings) {
3055
3175
  );
3056
3176
  if (unknownKeys.length > 0) {
3057
3177
  warnings.push(
3058
- `${path6}: unknown ${unknownKeys.length === 1 ? "key" : "keys"} ${unknownKeys.map((k) => `'${k}'`).join(", ")} ignored -- known keys: ${[...KNOWN_CONFIG_KEYS].join(", ")}.`
3178
+ `${path6}: unknown ${unknownKeys.length === 1 ? "key" : "keys"} ${unknownKeys.map((k) => `'${k}'`).join(", ")} ignored -- known keys: ${[...KNOWN_CONFIG_KEYS].join(", ")}. Full schema: ${CONFIG_SCHEMA_URL}`
3059
3179
  );
3060
3180
  }
3061
3181
  const servers = filterStringArray(obj.servers, "servers", path6, warnings);
3062
3182
  const blocked = filterStringArray(obj.blocked, "blocked", path6, warnings);
3063
3183
  const installNudge = typeof obj.installNudge === "boolean" ? obj.installNudge : void 0;
3184
+ if ("installNudge" in obj && installNudge === void 0) {
3185
+ warnings.push(
3186
+ `${path6}: 'installNudge' must be a boolean (found ${obj.installNudge === null ? "null" : typeof obj.installNudge}) -- ignored; the nudge stays off for this file.`
3187
+ );
3188
+ }
3064
3189
  return { path: path6, scope, version, servers, blocked, installNudge };
3065
3190
  }
3066
3191
  function pickServers(files) {
@@ -3295,11 +3420,7 @@ function renderMatch(match, installed, excluded, print) {
3295
3420
  print("");
3296
3421
  }
3297
3422
  if (match.partial.length > 0) {
3298
- const sorted = match.partial.slice().sort((a, b) => {
3299
- if (a.missing.length !== b.missing.length) return a.missing.length - b.missing.length;
3300
- if (a.have.length !== b.have.length) return b.have.length - a.have.length;
3301
- return a.bundle.id.localeCompare(b.bundle.id);
3302
- });
3423
+ const sorted = match.partial.slice().sort(comparePartialBundles);
3303
3424
  print("Partially installed (install more to complete):");
3304
3425
  for (const entry of sorted) {
3305
3426
  const have = entry.have.join(", ");
@@ -3467,16 +3588,9 @@ ${COMPLETION_USAGE}` };
3467
3588
  }
3468
3589
  return { ok: true, options: { shell } };
3469
3590
  }
3470
- async function runCompletion(opts = {}) {
3591
+ async function runCompletion(opts) {
3471
3592
  const write = opts.out ?? ((s) => process.stdout.write(s));
3472
- const writeErr = opts.err ?? ((s) => process.stderr.write(s));
3473
3593
  const lines = [];
3474
- if (!opts.shell) {
3475
- writeErr(`yaw-mcp completion: missing shell argument
3476
- ${COMPLETION_USAGE}
3477
- `);
3478
- return { exitCode: 2, lines };
3479
- }
3480
3594
  const script = renderScript(opts.shell);
3481
3595
  lines.push(script);
3482
3596
  write(script);
@@ -3514,7 +3628,7 @@ function renderBash() {
3514
3628
  ...posClauses,
3515
3629
  ` COMPREPLY=( $(compgen -W "${spec.flags.join(" ")}" -- "$cur") )`,
3516
3630
  " return 0"
3517
- ].filter((p) => p !== "");
3631
+ ];
3518
3632
  return ` ${spec.name})
3519
3633
  ${parts.join("\n")}
3520
3634
  ;;`;
@@ -3543,13 +3657,10 @@ function renderZsh() {
3543
3657
  const subcommandList = SUBCOMMAND_SPEC.map((s) => ` '${s.name}[${s.description}]'`).join(" \\\n");
3544
3658
  const argsCases = SUBCOMMAND_SPEC.map((spec) => {
3545
3659
  const lines = [` ${spec.name})`];
3546
- const positionals = realPositionals(spec);
3547
- if (positionals.length > 0) {
3548
- const posArgs = positionals.map(({ candidates, index }) => `'${index + 1}: :(${candidates.join(" ")})'`).join(" ");
3549
- lines.push(` _arguments ${posArgs} '*: :(${spec.flags.join(" ")})'`);
3550
- } else {
3551
- lines.push(` _arguments '*: :(${spec.flags.join(" ")})'`);
3552
- }
3660
+ const posArgs = realPositionals(spec).map(({ candidates, index }) => `'${index + 1}: :(${candidates.join(" ")})'`);
3661
+ const flagArgs = spec.flags.map((f) => `'${f}'`);
3662
+ const argSpecs = [...posArgs, ...flagArgs];
3663
+ lines.push(` _arguments ${argSpecs.length > 0 ? argSpecs.join(" ") : "'*: :()'"}`);
3553
3664
  lines.push(" ;;");
3554
3665
  return lines.join("\n");
3555
3666
  }).join("\n");
@@ -3582,6 +3693,19 @@ _yaw-mcp "$@"
3582
3693
  function renderFish() {
3583
3694
  const header = `# fish completion for yaw-mcp \u2014 generated by \`yaw-mcp completion fish\`
3584
3695
  # Install: save this to ~/.config/fish/completions/yaw-mcp.fish
3696
+ function __yaw_mcp_using_subcommand
3697
+ set -l tokens (commandline -opc)
3698
+ set -l known ${SUBCOMMAND_SPEC.map((s) => s.name).join(" ")}
3699
+ for tok in $tokens
3700
+ if contains -- $tok $known
3701
+ if test "$tok" = "$argv[1]"
3702
+ return 0
3703
+ end
3704
+ return 1
3705
+ end
3706
+ end
3707
+ return 1
3708
+ end
3585
3709
  complete -c yaw-mcp -f`;
3586
3710
  const subcommandLines = SUBCOMMAND_SPEC.map((spec) => {
3587
3711
  return `complete -c yaw-mcp -n __fish_use_subcommand -a ${spec.name}`;
@@ -3598,7 +3722,7 @@ complete -c yaw-mcp -f`;
3598
3722
  for (const f of spec.flags) {
3599
3723
  if (!f.startsWith("--")) continue;
3600
3724
  const long = f.slice(2);
3601
- flagLines.push(`complete -c yaw-mcp -n "__fish_seen_subcommand_from ${spec.name}" -l ${long}`);
3725
+ flagLines.push(`complete -c yaw-mcp -n "__yaw_mcp_using_subcommand ${spec.name}" -l ${long}`);
3602
3726
  }
3603
3727
  }
3604
3728
  return [header, "", ...subcommandLines, "", ...positionalLines, "", ...flagLines, ""].join("\n");
@@ -3671,6 +3795,7 @@ async function runComplianceCommand(argv, io = {}) {
3671
3795
  }
3672
3796
  const run2 = await runTest(argv, err, await resolveComplianceSuiteSpec());
3673
3797
  if (!run2) return 1;
3798
+ if ("interrupted" in run2) return run2.code;
3674
3799
  printSummary(run2.report, out);
3675
3800
  return run2.code ?? 1;
3676
3801
  }
@@ -3771,13 +3896,17 @@ function killTree(child) {
3771
3896
  }
3772
3897
  var INTERRUPT_GRACE_MS = 3e3;
3773
3898
  var INTERRUPT_EXIT_CODE = 130;
3899
+ var TERMINATED_EXIT_CODE = 143;
3900
+ function signalExitCode(signal) {
3901
+ return signal === "SIGTERM" ? TERMINATED_EXIT_CODE : INTERRUPT_EXIT_CODE;
3902
+ }
3774
3903
  function createInterruptHandler(child, opts = {}) {
3775
3904
  const graceMs = opts.graceMs ?? INTERRUPT_GRACE_MS;
3776
3905
  const exit = opts.exit ?? ((code) => process.exit(code));
3777
3906
  const kill = opts.kill ?? killTree;
3778
3907
  let timer;
3779
3908
  return {
3780
- onInterrupt: () => {
3909
+ onInterrupt: (signal) => {
3781
3910
  kill(child);
3782
3911
  if (timer !== void 0) return;
3783
3912
  timer = setTimeout(() => {
@@ -3785,7 +3914,7 @@ function createInterruptHandler(child, opts = {}) {
3785
3914
  child.kill();
3786
3915
  } catch {
3787
3916
  }
3788
- exit(INTERRUPT_EXIT_CODE);
3917
+ exit(signalExitCode(signal));
3789
3918
  }, graceMs);
3790
3919
  timer.unref?.();
3791
3920
  },
@@ -3828,7 +3957,11 @@ Failed to launch mcp-compliance: ${e instanceof Error ? e.message : String(e)}
3828
3957
  return;
3829
3958
  }
3830
3959
  const interrupt = createInterruptHandler(child);
3831
- const onInterrupt = interrupt.onInterrupt;
3960
+ let interruptedBy;
3961
+ const onInterrupt = (signal) => {
3962
+ interruptedBy ??= signal;
3963
+ interrupt.onInterrupt(signal);
3964
+ };
3832
3965
  process.once("SIGINT", onInterrupt);
3833
3966
  process.once("SIGTERM", onInterrupt);
3834
3967
  const releaseSignals = () => {
@@ -3878,10 +4011,18 @@ Failed to launch mcp-compliance: ${e.message}
3878
4011
  settled = true;
3879
4012
  clearTimeout(timer);
3880
4013
  releaseSignals();
4014
+ const cancelled = () => {
4015
+ err("\nmcp-compliance interrupted.\n");
4016
+ resolve8({ interrupted: true, code: signalExitCode(interruptedBy) });
4017
+ };
3881
4018
  const stdout = Buffer.concat(stdoutChunks).toString("utf8");
3882
4019
  try {
3883
4020
  const parsed = JSON.parse(stdout);
3884
4021
  if (!isRenderableReport(parsed)) {
4022
+ if (interruptedBy !== void 0) {
4023
+ cancelled();
4024
+ return;
4025
+ }
3885
4026
  err(`
3886
4027
  mcp-compliance returned unexpected JSON (exit ${code}).
3887
4028
  `);
@@ -3890,6 +4031,10 @@ mcp-compliance returned unexpected JSON (exit ${code}).
3890
4031
  }
3891
4032
  resolve8({ report: parsed, code });
3892
4033
  } catch {
4034
+ if (interruptedBy !== void 0) {
4035
+ cancelled();
4036
+ return;
4037
+ }
3893
4038
  err(`
3894
4039
  mcp-compliance exited ${code} without valid JSON output.
3895
4040
  `);
@@ -3912,7 +4057,7 @@ Target: ${url}
3912
4057
  import { closeSync, existsSync as existsSync7, fstatSync, openSync, readFileSync as readFileSync3, readSync } from "fs";
3913
4058
  import { readFile as readFile11 } from "fs/promises";
3914
4059
  import { homedir as homedir12 } from "os";
3915
- import { isAbsolute, join as join13, resolve as resolve6 } from "path";
4060
+ import { isAbsolute, join as join12, resolve as resolve6 } from "path";
3916
4061
 
3917
4062
  // src/cli-shadows.ts
3918
4063
  var EMPTY = [];
@@ -3959,9 +4104,7 @@ var NAMESPACE_REGISTRY = {
3959
4104
  "aws-api": [{ cli: "aws" }],
3960
4105
  awsapi: [{ cli: "aws" }],
3961
4106
  aws: [{ cli: "aws" }],
3962
- "aws-knowledge": EMPTY,
3963
4107
  awsknowledge: EMPTY,
3964
- "aws-pricing": EMPTY,
3965
4108
  awspricing: EMPTY,
3966
4109
  grafana: EMPTY,
3967
4110
  // —— YawLabs tools —————————————————————————————————————————
@@ -3987,12 +4130,9 @@ var NAMESPACE_REGISTRY = {
3987
4130
  atlassian: EMPTY,
3988
4131
  airtable: EMPTY,
3989
4132
  obsidian: EMPTY,
3990
- "google-workspace": EMPTY,
3991
4133
  googleworkspace: EMPTY,
3992
- "google-maps": EMPTY,
3993
4134
  googlemaps: EMPTY,
3994
4135
  // —— Search / web —————————————————————————————————————————————
3995
- "brave-search": EMPTY,
3996
4136
  bravesearch: EMPTY,
3997
4137
  firecrawl: EMPTY,
3998
4138
  exa: EMPTY,
@@ -4000,7 +4140,6 @@ var NAMESPACE_REGISTRY = {
4000
4140
  // —— Filesystem / local tools ——————————————————————————————————
4001
4141
  filesystem: EMPTY,
4002
4142
  memory: EMPTY,
4003
- "sequential-thinking": EMPTY,
4004
4143
  sequentialthinking: EMPTY,
4005
4144
  time: EMPTY,
4006
4145
  context7: EMPTY,
@@ -4038,7 +4177,9 @@ var KNOWN_CLI_PREFIXES = /* @__PURE__ */ new Set([
4038
4177
  function resolveShadowedClis(server) {
4039
4178
  const key = server.namespace.toLowerCase();
4040
4179
  const direct = Object.hasOwn(NAMESPACE_REGISTRY, key) ? NAMESPACE_REGISTRY[key] : void 0;
4041
- if (direct !== void 0) return [...direct];
4180
+ if (direct !== void 0) {
4181
+ return direct.map((s) => s.subcommands ? { ...s, subcommands: [...s.subcommands] } : { ...s });
4182
+ }
4042
4183
  const cache = server.toolCache ?? [];
4043
4184
  if (cache.length < 3) return [];
4044
4185
  const prefixes = /* @__PURE__ */ new Set();
@@ -4057,7 +4198,7 @@ function cliToNamespaces() {
4057
4198
  for (const [namespace, shadows] of Object.entries(NAMESPACE_REGISTRY)) {
4058
4199
  for (const s of shadows) {
4059
4200
  const list = map.get(s.cli) ?? [];
4060
- if (!list.includes(namespace)) list.push(namespace);
4201
+ list.push(namespace);
4061
4202
  map.set(s.cli, list);
4062
4203
  }
4063
4204
  }
@@ -4155,9 +4296,9 @@ async function loadProjectGuide(cwd, home, env) {
4155
4296
  const guide = await readGuide(guidePath(dir), "project");
4156
4297
  if (!guide) return null;
4157
4298
  const probe = await probeProjectTrust({ cwd, home, env }).catch(() => null);
4158
- const approved = probe !== null && (probe.bypassed || probe.status === "trusted");
4299
+ const approved = probe !== null && (probe.bypassed || projectFileIsHonoured(probe));
4159
4300
  if (approved) return guide;
4160
- log("warn", "Loading a project YAW-MCP.md from an unapproved project dir", {
4301
+ log("debug", "Loading a project YAW-MCP.md from an unapproved project dir", {
4161
4302
  path: guide.path,
4162
4303
  bundles: probe?.status ?? "unknown"
4163
4304
  });
@@ -4188,10 +4329,12 @@ ${guides.project.content}`);
4188
4329
  }
4189
4330
  function renderActiveServersSection(activeServers) {
4190
4331
  if (!activeServers || activeServers.length === 0) return null;
4191
- const rows = activeServers.filter((s) => resolveShadowedClis(s).length > 0).map((s) => {
4332
+ const rows = [];
4333
+ for (const s of activeServers) {
4192
4334
  const shadow = formatShadowLine(s);
4193
- return `- \`${s.namespace}\` (${s.name}) \u2014 ${shadow}`;
4194
- });
4335
+ if (shadow === null) continue;
4336
+ rows.push(`- \`${s.namespace}\` (${s.name}) \u2014 ${shadow}`);
4337
+ }
4195
4338
  if (rows.length === 0) return null;
4196
4339
  return [
4197
4340
  "<!-- source: yaw-mcp (auto-generated from installed servers) -->",
@@ -4228,6 +4371,7 @@ function statePath(configDir = userConfigDir()) {
4228
4371
  function emptyState() {
4229
4372
  return { version: STATE_SCHEMA_VERSION, savedAt: 0, learning: {}, packHistory: [], toolCache: {} };
4230
4373
  }
4374
+ var NO_RAW_COUNTS = { learning: 0, packHistory: 0, toolCache: 0 };
4231
4375
  async function loadState(filePath = statePath()) {
4232
4376
  return (await loadStateClassified(filePath)).state;
4233
4377
  }
@@ -4237,21 +4381,18 @@ async function loadStateClassified(filePath = statePath()) {
4237
4381
  raw = await readFile8(filePath, "utf8");
4238
4382
  } catch (err) {
4239
4383
  if (isFileNotFound(err) || err.code === "ENOTDIR")
4240
- return { state: emptyState(), parsedCleanly: true };
4241
- log(
4242
- "warn",
4243
- "Could not read yaw-mcp state file; state saves are disabled for this session so it is not overwritten",
4244
- {
4245
- error: errorMessage(err)
4246
- }
4247
- );
4248
- return { state: { ...emptyState(), loadFailed: true }, parsedCleanly: false };
4384
+ return { state: emptyState(), rawCounts: NO_RAW_COUNTS, parsedCleanly: true };
4385
+ log("warn", "Could not read yaw-mcp state file; flagged unreadable so a save cannot overwrite it", {
4386
+ error: errorMessage(err)
4387
+ });
4388
+ return { state: { ...emptyState(), loadFailed: true }, rawCounts: NO_RAW_COUNTS, parsedCleanly: false };
4249
4389
  }
4250
4390
  try {
4251
4391
  const parsed = JSON.parse(raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw);
4252
- if (!parsed || typeof parsed !== "object") return { state: emptyState(), parsedCleanly: false };
4392
+ if (!parsed || typeof parsed !== "object")
4393
+ return { state: emptyState(), rawCounts: NO_RAW_COUNTS, parsedCleanly: false };
4253
4394
  if (!isReadableStateVersion(parsed.version))
4254
- return { state: emptyState(), parsedCleanly: false };
4395
+ return { state: emptyState(), rawCounts: NO_RAW_COUNTS, parsedCleanly: false };
4255
4396
  const p = parsed;
4256
4397
  return {
4257
4398
  state: {
@@ -4263,13 +4404,24 @@ async function loadStateClassified(filePath = statePath()) {
4263
4404
  // the v1 -> v2 migration; no other field changed shape.
4264
4405
  toolCache: sanitizeToolCache(p.toolCache)
4265
4406
  },
4407
+ // Counted off `p`, BEFORE the sanitizers above run: what the file held,
4408
+ // not what survived. See RawStateCounts.
4409
+ rawCounts: {
4410
+ learning: countRawEntries(p.learning),
4411
+ packHistory: countRawEntries(p.packHistory),
4412
+ toolCache: countRawEntries(p.toolCache)
4413
+ },
4266
4414
  parsedCleanly: true
4267
4415
  };
4268
4416
  } catch (err) {
4269
4417
  log("warn", "Failed to load yaw-mcp state, starting fresh", { error: errorMessage(err) });
4270
- return { state: emptyState(), parsedCleanly: false };
4418
+ return { state: emptyState(), rawCounts: NO_RAW_COUNTS, parsedCleanly: false };
4271
4419
  }
4272
4420
  }
4421
+ function countRawEntries(input) {
4422
+ if (!input || typeof input !== "object") return 0;
4423
+ return Array.isArray(input) ? input.length : Object.keys(input).length;
4424
+ }
4273
4425
  var saveChain = Promise.resolve();
4274
4426
  function saveState(state, filePath = statePath()) {
4275
4427
  const next = saveChain.then(() => doSaveState(state, filePath));
@@ -4293,7 +4445,7 @@ async function doSaveState(state, filePath) {
4293
4445
  }
4294
4446
  }
4295
4447
  function sanitizeLearning(input) {
4296
- if (!input || typeof input !== "object") return {};
4448
+ if (!input || typeof input !== "object" || Array.isArray(input)) return {};
4297
4449
  const out = {};
4298
4450
  for (const [k, v] of Object.entries(input)) {
4299
4451
  if (!k) continue;
@@ -4320,8 +4472,9 @@ function sanitizePackHistory(input) {
4320
4472
  }
4321
4473
  return out;
4322
4474
  }
4323
- function sanitizeToolCache(input, now = Date.now()) {
4475
+ function sanitizeToolCache(input) {
4324
4476
  if (!input || typeof input !== "object" || Array.isArray(input)) return {};
4477
+ const now = Date.now();
4325
4478
  const kept = [];
4326
4479
  for (const [namespace, value] of Object.entries(input)) {
4327
4480
  if (!namespace) continue;
@@ -4357,23 +4510,26 @@ function errorMessage(err) {
4357
4510
  }
4358
4511
 
4359
4512
  // src/sidecar-refresh.ts
4360
- import { spawn as spawn4 } from "child_process";
4361
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync } from "fs";
4513
+ import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, utimesSync, writeFileSync } from "fs";
4362
4514
  import { homedir as homedir9 } from "os";
4363
- import { dirname as dirname4, join as join10 } from "path";
4515
+ import { dirname as dirname6, join as join10 } from "path";
4364
4516
 
4365
4517
  // src/sidecars-cmd.ts
4366
4518
  import { spawn as spawn3 } from "child_process";
4367
4519
  import { existsSync as existsSync4, mkdirSync, readFileSync } from "fs";
4368
4520
  import { homedir as homedir8 } from "os";
4369
- import { join as join9 } from "path";
4521
+ import { dirname as dirname5, join as join9 } from "path";
4522
+ function isLocalNpxServer(s) {
4523
+ return s.type === "local" && s.command !== void 0 && nodeLaunchKind(s.command) === "npx";
4524
+ }
4370
4525
  function collectSidecarSpecs(servers) {
4371
4526
  const byPkg = /* @__PURE__ */ new Map();
4372
4527
  for (const s of servers) {
4373
- if (s.type !== "local" || s.command === void 0 || nodeLaunchKind(s.command) !== "npx") continue;
4528
+ if (!isLocalNpxServer(s)) continue;
4374
4529
  const spec = npxSpec(s.args ?? []);
4375
4530
  if (spec === null) continue;
4376
4531
  if (!isRegistrySpec(spec)) continue;
4532
+ if (specConstraint(spec).kind === "range") continue;
4377
4533
  const pkg = packageName(spec);
4378
4534
  if (!pkg) continue;
4379
4535
  const existing = byPkg.get(pkg);
@@ -4389,18 +4545,32 @@ function collectSidecarSpecs(servers) {
4389
4545
  function collectNonRegistrySpecs(servers) {
4390
4546
  const out = [];
4391
4547
  for (const s of servers) {
4392
- if (s.type !== "local" || s.command === void 0 || nodeLaunchKind(s.command) !== "npx") continue;
4548
+ if (!isLocalNpxServer(s)) continue;
4393
4549
  const spec = npxSpec(s.args ?? []);
4394
4550
  if (spec === null || isRegistrySpec(spec)) continue;
4395
4551
  out.push({ namespace: s.namespace ?? "(unnamed)", spec });
4396
4552
  }
4397
4553
  return out;
4398
4554
  }
4555
+ function collectRangeSpecs(servers) {
4556
+ const out = [];
4557
+ for (const s of servers) {
4558
+ if (!isLocalNpxServer(s)) continue;
4559
+ const spec = npxSpec(s.args ?? []);
4560
+ if (spec === null || !isRegistrySpec(spec) || specConstraint(spec).kind !== "range") continue;
4561
+ out.push({ namespace: s.namespace ?? "(unnamed)", spec });
4562
+ }
4563
+ return out;
4564
+ }
4565
+ function configuredRange(spec) {
4566
+ if (!spec.spec.startsWith(spec.pkg)) return spec.spec;
4567
+ const raw = spec.spec.slice(spec.pkg.length).replace(/^@/, "");
4568
+ return raw === "" ? "latest" : raw;
4569
+ }
4399
4570
  function sidecarsManifest(specs) {
4400
4571
  const dependencies = {};
4401
- for (const { pkg, spec } of specs.slice().sort((a, b) => a.pkg.localeCompare(b.pkg))) {
4402
- const range = spec.slice(pkg.length).replace(/^@/, "");
4403
- dependencies[pkg] = range === "" ? "latest" : range;
4572
+ for (const spec of specs.slice().sort((a, b) => a.pkg.localeCompare(b.pkg))) {
4573
+ dependencies[spec.pkg] = configuredRange(spec);
4404
4574
  }
4405
4575
  return `${JSON.stringify(
4406
4576
  {
@@ -4454,22 +4624,30 @@ function jsonDocument(root, over = {}) {
4454
4624
  return `${JSON.stringify(doc, null, 2)}
4455
4625
  `;
4456
4626
  }
4457
- function defaultRunNpm(args, cwd) {
4627
+ function npmBin(platform = process.platform, nodeDir = dirname5(process.execPath)) {
4628
+ const name = platform === "win32" ? "npm.cmd" : "npm";
4629
+ const sibling = join9(nodeDir, name);
4630
+ if (!existsSync4(sibling)) return name;
4631
+ return platform === "win32" ? `"${sibling}"` : sibling;
4632
+ }
4633
+ function defaultRunNpm(args, cwd, opts = {}) {
4458
4634
  return new Promise((resolve8) => {
4459
- const isWindows = process.platform === "win32";
4635
+ const platform = opts.platform ?? process.platform;
4636
+ const isWindows = platform === "win32";
4460
4637
  let child;
4461
4638
  try {
4462
- child = spawn3(isWindows ? "npm.cmd" : "npm", args, {
4639
+ child = spawn3(npmBin(platform), args, {
4463
4640
  cwd,
4464
4641
  // npm's own progress ("added 220 packages in 12s") goes to its STDOUT,
4465
4642
  // and inheriting that put it ahead of the JSON document under --json --
4466
4643
  // enough to make `yaw-mcp sidecars install --json | jq` fail outright.
4467
4644
  // Routing the child's stdout to fd 2 keeps the progress visible while
4468
4645
  // leaving OUR stdout carrying only the result, which is what a caller
4469
- // parses. Unconditional rather than --json-only: progress belongs on
4470
- // stderr in both modes, and a mode-dependent stdio is a second shape to
4471
- // get wrong.
4472
- stdio: ["ignore", 2, "inherit"],
4646
+ // parses. The DEFAULT for every mode rather than a --json-only shape:
4647
+ // progress belongs on stderr in both, and a mode-dependent stdio is a
4648
+ // second shape to get wrong. Only a caller with nowhere to PUT the
4649
+ // progress overrides it (see RunNpmOptions.stdio).
4650
+ stdio: opts.stdio ?? ["ignore", 2, "inherit"],
4473
4651
  shell: isWindows
4474
4652
  });
4475
4653
  } catch {
@@ -4519,13 +4697,11 @@ ${SIDECARS_USAGE}` };
4519
4697
  ${SIDECARS_USAGE}` };
4520
4698
  return { ok: true, options: { json } };
4521
4699
  }
4522
- async function unhostedReasons(servers, opts, home) {
4523
- const npx = servers.filter(
4524
- (s) => s.type === "local" && s.command !== void 0 && nodeLaunchKind(s.command) === "npx"
4525
- );
4700
+ async function unhostedReasons(servers, opts, home, bundles) {
4701
+ const npx = servers.filter(isLocalNpxServer);
4526
4702
  if (npx.length === 0) return [];
4527
4703
  const probe = await (opts.oamProbe ?? probeOam)();
4528
- const { runtime: configDefault } = await describeDefaultRuntime({ cwd: opts.cwd, home });
4704
+ const { runtime: configDefault } = await describeDefaultRuntime({ cwd: opts.cwd, home, bundles });
4529
4705
  const verdicts = npx.map(
4530
4706
  (s) => (
4531
4707
  // `args` rides along because describeServerRuntime now mirrors
@@ -4558,15 +4734,20 @@ async function runSidecarsInstall(opts = {}) {
4558
4734
  for (const w of bundles.warnings) printErr(`warning: ${w}`);
4559
4735
  const servers = bundles.config?.servers ?? [];
4560
4736
  const specs = collectSidecarSpecs(servers);
4561
- const skipped = collectNonRegistrySpecs(servers);
4737
+ const nonRegistry = collectNonRegistrySpecs(servers);
4738
+ const ranges = collectRangeSpecs(servers);
4739
+ const skipped = [...nonRegistry, ...ranges];
4562
4740
  const root = sidecarsRoot(home);
4563
4741
  const conflicts = specs.filter((s) => s.conflicting.length > 0).map((s) => ({ pkg: s.pkg, used: s.spec, ignored: s.conflicting }));
4564
4742
  const printSkipped = () => {
4565
4743
  if (skipped.length === 0) return;
4566
4744
  print();
4567
- for (const k of skipped) {
4745
+ for (const k of nonRegistry) {
4568
4746
  print(` note: ${k.namespace} launches ${k.spec}, not a registry package; it keeps using npx`);
4569
4747
  }
4748
+ for (const k of ranges) {
4749
+ print(` note: ${k.namespace} launches ${k.spec}, a version range oam cannot resolve; it keeps using npx`);
4750
+ }
4570
4751
  };
4571
4752
  if (specs.length === 0) {
4572
4753
  if (bundles.config === null && bundles.path !== null) {
@@ -4584,9 +4765,18 @@ async function runSidecarsInstall(opts = {}) {
4584
4765
  return { exitCode: 0, installed: [], lines };
4585
4766
  }
4586
4767
  if (skipped.length > 0) {
4587
- print("Nothing to install -- every npx server points at a git or path target.");
4768
+ print(
4769
+ ranges.length === 0 ? "Nothing to install -- every npx server points at a git or path target." : "Nothing to install -- no npx server names a package this command can install."
4770
+ );
4588
4771
  printSkipped();
4589
- if (opts.json) write(jsonDocument(root, { reason: "only-non-registry-specs", skipped }));
4772
+ if (opts.json) {
4773
+ write(
4774
+ jsonDocument(root, {
4775
+ reason: ranges.length === 0 ? "only-non-registry-specs" : "only-skipped-specs",
4776
+ skipped
4777
+ })
4778
+ );
4779
+ }
4590
4780
  return { exitCode: 0, installed: [], lines };
4591
4781
  }
4592
4782
  print("No npx-launched servers in bundles.json -- nothing to install.");
@@ -4620,7 +4810,7 @@ async function runSidecarsInstall(opts = {}) {
4620
4810
  }
4621
4811
  }
4622
4812
  print();
4623
- const runNpm = opts.runNpm ?? defaultRunNpm;
4813
+ const runNpm = opts.runNpm ?? ((args, cwd) => defaultRunNpm(args, cwd, { platform: opts.platform }));
4624
4814
  const code = await runNpm(["install", "--no-audit", "--no-fund"], root);
4625
4815
  if (code !== 0) {
4626
4816
  print(`npm install failed (exit ${code}). Servers keep resolving from the npx cache.`);
@@ -4659,7 +4849,7 @@ async function runSidecarsInstall(opts = {}) {
4659
4849
  }
4660
4850
  print();
4661
4851
  print("These versions are now fixed. Re-run this command to move them forward.");
4662
- const unhosted = await unhostedReasons(servers, opts, home);
4852
+ const unhosted = await unhostedReasons(servers, opts, home, bundles);
4663
4853
  if (unhosted.length > 0) {
4664
4854
  print();
4665
4855
  print("Nothing reads these copies yet:");
@@ -4688,11 +4878,6 @@ function sidecarRefreshStatePath(home = homedir9()) {
4688
4878
  function inUnitTest() {
4689
4879
  return Boolean(process.env.VITEST);
4690
4880
  }
4691
- function configuredRange(spec) {
4692
- if (!spec.spec.startsWith(spec.pkg)) return spec.spec;
4693
- const raw = spec.spec.slice(spec.pkg.length).replace(/^@/, "");
4694
- return raw === "" ? "latest" : raw;
4695
- }
4696
4881
  function ineligibleReason(spec) {
4697
4882
  const range = configuredRange(spec);
4698
4883
  if (range === "latest") return null;
@@ -4746,31 +4931,38 @@ async function defaultFetchLatest(pkg) {
4746
4931
  clearTimeout(timer);
4747
4932
  }
4748
4933
  }
4934
+ var UPGRADE_LOCK_NAME = ".yaw-mcp-upgrade.lock";
4935
+ var SIDECAR_LOCK_HEARTBEAT_MS = 60 * 1e3;
4749
4936
  function defaultAcquireLock(dir) {
4750
4937
  if (inUnitTest()) return () => {
4751
4938
  };
4752
- return acquireUpgradeLock(dir);
4753
- }
4754
- function silentRunNpm(args, cwd) {
4755
- return new Promise((resolve8) => {
4756
- const isWindows = process.platform === "win32";
4757
- let child;
4939
+ const release = acquireUpgradeLock(dir);
4940
+ if (release === null) return null;
4941
+ const lockPath = join10(dir, UPGRADE_LOCK_NAME);
4942
+ const beat = setInterval(() => {
4758
4943
  try {
4759
- child = spawn4(isWindows ? "npm.cmd" : "npm", args, {
4760
- cwd,
4761
- stdio: "ignore",
4762
- // Not detached, so the install shares yaw-mcp's process group -- see the
4763
- // KNOWN GAP in the header about what a client-side teardown does to it.
4764
- detached: false,
4765
- shell: isWindows
4766
- });
4944
+ const now = /* @__PURE__ */ new Date();
4945
+ utimesSync(lockPath, now, now);
4767
4946
  } catch {
4768
- resolve8(-1);
4769
- return;
4947
+ clearInterval(beat);
4770
4948
  }
4771
- child.on("error", () => resolve8(-1));
4772
- child.on("close", (code, signal) => resolve8(code ?? (signal ? -1 : 0)));
4773
- });
4949
+ }, SIDECAR_LOCK_HEARTBEAT_MS);
4950
+ if (typeof beat.unref === "function") beat.unref();
4951
+ return () => {
4952
+ clearInterval(beat);
4953
+ release();
4954
+ };
4955
+ }
4956
+ function backgroundInstallOptions(home) {
4957
+ return {
4958
+ home,
4959
+ cwd: home,
4960
+ runNpm: (args, cwd) => defaultRunNpm(args, cwd, { stdio: "ignore" }),
4961
+ out: () => {
4962
+ },
4963
+ err: () => {
4964
+ }
4965
+ };
4774
4966
  }
4775
4967
  function defaultSpawnRefresh(stale, onDone, home) {
4776
4968
  if (inUnitTest()) {
@@ -4779,19 +4971,9 @@ function defaultSpawnRefresh(stale, onDone, home) {
4779
4971
  }
4780
4972
  void (async () => {
4781
4973
  try {
4782
- const result = await runSidecarsInstall({
4783
- home,
4784
- // Silent on all three channels. `out`/`err` default to writing the
4785
- // command's prose to stdout/stderr, which from inside serve would mean
4786
- // an "Installed:" table in the middle of the MCP stream.
4787
- runNpm: silentRunNpm,
4788
- out: () => {
4789
- },
4790
- err: () => {
4791
- }
4792
- });
4974
+ const result = await runSidecarsInstall(backgroundInstallOptions(home));
4793
4975
  if (result.exitCode === 0) {
4794
- log("info", "yaw-mcp sidecar refresh complete; restart your MCP client to spawn the new versions", {
4976
+ log("info", "yaw-mcp sidecar refresh complete; the next activation of each server spawns the new version", {
4795
4977
  refreshed: stale.map((s) => s.pkg),
4796
4978
  installed: result.installed.map((i) => `${i.pkg}@${i.version ?? "?"}`)
4797
4979
  });
@@ -4807,14 +4989,25 @@ function defaultSpawnRefresh(stale, onDone, home) {
4807
4989
  }
4808
4990
  })();
4809
4991
  }
4992
+ function parseSidecarRefreshState(text) {
4993
+ let parsed;
4994
+ try {
4995
+ parsed = JSON.parse(text);
4996
+ } catch {
4997
+ return null;
4998
+ }
4999
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
5000
+ const { lastSidecarRefreshCheck: at, ...rest } = parsed;
5001
+ if (typeof at !== "number" || !Number.isFinite(at) || at < 0) return rest;
5002
+ return { ...rest, lastSidecarRefreshCheck: at };
5003
+ }
5004
+ function mergeSidecarRefreshState(prev, patch) {
5005
+ return { ...prev ?? {}, ...patch };
5006
+ }
4810
5007
  function defaultReadState(home) {
4811
5008
  if (inUnitTest()) return null;
4812
5009
  try {
4813
- const parsed = JSON.parse(readFileSync2(sidecarRefreshStatePath(home), "utf8"));
4814
- if (!parsed || typeof parsed !== "object") return null;
4815
- const at = parsed.lastSidecarRefreshCheck;
4816
- if (typeof at !== "number" || !Number.isFinite(at) || at < 0) return {};
4817
- return { lastSidecarRefreshCheck: at };
5010
+ return parseSidecarRefreshState(readFileSync2(sidecarRefreshStatePath(home), "utf8"));
4818
5011
  } catch {
4819
5012
  return null;
4820
5013
  }
@@ -4823,8 +5016,8 @@ function defaultWriteState(home, patch) {
4823
5016
  if (inUnitTest()) return;
4824
5017
  try {
4825
5018
  const path6 = sidecarRefreshStatePath(home);
4826
- const next = { ...defaultReadState(home) ?? {}, ...patch };
4827
- mkdirSync2(dirname4(path6), { recursive: true });
5019
+ const next = mergeSidecarRefreshState(defaultReadState(home), patch);
5020
+ mkdirSync2(dirname6(path6), { recursive: true });
4828
5021
  writeFileSync(path6, `${JSON.stringify(next, null, 2)}
4829
5022
  `, "utf8");
4830
5023
  } catch (err) {
@@ -4833,15 +5026,18 @@ function defaultWriteState(home, patch) {
4833
5026
  });
4834
5027
  }
4835
5028
  }
4836
- async function defaultSpecs(home) {
4837
- if (inUnitTest()) return [];
5029
+ async function loadSidecarSpecs(home, load = loadLocalBundles) {
4838
5030
  try {
4839
- const bundles = await loadLocalBundles({ home });
5031
+ const bundles = await load({ cwd: home, home });
4840
5032
  return collectSidecarSpecs(bundles.config?.servers ?? []);
4841
5033
  } catch {
4842
5034
  return [];
4843
5035
  }
4844
5036
  }
5037
+ async function defaultSpecs(home) {
5038
+ if (inUnitTest()) return [];
5039
+ return loadSidecarSpecs(home);
5040
+ }
4845
5041
  function defaultHasManagedSidecars(home) {
4846
5042
  if (inUnitTest()) return false;
4847
5043
  return hasManagedSidecars(home);
@@ -4850,10 +5046,13 @@ function defaultInstalledVersion(pkg, home) {
4850
5046
  if (inUnitTest()) return null;
4851
5047
  return installedVersion(pkg, home);
4852
5048
  }
5049
+ function isSidecarRefreshDisabled(env = process.env) {
5050
+ const raw = env.YAW_MCP_SIDECAR_REFRESH;
5051
+ return raw === "0" || raw?.toLowerCase() === "false";
5052
+ }
4853
5053
  async function maybeRefreshSidecars(deps = {}) {
4854
5054
  try {
4855
- const optOut = process.env.YAW_MCP_SIDECAR_REFRESH;
4856
- if (optOut === "0" || optOut?.toLowerCase() === "false") return;
5055
+ if (isSidecarRefreshDisabled()) return;
4857
5056
  const home = deps.home ?? homedir9();
4858
5057
  const now = (deps.nowImpl ?? Date.now)();
4859
5058
  if (!(deps.hasManagedSidecarsImpl ?? defaultHasManagedSidecars)(home)) return;
@@ -4931,9 +5130,9 @@ async function maybeRefreshSidecars(deps = {}) {
4931
5130
 
4932
5131
  // src/try-cmd.ts
4933
5132
  import { existsSync as existsSync6 } from "fs";
4934
- import { chmod as chmod6, mkdir as mkdir4, readdir, readFile as readFile10, unlink as unlink2 } from "fs/promises";
5133
+ import { chmod as chmod6, mkdir as mkdir3, readdir, readFile as readFile10, unlink as unlink2 } from "fs/promises";
4935
5134
  import { homedir as homedir11 } from "os";
4936
- import { join as join12, resolve as resolve5 } from "path";
5135
+ import { join as join11, resolve as resolve5 } from "path";
4937
5136
 
4938
5137
  // src/catalog.ts
4939
5138
  var DEFAULT_CATALOG_URL = "https://yaw.sh/data/mcp-catalog.json";
@@ -4986,6 +5185,8 @@ function warnIfCatalogStale(body, opts) {
4986
5185
  function normalizeCatalogUrl(url) {
4987
5186
  return url !== void 0 && url.trim() !== "" ? url : DEFAULT_CATALOG_URL;
4988
5187
  }
5188
+ var CatalogError = class extends Error {
5189
+ };
4989
5190
  async function defaultFetchCatalog(catalogUrl = DEFAULT_CATALOG_URL, deps = {}) {
4990
5191
  const url = normalizeCatalogUrl(catalogUrl);
4991
5192
  const ac = new AbortController();
@@ -4994,29 +5195,31 @@ async function defaultFetchCatalog(catalogUrl = DEFAULT_CATALOG_URL, deps = {})
4994
5195
  try {
4995
5196
  const res = await fetch(url, { signal: ac.signal, headers: { accept: "application/json" } });
4996
5197
  if (!res.ok) {
4997
- throw new Error(`the Yaw MCP catalog at ${url} returned HTTP ${res.status}.`);
5198
+ throw new CatalogError(`the Yaw MCP catalog at ${url} returned HTTP ${res.status}.`);
4998
5199
  }
4999
5200
  try {
5000
5201
  body = await res.json();
5001
5202
  } catch (parseErr) {
5002
5203
  if (parseErr instanceof Error && parseErr.name === "AbortError") throw parseErr;
5003
5204
  const msg = parseErr instanceof Error ? parseErr.message : String(parseErr);
5004
- throw new Error(`the Yaw MCP catalog at ${url} did not return valid JSON (${msg}).`);
5205
+ throw new CatalogError(`the Yaw MCP catalog at ${url} did not return valid JSON (${msg}).`);
5005
5206
  }
5006
5207
  } catch (err) {
5007
5208
  if (err instanceof Error && err.name === "AbortError") {
5008
- throw new Error(`timed out fetching the Yaw MCP catalog at ${url}.`);
5209
+ throw new CatalogError(`timed out fetching the Yaw MCP catalog at ${url}.`);
5009
5210
  }
5010
- if (err instanceof Error && err.message.includes(url)) throw err;
5211
+ if (err instanceof CatalogError) throw err;
5011
5212
  const cause = err instanceof Error && err.cause instanceof Error ? err.cause.message : null;
5012
5213
  const detail = cause ?? (err instanceof Error ? err.message : String(err));
5013
- throw new Error(`could not reach the Yaw MCP catalog at ${url} (${detail}). Check your network, then retry.`);
5214
+ throw new CatalogError(
5215
+ `could not reach the Yaw MCP catalog at ${url} (${detail}). Check your network, then retry.`
5216
+ );
5014
5217
  } finally {
5015
5218
  clearTimeout(timer);
5016
5219
  }
5017
5220
  const servers = body?.servers;
5018
5221
  if (!Array.isArray(servers)) {
5019
- throw new Error(`the Yaw MCP catalog at ${url} was not in the expected shape.`);
5222
+ throw new CatalogError(`the Yaw MCP catalog at ${url} was not in the expected shape.`);
5020
5223
  }
5021
5224
  warnIfCatalogStale(body, deps);
5022
5225
  return servers.filter(
@@ -5045,10 +5248,10 @@ async function resolveCatalogSlug(slug, opts = {}) {
5045
5248
  throw new Error(`catalog entry "${slug}" has no install command.`);
5046
5249
  }
5047
5250
  const tokens = tokenizeCommand(cmdStr);
5048
- if (tokens.length === 0) {
5251
+ const [command, ...args] = tokens;
5252
+ if (!command) {
5049
5253
  throw new Error(`catalog entry "${slug}" install command was empty.`);
5050
5254
  }
5051
- const [command, ...args] = tokens;
5052
5255
  const requiredEnvKeys = Array.isArray(entry.requiredEnv) ? entry.requiredEnv.map((e) => e && typeof e === "object" ? e.key : void 0).filter((k) => typeof k === "string" && ENV_KEY_RE.test(k)) : [];
5053
5256
  const source = typeof entry.repo === "string" ? entry.repo : typeof entry.homepage === "string" ? entry.homepage : void 0;
5054
5257
  return {
@@ -5067,12 +5270,12 @@ async function resolveCatalogSlug(slug, opts = {}) {
5067
5270
  import { existsSync as existsSync5 } from "fs";
5068
5271
  import { readFile as readFile9 } from "fs/promises";
5069
5272
  import { homedir as homedir10 } from "os";
5070
- import { join as join11, resolve as resolve4 } from "path";
5273
+ import { resolve as resolve4 } from "path";
5071
5274
  import { createInterface } from "readline/promises";
5072
5275
  import { Writable } from "stream";
5073
- function oamAbsentNote(os) {
5276
+ function oamAbsentNote(os, publishesBinary = oamPublishesBinaryForThisMachine) {
5074
5277
  const head = "Runtime: node (oam is not installed, which is fine -- node is the supported default. ";
5075
- if (os === CURRENT_OS && !oamPublishesBinaryForThisMachine()) {
5278
+ if (os === CURRENT_OS && !publishesBinary()) {
5076
5279
  return `${head}oam is not an option on this machine: ${oamNoBinaryReason()}.)`;
5077
5280
  }
5078
5281
  return `${head}To host yaw-mcp on oam instead: \`${oamInstallCommand(os)}\`, then re-run install.)`;
@@ -5080,7 +5283,10 @@ function oamAbsentNote(os) {
5080
5283
  function oamIsAbsent(probe) {
5081
5284
  return probe.bin === null && probe.binPath === null && !probe.belowMin && probe.failure === null;
5082
5285
  }
5083
- var USAGE = "Usage: yaw-mcp install <claude-code|claude-desktop|cursor|vscode> [--scope user|project|local]\n [--project-dir <path>] [--os macos|linux|windows]\n [--force | --skip] [--dry-run]\n yaw-mcp install --list (detect clients; no writes)\n yaw-mcp install --all (install into every client available on this OS)\n\n Deprecated (accepted, ignored, warns): --token <mcp_pat_\u2026>, --no-yaw-mcp-config.\n yaw-mcp is local-only -- it stores no token and never writes ~/.yaw-mcp/config.json.\n Configure servers in ~/.yaw-mcp/bundles.json (see `yaw-mcp add <slug>`).";
5286
+ function resolveAppData(opts) {
5287
+ return resolveAppDataDir({ appData: opts.appData, home: opts.home });
5288
+ }
5289
+ var USAGE = "Usage: yaw-mcp install <claude-code|claude-desktop|cursor|vscode> [--scope user|project|local]\n [--project-dir <path>] [--os macos|linux|windows]\n [--force | --skip] [--dry-run]\n yaw-mcp install --list (detect clients; no writes)\n yaw-mcp install --all (install into every client available on this OS)\n\n Deprecated (accepted, ignored, warns): --token <mcp_pat_...>, --no-yaw-mcp-config.\n yaw-mcp is local-only -- it stores no token and never writes ~/.yaw-mcp/config.json.\n Configure servers in ~/.yaw-mcp/bundles.json (see `yaw-mcp add <slug>`).";
5084
5290
  var TOKEN_FLAG_DEPRECATION = "yaw-mcp install: --token is deprecated and ignored -- yaw-mcp is local-only and no longer stores a token. Drop the flag, and revoke that PAT at its source -- dropping it here does not deactivate it.";
5085
5291
  var NO_CONFIG_FLAG_DEPRECATION = "yaw-mcp install: --no-yaw-mcp-config is deprecated and ignored -- install no longer writes ~/.yaw-mcp/config.json at all, so there is nothing to suppress.";
5086
5292
  async function runInstall(opts) {
@@ -5103,12 +5309,12 @@ async function runInstall(opts) {
5103
5309
  err("yaw-mcp install: --list and --all are mutually exclusive");
5104
5310
  return { written: [], wouldWrite: [], messages, exitCode: 2 };
5105
5311
  }
5106
- if (opts.listOnly) return runInstallList(opts, log2, messages);
5107
- if (opts.all) return runInstallAll(opts, log2, err, messages);
5108
5312
  if (opts.force && opts.skip) {
5109
5313
  err("yaw-mcp install: --force and --skip are mutually exclusive");
5110
5314
  return { written: [], wouldWrite: [], messages, exitCode: 2 };
5111
5315
  }
5316
+ if (opts.listOnly) return runInstallList(opts, log2, messages);
5317
+ if (opts.all) return runInstallAll(opts, log2, err, messages);
5112
5318
  if (!opts.clientId) {
5113
5319
  err(`yaw-mcp install: client argument required
5114
5320
  ${USAGE}`);
@@ -5140,6 +5346,15 @@ ${USAGE}`);
5140
5346
  );
5141
5347
  return { written: [], wouldWrite: [], messages, exitCode: 2 };
5142
5348
  }
5349
+ if (opts.projectDir !== void 0 && !scopeSpec.requiresProjectDir) {
5350
+ const projectScopes = target.scopes.filter((s) => s.requiresProjectDir).map((s) => s.scope);
5351
+ const fix = projectScopes.length > 0 ? `Drop it, or install at a scope that reads it: --scope ${projectScopes.join(" | ")}.` : `Drop it -- ${target.label} has no project-directory scope.`;
5352
+ err(
5353
+ `yaw-mcp install: ${target.label} (${scope}) resolves no project directory, so it cannot honor --project-dir.
5354
+ ${fix}`
5355
+ );
5356
+ return { written: [], wouldWrite: [], messages, exitCode: 2 };
5357
+ }
5143
5358
  const projectDir = scopeSpec.requiresProjectDir ? resolve4(opts.cwd ?? process.cwd(), opts.projectDir ?? ".") : void 0;
5144
5359
  let resolved;
5145
5360
  try {
@@ -5148,7 +5363,7 @@ ${USAGE}`);
5148
5363
  scope,
5149
5364
  os,
5150
5365
  home: opts.home,
5151
- appData: opts.appData ?? (opts.home !== void 0 ? join11(opts.home, "AppData", "Roaming") : void 0),
5366
+ appData: resolveAppData(opts),
5152
5367
  projectDir,
5153
5368
  claudeConfigDir: opts.claudeConfigDir
5154
5369
  });
@@ -5177,7 +5392,7 @@ ${USAGE}`);
5177
5392
  const parsed = parseJsonc(raw);
5178
5393
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
5179
5394
  err(
5180
- `yaw-mcp install: ${resolved.absolute} is not a JSON object \u2014 refusing to overwrite. Edit by hand or rename the file and re-run.`
5395
+ `yaw-mcp install: ${resolved.absolute} is not a JSON object -- refusing to overwrite. Edit by hand or rename the file and re-run.`
5181
5396
  );
5182
5397
  return { written: [], wouldWrite: [], messages, exitCode: 1 };
5183
5398
  }
@@ -5198,6 +5413,34 @@ ${USAGE}`);
5198
5413
  legacyEntriesPresent = LEGACY_ENTRY_NAMES.filter((n) => n in c);
5199
5414
  }
5200
5415
  }
5416
+ if (existingHasEntry) {
5417
+ let decision;
5418
+ if (opts.skip) decision = "skip";
5419
+ else if (opts.force || opts.dryRun) decision = "overwrite";
5420
+ else if (opts.promptAnswer) decision = opts.promptAnswer;
5421
+ else if (opts.io?.isTTY ?? (Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY))) {
5422
+ decision = await promptCollision(resolved.absolute, opts.io);
5423
+ } else {
5424
+ err(
5425
+ `yaw-mcp install: ${resolved.absolute} already has a "${ENTRY_NAME}" entry and stdin is not a TTY.
5426
+ Re-run with --force to overwrite, --skip to leave it, or --dry-run to preview.`
5427
+ );
5428
+ return { written: [], wouldWrite: [], messages, exitCode: 1 };
5429
+ }
5430
+ if (decision === "skip") {
5431
+ log2(
5432
+ opts.dryRun ? `Would leave existing "${ENTRY_NAME}" entry untouched (--skip). Nothing to do.` : `Existing "${ENTRY_NAME}" entry left untouched. Nothing to do.`
5433
+ );
5434
+ return { written: [], wouldWrite: [], messages, exitCode: 0 };
5435
+ }
5436
+ if (decision === "abort") {
5437
+ err("Aborted.");
5438
+ return { written: [], wouldWrite: [], messages, exitCode: 1 };
5439
+ }
5440
+ log2(
5441
+ opts.dryRun ? `Would overwrite existing "${ENTRY_NAME}" entry.` : `Overwriting existing "${ENTRY_NAME}" entry.`
5442
+ );
5443
+ }
5201
5444
  const oamProbeResult = await (opts.oamProbe ?? probeOam)();
5202
5445
  const resolveEntry = opts.resolveOamEntry ?? resolveStableNpmEntry;
5203
5446
  const oamBinPath = oamProbeResult.binPath;
@@ -5230,35 +5473,7 @@ ${USAGE}`);
5230
5473
  `Runtime: node (oam is installed but unusable: ${oamFailureLabel(oamProbeResult.failure)}${oamProbeResult.failureDetail ? ` -- ${oamProbeResult.failureDetail}` : ""}. Fix or reinstall oam and re-run install to host yaw-mcp on it.)`
5231
5474
  );
5232
5475
  } else if (!opts.suppressOamAbsentNote) {
5233
- log2(oamAbsentNote(os));
5234
- }
5235
- if (existingHasEntry) {
5236
- let decision;
5237
- if (opts.skip) decision = "skip";
5238
- else if (opts.force || opts.dryRun) decision = "overwrite";
5239
- else if (opts.promptAnswer) decision = opts.promptAnswer;
5240
- else if (opts.io?.isTTY ?? (Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY))) {
5241
- decision = await promptCollision(resolved.absolute, opts.io);
5242
- } else {
5243
- err(
5244
- `yaw-mcp install: ${resolved.absolute} already has a "${ENTRY_NAME}" entry and stdin is not a TTY.
5245
- Re-run with --force to overwrite, --skip to leave it, or --dry-run to preview.`
5246
- );
5247
- return { written: [], wouldWrite: [], messages, exitCode: 1 };
5248
- }
5249
- if (decision === "skip") {
5250
- log2(
5251
- opts.dryRun ? `Would leave existing "${ENTRY_NAME}" entry untouched (--skip). Nothing to do.` : `Existing "${ENTRY_NAME}" entry left untouched. Nothing to do.`
5252
- );
5253
- return { written: [], wouldWrite: [], messages, exitCode: 0 };
5254
- }
5255
- if (decision === "abort") {
5256
- err("Aborted.");
5257
- return { written: [], wouldWrite: [], messages, exitCode: 1 };
5258
- }
5259
- log2(
5260
- opts.dryRun ? `Would overwrite existing "${ENTRY_NAME}" entry.` : `Overwriting existing "${ENTRY_NAME}" entry.`
5261
- );
5476
+ log2(oamAbsentNote(os, opts.oamPublishesBinary));
5262
5477
  }
5263
5478
  const previousEntry = readEntryAt(existing, containerPath, ENTRY_NAME);
5264
5479
  const previousEnv = previousEntry?.env;
@@ -5274,7 +5489,7 @@ ${USAGE}`);
5274
5489
  const keyPath = blocked.path.join(".");
5275
5490
  if (!blocked.reparable) {
5276
5491
  err(
5277
- `yaw-mcp install: "${keyPath}" in ${resolved.absolute} is ${describeJsonShape(blocked.value)}, not a JSON object \u2014 refusing to overwrite. Make it an object (or remove the key) and re-run.`
5492
+ `yaw-mcp install: "${keyPath}" in ${resolved.absolute} is ${describeJsonShape(blocked.value)}, not a JSON object -- refusing to overwrite. Make it an object (or remove the key) and re-run.`
5278
5493
  );
5279
5494
  return { written: [], wouldWrite: [], messages, exitCode: 1 };
5280
5495
  }
@@ -5292,7 +5507,7 @@ ${USAGE}`);
5292
5507
  return { written: [], wouldWrite: [], messages, exitCode: 1 };
5293
5508
  }
5294
5509
  log2(
5295
- `Note: "${keyPath}" in ${resolved.absolute} is ${describeJsonShape(blocked.value)}, not an object \u2014 ${opts.dryRun ? "would replace" : "replaced"} it with an empty object so the "${ENTRY_NAME}" entry has somewhere to live.`
5510
+ `Note: "${keyPath}" in ${resolved.absolute} is ${describeJsonShape(blocked.value)}, not an object -- ${opts.dryRun ? "would replace" : "replaced"} it with an empty object so the "${ENTRY_NAME}" entry has somewhere to live.`
5296
5511
  );
5297
5512
  }
5298
5513
  try {
@@ -5326,7 +5541,7 @@ ${USAGE}`);
5326
5541
  }) : null;
5327
5542
  if (settingsPatch?.malformed) {
5328
5543
  err(
5329
- `yaw-mcp install: warning \u2014 could not patch ${settingsPatch.path} (${settingsPatch.malformedReason}); left unchanged. Add "${CLAUDE_CODE_ALLOW_PATTERN}" to permissions.allow by hand, or you may be re-prompted for each yaw-mcp tool call.`
5544
+ `yaw-mcp install: warning -- could not patch ${settingsPatch.path} (${settingsPatch.malformedReason}); left unchanged. Add "${CLAUDE_CODE_ALLOW_PATTERN}" to permissions.allow by hand, or you may be re-prompted for each yaw-mcp tool call.`
5330
5545
  );
5331
5546
  }
5332
5547
  if (opts.dryRun) {
@@ -5338,7 +5553,7 @@ ${clientJson}`);
5338
5553
  ${settingsPatch.nextJson}`);
5339
5554
  if (legacyEntry) {
5340
5555
  log2(
5341
- `Note: legacy "${legacyEntry}" entry at ${resolved.absolute} would remain \u2014 remove it to avoid running yaw-mcp twice.`
5556
+ `Note: legacy "${legacyEntry}" entry at ${resolved.absolute} would remain -- remove it to avoid running yaw-mcp twice.`
5342
5557
  );
5343
5558
  }
5344
5559
  const wouldWrite = [resolved.absolute];
@@ -5361,7 +5576,7 @@ ${settingsPatch.nextJson}`);
5361
5576
  written.push(settingsPatch.path);
5362
5577
  } catch (e) {
5363
5578
  err(
5364
- `yaw-mcp install: warning \u2014 failed to patch ${settingsPatch.path}: ${e.message}. You may be re-prompted for each yaw-mcp tool call; add "${CLAUDE_CODE_ALLOW_PATTERN}" to permissions.allow to silence.`
5579
+ `yaw-mcp install: warning -- failed to patch ${settingsPatch.path}: ${e.message}. You may be re-prompted for each yaw-mcp tool call; add "${CLAUDE_CODE_ALLOW_PATTERN}" to permissions.allow to silence.`
5365
5580
  );
5366
5581
  }
5367
5582
  }
@@ -5373,7 +5588,7 @@ ${settingsPatch.nextJson}`);
5373
5588
  }
5374
5589
  log2(
5375
5590
  target.clientId === "claude-code" && scope === "project" ? `
5376
- Done: ${target.label} is configured. Restart it in this project and approve the .mcp.json server when prompted \u2014 Claude Code keeps project-scope (.mcp.json) servers disabled until you approve them.` : `
5591
+ Done: ${target.label} is configured. Restart it in this project and approve the .mcp.json server when prompted -- Claude Code keeps project-scope (.mcp.json) servers disabled until you approve them.` : `
5377
5592
  Done: ${target.label} is configured. Restart it to pick up the new MCP server.`
5378
5593
  );
5379
5594
  return { written, wouldWrite: [], messages, exitCode: 0 };
@@ -5409,13 +5624,29 @@ async function prepareClaudeCodeSettingsPatch(opts) {
5409
5624
  const after = JSON.stringify(merged);
5410
5625
  if (before === after) return { path: path6, nextJson: "", changed: false };
5411
5626
  if (rawSettings !== null) {
5627
+ const blockedPermissions = findBlockedContainerSegment(existing, ["permissions"]);
5628
+ if (blockedPermissions) {
5629
+ return {
5630
+ path: path6,
5631
+ nextJson: "",
5632
+ changed: false,
5633
+ malformed: true,
5634
+ malformedReason: `"permissions" is ${describeJsonShape(blockedPermissions.value)}, not a JSON object`
5635
+ };
5636
+ }
5412
5637
  const nextAllow = merged.permissions.allow;
5413
5638
  try {
5414
5639
  const next = editJsoncEntry(rawSettings, ["permissions"], "allow", nextAllow);
5415
5640
  return { path: path6, nextJson: next.endsWith("\n") ? next : `${next}
5416
5641
  `, changed: true };
5417
5642
  } catch (e) {
5418
- return { path: path6, nextJson: "", changed: false, malformed: true, malformedReason: e.message };
5643
+ return {
5644
+ path: path6,
5645
+ nextJson: "",
5646
+ changed: false,
5647
+ malformed: true,
5648
+ malformedReason: `could not splice permissions.allow (${e.message})`
5649
+ };
5419
5650
  }
5420
5651
  }
5421
5652
  return { path: path6, nextJson: `${JSON.stringify(merged, null, 2)}
@@ -5523,6 +5754,9 @@ function mergeClientConfig(existing, containerPath, entry, entryName = ENTRY_NAM
5523
5754
  parent[leafKey] = container;
5524
5755
  return out;
5525
5756
  }
5757
+ function looksLikeFlag(value) {
5758
+ return value.startsWith("-");
5759
+ }
5526
5760
  function parseInstallArgs(argv) {
5527
5761
  if (argv.length === 0) return { ok: false, error: USAGE };
5528
5762
  const positional = [];
@@ -5551,13 +5785,13 @@ function parseInstallArgs(argv) {
5551
5785
  // positional and fail the argv check below with exit 2.
5552
5786
  case "--token": {
5553
5787
  const v = next();
5554
- if (!v || v.startsWith("--")) return { ok: false, error: "--token requires a value" };
5788
+ if (!v || looksLikeFlag(v)) return { ok: false, error: "--token requires a value" };
5555
5789
  opts.token = v;
5556
5790
  break;
5557
5791
  }
5558
5792
  case "--project-dir": {
5559
5793
  const v = next();
5560
- if (!v || v.startsWith("--")) return { ok: false, error: "--project-dir requires a value" };
5794
+ if (!v || looksLikeFlag(v)) return { ok: false, error: "--project-dir requires a value" };
5561
5795
  opts.projectDir = v;
5562
5796
  break;
5563
5797
  }
@@ -5592,7 +5826,7 @@ ${USAGE}` };
5592
5826
  if (opts.os && opts.os !== CURRENT_OS && !opts.dryRun && !opts.listOnly) {
5593
5827
  return {
5594
5828
  ok: false,
5595
- error: `yaw-mcp install: --os ${opts.os} does not match this machine (${CURRENT_OS}), and install can only resolve config paths for the machine it runs on \u2014 a cross-OS write would create a ${CURRENT_OS}-shaped junk tree. Add --dry-run to preview, or run install on the ${opts.os} machine itself.`
5829
+ error: `yaw-mcp install: --os ${opts.os} does not match this machine (${CURRENT_OS}), and install can only resolve config paths for the machine it runs on -- a cross-OS write would create a ${CURRENT_OS}-shaped junk tree. Add --dry-run to preview, or run install on the ${opts.os} machine itself.`
5596
5830
  };
5597
5831
  }
5598
5832
  if (opts.listOnly || opts.all) {
@@ -5608,6 +5842,13 @@ ${USAGE}`
5608
5842
  return {
5609
5843
  ok: false,
5610
5844
  error: `yaw-mcp install: --list never writes a file, so it cannot honor ${flag}. Drop ${flag}, or install the client you want.
5845
+ ${USAGE}`
5846
+ };
5847
+ }
5848
+ if (opts.listOnly && opts.scope) {
5849
+ return {
5850
+ ok: false,
5851
+ error: `yaw-mcp install: --list reports every scope, so it cannot honor --scope. Drop --scope, or install a client at that scope.
5611
5852
  ${USAGE}`
5612
5853
  };
5613
5854
  }
@@ -5642,7 +5883,7 @@ async function runInstallList(opts, log2, messages) {
5642
5883
  os,
5643
5884
  cwd,
5644
5885
  claudeConfigDir: opts.claudeConfigDir,
5645
- appData: opts.appData ?? (opts.home !== void 0 ? join11(opts.home, "AppData", "Roaming") : void 0)
5886
+ appData: resolveAppData(opts)
5646
5887
  });
5647
5888
  const rows = probes.map((p) => ({
5648
5889
  client: INSTALL_TARGETS.find((t) => t.clientId === p.clientId)?.label ?? p.clientId,
@@ -5676,12 +5917,15 @@ function statusFor(p) {
5676
5917
  if (p.unavailable) return "unavailable";
5677
5918
  if (p.malformed) return "malformed";
5678
5919
  if (p.hasMcpEntry) return "installed";
5920
+ if (p.hasLegacyEntry) return `legacy: ${p.legacyEntryName ?? "unknown"}`;
5679
5921
  if (p.exists) return "other-entries";
5680
5922
  return "not installed";
5681
5923
  }
5682
5924
  function displayPath(abs, home, os) {
5683
5925
  if (abs === "(n/a)") return abs;
5684
- if (home && abs.startsWith(home)) {
5926
+ const afterHome = abs.slice(home.length, home.length + 1);
5927
+ const endsAtBoundary = afterHome === "" || afterHome === "/" || afterHome === "\\" || /[\\/]$/.test(home);
5928
+ if (home && abs.startsWith(home) && endsAtBoundary) {
5685
5929
  const sep = os === "windows" ? "\\" : "/";
5686
5930
  const hostSep = process.platform === "win32" ? /[\\/]/g : /\//g;
5687
5931
  const tail = abs.slice(home.length).replace(/^[\\/]/, "").replace(hostSep, sep);
@@ -5701,16 +5945,16 @@ async function runInstallAll(opts, log2, err, messages) {
5701
5945
  for (const t of targets) {
5702
5946
  const userScope = t.scopes.find((s) => s.scope === "user");
5703
5947
  if (userScope) {
5704
- plans.push({ clientId: t.clientId, scope: "user" });
5948
+ plans.push({ clientId: t.clientId, scope: "user", usesProjectDir: userScope.requiresProjectDir });
5705
5949
  continue;
5706
5950
  }
5707
5951
  const firstNoProj = t.scopes.find((s) => !s.requiresProjectDir);
5708
5952
  if (firstNoProj) {
5709
- plans.push({ clientId: t.clientId, scope: firstNoProj.scope });
5953
+ plans.push({ clientId: t.clientId, scope: firstNoProj.scope, usesProjectDir: false });
5710
5954
  continue;
5711
5955
  }
5712
5956
  if (opts.projectDir) {
5713
- plans.push({ clientId: t.clientId, scope: t.scopes[0].scope });
5957
+ plans.push({ clientId: t.clientId, scope: t.scopes[0].scope, usesProjectDir: t.scopes[0].requiresProjectDir });
5714
5958
  continue;
5715
5959
  }
5716
5960
  skipped.push({
@@ -5718,7 +5962,7 @@ async function runInstallAll(opts, log2, err, messages) {
5718
5962
  reason: `requires --project-dir (scopes: ${t.scopes.map((s) => s.scope).join(", ")})`
5719
5963
  });
5720
5964
  }
5721
- log2(`Installing into ${plans.length} client${plans.length === 1 ? "" : "s"}\u2026`);
5965
+ log2(`Installing into ${plans.length} client${plans.length === 1 ? "" : "s"}...`);
5722
5966
  if (skipped.length > 0) {
5723
5967
  for (const s of skipped) log2(` skip ${s.clientId}: ${s.reason}`);
5724
5968
  }
@@ -5731,7 +5975,7 @@ async function runInstallAll(opts, log2, err, messages) {
5731
5975
  const realStderr = opts.io?.stderr ?? process.stderr;
5732
5976
  const isCollisionRefusal = (s) => s.includes(`already has a "${ENTRY_NAME}" entry and stdin is not a TTY`);
5733
5977
  for (const plan of plans) {
5734
- log2(`\u2500\u2500 ${plan.clientId} (${plan.scope}) \u2500\u2500`);
5978
+ log2(`-- ${plan.clientId} (${plan.scope}) --`);
5735
5979
  let sawCollision = false;
5736
5980
  const subStderr = new Writable({
5737
5981
  write(chunk, _enc, cb) {
@@ -5760,6 +6004,12 @@ async function runInstallAll(opts, log2, err, messages) {
5760
6004
  suppressOamAbsentNote: true,
5761
6005
  clientId: plan.clientId,
5762
6006
  scope: plan.scope,
6007
+ // Only the plans whose scope actually resolves a path from --project-dir
6008
+ // get it. runInstall refuses the flag for a scope that would drop it, so
6009
+ // passing the parent's copy to every client would fail each user-scope
6010
+ // one the moment --project-dir was passed to pull the project-only
6011
+ // client (vscode) into the run.
6012
+ projectDir: plan.usesProjectDir ? opts.projectDir : void 0,
5763
6013
  io: { ...baseIo, stderr: subStderr }
5764
6014
  });
5765
6015
  if (sawCollision) collisionClients.push(plan.clientId);
@@ -5771,7 +6021,9 @@ async function runInstallAll(opts, log2, err, messages) {
5771
6021
  log2("");
5772
6022
  }
5773
6023
  const runLeftAnEntry = aggregateWritten.length > 0 || aggregateWouldWrite.length > 0 || succeeded > 0;
5774
- if (runLeftAnEntry && oamIsAbsent(await (opts.oamProbe ?? probeOam)())) log2(oamAbsentNote(os));
6024
+ if (runLeftAnEntry && oamIsAbsent(await (opts.oamProbe ?? probeOam)())) {
6025
+ log2(oamAbsentNote(os, opts.oamPublishesBinary));
6026
+ }
5775
6027
  if (collisionClients.length > 0) {
5776
6028
  err(
5777
6029
  `yaw-mcp install --all: ${collisionClients.length} client${collisionClients.length === 1 ? "" : "s"} already have a "${ENTRY_NAME}" entry (${collisionClients.join(", ")}) and stdin is not a TTY.
@@ -5926,6 +6178,7 @@ ${TRY_CLEANUP_USAGE}` };
5926
6178
  opts.slug = positional[0];
5927
6179
  return { ok: true, options: opts };
5928
6180
  }
6181
+ var MAX_TTL_MS = 100 * 365 * 864e5;
5929
6182
  function parseDurationMs(s) {
5930
6183
  const m = /^(\d+)\s*([smhd])$/i.exec(s.trim());
5931
6184
  if (!m) return null;
@@ -5933,13 +6186,14 @@ function parseDurationMs(s) {
5933
6186
  if (!Number.isFinite(n) || n <= 0) return null;
5934
6187
  const unit = m[2].toLowerCase();
5935
6188
  const factor = unit === "s" ? 1e3 : unit === "m" ? 6e4 : unit === "h" ? 36e5 : 864e5;
5936
- return n * factor;
6189
+ const ms = n * factor;
6190
+ return ms > MAX_TTL_MS ? null : ms;
5937
6191
  }
5938
6192
  function trialsDir(home = homedir11()) {
5939
- return join12(home, CONFIG_DIRNAME, TRIALS_DIRNAME);
6193
+ return join11(home, CONFIG_DIRNAME, TRIALS_DIRNAME);
5940
6194
  }
5941
6195
  function trialMarkerPath(slug, home = homedir11()) {
5942
- return join12(trialsDir(home), `${slug}.json`);
6196
+ return join11(trialsDir(home), `${slug}.json`);
5943
6197
  }
5944
6198
  function rejectUntrustedMarker(marker) {
5945
6199
  if (!marker.entryName.startsWith(TRIAL_ENTRY_PREFIX)) {
@@ -5950,30 +6204,40 @@ function rejectUntrustedMarker(marker) {
5950
6204
  }
5951
6205
  return null;
5952
6206
  }
6207
+ function assertTrialMarkerShape(parsed) {
6208
+ const m = parsed;
6209
+ if (!m || typeof m !== "object" || typeof m.clientPath !== "string" || typeof m.entryName !== "string" || !Array.isArray(m.containerPath)) {
6210
+ throw new Error("marker is missing required fields");
6211
+ }
6212
+ }
5953
6213
  async function readTrialMarker(markerPath) {
5954
6214
  try {
5955
- const parsed = JSON.parse(await readFile10(markerPath, "utf8"));
5956
- if (!parsed || typeof parsed !== "object") return null;
5957
- if (typeof parsed.clientPath !== "string" || typeof parsed.entryName !== "string") return null;
5958
- if (!Array.isArray(parsed.containerPath)) return null;
5959
- return parsed;
6215
+ const raw = await readFile10(markerPath, "utf8");
6216
+ const parsed = JSON.parse(raw);
6217
+ assertTrialMarkerShape(parsed);
6218
+ return { marker: parsed, raw };
5960
6219
  } catch {
5961
6220
  return null;
5962
6221
  }
5963
6222
  }
5964
- async function peelTrialEntry(marker) {
6223
+ async function peelEntryFromConfig(clientPath, containerPath, entryName, dryRun = false) {
6224
+ if (!existsSync6(clientPath)) return "absent";
6225
+ const raw = await readFile10(clientPath, "utf8");
6226
+ if (raw.trim().length === 0) return "absent";
6227
+ const parsed = parseJsonc(raw);
6228
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return "not-object";
6229
+ const next = removeJsoncEntry(raw, containerPath, entryName);
6230
+ if (next === raw) return "absent";
6231
+ if (dryRun) return "removed";
6232
+ await atomicWriteFile(clientPath, next.endsWith("\n") ? next : `${next}
6233
+ `);
6234
+ return "removed";
6235
+ }
6236
+ async function peelTrialEntry(marker, dryRun = false) {
5965
6237
  if (rejectUntrustedMarker(marker) !== null) return "failed";
5966
- if (!existsSync6(marker.clientPath)) return "absent";
5967
6238
  try {
5968
- const raw = await readFile10(marker.clientPath, "utf8");
5969
- if (raw.trim().length === 0) return "absent";
5970
- const parsed = parseJsonc(raw);
5971
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return "failed";
5972
- const next = removeJsoncEntry(raw, marker.containerPath, marker.entryName);
5973
- if (next === raw) return "absent";
5974
- await atomicWriteFile(marker.clientPath, next.endsWith("\n") ? next : `${next}
5975
- `);
5976
- return "removed";
6239
+ const outcome = await peelEntryFromConfig(marker.clientPath, marker.containerPath, marker.entryName, dryRun);
6240
+ return outcome === "not-object" ? "failed" : outcome;
5977
6241
  } catch {
5978
6242
  return "failed";
5979
6243
  }
@@ -6038,6 +6302,7 @@ async function runTry(opts) {
6038
6302
  ttlMs = parsedTtl;
6039
6303
  }
6040
6304
  const claudeConfigDir = env.CLAUDE_CONFIG_DIR && env.CLAUDE_CONFIG_DIR.length > 0 ? env.CLAUDE_CONFIG_DIR : void 0;
6305
+ const appData = resolveAppDataDir({ home: opts.home, env });
6041
6306
  const fetchExplore = opts.fetchExplore ?? defaultFetchExplore;
6042
6307
  const catalogUrl = env.YAW_MCP_CATALOG_URL !== void 0 && env.YAW_MCP_CATALOG_URL.length > 0 ? env.YAW_MCP_CATALOG_URL : void 0;
6043
6308
  let server;
@@ -6052,7 +6317,7 @@ async function runTry(opts) {
6052
6317
  os,
6053
6318
  cwd,
6054
6319
  claudeConfigDir,
6055
- appData: opts.home !== void 0 ? join12(opts.home, "AppData", "Roaming") : void 0
6320
+ appData
6056
6321
  });
6057
6322
  const scope = clientId === "vscode" ? "project" : "user";
6058
6323
  const projectDir = scope === "project" ? resolve5(cwd) : void 0;
@@ -6063,9 +6328,7 @@ async function runTry(opts) {
6063
6328
  scope,
6064
6329
  os,
6065
6330
  home,
6066
- // Hermetic-home seam: keep the %APPDATA%-based claude-desktop path
6067
- // inside an overridden home (mirrors install-cmd / doctor).
6068
- appData: opts.home !== void 0 ? join12(opts.home, "AppData", "Roaming") : void 0,
6331
+ appData,
6069
6332
  projectDir,
6070
6333
  claudeConfigDir
6071
6334
  });
@@ -6073,8 +6336,8 @@ async function runTry(opts) {
6073
6336
  printErr(`yaw-mcp try: ${e.message}`);
6074
6337
  return { exitCode: 1, written: [] };
6075
6338
  }
6076
- const supplied = { ...env, ...opts.envOverrides ?? {} };
6077
- const missing = (server.requiredEnvVars ?? []).filter((k) => (supplied[k] ?? "").trim() === "");
6339
+ const lookup = (k) => opts.envOverrides?.[k] ?? env[k];
6340
+ const missing = (server.requiredEnvVars ?? []).filter((k) => (lookup(k) ?? "").trim() === "");
6078
6341
  if (missing.length > 0) {
6079
6342
  printErr(`yaw-mcp try: ${server.name} needs the following env var(s) before it can run:`);
6080
6343
  for (const k of missing) printErr(` - ${k}`);
@@ -6087,7 +6350,7 @@ async function runTry(opts) {
6087
6350
  }
6088
6351
  const trialEnv = {};
6089
6352
  for (const k of server.requiredEnvVars ?? []) {
6090
- const v = (supplied[k] ?? "").trim();
6353
+ const v = (lookup(k) ?? "").trim();
6091
6354
  if (v) trialEnv[k] = v;
6092
6355
  }
6093
6356
  for (const [k, v] of Object.entries(opts.envOverrides ?? {})) {
@@ -6097,7 +6360,7 @@ async function runTry(opts) {
6097
6360
  }
6098
6361
  const overrides = opts.envOverrides ?? {};
6099
6362
  const ambientOnlyRequired = (server.requiredEnvVars ?? []).filter(
6100
- (k) => (!overrides[k] || overrides[k] === "") && (supplied[k] ?? "").trim() !== ""
6363
+ (k) => !overrides[k] && (lookup(k) ?? "").trim() !== ""
6101
6364
  );
6102
6365
  const entry = buildLaunchEntry({
6103
6366
  os,
@@ -6168,7 +6431,8 @@ async function runTry(opts) {
6168
6431
  let clientJson = firstSplice.json;
6169
6432
  const markerJson = `${JSON.stringify(marker, null, 2)}
6170
6433
  `;
6171
- const previousMarker = await readTrialMarker(trialMarkerPath(slug, home));
6434
+ const previousRead = await readTrialMarker(trialMarkerPath(slug, home));
6435
+ const previousMarker = previousRead?.marker ?? null;
6172
6436
  const peelsPrevious = previousMarker !== null && (previousMarker.clientPath !== resolved.absolute || previousMarker.entryName !== entryName);
6173
6437
  const previousRefusal = previousMarker === null ? null : rejectUntrustedMarker(previousMarker);
6174
6438
  if (opts.dryRun) {
@@ -6179,18 +6443,19 @@ async function runTry(opts) {
6179
6443
  print(` expires: ${new Date(expiresAt).toISOString()}`);
6180
6444
  print(` marker: ${trialMarkerPath(slug, home)}`);
6181
6445
  if (previousMarker && peelsPrevious) {
6182
- if (previousRefusal === null) {
6446
+ if (previousRefusal !== null) {
6183
6447
  print(
6184
- ` would remove: the previous ${slug} trial (${previousMarker.entryName}) from ${previousMarker.clientPath}`
6448
+ ` would NOT remove: the previous ${slug} marker ${previousRefusal} -- remove that entry from ${previousMarker.clientPath} by hand`
6185
6449
  );
6186
- } else {
6450
+ } else if (await peelTrialEntry(previousMarker, true) === "removed") {
6187
6451
  print(
6188
- ` would NOT remove: the previous ${slug} marker ${previousRefusal} -- remove that entry from ${previousMarker.clientPath} by hand`
6452
+ ` would remove: the previous ${slug} trial (${previousMarker.entryName}) from ${previousMarker.clientPath}`
6189
6453
  );
6190
6454
  }
6191
6455
  }
6192
6456
  return { exitCode: 0, written: [], marker };
6193
6457
  }
6458
+ let previousPeelFailedWhileTrusted = false;
6194
6459
  if (previousMarker && peelsPrevious) {
6195
6460
  const outcome = await peelTrialEntry(previousMarker);
6196
6461
  if (outcome === "removed") {
@@ -6203,6 +6468,7 @@ async function runTry(opts) {
6203
6468
  clientJson = respliced.json;
6204
6469
  }
6205
6470
  } else if (outcome === "failed") {
6471
+ previousPeelFailedWhileTrusted = previousRefusal === null;
6206
6472
  printErr(
6207
6473
  `yaw-mcp try: warning -- couldn't remove the previous ${slug} trial (${previousMarker.entryName}) from ${previousMarker.clientPath}. Remove that entry by hand; the marker below no longer points at it.`
6208
6474
  );
@@ -6210,7 +6476,7 @@ async function runTry(opts) {
6210
6476
  }
6211
6477
  const written = [];
6212
6478
  try {
6213
- await mkdir4(trialsDir(home), { recursive: true });
6479
+ await mkdir3(trialsDir(home), { recursive: true });
6214
6480
  await atomicWriteFile(trialMarkerPath(slug, home), markerJson);
6215
6481
  written.push(trialMarkerPath(slug, home));
6216
6482
  } catch (e) {
@@ -6218,7 +6484,7 @@ async function runTry(opts) {
6218
6484
  return { exitCode: 1, written: [] };
6219
6485
  }
6220
6486
  const entryHasSecrets = entry.env !== void 0 && Object.keys(entry.env).length > 0;
6221
- const tightenPerms = entryHasSecrets && process.platform !== "win32";
6487
+ const tightenPerms = entryHasSecrets && (opts.platform ?? process.platform) !== "win32";
6222
6488
  try {
6223
6489
  await atomicWriteFile(resolved.absolute, clientJson, "utf8", tightenPerms ? 384 : void 0);
6224
6490
  written.push(resolved.absolute);
@@ -6230,11 +6496,15 @@ async function runTry(opts) {
6230
6496
  }
6231
6497
  } catch (e) {
6232
6498
  printErr(`yaw-mcp try: failed to write ${resolved.absolute}: ${e.message}`);
6233
- await unlink2(trialMarkerPath(slug, home)).catch(() => void 0);
6499
+ if (previousRead !== null && (!peelsPrevious || previousPeelFailedWhileTrusted)) {
6500
+ await atomicWriteFile(trialMarkerPath(slug, home), previousRead.raw).catch(() => void 0);
6501
+ } else {
6502
+ await unlink2(trialMarkerPath(slug, home)).catch(() => void 0);
6503
+ }
6234
6504
  return { exitCode: 1, written: [] };
6235
6505
  }
6236
6506
  const ttlPretty = formatTtl(ttlMs);
6237
- print(`Trial wired: ${server.name} via yaw-mcp-try-${slug} -> ${resolved.absolute}`);
6507
+ print(`Trial wired: ${server.name} via ${entryName} -> ${resolved.absolute}`);
6238
6508
  print(
6239
6509
  `Expires in ${ttlPretty}, then swept by the next \`yaw-mcp doctor\` run; remove it now with: yaw-mcp try-cleanup ${slug}`
6240
6510
  );
@@ -6270,11 +6540,8 @@ async function runTryCleanup(opts) {
6270
6540
  }
6271
6541
  let marker;
6272
6542
  try {
6273
- const raw = await readFile10(markerPath, "utf8");
6274
- const parsed = JSON.parse(raw);
6275
- if (!parsed || typeof parsed !== "object" || typeof parsed.entryName !== "string" || typeof parsed.clientPath !== "string" || !Array.isArray(parsed.containerPath)) {
6276
- throw new Error("marker is missing required fields");
6277
- }
6543
+ const parsed = JSON.parse(await readFile10(markerPath, "utf8"));
6544
+ assertTrialMarkerShape(parsed);
6278
6545
  marker = parsed;
6279
6546
  } catch (e) {
6280
6547
  printErr(`yaw-mcp try-cleanup: marker at ${markerPath} is unreadable (${e.message}).`);
@@ -6287,27 +6554,20 @@ async function runTryCleanup(opts) {
6287
6554
  return { exitCode: 1, written: [] };
6288
6555
  }
6289
6556
  const written = [];
6290
- if (existsSync6(marker.clientPath)) {
6291
- try {
6292
- const raw = await readFile10(marker.clientPath, "utf8");
6293
- if (raw.trim().length > 0) {
6294
- const parsed = parseJsonc(raw);
6295
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
6296
- const next = removeJsoncEntry(raw, marker.containerPath, marker.entryName);
6297
- if (next !== raw) {
6298
- const out2 = next.endsWith("\n") ? next : `${next}
6299
- `;
6300
- await atomicWriteFile(marker.clientPath, out2);
6301
- written.push(marker.clientPath);
6302
- print(`Removed ${marker.entryName} from ${marker.clientPath}`);
6303
- }
6304
- }
6305
- }
6306
- } catch (e) {
6557
+ try {
6558
+ const outcome = await peelEntryFromConfig(marker.clientPath, marker.containerPath, marker.entryName);
6559
+ if (outcome === "removed") {
6560
+ written.push(marker.clientPath);
6561
+ print(`Removed ${marker.entryName} from ${marker.clientPath}`);
6562
+ } else if (outcome === "not-object") {
6307
6563
  printErr(
6308
- `yaw-mcp try-cleanup: warning -- couldn't strip ${marker.entryName} from ${marker.clientPath} (${e.message}).`
6564
+ `yaw-mcp try-cleanup: warning -- couldn't strip ${marker.entryName} from ${marker.clientPath} (${marker.clientPath} is not a JSON object).`
6309
6565
  );
6310
6566
  }
6567
+ } catch (e) {
6568
+ printErr(
6569
+ `yaw-mcp try-cleanup: warning -- couldn't strip ${marker.entryName} from ${marker.clientPath} (${e.message}).`
6570
+ );
6311
6571
  }
6312
6572
  try {
6313
6573
  await unlink2(markerPath);
@@ -6339,11 +6599,15 @@ async function scanTrials(opts = {}) {
6339
6599
  }
6340
6600
  for (const filename of entries) {
6341
6601
  if (!filename.endsWith(".json")) continue;
6342
- const path6 = join12(dir, filename);
6602
+ const path6 = join11(dir, filename);
6343
6603
  try {
6344
6604
  const raw = await readFile10(path6, "utf8");
6345
6605
  const parsed = JSON.parse(raw);
6346
- if (!parsed || typeof parsed !== "object" || typeof parsed.slug !== "string" || typeof parsed.expiresAt !== "number" || typeof parsed.clientPath !== "string" || !Array.isArray(parsed.containerPath) || typeof parsed.entryName !== "string" || // Same trust check runTryCleanup applies: the GC deletes these three
6606
+ if (!parsed || typeof parsed !== "object" || typeof parsed.slug !== "string" || typeof parsed.expiresAt !== "number" || typeof parsed.clientPath !== "string" || // Not consumed by the peel, but doctor PRINTS it verbatim ("demo ->
6607
+ // claude-code (expires in 42m)"), so a hand-rolled marker without it
6608
+ // renders as "demo -> undefined". Malformed is the honest reading of a
6609
+ // marker missing a field every writer of ours fills in.
6610
+ typeof parsed.clientName !== "string" || !Array.isArray(parsed.containerPath) || typeof parsed.entryName !== "string" || // Same trust check runTryCleanup applies: the GC deletes these three
6347
6611
  // fields' worth of state from a file named by the marker itself, so a
6348
6612
  // marker naming a non-trial entry -- or written by a schema we don't
6349
6613
  // understand -- is surfaced as malformed for the user rather than
@@ -6372,21 +6636,9 @@ async function gcExpiredTrials(opts) {
6372
6636
  for (const { marker, path: path6 } of scan.expired) {
6373
6637
  let stage = "peel";
6374
6638
  try {
6375
- if (existsSync6(marker.clientPath)) {
6376
- const raw = await readFile10(marker.clientPath, "utf8");
6377
- if (raw.trim().length > 0) {
6378
- const parsed = parseJsonc(raw);
6379
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
6380
- const next = removeJsoncEntry(raw, marker.containerPath, marker.entryName);
6381
- if (next !== raw) {
6382
- const out = next.endsWith("\n") ? next : `${next}
6383
- `;
6384
- await atomicWriteFile(marker.clientPath, out);
6385
- }
6386
- } else {
6387
- throw new Error(`${marker.clientPath} is not a JSON object`);
6388
- }
6389
- }
6639
+ const outcome = await peelEntryFromConfig(marker.clientPath, marker.containerPath, marker.entryName);
6640
+ if (outcome === "not-object") {
6641
+ throw new Error(`${marker.clientPath} is not a JSON object`);
6390
6642
  }
6391
6643
  stage = "unlink";
6392
6644
  await unlink2(path6);
@@ -6419,9 +6671,10 @@ var LearningStore = class {
6419
6671
  /**
6420
6672
  * @deprecated Test-only. The binary recordDispatch + recordSuccess pair was
6421
6673
  * replaced on the proxy path by the graded recordOutcome; no production
6422
- * caller remains (grep src/ outside tests). Kept because existing tests in
6423
- * persistence.test.ts and server.test.ts still seed stores through it --
6424
- * delete both methods together with those call sites, not before. Do NOT
6674
+ * caller remains (grep src/ outside tests). Kept because existing tests still
6675
+ * seed stores through it: learning.test.ts is by far the heaviest user, with
6676
+ * persistence.test.ts and server.test.ts behind it -- delete both methods
6677
+ * together with all three sets of call sites, not before. Do NOT
6425
6678
  * reach for it in new code: it records a denominator with no numerator,
6426
6679
  * which recordMiss already expresses with an accurate name.
6427
6680
  */
@@ -6568,15 +6821,17 @@ var LearningStore = class {
6568
6821
  // src/usage-hints.ts
6569
6822
  var MAX_PEERS = 3;
6570
6823
  var MIN_SUCCESS_TO_SHOW = 1;
6571
- function buildCoUsageMap(packs) {
6824
+ function buildCoUsageMap(packs, installed) {
6572
6825
  const result = /* @__PURE__ */ new Map();
6826
+ const isInstalled = (ns) => installed === void 0 || installed.has(ns);
6573
6827
  for (const pack of packs) {
6574
- for (const ns of pack.namespaces) {
6828
+ const namespaces = pack.namespaces.filter(isInstalled);
6829
+ for (const ns of namespaces) {
6575
6830
  const bucket = result.get(ns) ?? /* @__PURE__ */ new Set();
6576
- for (const peer of pack.namespaces) {
6831
+ for (const peer of namespaces) {
6577
6832
  if (peer !== ns) bucket.add(peer);
6578
6833
  }
6579
- result.set(ns, bucket);
6834
+ if (bucket.size > 0) result.set(ns, bucket);
6580
6835
  }
6581
6836
  }
6582
6837
  const sorted = /* @__PURE__ */ new Map();
@@ -6642,7 +6897,7 @@ function foldBundleWarnings(warnings, probe) {
6642
6897
  const prefix = `${probe.path}:`;
6643
6898
  return warnings.filter((w) => !w.startsWith(prefix));
6644
6899
  }
6645
- var VERSION = true ? "0.79.0" : "dev";
6900
+ var VERSION = true ? "0.79.2" : "dev";
6646
6901
  var DOCTOR_USAGE = `Usage: yaw-mcp doctor [--json]
6647
6902
 
6648
6903
  Print a diagnostic of your yaw-mcp setup.
@@ -6663,6 +6918,20 @@ function parseDoctorArgs(argv) {
6663
6918
  }
6664
6919
  return { ok: true, options: { json: argv.includes("--json") } };
6665
6920
  }
6921
+ async function collectDoctorBase(opts) {
6922
+ const cwd = opts.cwd ?? process.cwd();
6923
+ const home = opts.home ?? homedir12();
6924
+ const appData = resolveAppDataDir({ home: opts.home, env: opts.env });
6925
+ const os = opts.os ?? CURRENT_OS;
6926
+ const env = opts.env ?? process.env;
6927
+ const timestamp = (/* @__PURE__ */ new Date()).toISOString();
6928
+ const config = await loadYawMcpConfig({ cwd, home, env });
6929
+ const trustProbe = await probeProjectTrust({ cwd, home, env }).catch(() => null);
6930
+ const trustWarning = projectTrustWarning(trustProbe);
6931
+ if (trustWarning) config.warnings = [...config.warnings, trustWarning];
6932
+ const claudeConfigDir = env.CLAUDE_CONFIG_DIR && env.CLAUDE_CONFIG_DIR.length > 0 ? env.CLAUDE_CONFIG_DIR : void 0;
6933
+ return { cwd, home, appData, os, env, timestamp, config, trustProbe, claudeConfigDir };
6934
+ }
6666
6935
  async function runDoctor(opts = {}) {
6667
6936
  if (opts.json) return runDoctorJson(opts);
6668
6937
  const lines = [];
@@ -6672,19 +6941,11 @@ async function runDoctor(opts = {}) {
6672
6941
  write(`${s}
6673
6942
  `);
6674
6943
  };
6675
- const cwd = opts.cwd ?? process.cwd();
6676
- const home = opts.home ?? homedir12();
6677
- const appData = opts.home !== void 0 ? join13(opts.home, "AppData", "Roaming") : void 0;
6678
- const os = opts.os ?? CURRENT_OS;
6679
- const env = opts.env ?? process.env;
6680
- print(`yaw-mcp doctor -- ${(/* @__PURE__ */ new Date()).toISOString()}`);
6944
+ const { cwd, home, appData, os, env, timestamp, config, trustProbe, claudeConfigDir } = await collectDoctorBase(opts);
6945
+ print(`yaw-mcp doctor -- ${timestamp}`);
6681
6946
  print(`yaw-mcp version: ${VERSION}`);
6682
6947
  print(`platform: ${os}`);
6683
6948
  print("");
6684
- const config = await loadYawMcpConfig({ cwd, home, env });
6685
- const trustProbe = await probeProjectTrust({ cwd, home, env }).catch(() => null);
6686
- const trustWarning = projectTrustWarning(trustProbe);
6687
- if (trustWarning) config.warnings = [...config.warnings, trustWarning];
6688
6949
  print("CONFIG FILES");
6689
6950
  if (config.loadedFiles.length === 0) {
6690
6951
  print(" (none -- using defaults + env)");
@@ -6708,7 +6969,7 @@ async function runDoctor(opts = {}) {
6708
6969
  renderOamRuntimeSection({ status: oamStatus, print, os });
6709
6970
  renderVaultSection({ status: await collectVaultStatus({ home, env, servers: oamStatus.servers }), print });
6710
6971
  const persistenceDisabled = isPersistenceDisabled(env);
6711
- const stateFilePath = join13(userConfigDir(home), STATE_FILENAME);
6972
+ const stateFilePath = join12(userConfigDir(home), STATE_FILENAME);
6712
6973
  const statePeek = persistenceDisabled ? null : await peekStateFile(stateFilePath);
6713
6974
  const persistedState = statePeek?.kind === "ok" ? await loadState(stateFilePath) : null;
6714
6975
  renderStateSection({
@@ -6721,7 +6982,6 @@ async function runDoctor(opts = {}) {
6721
6982
  renderReliabilitySection({ disabled: persistenceDisabled, persisted: persistedState, print });
6722
6983
  const trialWarnings = await renderTrialsSection({ home, print, now: opts.now });
6723
6984
  if (trialWarnings.length > 0) config.warnings = [...config.warnings, ...trialWarnings];
6724
- const claudeConfigDir = env.CLAUDE_CONFIG_DIR && env.CLAUDE_CONFIG_DIR.length > 0 ? env.CLAUDE_CONFIG_DIR : void 0;
6725
6985
  const clients = probeClients({ home, os, cwd, claudeConfigDir, appData });
6726
6986
  print("INSTALLED CLIENTS (probed config files)");
6727
6987
  for (const c of clients) {
@@ -6798,17 +7058,7 @@ async function runDoctor(opts = {}) {
6798
7058
  async function runDoctorJson(opts) {
6799
7059
  const lines = [];
6800
7060
  const write = opts.out ?? ((s) => process.stdout.write(s));
6801
- const cwd = opts.cwd ?? process.cwd();
6802
- const home = opts.home ?? homedir12();
6803
- const appData = opts.home !== void 0 ? join13(opts.home, "AppData", "Roaming") : void 0;
6804
- const os = opts.os ?? CURRENT_OS;
6805
- const env = opts.env ?? process.env;
6806
- const timestamp = (/* @__PURE__ */ new Date()).toISOString();
6807
- const config = await loadYawMcpConfig({ cwd, home, env });
6808
- const trustProbe = await probeProjectTrust({ cwd, home, env }).catch(() => null);
6809
- const trustWarning = projectTrustWarning(trustProbe);
6810
- if (trustWarning) config.warnings = [...config.warnings, trustWarning];
6811
- const claudeConfigDir = env.CLAUDE_CONFIG_DIR && env.CLAUDE_CONFIG_DIR.length > 0 ? env.CLAUDE_CONFIG_DIR : void 0;
7061
+ const { cwd, home, appData, os, env, timestamp, config, trustProbe, claudeConfigDir } = await collectDoctorBase(opts);
6812
7062
  const trialScan = await scanTrials({ home, now: opts.now });
6813
7063
  const trialGc = await gcExpiredTrials({
6814
7064
  home,
@@ -6825,7 +7075,7 @@ async function runDoctorJson(opts) {
6825
7075
  envOverrides[name] = raw === void 0 || raw === "" ? null : raw;
6826
7076
  }
6827
7077
  const persistDisabled = isPersistenceDisabled(env);
6828
- const stateFilePath = join13(userConfigDir(home), STATE_FILENAME);
7078
+ const stateFilePath = join12(userConfigDir(home), STATE_FILENAME);
6829
7079
  const statePeek = persistDisabled ? null : await peekStateFile(stateFilePath);
6830
7080
  const stateUsable = statePeek !== null && (statePeek.kind === "ok" || statePeek.kind === "missing");
6831
7081
  const persisted = stateUsable ? await loadState(stateFilePath) : null;
@@ -7010,10 +7260,10 @@ function renderEnvSection(opts) {
7010
7260
  }
7011
7261
  async function collectVaultStatus(opts) {
7012
7262
  const path6 = vaultPath(opts.home);
7013
- const exists3 = existsSync7(path6);
7014
- let entries = exists3 ? null : [];
7263
+ const exists2 = existsSync7(path6);
7264
+ let entries = exists2 ? null : [];
7015
7265
  let unreadable = null;
7016
- if (exists3) {
7266
+ if (exists2) {
7017
7267
  try {
7018
7268
  const vault = await loadVault(path6);
7019
7269
  entries = vault ? listKeys(vault) : [];
@@ -7024,12 +7274,7 @@ async function collectVaultStatus(opts) {
7024
7274
  const refs = [];
7025
7275
  for (const s of opts.servers) {
7026
7276
  if (s.type === "remote") continue;
7027
- const names = /* @__PURE__ */ new Set();
7028
- for (const value of Object.values(s.env ?? {})) {
7029
- if (typeof value !== "string") continue;
7030
- const re = new RegExp(SECRET_REF_RE.source, SECRET_REF_RE.flags);
7031
- for (const m of value.matchAll(re)) if (m[1]) names.add(m[1]);
7032
- }
7277
+ const names = collectSecretRefNames(s.env);
7033
7278
  if (names.size > 0) refs.push({ namespace: s.namespace, secretNames: [...names].sort() });
7034
7279
  }
7035
7280
  const known = entries;
@@ -7037,7 +7282,7 @@ async function collectVaultStatus(opts) {
7037
7282
  const missing = known === null ? [] : [...referenced].filter((n) => !known.includes(n)).sort();
7038
7283
  return {
7039
7284
  path: path6,
7040
- exists: exists3,
7285
+ exists: exists2,
7041
7286
  entries,
7042
7287
  unreadable,
7043
7288
  passphraseSet: (opts.env.YAW_MCP_VAULT_PASSPHRASE ?? "") !== "",
@@ -7139,8 +7384,7 @@ async function collectOamRuntimeStatus(opts) {
7139
7384
  for (const skip of plan.skipped) refreshSkips.set(skip.pkg, skip.reason);
7140
7385
  } catch {
7141
7386
  }
7142
- const refreshOptOut = opts.env.YAW_MCP_SIDECAR_REFRESH;
7143
- const refreshDisabled = refreshOptOut === "0" || refreshOptOut?.toLowerCase() === "false";
7387
+ const refreshDisabled = isSidecarRefreshDisabled(opts.env);
7144
7388
  const installedFor = anyManaged ? installedPlatform(opts.home) : null;
7145
7389
  const managed = {
7146
7390
  root: sidecarsRoot(opts.home),
@@ -7415,13 +7659,13 @@ function* enumerateProbeSlots(opts) {
7415
7659
  } catch {
7416
7660
  continue;
7417
7661
  }
7418
- const exists3 = existsSync7(resolved.absolute);
7662
+ const exists2 = existsSync7(resolved.absolute);
7419
7663
  yield {
7420
7664
  result: {
7421
7665
  clientId: target.clientId,
7422
7666
  scope: scope.scope,
7423
7667
  path: resolved.absolute,
7424
- exists: exists3,
7668
+ exists: exists2,
7425
7669
  hasMcpEntry: false,
7426
7670
  launchCommandMissing: null,
7427
7671
  launchRuntime: null,
@@ -7432,7 +7676,7 @@ function* enumerateProbeSlots(opts) {
7432
7676
  malformed: false,
7433
7677
  unavailable: false
7434
7678
  },
7435
- read: exists3 ? { path: resolved.absolute, containerPath: resolved.containerPath } : null
7679
+ read: exists2 ? { path: resolved.absolute, containerPath: resolved.containerPath } : null
7436
7680
  };
7437
7681
  }
7438
7682
  }
@@ -7486,7 +7730,7 @@ function oamRunEntryPath(command, args) {
7486
7730
  if (sub < 0 || tokens[sub] !== "run") return null;
7487
7731
  return tokens.slice(sub + 1).find((t) => !t.startsWith("-")) ?? null;
7488
7732
  }
7489
- function classifyProbeContent(raw, containerPath, exists3 = existsSync7) {
7733
+ function classifyProbeContent(raw, containerPath, exists2 = existsSync7) {
7490
7734
  if (raw.trim().length === 0) {
7491
7735
  return { ...EMPTY_PROBE };
7492
7736
  }
@@ -7508,14 +7752,14 @@ function classifyProbeContent(raw, containerPath, exists3 = existsSync7) {
7508
7752
  if (typeof entry === "object" && entry !== null && !Array.isArray(entry)) {
7509
7753
  const command = entry.command;
7510
7754
  if (typeof command === "string") {
7511
- if (isAbsolute(command) && !exists3(command)) launchCommandMissing = command;
7755
+ if (isAbsolute(command) && !exists2(command)) launchCommandMissing = command;
7512
7756
  const entryArgs = entry.args;
7513
- const args = Array.isArray(entryArgs) ? entryArgs : [];
7757
+ const args = Array.isArray(entryArgs) ? entryArgs.filter((a) => typeof a === "string") : [];
7514
7758
  launchRuntime = isOamLaunch(command, args) ? "oam" : "node";
7515
7759
  if (isOamCommand(command) && !isAbsolute(command)) launchOamNotAbsolute = command;
7516
7760
  if (launchRuntime === "oam") {
7517
7761
  const entryPath = oamRunEntryPath(command, args);
7518
- if (entryPath !== null && isAbsolute(entryPath) && !exists3(entryPath)) {
7762
+ if (entryPath !== null && isAbsolute(entryPath) && !exists2(entryPath)) {
7519
7763
  launchOamEntryMissing = entryPath;
7520
7764
  }
7521
7765
  }
@@ -7577,9 +7821,9 @@ function scanShellHistoryForShadows(opts) {
7577
7821
  function shellHistorySources(opts) {
7578
7822
  const sources = [];
7579
7823
  const plain = (l) => l.trim() || null;
7580
- sources.push({ path: opts.env.HISTFILE || join13(opts.home, ".bash_history"), extractCommand: plain });
7824
+ sources.push({ path: opts.env.HISTFILE || join12(opts.home, ".bash_history"), extractCommand: plain });
7581
7825
  sources.push({
7582
- path: join13(opts.home, ".zsh_history"),
7826
+ path: join12(opts.home, ".zsh_history"),
7583
7827
  // Zsh extended-history lines look like `: 1700000000:0;npm audit`.
7584
7828
  // Strip the metadata prefix so we get just the command.
7585
7829
  extractCommand: (l) => {
@@ -7595,17 +7839,17 @@ function shellHistorySources(opts) {
7595
7839
  const appData = opts.env.APPDATA;
7596
7840
  if (appData) {
7597
7841
  sources.push({
7598
- path: join13(appData, "Microsoft", "Windows", "PowerShell", "PSReadLine", "ConsoleHost_history.txt"),
7842
+ path: join12(appData, "Microsoft", "Windows", "PowerShell", "PSReadLine", "ConsoleHost_history.txt"),
7599
7843
  extractCommand: plain
7600
7844
  });
7601
7845
  }
7602
- const xdgData = opts.env.XDG_DATA_HOME || join13(opts.home, ".local", "share");
7846
+ const xdgData = opts.env.XDG_DATA_HOME || join12(opts.home, ".local", "share");
7603
7847
  sources.push({
7604
- path: join13(xdgData, "powershell", "PSReadLine", "ConsoleHost_history.txt"),
7848
+ path: join12(xdgData, "powershell", "PSReadLine", "ConsoleHost_history.txt"),
7605
7849
  extractCommand: plain
7606
7850
  });
7607
7851
  sources.push({
7608
- path: join13(xdgData, "fish", "fish_history"),
7852
+ path: join12(xdgData, "fish", "fish_history"),
7609
7853
  extractCommand: (l) => {
7610
7854
  const trimmed = l.trim();
7611
7855
  if (!trimmed.startsWith("- cmd:")) return null;
@@ -7666,7 +7910,7 @@ function extractLeadingBinary(command) {
7666
7910
  if (/[|&;<>()`$]/.test(first)) return null;
7667
7911
  const slash = Math.max(first.lastIndexOf("/"), first.lastIndexOf("\\"));
7668
7912
  const name = slash === -1 ? first : first.slice(slash + 1);
7669
- return name.replace(/\.(exe|cmd|bat)$/i, "");
7913
+ return name.replace(/\.(exe|cmd|bat)$/i, "").toLowerCase();
7670
7914
  }
7671
7915
  function compareSemver(a, b) {
7672
7916
  const strip = (s) => s.startsWith("v") ? s.slice(1) : s;
@@ -7679,7 +7923,7 @@ import { homedir as homedir14 } from "os";
7679
7923
  import path5 from "path";
7680
7924
 
7681
7925
  // src/foundry.ts
7682
- import { appendFile as appendFile2, mkdir as mkdir5, stat as stat4 } from "fs/promises";
7926
+ import { appendFile as appendFile2, mkdir as mkdir4, stat as stat4 } from "fs/promises";
7683
7927
  import { homedir as homedir13 } from "os";
7684
7928
  import path4 from "path";
7685
7929
 
@@ -7816,8 +8060,9 @@ function touch(cache, key, value) {
7816
8060
  cache.set(key, value);
7817
8061
  }
7818
8062
  var SEP = "\0";
8063
+ var ESC = String.fromCharCode(1);
7819
8064
  function esc(text) {
7820
- return text.includes(SEP) ? text.replaceAll(SEP, SEP + SEP) : text;
8065
+ return text.includes(ESC) || text.includes(SEP) ? text.replaceAll(ESC, ESC + ESC).replaceAll(SEP, ESC + SEP) : text;
7821
8066
  }
7822
8067
  function serverSignature(server) {
7823
8068
  let sig = `${esc(server.namespace)}${SEP}${esc(server.name)}${SEP}${esc(server.description ?? "")}`;
@@ -7926,7 +8171,8 @@ var DOTTED_NUMERIC_RE = /^\d+(?:\.\d+){3,}$/;
7926
8171
  function isPhoneShape(match) {
7927
8172
  const digits = match.replace(/[^0-9]/g, "");
7928
8173
  if (digits.length < 9) return false;
7929
- return !DOTTED_NUMERIC_RE.test(match.trim());
8174
+ const groups = match.trim().split(/\s+/);
8175
+ return !groups.every((g) => DOTTED_NUMERIC_RE.test(g));
7930
8176
  }
7931
8177
  var TECH_REF_PREFIXES = /* @__PURE__ */ new Set([
7932
8178
  "aes",
@@ -7957,7 +8203,7 @@ function isTicketRef(match) {
7957
8203
  var RAW_PII_RULES = [
7958
8204
  { re: /(?<![A-Za-z0-9])[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}(?![A-Za-z0-9])/g },
7959
8205
  { re: /(?<![A-Za-z0-9])\+?[0-9][0-9\s().-]{8,}(?![A-Za-z0-9])/g, applies: isPhoneShape },
7960
- { re: /(?<![A-Za-z0-9])#\d+(?![A-Za-z0-9])/g },
8206
+ { re: /(?<![A-Za-z0-9])#\d{2,}(?![A-Za-z0-9])/g },
7961
8207
  { re: /(?<![A-Za-z0-9])[A-Z]+-\d+(?![A-Za-z0-9])/g, applies: isTicketRef }
7962
8208
  ];
7963
8209
  var RAW_SECRET_PREFIX_PATTERN = RAW_SECRET_PREFIXES.length > 0 ? new RegExp(
@@ -8008,15 +8254,13 @@ async function appendFoundryTrace(trace, home = homedir13()) {
8008
8254
  if (info.size >= MAX_FOUNDRY_BYTES) return;
8009
8255
  } catch {
8010
8256
  }
8011
- const candidatesNoScores = trace.candidates.map((c) => ({ ns: c.ns }));
8012
8257
  const line = `${JSON.stringify({
8013
8258
  tokens: trace.tokens,
8014
- candidates: candidatesNoScores,
8015
8259
  chosen: trace.chosen,
8016
8260
  redactedCount: trace.redactedCount
8017
8261
  })}
8018
8262
  `;
8019
- await mkdir5(dir, { recursive: true });
8263
+ await mkdir4(dir, { recursive: true });
8020
8264
  await appendFile2(file, line, "utf8");
8021
8265
  } catch {
8022
8266
  }
@@ -8123,7 +8367,7 @@ function parseFoundryArgs(argv) {
8123
8367
  let json = false;
8124
8368
  for (let i = 0; i < argv.length; i++) {
8125
8369
  const a = argv[i];
8126
- if (a === "--help" || a === "-h") return { ok: false, error: FOUNDRY_USAGE };
8370
+ if (a === "--help" || a === "-h") return { ok: false, error: FOUNDRY_USAGE, help: true };
8127
8371
  if (a === "--json") {
8128
8372
  json = true;
8129
8373
  } else if (a === "--out") {
@@ -8162,11 +8406,12 @@ ${FOUNDRY_USAGE}` };
8162
8406
  }
8163
8407
  async function defaultLoadServers(cwd, home) {
8164
8408
  const { config } = await loadLocalBundles({ cwd, home });
8409
+ const state = await loadState(statePath(userConfigDir(home)));
8165
8410
  return (config?.servers ?? []).map((s) => ({
8166
8411
  namespace: s.namespace,
8167
8412
  name: s.name,
8168
8413
  description: s.description,
8169
- tools: s.toolCache ?? []
8414
+ tools: state.toolCache[s.namespace]?.tools ?? s.toolCache ?? []
8170
8415
  }));
8171
8416
  }
8172
8417
  async function runFoundryExport(opts) {
@@ -8209,8 +8454,15 @@ async function runFoundryExport(opts) {
8209
8454
  );
8210
8455
  return { exitCode: 1, lines };
8211
8456
  }
8212
- mkdirSync3(path5.dirname(path5.resolve(opts.out)), { recursive: true });
8213
- writeFileSync2(opts.out, `${JSON.stringify(corpus, null, 2)}
8457
+ const toolless = servers.filter((s) => s.tools.length === 0).length;
8458
+ if (toolless > 0) {
8459
+ printErr(
8460
+ `yaw-mcp foundry: warning -- ${toolless}/${servers.length} snapshot servers carry no tools (no entry in ~/.yaw-mcp/state.json, or it aged past the tool-cache TTL). Those rank on name + namespace only, which depresses the accuracy printed below; activate them once and re-export.`
8461
+ );
8462
+ }
8463
+ const outPath = path5.resolve(opts.cwd ?? process.cwd(), opts.out);
8464
+ mkdirSync3(path5.dirname(outPath), { recursive: true });
8465
+ writeFileSync2(outPath, `${JSON.stringify(corpus, null, 2)}
8214
8466
  `, "utf8");
8215
8467
  const score = scoreCorpus(corpus);
8216
8468
  const belowFloor = score.top3 < FOUNDRY_TOP3_FLOOR;
@@ -8218,9 +8470,10 @@ async function runFoundryExport(opts) {
8218
8470
  print(
8219
8471
  JSON.stringify(
8220
8472
  {
8221
- out: opts.out,
8473
+ out: outPath,
8222
8474
  entries: corpus.entries.length,
8223
8475
  servers: corpus.servers.length,
8476
+ toollessServers: toolless,
8224
8477
  fromTraces: traces.length,
8225
8478
  top1: score.top1,
8226
8479
  top3: score.top3,
@@ -8233,7 +8486,7 @@ async function runFoundryExport(opts) {
8233
8486
  );
8234
8487
  return { exitCode: 0, lines };
8235
8488
  }
8236
- print(`Wrote ${corpus.entries.length} entries (from ${traces.length} traces) to ${opts.out}`);
8489
+ print(`Wrote ${corpus.entries.length} entries (from ${traces.length} traces) to ${outPath}`);
8237
8490
  print(
8238
8491
  `BM25-floor accuracy on this corpus: top-1 ${(score.top1 * 100).toFixed(1)}%, top-3 ${(score.top3 * 100).toFixed(1)}%`
8239
8492
  );
@@ -8253,7 +8506,7 @@ import { createInterface as createInterface2 } from "readline/promises";
8253
8506
  // src/trust-cmd.ts
8254
8507
  import { readFile as readFile13, stat as stat5 } from "fs/promises";
8255
8508
  import { homedir as homedir16 } from "os";
8256
- import { basename, isAbsolute as isAbsolute2, join as join14, resolve as resolve7 } from "path";
8509
+ import { basename as basename2, isAbsolute as isAbsolute2, join as join13, resolve as resolve7 } from "path";
8257
8510
 
8258
8511
  // src/secrets-cmd.ts
8259
8512
  import { createHash as createHash5 } from "crypto";
@@ -9121,6 +9374,11 @@ ${TRUST_USAGE}` };
9121
9374
  ${TRUST_USAGE}` };
9122
9375
  }
9123
9376
  if (positional.length === 1) {
9377
+ if (positional[0].length === 0) {
9378
+ return { ok: false, error: `yaw-mcp trust: empty path argument
9379
+
9380
+ ${TRUST_USAGE}` };
9381
+ }
9124
9382
  if (opts.mode !== "revoke") {
9125
9383
  return {
9126
9384
  ok: false,
@@ -9166,7 +9424,7 @@ async function runTrustGrant(opts) {
9166
9424
  const probe = await probeProjectTrust({ cwd, home, env });
9167
9425
  if (probe.status === "none") {
9168
9426
  printErr(
9169
- probe.path === null ? `yaw-mcp trust: no .yaw-mcp/ directory found by walking up from ${displaySafe(cwd)}. There is no project bundles.json to approve; your user-global ~/.yaw-mcp/bundles.json is always loaded.` : `yaw-mcp trust: no project bundles.json at ${displaySafe(probe.path)}. Nothing to approve.`
9427
+ probe.path === null ? `yaw-mcp trust: no .yaw-mcp/ directory that yaw-mcp can use was found by walking up from ${displaySafe(cwd)}. One OUTSIDE your home directory is SKIPPED unless yaw-mcp can verify you own it -- set ${ALLOW_UNOWNED_ENV}=1 to trust this checkout, then re-run. Otherwise there is no project bundles.json to approve; your user-global ~/.yaw-mcp/bundles.json is always loaded.` : `yaw-mcp trust: no project bundles.json at ${displaySafe(probe.path)}. Nothing to approve.`
9170
9428
  );
9171
9429
  return { exitCode: 1 };
9172
9430
  }
@@ -9314,7 +9572,9 @@ function printStoreRefusal(printErr, e) {
9314
9572
  }
9315
9573
  function renderLaunch(s) {
9316
9574
  if (s.type === "remote" || !s.command && s.url) return `HTTP ${displaySafe(s.url ?? "(no url)")}`;
9317
- const parts = [s.command ?? "", ...s.args ?? []].filter((p) => p.length > 0);
9575
+ const command = s.command ?? "";
9576
+ const args = s.args ?? [];
9577
+ const parts = command.length > 0 ? [command, ...args] : args;
9318
9578
  if (parts.length === 0) return "(no command)";
9319
9579
  return `$ ${parts.map((p) => displayArg(p)).join(" ")}`;
9320
9580
  }
@@ -9328,7 +9588,7 @@ function displaySafe(s) {
9328
9588
  return DISPLAY_CONTROL_RE.test(s) ? quoteVisible(s) : s;
9329
9589
  }
9330
9590
  function displayArg(s) {
9331
- return /[\s"']/.test(s) || DISPLAY_CONTROL_RE.test(s) ? quoteVisible(s) : s;
9591
+ return s.length === 0 || /[\s"']/.test(s) || DISPLAY_CONTROL_RE.test(s) ? quoteVisible(s) : s;
9332
9592
  }
9333
9593
  var SCRIPT_EXT_RE = /\.(?:js|mjs|cjs|ts|mts|cts|py|rb|sh|bash|zsh|pl|php|lua|jar|bat|cmd|ps1|exe)$/i;
9334
9594
  function inRepoTokens(s) {
@@ -9344,10 +9604,10 @@ function inRepoTokens(s) {
9344
9604
  var REGISTRY_RUNNERS = [
9345
9605
  { cmd: "npx" },
9346
9606
  { cmd: "bunx" },
9347
- { cmd: "uvx" },
9607
+ { cmd: "uvx", python: true },
9348
9608
  { cmd: "pnpm", sub: "dlx" },
9349
9609
  { cmd: "npm", sub: "exec" },
9350
- { cmd: "pipx", sub: "run" }
9610
+ { cmd: "pipx", sub: "run", python: true }
9351
9611
  ];
9352
9612
  var VALUELESS_RUNNER_FLAGS = /* @__PURE__ */ new Set([
9353
9613
  "-y",
@@ -9368,6 +9628,12 @@ function stripVersionPrefixV(spec) {
9368
9628
  const suffix = spec.slice(at + 1);
9369
9629
  return /^v\d/.test(suffix) ? spec.slice(0, at + 1) + suffix.slice(1) : spec;
9370
9630
  }
9631
+ function specVersionSuffix(spec) {
9632
+ const start = spec.startsWith("@") ? 1 : 0;
9633
+ const at = spec.indexOf("@", start);
9634
+ return at === -1 ? null : spec.slice(at + 1);
9635
+ }
9636
+ var PEP440_EXACT_RE = /^\d+(?:\.\d+)*(?:(?:a|b|rc)\d+)?(?:\.post\d+)?(?:\.dev\d+)?$/;
9371
9637
  function unversionedRegistrySpec(s) {
9372
9638
  const base = (s.command ?? "").split(/[\\/]/).pop()?.replace(/\.(?:exe|cmd|bat)$/i, "") ?? "";
9373
9639
  const runner = REGISTRY_RUNNERS.find((r) => r.cmd === base);
@@ -9387,8 +9653,9 @@ function unversionedRegistrySpec(s) {
9387
9653
  break;
9388
9654
  }
9389
9655
  if (spec === null || spec.length === 0) return null;
9390
- if (spec.includes("://") || isAbsolute2(spec) || /^\.{1,2}[\\/]/.test(spec)) return null;
9656
+ if (!isRegistrySpec(spec)) return null;
9391
9657
  if (spec.includes("==")) return null;
9658
+ if (runner.python) return PEP440_EXACT_RE.test(specVersionSuffix(spec) ?? "") ? null : spec;
9392
9659
  if (specConstraint(stripVersionPrefixV(spec)).kind === "exact") return null;
9393
9660
  return spec;
9394
9661
  }
@@ -9470,9 +9737,18 @@ async function runTrustList(opts) {
9470
9737
  for (const r of rows) print(fmt(cols.map(([, get]) => get(r))));
9471
9738
  print("");
9472
9739
  print(`${rows.length} approved in ${trustStorePath(home)}`);
9473
- if (rows.some((r) => r.status !== "ok")) {
9740
+ const hasStatus = (s) => rows.some((r) => r.status === s);
9741
+ if (hasStatus("stale (content changed)")) {
9474
9742
  print("A stale entry is NOT loaded -- re-run `yaw-mcp trust` from that project to re-approve.");
9475
9743
  }
9744
+ if (hasStatus("missing (file not found)")) {
9745
+ print("A missing entry loads nothing -- drop the row with `yaw-mcp trust --revoke <path>`.");
9746
+ }
9747
+ if (hasStatus("unreadable")) {
9748
+ print(
9749
+ "An unreadable entry is STILL honoured by the loader: an approved path yaw-mcp cannot read shadows your user-global ~/.yaw-mcp/bundles.json, so that project loads NO servers. Fix its permissions, or drop it with `yaw-mcp trust --revoke <path>`."
9750
+ );
9751
+ }
9476
9752
  return { exitCode: 0 };
9477
9753
  }
9478
9754
  async function classifyRecord(path6, sha256) {
@@ -9481,7 +9757,7 @@ async function classifyRecord(path6, sha256) {
9481
9757
  return hashTrustContent(raw) === sha256 ? "ok" : "stale (content changed)";
9482
9758
  } catch (e) {
9483
9759
  const code = e.code;
9484
- return code === "ENOENT" || code === "EISDIR" ? "missing (file not found)" : "unreadable";
9760
+ return code === "ENOENT" ? "missing (file not found)" : "unreadable";
9485
9761
  }
9486
9762
  }
9487
9763
  async function resolveRevokeTarget(target) {
@@ -9492,7 +9768,7 @@ async function resolveRevokeTarget(target) {
9492
9768
  return target;
9493
9769
  }
9494
9770
  if (!isDir) return target;
9495
- return basename(target) === CONFIG_DIRNAME ? localBundlesPath(target) : localBundlesPath(join14(target, CONFIG_DIRNAME));
9771
+ return basename2(target) === CONFIG_DIRNAME ? localBundlesPath(target) : localBundlesPath(join13(target, CONFIG_DIRNAME));
9496
9772
  }
9497
9773
  async function runTrustRevoke(opts) {
9498
9774
  const out = opts.out ?? ((s) => process.stdout.write(s));
@@ -9504,8 +9780,9 @@ async function runTrustRevoke(opts) {
9504
9780
  const home = opts.home ?? homedir16();
9505
9781
  const cwd = opts.cwd ?? process.cwd();
9506
9782
  const env = opts.env ?? process.env;
9783
+ const bypassed = isTrustBypassEnabled(env);
9507
9784
  let target;
9508
- if (opts.path) {
9785
+ if (opts.path !== void 0) {
9509
9786
  target = await resolveRevokeTarget(resolve7(cwd, opts.path));
9510
9787
  } else {
9511
9788
  const probe = await probeProjectTrust({ cwd, home, env });
@@ -9520,15 +9797,19 @@ async function runTrustRevoke(opts) {
9520
9797
  }
9521
9798
  const res = await revokeTrust(target, { home });
9522
9799
  if (res.storeWasMalformed) {
9523
- const msg = `the trust store at ${res.storePath} is unreadable, so nothing is trusted and there was nothing to revoke`;
9800
+ const store = await readTrustStore(home);
9801
+ const fix = store.malformedKind === "io" ? "fix its permissions (do NOT delete it -- your approvals are still in there)" : store.malformedKind === "schema" ? "upgrade with `npm i -g @yawlabs/mcp@latest` (do NOT delete it -- your approvals are still in there)" : "fix or delete it";
9802
+ const msg = `trust store unusable: ${store.malformedReason ?? "unknown"} -- nothing was revoked; ${fix}, then re-run`;
9524
9803
  if (opts.json) out(`${JSON.stringify({ ok: false, path: target, removed: false, error: msg }, null, 2)}
9525
9804
  `);
9526
9805
  else printErr(`yaw-mcp trust --revoke: ${msg}`);
9527
9806
  return { exitCode: 1 };
9528
9807
  }
9529
9808
  if (opts.json) {
9530
- out(`${JSON.stringify({ ok: true, path: target, removed: res.removed, storePath: res.storePath }, null, 2)}
9531
- `);
9809
+ out(
9810
+ `${JSON.stringify({ ok: true, path: target, removed: res.removed, storePath: res.storePath, bypassed }, null, 2)}
9811
+ `
9812
+ );
9532
9813
  return { exitCode: 0 };
9533
9814
  }
9534
9815
  if (!res.removed) {
@@ -9537,7 +9818,13 @@ async function runTrustRevoke(opts) {
9537
9818
  }
9538
9819
  print(`Revoked ${displaySafe(target)}`);
9539
9820
  print(` removed from ${res.storePath}`);
9540
- print("Restart your MCP client (or yaw-mcp) to stop loading it.");
9821
+ if (bypassed) {
9822
+ print(
9823
+ `NOTE: ${TRUST_BYPASS_ENV} is set, so this file KEEPS loading without approval. This revocation takes effect once the variable is unset.`
9824
+ );
9825
+ } else {
9826
+ print("Restart your MCP client (or yaw-mcp) to stop loading it.");
9827
+ }
9541
9828
  return { exitCode: 0 };
9542
9829
  }
9543
9830
  function isInteractive(opts) {
@@ -9600,7 +9887,7 @@ function parseAddArgs(argv) {
9600
9887
  break;
9601
9888
  case "--catalog": {
9602
9889
  const v = next();
9603
- if (!v || v.startsWith("--")) return { ok: false, error: "--catalog requires a URL" };
9890
+ if (!v || v.startsWith("-")) return { ok: false, error: "--catalog requires a URL" };
9604
9891
  opts.catalogUrl = v;
9605
9892
  break;
9606
9893
  }
@@ -9608,7 +9895,7 @@ function parseAddArgs(argv) {
9608
9895
  case "--help":
9609
9896
  return { ok: false, error: ADD_USAGE, help: true };
9610
9897
  default:
9611
- if (a.startsWith("--")) return { ok: false, error: `Unknown flag: ${a}
9898
+ if (a.startsWith("-")) return { ok: false, error: `Unknown flag: ${a}
9612
9899
  ${ADD_USAGE}` };
9613
9900
  positional.push(a);
9614
9901
  }
@@ -9706,6 +9993,8 @@ async function runAdd(opts) {
9706
9993
  return { exitCode: 1, written: [] };
9707
9994
  }
9708
9995
  const previewNamespace = preview.namespace ?? namespace;
9996
+ const previewEntry = preview.entry;
9997
+ const previewPath = localBundlesPath(userConfigDir(home));
9709
9998
  if (preview.launchChanged) {
9710
9999
  printErr(
9711
10000
  `Note: this would CHANGE the entry's launch command:
@@ -9721,9 +10010,9 @@ If the existing entry is a different server you meant to keep, remove/re-add via
9721
10010
  ok: true,
9722
10011
  dryRun: true,
9723
10012
  namespace: previewNamespace,
9724
- path: localBundlesPath(userConfigDir(home)),
10013
+ path: previewPath,
9725
10014
  replaced: preview.replaced,
9726
- entry: jsonEntry(entry)
10015
+ entry: jsonEntry(previewEntry)
9727
10016
  },
9728
10017
  null,
9729
10018
  2
@@ -9732,8 +10021,13 @@ If the existing entry is a different server you meant to keep, remove/re-add via
9732
10021
  } else {
9733
10022
  const nsNote = previewNamespace === namespace ? `as namespace "${previewNamespace}"` : `keeping existing namespace "${previewNamespace}"`;
9734
10023
  print(`yaw-mcp add (dry-run): would ${preview.replaced ? "update" : "write"} ${server.name} ${nsNote}`);
9735
- print(` command: ${entry.command} ${(entry.args ?? []).join(" ")}`);
9736
- if (entry.env) print(` env keys: ${Object.keys(entry.env).join(", ")}`);
10024
+ print(` command: ${previewEntry.command} ${(previewEntry.args ?? []).join(" ")}`);
10025
+ if (previewEntry.env) print(` env keys: ${Object.keys(previewEntry.env).join(", ")}`);
10026
+ if (previewEntry.isActive === false) {
10027
+ print(
10028
+ `Note: this entry is "isActive": false in ${previewPath}, so it would stay disabled and NOT load. Set it to true there to enable it.`
10029
+ );
10030
+ }
9737
10031
  }
9738
10032
  return { exitCode: 0, written: [] };
9739
10033
  }
@@ -9955,7 +10249,7 @@ async function runRemove(opts) {
9955
10249
  return { exitCode: 1, written: [] };
9956
10250
  }
9957
10251
  if (!res?.removed) {
9958
- print(`yaw-mcp remove: no server matching "${opts.target}" in ${res?.path ?? "bundles.json"} (nothing to do).`);
10252
+ print(`yaw-mcp remove: no server matching "${opts.target}" in ${path6} (nothing to do).`);
9959
10253
  const shadow2 = await findShadowingProjectBundles(cwd, home, env).catch(() => null);
9960
10254
  if (shadow2) {
9961
10255
  printErr(
@@ -10015,7 +10309,7 @@ async function runList(opts) {
10015
10309
  `);
10016
10310
  const home = opts.home ?? homedir17();
10017
10311
  const cwd = opts.cwd ?? process.cwd();
10018
- const loaded = await loadLocalBundles({ home, cwd });
10312
+ const loaded = await loadLocalBundles({ home, cwd, env: opts.env ?? process.env });
10019
10313
  const servers = loaded.config?.servers ?? [];
10020
10314
  for (const w of loaded.warnings) printErr(`warning: ${w}`);
10021
10315
  const gradesReader = opts.gradesReader ?? readGradesCache;
@@ -10121,14 +10415,14 @@ async function runResetLearning(opts = {}) {
10121
10415
  print("yaw-mcp reset-learning: persistence is disabled (YAW_MCP_DISABLE_PERSISTENCE) \u2014 nothing to clear.");
10122
10416
  return { exitCode: 0, lines, removed: false, path: filePath };
10123
10417
  }
10124
- const { state: persisted, parsedCleanly } = await loadStateClassified(filePath);
10125
- const learningCount = Object.keys(persisted.learning).length;
10126
- const packCount = persisted.packHistory.length;
10127
- const toolCacheCount = Object.keys(persisted.toolCache).length;
10418
+ const { parsedCleanly, rawCounts } = await loadStateClassified(filePath);
10419
+ const learningCount = rawCounts.learning;
10420
+ const packCount = rawCounts.packHistory;
10421
+ const toolCacheCount = rawCounts.toolCache;
10128
10422
  try {
10129
10423
  await unlink3(filePath);
10130
10424
  } catch (err) {
10131
- if (isFileNotFound2(err)) {
10425
+ if (isFileNotFound(err)) {
10132
10426
  print("yaw-mcp reset-learning: no persisted state to reset.");
10133
10427
  print(` path: ${filePath}`);
10134
10428
  return { exitCode: 0, lines, removed: false, path: filePath };
@@ -10151,9 +10445,6 @@ async function runResetLearning(opts = {}) {
10151
10445
  for (const line of RUNNING_SERVE_NOTE) print(line);
10152
10446
  return { exitCode: 0, lines, removed: true, path: filePath };
10153
10447
  }
10154
- function isFileNotFound2(err) {
10155
- return !!err && typeof err === "object" && "code" in err && err.code === "ENOENT";
10156
- }
10157
10448
 
10158
10449
  // src/server.ts
10159
10450
  import { homedir as homedir19 } from "os";
@@ -10287,7 +10578,7 @@ function formatCostLabel(sample) {
10287
10578
 
10288
10579
  // src/credentials.ts
10289
10580
  var MISSING_PATTERNS = [
10290
- /\bmissing\s+(?:env\s+|environment\s+)?(?:variable\s+|var\s+)?([A-Z_][A-Z0-9_]{2,})\b/gi,
10581
+ /\bmissing\s+(?:required\s+)?(?:env\s+|environment\s+)?(?:(?:variable|var)\s*:?\s+)?([A-Z_][A-Z0-9_]{2,})\b/gi,
10291
10582
  /\b([A-Z_][A-Z0-9_]{2,})\s+is\s+(?:required|not\s+set|missing|empty|undefined)\b/gi,
10292
10583
  /\b([A-Z_][A-Z0-9_]{2,})\s+must\s+be\s+set\b/gi,
10293
10584
  /\bplease\s+set\s+(?:env\s+(?:var\s+|variable\s+)?)?([A-Z_][A-Z0-9_]{2,})\b/gi
@@ -10300,7 +10591,6 @@ var CREDENTIAL_SEGMENTS = /* @__PURE__ */ new Set([
10300
10591
  "KEY",
10301
10592
  "KEYS",
10302
10593
  "APIKEY",
10303
- "API",
10304
10594
  "PASSWORD",
10305
10595
  "PASSWD",
10306
10596
  "PASS",
@@ -10392,10 +10682,15 @@ function httpStatusRe(code) {
10392
10682
  const shapeC = `^[\\s"'\`\\[(]*${code}\\b${notCountOrDomain}`;
10393
10683
  return new RegExp(`${shapeA1}|${shapeA2}|${shapeB}|${shapeC}`);
10394
10684
  }
10395
- var RX_HTTP_401 = httpStatusRe(401);
10396
- var RX_HTTP_403 = httpStatusRe(403);
10397
- var RX_HTTP_404 = httpStatusRe(404);
10398
- var RX_HTTP_429 = httpStatusRe(429);
10685
+ function httpStatusMatcher(code) {
10686
+ const digits = String(code);
10687
+ const re = httpStatusRe(code);
10688
+ return (t) => t.includes(digits) && re.test(t);
10689
+ }
10690
+ var HAS_HTTP_401 = httpStatusMatcher(401);
10691
+ var HAS_HTTP_403 = httpStatusMatcher(403);
10692
+ var HAS_HTTP_404 = httpStatusMatcher(404);
10693
+ var HAS_HTTP_429 = httpStatusMatcher(429);
10399
10694
  var RX_NO_TOKEN = /no [a-z_]*token (configured|set)/i;
10400
10695
  var RX_TIMEOUT = /(?<!["'`])\btimeout\b(?!["'`])/;
10401
10696
  function classifyError(text) {
@@ -10413,17 +10708,17 @@ function classifyError(text) {
10413
10708
  if (t.includes("auto-reconnect failed") || t.includes("connection closed")) {
10414
10709
  return "connection_lost";
10415
10710
  }
10416
- if (RX_HTTP_429.test(t) || t.includes("rate limit") || t.includes("too many requests") || // OpenAI SDK quota body: "429 You exceeded your current quota, ..."
10711
+ if (HAS_HTTP_429(t) || t.includes("rate limit") || t.includes("too many requests") || // OpenAI SDK quota body: "429 You exceeded your current quota, ..."
10417
10712
  t.includes("exceeded your current quota")) {
10418
10713
  return "rate_limited";
10419
10714
  }
10420
- if (RX_HTTP_401.test(t) || RX_HTTP_403.test(t) || t.includes("unauthorized") || t.includes("forbidden") || t.includes("permission denied") || t.includes("access denied") || // go-github / github-mcp-server reason phrases, which follow a URL
10715
+ if (HAS_HTTP_401(t) || HAS_HTTP_403(t) || t.includes("unauthorized") || t.includes("forbidden") || t.includes("permission denied") || t.includes("access denied") || // go-github / github-mcp-server reason phrases, which follow a URL
10421
10716
  // rather than an intro word ("GET https://api.github.com/...: 401 Bad
10422
10717
  // credentials []") so the status regex cannot see the code.
10423
10718
  t.includes("bad credentials") || t.includes("requires authentication") || t.includes("not accessible by") || RX_NO_TOKEN.test(t)) {
10424
10719
  return "unauthorized";
10425
10720
  }
10426
- if (RX_HTTP_404.test(t) || t.includes("not found")) {
10721
+ if (HAS_HTTP_404(t) || t.includes("not found")) {
10427
10722
  return "not_found";
10428
10723
  }
10429
10724
  return "upstream_error";
@@ -10617,6 +10912,12 @@ function validateExecRequest(req) {
10617
10912
  if (typeof s.id !== "string" || s.id.length === 0) {
10618
10913
  return { ok: false, message: `step ${i}: \`id\` must be a non-empty string` };
10619
10914
  }
10915
+ if (/[.[\]]/.test(s.id)) {
10916
+ return {
10917
+ ok: false,
10918
+ message: `step ${i}: \`id\` "${s.id}" may not contain '.', '[' or ']' (they are $ref path separators)`
10919
+ };
10920
+ }
10620
10921
  if (s.id === "__proto__") {
10621
10922
  return { ok: false, message: `step ${i}: \`id\` "__proto__" is reserved; use a different id` };
10622
10923
  }
@@ -10630,6 +10931,11 @@ function validateExecRequest(req) {
10630
10931
  if (s.args !== void 0 && (s.args === null || typeof s.args !== "object" || Array.isArray(s.args))) {
10631
10932
  return { ok: false, message: `step ${i}: \`args\` must be an object if provided` };
10632
10933
  }
10934
+ for (const k of Object.keys(s)) {
10935
+ if (k !== "id" && k !== "tool" && k !== "args") {
10936
+ return { ok: false, message: `step ${i}: unknown key "${k}" (allowed: id, tool, args)` };
10937
+ }
10938
+ }
10633
10939
  }
10634
10940
  for (const id of seenIds) {
10635
10941
  if (positionalSlots.has(id)) {
@@ -10643,13 +10949,7 @@ function validateExecRequest(req) {
10643
10949
  if (typeof ret !== "string" || ret.length === 0) {
10644
10950
  return { ok: false, message: "`return` must be a non-empty step id string" };
10645
10951
  }
10646
- const allBindingKeys = new Set(seenIds);
10647
- for (let i = 0; i < steps.length; i++) {
10648
- const s = steps[i];
10649
- if (typeof s.id !== "string" || s.id.length === 0) {
10650
- allBindingKeys.add(String(i));
10651
- }
10652
- }
10952
+ const allBindingKeys = /* @__PURE__ */ new Set([...seenIds, ...positionalSlots]);
10653
10953
  if (!allBindingKeys.has(ret)) {
10654
10954
  return { ok: false, message: `\`return\` references unknown step id "${ret}"` };
10655
10955
  }
@@ -10659,6 +10959,52 @@ function validateExecRequest(req) {
10659
10959
  function stepBindingKey(step, index) {
10660
10960
  return typeof step.id === "string" && step.id.length > 0 ? step.id : String(index);
10661
10961
  }
10962
+ function checkRefsAt(node, bound, stepIndex, depth) {
10963
+ if (depth > MAX_REF_DEPTH) throw new ExecDepthError(MAX_REF_DEPTH);
10964
+ if (isRefNode(node)) {
10965
+ const raw = node.$ref;
10966
+ const tokens = parseRefPath(raw);
10967
+ if (!tokens) return `step ${stepIndex}: $ref "${raw}" is malformed`;
10968
+ const head = tokens[0];
10969
+ if (typeof head !== "string") {
10970
+ return `step ${stepIndex}: $ref "${raw}": missing step id (a bracket index cannot name a step)`;
10971
+ }
10972
+ if (!bound.has(head)) {
10973
+ return `step ${stepIndex}: $ref "${raw}" names step "${head}" which has not run by then`;
10974
+ }
10975
+ return null;
10976
+ }
10977
+ if (Array.isArray(node)) {
10978
+ for (const v of node) {
10979
+ const problem = checkRefsAt(v, bound, stepIndex, depth + 1);
10980
+ if (problem) return problem;
10981
+ }
10982
+ return null;
10983
+ }
10984
+ if (node !== null && typeof node === "object") {
10985
+ for (const v of Object.values(node)) {
10986
+ const problem = checkRefsAt(v, bound, stepIndex, depth + 1);
10987
+ if (problem) return problem;
10988
+ }
10989
+ return null;
10990
+ }
10991
+ return null;
10992
+ }
10993
+ function validateExecRefs(steps) {
10994
+ const bound = /* @__PURE__ */ new Set();
10995
+ for (let i = 0; i < steps.length; i++) {
10996
+ const step = steps[i];
10997
+ try {
10998
+ const problem = checkRefsAt(step.args, bound, i, 0);
10999
+ if (problem) return { ok: false, message: problem };
11000
+ } catch (err) {
11001
+ if (err instanceof ExecDepthError) return { ok: false, message: `step ${i}: ${err.message}` };
11002
+ throw err;
11003
+ }
11004
+ bound.add(stepBindingKey(step, i));
11005
+ }
11006
+ return { ok: true };
11007
+ }
10662
11008
 
10663
11009
  // src/fuzzy.ts
10664
11010
  function levenshtein(a, b) {
@@ -10704,11 +11050,14 @@ function closestNames(query, candidates, limit) {
10704
11050
  } else if (
10705
11051
  // Substring containment is only a credible "typo" signal when the
10706
11052
  // shorter string covers at least half the longer one. Without this
10707
- // gate a short query ("set") substring-matches long commands
10708
- // ("set-active") and surfaces misleading suggestions the header
10709
- // calls conservative. The Levenshtein tier still catches genuine
10710
- // short typos. (The old q.length >= 3 gate here is subsumed by the
10711
- // MIN_TYPO_QUERY_LEN gate on the whole inexact block.)
11053
+ // gate an interior fragment of a long command ("ctiv", "act" inside
11054
+ // "set-active") substring-matches it and surfaces the misleading
11055
+ // suggestions the header calls conservative. What the gate does NOT
11056
+ // suppress is a genuine prefix like "set": that never reaches here,
11057
+ // because the ungated prefix tier above already scored it 1. The
11058
+ // Levenshtein tier still catches genuine short typos. (The old
11059
+ // q.length >= 3 gate here is subsumed by the MIN_TYPO_QUERY_LEN gate
11060
+ // on the whole inexact block.)
10712
11061
  (lc.includes(q) || q.includes(lc)) && Math.min(q.length, lc.length) * 2 >= Math.max(q.length, lc.length)
10713
11062
  ) {
10714
11063
  score = 2;
@@ -10738,16 +11087,20 @@ function errorRateFactor(health) {
10738
11087
  const factor = 1 - rate;
10739
11088
  return Math.max(MIN_FACTOR, factor);
10740
11089
  }
11090
+ function isWithinActivationTtl(failure, now) {
11091
+ const age = now - failure.at;
11092
+ return age >= 0 && age <= ACTIVATION_FAILURE_TTL_MS;
11093
+ }
10741
11094
  function activationFailureFactor(failure, now = Date.now()) {
10742
11095
  if (!failure) return 1;
10743
- if (now - failure.at > ACTIVATION_FAILURE_TTL_MS) return 1;
11096
+ if (!isWithinActivationTtl(failure, now)) return 1;
10744
11097
  return MIN_FACTOR;
10745
11098
  }
10746
11099
  function healthFactor(health, activationFailure, now = Date.now()) {
10747
11100
  return Math.min(errorRateFactor(health), activationFailureFactor(activationFailure, now));
10748
11101
  }
10749
11102
  function formatHealthWarning(health, activationFailure, now = Date.now()) {
10750
- if (activationFailure && now - activationFailure.at <= ACTIVATION_FAILURE_TTL_MS) {
11103
+ if (activationFailure && isWithinActivationTtl(activationFailure, now)) {
10751
11104
  const ageMin = Math.max(1, Math.round((now - activationFailure.at) / 6e4));
10752
11105
  const msg = activationFailure.message ? `: ${truncateForWarning(activationFailure.message)}` : "";
10753
11106
  return `warn: last activation failed ${ageMin}m ago${msg}`;
@@ -10756,25 +11109,67 @@ function formatHealthWarning(health, activationFailure, now = Date.now()) {
10756
11109
  const rate = health.errorCount / health.totalCalls;
10757
11110
  if (rate >= WARN_RATE_FLOOR) {
10758
11111
  const lastErr = health.lastErrorMessage ? `: ${truncateForWarning(health.lastErrorMessage)}` : "";
10759
- return `warn: ${health.errorCount} of last ${health.totalCalls} calls failed${lastErr}`;
11112
+ return `warn: ${health.errorCount} of ${health.totalCalls} calls failed${lastErr}`;
10760
11113
  }
10761
11114
  }
10762
11115
  return null;
10763
11116
  }
10764
11117
  var REDACTED = "<redacted>";
10765
11118
  var SECRET_KEY_NAMES = "api[-_]?key|apikey|access[-_]?token|refresh[-_]?token|id[-_]?token|client[-_]?secret|private[-_]?key|secret|password|passwd|pwd|token|authorization|auth|credential|signature|sig";
11119
+ var ABSENCE_VALUE = /^(?:not|no|missing|unset|undefined|null|none|empty|required|absent|blank|nil|n\/a|must|invalid|expected|cannot|failed)$/i;
10766
11120
  var SECRET_PATTERNS = [
10767
11121
  // 1. An HTTP `Authorization: Bearer <blob>` / `Basic <blob>` header value.
10768
- { re: /\b(?:bearer|basic)\s+[A-Za-z0-9._~+/=-]{8,}/gi, replace: REDACTED },
11122
+ // Scheme list is not just bearer/basic: any other scheme fell through to
11123
+ // rule 2, which then captured the SCHEME WORD as the value and left the
11124
+ // token itself in the clear ("Authorization: Token abc123def456").
11125
+ { re: /\b(?:bearer|basic|token|apikey|api-key|digest|key|hmac)\s+[A-Za-z0-9._~+/=-]{8,}/gi, replace: () => REDACTED },
10769
11126
  // 2. A secret-ish key followed by = or : and a value -- a query string, a
10770
11127
  // JSON body, a header dump, or a Python repr ({'token': 'abc'}).
10771
- { re: new RegExp(`\\b(${SECRET_KEY_NAMES})("?\\s*[=:]\\s*"?)[^\\s,;&"'}\\]<]+`, "gi"), replace: `$1$2${REDACTED}` },
11128
+ //
11129
+ // The name may carry an underscore/hyphen-joined PREFIX (NOTION_API_KEY,
11130
+ // auth_token, MY_SECRET), and that prefix is part of the match rather than
11131
+ // something \b can skip over: `_` is a word character, so a bare \b in
11132
+ // front of the name token never matches inside SOMETHING_TOKEN. Env-var
11133
+ // spellings are the dominant shape in MCP spawn/config errors, so that gap
11134
+ // left the raw value in the excerpt whenever the key carried a prefix and
11135
+ // the value itself had no vendor prefix for rule 3 to catch. The prefix
11136
+ // group sits INSIDE $1 so the full name still survives into the output.
11137
+ //
11138
+ // Prefixed NON-secrets stay readable, because the name has to both END the
11139
+ // prefixed run and be followed by = or : -- "SSH_AUTH_SOCK=/tmp/..." has
11140
+ // `_SOCK` sitting after `AUTH`, so no alternative matches. The VALUE and
11141
+ // the SEPARATOR are gated too: prose there is a diagnostic, not a
11142
+ // credential, so the whole match is handed back untouched (see
11143
+ // ABSENCE_VALUE / PROSE_VALUE / PROSE_SEPARATOR above).
11144
+ //
11145
+ // Everything the callback needs is inside the match, so this stays a
11146
+ // single linear pass. An earlier revision looked ahead at the rest of the
11147
+ // line to decide; that was both wrong (any later word exempted the value)
11148
+ // and quadratic on a long collapsed line.
11149
+ {
11150
+ // The prefix repetition is BOUNDED. `(?:[A-Za-z0-9]+[-_])*` is O(n^2)
11151
+ // against a long hyphen-joined run, because `\b` matches at every hyphen so
11152
+ // the scan restarts per position: 784 ms on a 64 KB kebab chain, 12.4 s at
11153
+ // 100 KB, and the message is stored, so it recurs on every discover().
11154
+ // Nothing real has 8 prefix segments of 32 chars.
11155
+ re: new RegExp(
11156
+ `\\b((?:[A-Za-z0-9]{1,32}[-_]){0,8}(?:${SECRET_KEY_NAMES}))(["']?\\s*[=:][ \\t]*)(?:'([^'\\n]*)'|"([^"\\n]*)"|([^\\s,;&"'}\\]<]+)((?:[ \\t]+(?!-)(?![A-Za-z0-9_-]+["']?[ \\t]*[=:])[^\\s,;&"'}\\]<]+)*))`,
11157
+ "gi"
11158
+ ),
11159
+ replace: (_match, name, sep, single, double, bare, tail) => {
11160
+ if (single !== void 0) return `${name}${sep}'${REDACTED}'`;
11161
+ if (double !== void 0) return `${name}${sep}"${REDACTED}"`;
11162
+ if (ABSENCE_VALUE.test(bare)) return `${name}${sep}${bare}${tail}`;
11163
+ if (!/[ \t]$/.test(sep)) return `${name}${sep}${REDACTED}${tail}`;
11164
+ return `${name}${sep}${REDACTED}`;
11165
+ }
11166
+ },
10772
11167
  // 3. A vendor-prefixed key carrying no name for rule 2 to anchor on.
10773
11168
  {
10774
11169
  re: /\b(?:sk|pk|rk|ghp|gho|ghu|ghs|ghr|github_pat|xoxb|xoxp|xoxa|xapp|glpat)[-_][A-Za-z0-9_-]{8,}/g,
10775
- replace: REDACTED
11170
+ replace: () => REDACTED
10776
11171
  },
10777
- { re: /\bAKIA[0-9A-Z]{16}\b/g, replace: REDACTED }
11172
+ { re: /\bAKIA[0-9A-Z]{16}\b/g, replace: () => REDACTED }
10778
11173
  ];
10779
11174
  function scrubForWarning(msg) {
10780
11175
  let out = msg;
@@ -10820,12 +11215,12 @@ function pushToolCall(history, record, limit = HISTORY_LIMIT) {
10820
11215
 
10821
11216
  // src/install-nudge.ts
10822
11217
  import { existsSync as existsSync9, mkdirSync as mkdirSync4, readFileSync as readFileSync6, statSync as statSync2, writeFileSync as writeFileSync3 } from "fs";
10823
- import { dirname as dirname5, join as join15 } from "path";
11218
+ import { dirname as dirname7, join as join14 } from "path";
10824
11219
  var INSTALL_NUDGE_MIN_COUNT = 5;
10825
11220
  var INSTALL_NUDGE_COOLDOWN_MS = 7 * 24 * 60 * 60 * 1e3;
10826
11221
  var INSTALL_NUDGE_STATE_FILENAME = "install-nudge-state.json";
10827
11222
  function installNudgeStatePath(home) {
10828
- return join15(home, CONFIG_DIRNAME, INSTALL_NUDGE_STATE_FILENAME);
11223
+ return join14(home, CONFIG_DIRNAME, INSTALL_NUDGE_STATE_FILENAME);
10829
11224
  }
10830
11225
  function installNudgeEnabled(env, config) {
10831
11226
  if (env.YAW_MCP_INSTALL_NUDGE === "1") return true;
@@ -10874,13 +11269,18 @@ function shouldNudge(cli, home, now = Date.now) {
10874
11269
  return at - clampToNow(rec.nudgedAt, at) >= INSTALL_NUDGE_COOLDOWN_MS;
10875
11270
  }
10876
11271
  function recordNudge(cli, home, now = Date.now) {
11272
+ recordNudges([cli], home, now);
11273
+ }
11274
+ function recordNudges(clis, home, now = Date.now) {
11275
+ if (clis.length === 0) return;
11276
+ const recorded = new Set(clis);
10877
11277
  try {
10878
11278
  const at = now();
10879
11279
  const state = readState(home);
10880
- const kept = state.nudges.filter((n) => n.cli !== cli && at - clampToNow(n.nudgedAt, at) < INSTALL_NUDGE_COOLDOWN_MS).map((n) => ({ cli: n.cli, nudgedAt: clampToNow(n.nudgedAt, at) }));
10881
- kept.push({ cli, nudgedAt: at });
11280
+ const kept = state.nudges.filter((n) => !recorded.has(n.cli) && at - clampToNow(n.nudgedAt, at) < INSTALL_NUDGE_COOLDOWN_MS).map((n) => ({ cli: n.cli, nudgedAt: clampToNow(n.nudgedAt, at) }));
11281
+ for (const cli of recorded) kept.push({ cli, nudgedAt: at });
10882
11282
  const path6 = installNudgeStatePath(home);
10883
- mkdirSync4(dirname5(path6), { recursive: true });
11283
+ mkdirSync4(dirname7(path6), { recursive: true });
10884
11284
  writeFileSync3(path6, `${JSON.stringify({ nudges: kept }, null, 2)}
10885
11285
  `, "utf8");
10886
11286
  try {
@@ -10891,13 +11291,14 @@ function recordNudge(cli, home, now = Date.now) {
10891
11291
  }
10892
11292
  } catch (err) {
10893
11293
  log("debug", "install-nudge: failed to record nudge state", {
10894
- cli,
11294
+ cli: [...recorded].join(", "),
10895
11295
  error: err instanceof Error ? err.message : String(err)
10896
11296
  });
10897
11297
  }
10898
11298
  }
10899
11299
 
10900
11300
  // src/meta-tools.ts
11301
+ var PENALTY_RATE_PCT = Math.round(PENALTY_RATE_THRESHOLD * 100);
10901
11302
  var META_TOOLS = {
10902
11303
  discover: {
10903
11304
  name: "mcp_connect_discover",
@@ -10976,7 +11377,7 @@ var META_TOOLS = {
10976
11377
  },
10977
11378
  health: {
10978
11379
  name: "mcp_connect_health",
10979
- description: "Show health stats for MCP servers loaded in the current session: total calls, error count, average latency, and last error. Per-call telemetry covers LOADED servers only; installed-but-unloaded servers with a poor persisted success rate (<80% across sessions) are listed in a separate cross-session reliability block \u2014 do NOT load a server just to see its history, loading it resets the in-session counters to zero.",
11380
+ description: `Show health stats for MCP servers loaded in the current session: total calls, error count, average latency, and last error. Per-call telemetry covers LOADED servers only; installed-but-unloaded servers with a poor persisted success rate (<${PENALTY_RATE_PCT}% across sessions) are listed in a separate cross-session reliability block \u2014 do NOT load a server just to see its history, loading it resets the in-session counters to zero.`,
10980
11381
  inputSchema: {
10981
11382
  type: "object",
10982
11383
  properties: {}
@@ -11110,7 +11511,13 @@ var META_TOOLS = {
11110
11511
  },
11111
11512
  exec: {
11112
11513
  name: "mcp_connect_exec",
11113
- description: "Run a short DECLARATIVE pipeline of upstream tool calls in a single round-trip. Use this when you already know the exact 2-4 tool calls to make and one call's output feeds another's args \u2014 e.g. `a = gh_list_prs(); b = gh_get_pr(a[0].number); return b`. NOT a code sandbox: there is no expression language, no loops, no branching, no arithmetic. The only control flow is sequential step execution; the only data-flow primitive is `{\"$ref\": \"<stepId>[.path.to.value]\"}` which substitutes a prior step's output (or a nested field of it) into the next step's args. Paths support dot keys and `[N]` / `.N` array indexing. Each step's `tool` must be a namespaced, already-loaded tool name (the exec does not auto-activate \u2014 call `mcp_connect_activate` first). Max 16 steps per exec. If any step fails, the whole pipeline fails and returns `{ ok: false, failedStep, error, partial: { ...completed outputs } }`. On success returns `{ ok: true, result: <return-step output>, steps: { ...all outputs } }`. Prefer this over back-to-back tool calls when the chain is deterministic \u2014 it saves prompt-token replay and client round-trips.",
11514
+ // Joined rather than one literal so the step cap can be interpolated from
11515
+ // MAX_EXEC_STEPS -- the constant validateExecRequest actually enforces.
11516
+ description: [
11517
+ "Run a short DECLARATIVE pipeline of upstream tool calls in a single round-trip. Use this when you already know the exact 2-4 tool calls to make and one call's output feeds another's args \u2014 e.g. `a = gh_list_prs(); b = gh_get_pr(a[0].number); return b`. NOT a code sandbox: there is no expression language, no loops, no branching, no arithmetic. The only control flow is sequential step execution; the only data-flow primitive is `{\"$ref\": \"<stepId>[.path.to.value]\"}` which substitutes a prior step's output (or a nested field of it) into the next step's args. Paths support dot keys and `[N]` / `.N` array indexing. Each step's `tool` is a namespaced upstream tool name: an already-loaded server is called directly, and a not-yet-loaded server whose tools are known from cache is loaded on first use exactly as a direct tools/call would be \u2014 that adds its tools to this session, and can still be refused (server cap, compliance floor). A name that is neither loaded nor cached fails the step.",
11518
+ `Max ${MAX_EXEC_STEPS} steps per exec.`,
11519
+ "If any step fails, the whole pipeline fails and returns `{ ok: false, failedStep, error, partial: { ...completed outputs } }`. On success returns `{ ok: true, result: <return-step output>, steps: { ...all outputs } }`. Prefer this over back-to-back tool calls when the chain is deterministic \u2014 it saves prompt-token replay and client round-trips."
11520
+ ].join(" "),
11114
11521
  inputSchema: {
11115
11522
  type: "object",
11116
11523
  properties: {
@@ -11126,7 +11533,7 @@ var META_TOOLS = {
11126
11533
  },
11127
11534
  tool: {
11128
11535
  type: "string",
11129
- description: 'Namespaced tool name (e.g. "gh_list_prs"). Must be a tool currently loaded in the session. Meta-tools (mcp_connect_*) are not callable from exec.'
11536
+ description: 'Namespaced tool name (e.g. "gh_list_prs"). Loaded servers are called directly; a not-yet-loaded server whose tools are known from cache is loaded on first use, adding its tools to the session. A name that is neither loaded nor cached fails the step. Meta-tools (mcp_connect_*) are not callable from exec.'
11130
11537
  },
11131
11538
  args: {
11132
11539
  type: "object",
@@ -11134,7 +11541,14 @@ var META_TOOLS = {
11134
11541
  additionalProperties: true
11135
11542
  }
11136
11543
  },
11137
- required: ["tool"]
11544
+ required: ["tool"],
11545
+ // A misspelled `arguments` / `arg` / `input` key would otherwise
11546
+ // read as a legal extension and the step would dispatch with no
11547
+ // arguments at all. validateExecRequest rejects the same shape at
11548
+ // runtime (the low-level Server never validates against this
11549
+ // schema); declaring it here is what steers a schema-aware client
11550
+ // away from sending it in the first place.
11551
+ additionalProperties: false
11138
11552
  }
11139
11553
  },
11140
11554
  return: {
@@ -11155,13 +11569,8 @@ var META_TOOLS = {
11155
11569
  };
11156
11570
  function computeSecretsReport(servers, vaultKeys) {
11157
11571
  const rows = [];
11158
- const re = new RegExp(SECRET_REF_RE.source, SECRET_REF_RE.flags);
11159
11572
  for (const server of servers) {
11160
- const referenced = /* @__PURE__ */ new Set();
11161
- for (const v of Object.values(server.env ?? {})) {
11162
- if (typeof v !== "string") continue;
11163
- for (const m of v.matchAll(re)) referenced.add(m[1]);
11164
- }
11573
+ const referenced = collectSecretRefNames(server.env);
11165
11574
  if (referenced.size === 0) continue;
11166
11575
  const injectedSecrets = [];
11167
11576
  const missing = [];
@@ -11469,12 +11878,16 @@ function buildToolRoutes(activeConnections, inactiveWithCache = []) {
11469
11878
  }
11470
11879
  function buildResourceList(activeConnections, builtins = [], exposure = "full", exposedNamespaces) {
11471
11880
  const resources = [];
11881
+ const seen = /* @__PURE__ */ new Set();
11472
11882
  for (const b of builtins) {
11883
+ if (seen.has(b.uri)) continue;
11473
11884
  resources.push({ uri: b.uri, name: b.name, description: b.description, mimeType: b.mimeType });
11885
+ seen.add(b.uri);
11474
11886
  }
11475
11887
  for (const conn of activeConnections.values()) {
11476
11888
  if (exposure === "gateway" && !exposedNamespaces?.has(conn.config.namespace)) continue;
11477
11889
  for (const r of conn.resources) {
11890
+ if (seen.has(r.namespacedUri)) continue;
11478
11891
  resources.push({
11479
11892
  uri: r.namespacedUri,
11480
11893
  name: r.name,
@@ -11483,6 +11896,7 @@ function buildResourceList(activeConnections, builtins = [], exposure = "full",
11483
11896
  mimeType: r.mimeType,
11484
11897
  _meta: r._meta
11485
11898
  });
11899
+ seen.add(r.namespacedUri);
11486
11900
  }
11487
11901
  }
11488
11902
  return resources;
@@ -11491,6 +11905,17 @@ function buildResourceRoutes(activeConnections) {
11491
11905
  const routes = /* @__PURE__ */ new Map();
11492
11906
  for (const conn of activeConnections.values()) {
11493
11907
  for (const r of conn.resources) {
11908
+ const existing = routes.get(r.namespacedUri);
11909
+ if (existing) {
11910
+ if (existing.namespace !== conn.config.namespace) {
11911
+ log("warn", "Resource route collision; keeping the first upstream, ignoring the later one", {
11912
+ uri: r.namespacedUri,
11913
+ keptNamespace: existing.namespace,
11914
+ ignoredNamespace: conn.config.namespace
11915
+ });
11916
+ }
11917
+ continue;
11918
+ }
11494
11919
  routes.set(r.namespacedUri, { namespace: conn.config.namespace, originalUri: r.uri });
11495
11920
  }
11496
11921
  }
@@ -11554,7 +11979,10 @@ async function routeResourceRead(uri, resourceRoutes, activeConnections, builtin
11554
11979
  }
11555
11980
  try {
11556
11981
  const result = await connection.client.readResource({ uri: route.originalUri });
11557
- return result;
11982
+ return {
11983
+ ...result,
11984
+ contents: (result.contents ?? []).map((c) => ({ ...c, uri: `connect://${route.namespace}/${c.uri}` }))
11985
+ };
11558
11986
  } catch (err) {
11559
11987
  const message = err instanceof Error ? err.message : String(err);
11560
11988
  log("error", "Resource read failed", { uri, namespace: route.namespace, error: message });
@@ -11589,6 +12017,7 @@ function brandRoutingFault(result) {
11589
12017
  function isRoutingFaultResult(result) {
11590
12018
  return typeof result === "object" && result !== null && result[ROUTING_FAULT_BRAND] === true;
11591
12019
  }
12020
+ var CALL_TIMEOUT = resolveTimeoutEnv("MCP_CALL_TIMEOUT", 6e4);
11592
12021
  async function routeToolCall(toolName, args, toolRoutes, activeConnections) {
11593
12022
  const route = toolRoutes.get(toolName);
11594
12023
  if (!route) {
@@ -11615,10 +12044,18 @@ async function routeToolCall(toolName, args, toolRoutes, activeConnections) {
11615
12044
  });
11616
12045
  }
11617
12046
  try {
11618
- const result = await connection.client.callTool({
11619
- name: route.originalName,
11620
- arguments: args
11621
- });
12047
+ const result = await connection.client.callTool(
12048
+ {
12049
+ name: route.originalName,
12050
+ arguments: args
12051
+ },
12052
+ // The second argument is the RESULT SCHEMA, not the options: passing the
12053
+ // options object there would silently replace CallToolResultSchema and
12054
+ // take the SDK's structured-output validation with it. `undefined` keeps
12055
+ // the SDK default; the request options belong in the third slot.
12056
+ void 0,
12057
+ { timeout: CALL_TIMEOUT }
12058
+ );
11622
12059
  return result;
11623
12060
  } catch (err) {
11624
12061
  const message = err instanceof Error ? err.message : String(err);
@@ -11669,7 +12106,6 @@ function pruneText(text) {
11669
12106
  }
11670
12107
  return pruneWhitespace(text);
11671
12108
  }
11672
- var MAX_FAITHFUL_MANTISSA_DIGITS = 17;
11673
12109
  var JSON_STRING_OR_NUMBER_RE = /"(?:[^"\\]|\\.)*"|-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?/g;
11674
12110
  function jsonNumbersAreFaithful(text) {
11675
12111
  JSON_STRING_OR_NUMBER_RE.lastIndex = 0;
@@ -11688,7 +12124,18 @@ function numberLiteralIsFaithful(literal) {
11688
12124
  const mantissa = literal.replace(/^-/, "").split(/[eE]/)[0];
11689
12125
  const digits = mantissa.replace(".", "").replace(/^0+/, "");
11690
12126
  if (n === 0) return !/[1-9]/.test(digits);
11691
- return digits.replace(/0+$/, "").length <= MAX_FAITHFUL_MANTISSA_DIGITS;
12127
+ const canonical = canonicalDecimal(literal);
12128
+ return canonical !== null && canonical === canonicalDecimal(String(n));
12129
+ }
12130
+ function canonicalDecimal(s) {
12131
+ const m = /^([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/.exec(s);
12132
+ if (m === null) return null;
12133
+ const [, sign, intPart, fracPart = "", expPart = ""] = m;
12134
+ const digits = `${intPart}${fracPart}`.replace(/^0+/, "");
12135
+ if (digits === "") return "0";
12136
+ const significant = digits.replace(/0+$/, "");
12137
+ const pow = Number(expPart) - fracPart.length + (digits.length - significant.length);
12138
+ return `${sign === "-" ? "-" : ""}${significant}e${pow}`;
11692
12139
  }
11693
12140
  function pruneWhitespace(text) {
11694
12141
  return text.split("\n").map((line) => line.replace(/[ \t]+(?=\r?$)/, "")).join("\n").replace(/(?:\r?\n){3,}/g, (run2) => run2.includes("\r") ? "\r\n\r\n" : "\n\n");
@@ -11733,14 +12180,25 @@ function findTool(tools, toolName) {
11733
12180
  function formatReadToolOutput(result) {
11734
12181
  const { tool, server, loaded } = result;
11735
12182
  const lines = [];
11736
- lines.push(`Tool: ${server.namespace}_${tool.name}`);
12183
+ lines.push(`Tool: ${tool.namespacedName}`);
11737
12184
  lines.push(`Server: ${server.name} (${server.namespace})`);
12185
+ if (tool.title) {
12186
+ lines.push(`Title: ${tool.title}`);
12187
+ }
11738
12188
  if (tool.description) {
11739
12189
  lines.push(`Description: ${tool.description}`);
11740
12190
  }
12191
+ if (tool.annotations) {
12192
+ lines.push(`Annotations: ${JSON.stringify(tool.annotations)}`);
12193
+ }
11741
12194
  lines.push("");
11742
12195
  lines.push("Input schema:");
11743
12196
  lines.push(JSON.stringify(tool.inputSchema ?? {}, null, 2));
12197
+ if (tool.outputSchema) {
12198
+ lines.push("");
12199
+ lines.push("Output schema:");
12200
+ lines.push(JSON.stringify(tool.outputSchema, null, 2));
12201
+ }
11744
12202
  if (!loaded) {
11745
12203
  lines.push("");
11746
12204
  lines.push(
@@ -11868,6 +12326,9 @@ var ERROR_SHAPED_CATEGORIES = /* @__PURE__ */ new Set([
11868
12326
  "rate_limited",
11869
12327
  "not_found"
11870
12328
  ]);
12329
+ var REWARD_ERROR_SHAPED = 0.2;
12330
+ var REWARD_EMPTY_BODY = 0.3;
12331
+ var RULE2_SCAN_LEN = 1e3;
11871
12332
  function firstTextBlock(result) {
11872
12333
  const content = result.content;
11873
12334
  if (!content || content.length === 0) return void 0;
@@ -11892,11 +12353,12 @@ function computeOutcomeReward(result) {
11892
12353
  if (result.isError === true) return 0;
11893
12354
  const text = firstTextBlock(result);
11894
12355
  if (text !== void 0) {
11895
- if (ERROR_SHAPED_CATEGORIES.has(classifyError(text))) {
11896
- return 0.2;
12356
+ const head = text.length > RULE2_SCAN_LEN ? text.slice(0, RULE2_SCAN_LEN) : text;
12357
+ if (ERROR_SHAPED_CATEGORIES.has(classifyError(head))) {
12358
+ return REWARD_ERROR_SHAPED;
11897
12359
  }
11898
12360
  }
11899
- if (isEmptyBody(result)) return 0.3;
12361
+ if (isEmptyBody(result)) return REWARD_EMPTY_BODY;
11900
12362
  return 1;
11901
12363
  }
11902
12364
 
@@ -11908,11 +12370,12 @@ function isRewardGraderEnabled() {
11908
12370
  return v === "1" || v === "true";
11909
12371
  }
11910
12372
  function isUncertainReward(heuristic) {
11911
- return heuristic >= 0.2 && heuristic <= 0.3;
12373
+ return heuristic === REWARD_ERROR_SHAPED || heuristic === REWARD_EMPTY_BODY;
11912
12374
  }
11913
- var GRADER_MAX_TOKENS = 8;
12375
+ var GRADER_MAX_TOKENS = 64;
11914
12376
  var GRADER_TIMEOUT_MS = 4e3;
11915
12377
  var RESULT_SNIPPET_LEN = 600;
12378
+ var INTENT_MAX = 200;
11916
12379
  function firstResultText(result) {
11917
12380
  const content = result.content;
11918
12381
  if (Array.isArray(content)) {
@@ -11928,8 +12391,10 @@ function firstResultText(result) {
11928
12391
  var FENCED_CONTENT_MAX = 4e3;
11929
12392
  function buildGraderPrompt(ctx) {
11930
12393
  const lines = ["You are grading whether an MCP tool call accomplished its goal."];
11931
- if (ctx.intent && ctx.intent.trim().length > 0) {
11932
- lines.push("", `Goal: ${ctx.intent.trim()}`);
12394
+ const intent = ctx.intent?.trim() ?? "";
12395
+ if (intent.length > 0) {
12396
+ const goal = intent.length > INTENT_MAX ? `${intent.slice(0, INTENT_MAX)}...` : intent;
12397
+ lines.push("", `Goal: ${goal}`);
11933
12398
  }
11934
12399
  let fenced = ctx.resultText;
11935
12400
  if (fenced.length > FENCED_CONTENT_MAX) {
@@ -12029,6 +12494,7 @@ var SAMPLING_TIEBREAK_RATIO = 0.9;
12029
12494
  var SAMPLING_MAX_TOKENS = 120;
12030
12495
  var MAX_SAMPLES = 5;
12031
12496
  var SAMPLING_TIMEOUT_MS = 2e3;
12497
+ var BEST_OF_N_TEMPERATURE = 0.7;
12032
12498
  var AGGRESSIVE_AMBIGUITY_THRESHOLD = 0.6;
12033
12499
  function shouldTiebreak(ranked, ratio = SAMPLING_TIEBREAK_RATIO) {
12034
12500
  if (ranked.length < 2) return false;
@@ -12106,15 +12572,26 @@ function buildCandidates(topRanked, serversByNamespace, toolsByNamespace) {
12106
12572
  }
12107
12573
  return out;
12108
12574
  }
12109
- function parseRouteEffort(raw) {
12110
- if (raw === void 0) return "auto";
12575
+ function parseRouteEffort(raw, fallbackRaw = process.env.YAW_MCP_ROUTE_EFFORT) {
12576
+ const direct = matchRouteEffort(raw);
12577
+ if (direct) return direct;
12578
+ if (raw !== void 0 && raw.trim() !== "") {
12579
+ const fromEnv = matchRouteEffort(fallbackRaw);
12580
+ if (fromEnv) return fromEnv;
12581
+ }
12582
+ return "auto";
12583
+ }
12584
+ function matchRouteEffort(raw) {
12585
+ if (raw === void 0) return null;
12111
12586
  switch (raw.trim().toLowerCase()) {
12112
12587
  case "off":
12113
12588
  return "off";
12589
+ case "auto":
12590
+ return "auto";
12114
12591
  case "aggressive":
12115
12592
  return "aggressive";
12116
12593
  default:
12117
- return "auto";
12594
+ return null;
12118
12595
  }
12119
12596
  }
12120
12597
  function computeAmbiguity(ranked, k = 3) {
@@ -12161,21 +12638,21 @@ async function bestOfNViaSampling(server, intent, candidates, n) {
12161
12638
  if (candidates.length < 2) return null;
12162
12639
  const samples = Math.min(MAX_SAMPLES, Math.max(1, Math.floor(n)));
12163
12640
  const prompt = buildTiebreakPrompt(intent, candidates);
12641
+ const params = {
12642
+ messages: [{ role: "user", content: { type: "text", text: prompt } }],
12643
+ maxTokens: SAMPLING_MAX_TOKENS,
12644
+ includeContext: "none"
12645
+ };
12646
+ if (samples > 1) params.temperature = BEST_OF_N_TEMPERATURE;
12164
12647
  const controller = new AbortController();
12165
12648
  const sampleOnce = async () => {
12166
12649
  try {
12167
- const result = await server.createMessage(
12168
- {
12169
- messages: [{ role: "user", content: { type: "text", text: prompt } }],
12170
- maxTokens: SAMPLING_MAX_TOKENS,
12171
- includeContext: "none"
12172
- },
12173
- { signal: controller.signal, timeout: SAMPLING_TIMEOUT_MS }
12174
- );
12650
+ const result = await server.createMessage(params, { signal: controller.signal, timeout: SAMPLING_TIMEOUT_MS });
12175
12651
  const text = result && typeof result === "object" && "content" in result && result.content ? extractText2(result.content) : "";
12176
12652
  if (!text) return null;
12177
12653
  return parseTiebreakResponse(text, candidates);
12178
12654
  } catch (err) {
12655
+ if (controller.signal.aborted) return null;
12179
12656
  log("warn", "Best-of-N sample failed", { error: err instanceof Error ? err.message : String(err) });
12180
12657
  return null;
12181
12658
  }
@@ -12259,18 +12736,23 @@ function isAutoLoadEnabled() {
12259
12736
  if (raw === void 0 || raw === "") return false;
12260
12737
  return raw === "1" || raw.toLowerCase() === "true";
12261
12738
  }
12739
+ var exposureWarnedFor = null;
12262
12740
  function resolveToolExposure() {
12263
12741
  const raw = process.env.YAW_MCP_TOOL_EXPOSURE?.trim().toLowerCase();
12264
12742
  if (raw === "full") return "full";
12265
12743
  if (raw === void 0 || raw === "" || raw === "gateway") return "gateway";
12266
- log("warn", `unrecognized YAW_MCP_TOOL_EXPOSURE "${raw}"; using "gateway"`, { raw });
12744
+ if (exposureWarnedFor !== raw) {
12745
+ exposureWarnedFor = raw;
12746
+ log("warn", `unrecognized YAW_MCP_TOOL_EXPOSURE "${raw}"; using "gateway"`, { raw });
12747
+ }
12267
12748
  return "gateway";
12268
12749
  }
12269
12750
  var DEFAULT_IDLE_CALL_THRESHOLD = 10;
12270
12751
  var MAX_VAULT_PASSPHRASE_PROMPTS = 2;
12752
+ var MAX_CREDENTIAL_PROMPTS = 2;
12271
12753
  var idleThresholdClampWarnedFor = null;
12272
12754
  function resolveIdleThreshold() {
12273
- const current = process.env.YAW_MCP_IDLE_THRESHOLD;
12755
+ const current = process.env.YAW_MCP_IDLE_THRESHOLD?.trim();
12274
12756
  const raw = current !== void 0 && current !== "" ? current : process.env.MCP_CONNECT_IDLE_THRESHOLD;
12275
12757
  if (!raw) return DEFAULT_IDLE_CALL_THRESHOLD;
12276
12758
  const trimmed = raw.trim();
@@ -12284,6 +12766,13 @@ function resolveIdleThreshold() {
12284
12766
  effectiveMax: ADAPTIVE_MAX
12285
12767
  });
12286
12768
  }
12769
+ if (n < ADAPTIVE_MIN && idleThresholdClampWarnedFor !== n) {
12770
+ idleThresholdClampWarnedFor = n;
12771
+ log("warn", "Idle threshold below the adaptive floor; it will be clamped", {
12772
+ configured: n,
12773
+ effectiveMin: ADAPTIVE_MIN
12774
+ });
12775
+ }
12287
12776
  return n;
12288
12777
  }
12289
12778
  function isAutoActivateEnabled() {
@@ -12315,10 +12804,29 @@ function settledWithin(p, ms) {
12315
12804
  p.then(done, done);
12316
12805
  });
12317
12806
  }
12807
+ var SUMMARY_STOPWORDS = /* @__PURE__ */ new Set([
12808
+ "the",
12809
+ "and",
12810
+ "for",
12811
+ "with",
12812
+ "from",
12813
+ "that",
12814
+ "this",
12815
+ "into",
12816
+ "your",
12817
+ "you",
12818
+ "are",
12819
+ "was",
12820
+ "has",
12821
+ "how",
12822
+ "can",
12823
+ "will",
12824
+ "some",
12825
+ "any",
12826
+ "all"
12827
+ ]);
12318
12828
  function tokenizeForSummary(text) {
12319
- return new Set(
12320
- text.toLowerCase().split(/[^a-z0-9]+/).filter((w) => w.length >= 2)
12321
- );
12829
+ return new Set(tokenizeQuery(text).filter((t) => !SUMMARY_STOPWORDS.has(t)));
12322
12830
  }
12323
12831
  function computeToolOverlaps(connections) {
12324
12832
  const byName = /* @__PURE__ */ new Map();
@@ -12437,6 +12945,18 @@ var ConnectServer = class _ConnectServer {
12437
12945
  // Separate from the latch so a wrong entry stays re-askable while still
12438
12946
  // being bounded -- the pestering maybeElicitAndRetry exists to avoid.
12439
12947
  vaultPassphrasePrompts = 0;
12948
+ // The vault-passphrase elicitation currently in flight, if any. One vault,
12949
+ // one passphrase: prewarm activates three namespaces at a time, so without
12950
+ // this each locked-vault namespace in a batch opened its own modal for the
12951
+ // same question and the batch spent the whole
12952
+ // MAX_VAULT_PASSPHRASE_PROMPTS budget in a single round. Followers await
12953
+ // this instead of prompting. Cleared when the prompt settles.
12954
+ vaultElicitInflight = null;
12955
+ // How many times we have asked for a given NAMESPACE's missing child
12956
+ // credentials. Per-namespace (unlike the vault counter) because these are
12957
+ // the child's own secrets. Bounds the re-ask that replaced the old
12958
+ // "already elicited, never ask again" latch -- see MAX_CREDENTIAL_PROMPTS.
12959
+ credentialPrompts = /* @__PURE__ */ new Map();
12440
12960
  // In-flight activation promises, keyed by namespace. Dedupes
12441
12961
  // concurrent activation attempts for the same namespace so that two
12442
12962
  // tool calls landing on a disconnected upstream don't each spawn
@@ -12512,6 +13032,12 @@ var ConnectServer = class _ConnectServer {
12512
13032
  // field (not static) so tests can override per-instance without
12513
13033
  // poisoning other instances or re-importing the module.
12514
13034
  serverCap = resolveServerCap();
13035
+ // Delay before runActivateOne's single retry. One fixed step, not
13036
+ // exponential backoff. An instance field (not a literal at the call site)
13037
+ // purely so a test exercising the second attempt can set it to 0 rather
13038
+ // than spending a real second of wall time per case; production never
13039
+ // changes it.
13040
+ activationRetryDelayMs = 1e3;
12515
13041
  // Cross-session persistence state (learning + pack history).
12516
13042
  // `persistenceReady` gates the save path so unit tests — which
12517
13043
  // never call start() — don't write to ~/.yaw-mcp/state.json. The
@@ -12527,7 +13053,7 @@ var ConnectServer = class _ConnectServer {
12527
13053
  static SHUTDOWN_DRAIN_MS = 2e3;
12528
13054
  constructor() {
12529
13055
  this.server = new Server(
12530
- { name: "yaw-mcp", version: true ? "0.79.0" : "dev" },
13056
+ { name: "yaw-mcp", version: true ? "0.79.2" : "dev" },
12531
13057
  {
12532
13058
  capabilities: {
12533
13059
  tools: { listChanged: true },
@@ -12616,6 +13142,15 @@ var ConnectServer = class _ConnectServer {
12616
13142
  };
12617
13143
  onUpstreamListChanged = (ns) => {
12618
13144
  log("info", "Upstream list changed, rebuilding routes", { namespace: ns });
13145
+ const conn = this.connections.get(ns);
13146
+ if (conn?.status === "connected") {
13147
+ this.toolCache.set(
13148
+ ns,
13149
+ conn.tools.map((t) => ({ name: t.name, description: t.description }))
13150
+ );
13151
+ this.toolCacheLearnedAt.set(ns, Date.now());
13152
+ this.scheduleStateSave();
13153
+ }
12619
13154
  this.refreshRoutesAndNotify().catch((err) => {
12620
13155
  log("warn", "Failed to notify client of upstream list change", {
12621
13156
  namespace: ns,
@@ -12820,7 +13355,9 @@ var ConnectServer = class _ConnectServer {
12820
13355
  block: this.profile.blocked
12821
13356
  });
12822
13357
  }
12823
- this.installNudge = installNudgeEnabled(process.env, resolvedConfig);
13358
+ const rawNudge = process.env.YAW_MCP_INSTALL_NUDGE?.trim();
13359
+ const nudgeGateEnv = rawNudge === void 0 ? process.env : { ...process.env, YAW_MCP_INSTALL_NUDGE: rawNudge };
13360
+ this.installNudge = installNudgeEnabled(nudgeGateEnv, resolvedConfig);
12824
13361
  if (this.installNudge) {
12825
13362
  log("info", "Shadow-driven install nudge enabled");
12826
13363
  }
@@ -12852,7 +13389,7 @@ var ConnectServer = class _ConnectServer {
12852
13389
  serverCount: this.config.servers.length
12853
13390
  });
12854
13391
  await this.hydrateComplianceGrades();
12855
- if (this.config?.servers.some((s) => s.command !== void 0 && uvLaunchKind(s.command) !== null)) {
13392
+ if (this.getProfiledActiveServers().some((s) => s.command !== void 0 && uvLaunchKind(s.command) !== null)) {
12856
13393
  ensureUv().catch((err) => log("warn", "uv prewarm failed", { error: err?.message }));
12857
13394
  }
12858
13395
  const transport = new StdioServerTransport();
@@ -12893,6 +13430,7 @@ var ConnectServer = class _ConnectServer {
12893
13430
  const result = await this.activateOne(namespace);
12894
13431
  if (result.ok) {
12895
13432
  loaded.push(namespace);
13433
+ this.sessionActivated.add(namespace);
12896
13434
  } else {
12897
13435
  refused.push({ namespace, message: result.message });
12898
13436
  }
@@ -13058,6 +13596,7 @@ var ConnectServer = class _ConnectServer {
13058
13596
  let route = routes.get(name);
13059
13597
  if (route?.deferred) {
13060
13598
  const deferredNs = route.namespace;
13599
+ const joinedExisting = this.activationInflight.has(deferredNs) && !this.prewarmNamespaces.has(deferredNs);
13061
13600
  progress?.(`Loading "${deferredNs}" on first tools/call\u2026`);
13062
13601
  const activation = await this.activateOne(deferredNs, progress);
13063
13602
  if (!activation.ok) {
@@ -13071,7 +13610,11 @@ var ConnectServer = class _ConnectServer {
13071
13610
  isError: true
13072
13611
  });
13073
13612
  }
13074
- await this.refreshRoutesAndNotify();
13613
+ if (joinedExisting) {
13614
+ this.rebuildRoutes();
13615
+ } else {
13616
+ await this.refreshRoutesAndNotify();
13617
+ }
13075
13618
  routes = this.toolRoutes;
13076
13619
  route = routes.get(name);
13077
13620
  if (!route || route.deferred) {
@@ -13208,19 +13751,30 @@ var ConnectServer = class _ConnectServer {
13208
13751
  // names when nothing overlaps (the server scored on name/description,
13209
13752
  // not tools — still useful to surface the shape of what's available).
13210
13753
  // Used by the discover "Matches your query" summary only.
13754
+ //
13755
+ // NAME hits win over DESCRIPTION hits, and the whole list is collected
13756
+ // before the cap is applied. This is a bare set-intersection with no IDF
13757
+ // to flatten a common term (`queryTokens` already dropped the closed-class
13758
+ // words -- see tokenizeForSummary), so a term that survives can still be
13759
+ // common in prose: taking the first five in LIST order dropped a tool
13760
+ // whose NAME matched in favor of five earlier tools that merely mention
13761
+ // the word in their description.
13211
13762
  matchedToolNames(server, queryTokens) {
13212
13763
  const tools = this.rankableFor(server).tools;
13213
13764
  if (tools.length === 0) return [];
13214
- const hits = [];
13765
+ const nameHits = [];
13766
+ const descHits = [];
13215
13767
  for (const tool of tools) {
13216
13768
  const nameTokens = tool.name.toLowerCase().split(/[^a-z0-9]+/);
13217
- const descTokens = (tool.description ?? "").toLowerCase().split(/[^a-z0-9]+/);
13218
- if (nameTokens.some((t) => queryTokens.has(t)) || descTokens.some((t) => queryTokens.has(t))) {
13219
- hits.push(tool.name);
13220
- if (hits.length >= 5) break;
13769
+ if (nameTokens.some((t) => queryTokens.has(t))) {
13770
+ nameHits.push(tool.name);
13771
+ continue;
13221
13772
  }
13773
+ const descTokens = (tool.description ?? "").toLowerCase().split(/[^a-z0-9]+/);
13774
+ if (descTokens.some((t) => queryTokens.has(t))) descHits.push(tool.name);
13222
13775
  }
13223
- if (hits.length > 0) return hits;
13776
+ const hits = [...nameHits, ...descHits];
13777
+ if (hits.length > 0) return hits.slice(0, 5);
13224
13778
  return tools.slice(0, 3).map((t) => t.name);
13225
13779
  }
13226
13780
  rankableFor(server) {
@@ -13315,8 +13869,8 @@ var ConnectServer = class _ConnectServer {
13315
13869
  };
13316
13870
  }
13317
13871
  // Drop the memoized discover body. The cache key only covers
13318
- // (configVersion, context, warmedNamespace, connected set, tool filters),
13319
- // so state that
13872
+ // (configVersion, context, warmedNamespace, connected set, tool filters,
13873
+ // advertised set), so state that
13320
13874
  // discover RENDERS but the key does not see -- activation failures
13321
13875
  // (formatHealthWarning) and learning counters (usage:/reliability: lines)
13322
13876
  // -- has to invalidate explicitly. Without this the exact case the cache
@@ -13328,7 +13882,8 @@ var ConnectServer = class _ConnectServer {
13328
13882
  discoverCacheKey(context, warmedNamespace) {
13329
13883
  const activeNamespaces = [...this.connections.entries()].filter(([, c]) => c.status === "connected").map(([ns]) => ns).sort().join(",");
13330
13884
  const filterSignature = [...this.toolFilters.entries()].map(([ns, names]) => `${ns}:${[...names].sort().join("+")}`).sort().join(";");
13331
- return `${this.configVersion ?? ""}|${context ?? ""}|${warmedNamespace ?? ""}|${activeNamespaces}|${filterSignature}`;
13885
+ const advertisedSignature = [...this.sessionActivated].sort().join(",");
13886
+ return `${this.configVersion ?? ""}|${context ?? ""}|${warmedNamespace ?? ""}|${activeNamespaces}|${filterSignature}|${advertisedSignature}`;
13332
13887
  }
13333
13888
  buildDiscoverOutput(context, warmedNamespace) {
13334
13889
  const key = this.discoverCacheKey(context, warmedNamespace);
@@ -13395,9 +13950,9 @@ var ConnectServer = class _ConnectServer {
13395
13950
  lines.push("");
13396
13951
  }
13397
13952
  }
13398
- const chains = this.packDetector.detectChains();
13399
- const coUsageMap = buildCoUsageMap(chains);
13400
13953
  const installedNamespaces = new Set(activeServers.map((s) => s.namespace));
13954
+ const chains = this.packDetector.detectChains();
13955
+ const coUsageMap = buildCoUsageMap(chains, installedNamespaces);
13401
13956
  const connectedNamespaces = new Set(
13402
13957
  [...this.connections.entries()].filter(([, c]) => c.status === "connected").map(([ns]) => ns)
13403
13958
  );
@@ -13413,6 +13968,8 @@ var ConnectServer = class _ConnectServer {
13413
13968
  }
13414
13969
  lines.push("");
13415
13970
  }
13971
+ const exposure = resolveToolExposure();
13972
+ const isAdvertised = (namespace) => exposure === "full" || this.sessionActivated.has(namespace);
13416
13973
  let totalContextTokens = 0;
13417
13974
  for (const server of sorted) {
13418
13975
  const connection = this.connections.get(server.namespace);
@@ -13420,7 +13977,7 @@ var ConnectServer = class _ConnectServer {
13420
13977
  const total = connection?.tools.length ?? 0;
13421
13978
  const exposed = connection ? filter ? connection.tools.filter((t) => filter.has(t.name)).length : total : 0;
13422
13979
  const filterSuffix = connection && filter ? ` (filtered: ${exposed} of ${total})` : "";
13423
- const status = connection ? connection.status === "error" ? "ERROR (disconnected, will auto-reconnect on use)" : `loaded (${exposed} tools)${filterSuffix}` : "ready";
13980
+ const status = connection ? connection.status === "error" ? "ERROR (disconnected, will auto-reconnect on use)" : isAdvertised(server.namespace) ? `loaded (${exposed} tools)${filterSuffix}` : "connected (not advertised \u2014 activate to expose)" : "ready";
13424
13981
  const score = scores.get(server.namespace);
13425
13982
  const relevance = score && score > 0 ? ` (relevance: ${score.toFixed(2)})` : "";
13426
13983
  let costLabel = "";
@@ -13428,7 +13985,7 @@ var ConnectServer = class _ConnectServer {
13428
13985
  const visible = filter ? connection.tools.filter((t) => filter.has(t.name)) : connection.tools;
13429
13986
  if (visible.length > 0) {
13430
13987
  const sample = estimateFromConnectedTools(visible);
13431
- totalContextTokens += sample.tokens;
13988
+ if (isAdvertised(server.namespace)) totalContextTokens += sample.tokens;
13432
13989
  costLabel = ` \u2014 ${formatCostLabel(sample)}`;
13433
13990
  }
13434
13991
  } else {
@@ -13477,7 +14034,7 @@ var ConnectServer = class _ConnectServer {
13477
14034
  lines.push(` ${o.bareName} \u2014 available in: ${o.namespaces.join(", ")}${suffix}`);
13478
14035
  }
13479
14036
  }
13480
- const allInstalled = this.getProfiledActiveServers().map((s) => s.namespace);
14037
+ const allInstalled = activeServers.map((s) => s.namespace);
13481
14038
  const bundleGaps = topPartialBundles(allInstalled, 3);
13482
14039
  if (bundleGaps.length > 0) {
13483
14040
  lines.push("\nBundle completions (install to unlock curated stacks):");
@@ -13495,7 +14052,9 @@ var ConnectServer = class _ConnectServer {
13495
14052
  lines.push(...this.buildInstallCandidatesLines(activeServers));
13496
14053
  const activeCount = Array.from(this.connections.values()).filter((c) => c.status === "connected").length;
13497
14054
  const totalTools = Array.from(this.connections.values()).reduce((sum, c) => {
13498
- const f = this.toolFilters.get(c.config.namespace);
14055
+ const ns = c.config.namespace;
14056
+ if (c.status !== "connected" || !isAdvertised(ns)) return sum;
14057
+ const f = this.toolFilters.get(ns);
13499
14058
  return sum + (f ? c.tools.filter((t) => f.has(t.name)).length : c.tools.length);
13500
14059
  }, 0);
13501
14060
  const tokenSummary = totalContextTokens > 0 ? ` (~${totalContextTokens.toLocaleString()} tokens)` : "";
@@ -13602,10 +14161,10 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
13602
14161
  }
13603
14162
  }
13604
14163
  }
13605
- const inflight = this.activationInflight.get(namespace);
13606
- if (inflight) {
14164
+ const inflight2 = this.activationInflight.get(namespace);
14165
+ if (inflight2) {
13607
14166
  progress?.(`"${namespace}" load already in flight \u2014 awaiting existing attempt`);
13608
- return inflight;
14167
+ return inflight2;
13609
14168
  }
13610
14169
  if (fromPrewarm) {
13611
14170
  this.prewarmNamespaces.add(namespace);
@@ -13664,7 +14223,46 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
13664
14223
  }
13665
14224
  return evaluateServerCap(namespace, loadedSlots, this.serverCap);
13666
14225
  }
13667
- async runActivateOne(namespace, progress, fromPrewarm = false) {
14226
+ // The policy gates every SPAWN path shares, in one place and one order:
14227
+ // disabled, then project profile, then the YAW_MCP_MIN_COMPLIANCE floor.
14228
+ // Returns the refusal text, or null when the server clears all three.
14229
+ //
14230
+ // Both callers -- runActivateOne (persistent activation) and handleReadTool
14231
+ // (transient inspect) -- actually execute the server's configured command
14232
+ // with its resolved env, so "we disconnect afterwards" buys read_tool no
14233
+ // exemption. They used to carry line-for-line copies of this block, which
14234
+ // meant a policy change had to land twice to stay consistent. `purpose`
14235
+ // supplies the only words that legitimately differ: what the caller was
14236
+ // about to do with the server once it started.
14237
+ spawnGateRefusal(server, purpose) {
14238
+ if (!server.isActive) {
14239
+ return `"${server.namespace}" is installed but disabled. Set "isActive": true for it in ~/.yaw-mcp/bundles.json and restart this MCP client to ${purpose}.`;
14240
+ }
14241
+ if (!profileAllows(this.profile, server.namespace)) {
14242
+ return `"${server.namespace}" is not allowed by the project profile at ${this.profile?.path}.`;
14243
+ }
14244
+ const minCompliance = resolveMinCompliance();
14245
+ if (minCompliance !== null && !passesMinCompliance(server.complianceGrade, minCompliance)) {
14246
+ return `Refused to load "${server.namespace}": ${complianceRefusalReason(server.complianceGrade, minCompliance)}. Unset YAW_MCP_MIN_COMPLIANCE (or lower it) to override.`;
14247
+ }
14248
+ return null;
14249
+ }
14250
+ // `skipCap` is for the post-elicitation retry only: that caller is already
14251
+ // inside this namespace's own activation, holding its pendingActivations
14252
+ // reservation, and the user has just typed a credential. evaluateCapFor
14253
+ // deliberately does NOT grant a self-allowance for a pending reservation
14254
+ // (see its "skip self" comment), so a re-check there could refuse the
14255
+ // retry because OTHER namespaces filled the cap while the modal was open --
14256
+ // credentials typed, slot gone, nothing to show for it.
14257
+ //
14258
+ // `isElicitRetry` marks the ONE re-entry maybeElicitAndRetry makes after the
14259
+ // user typed credentials. It exists to stop that re-entry eliciting again:
14260
+ // the prompt budget is per namespace, not per activate, so a child that
14261
+ // keeps reporting the same key missing would otherwise open a second,
14262
+ // byte-identical modal inside the same activate call -- spending the whole
14263
+ // budget (and three spawn attempts plus their retry sleeps) before the user
14264
+ // has any chance to go fix the value somewhere else.
14265
+ async runActivateOne(namespace, progress, fromPrewarm = false, skipCap = false, isElicitRetry = false) {
13668
14266
  const existing = this.connections.get(namespace);
13669
14267
  if (existing && existing.status === "connected") {
13670
14268
  progress?.(`"${namespace}" already loaded`);
@@ -13682,30 +14280,12 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
13682
14280
  const hint = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(", ")}?` : " Use mcp_connect_discover to see installed servers.";
13683
14281
  return { ok: false, isChanged: false, message: `"${namespace}" is not installed.${hint}` };
13684
14282
  }
13685
- if (!anyMatch.isActive) {
13686
- return {
13687
- ok: false,
13688
- isChanged: false,
13689
- message: `"${namespace}" is installed but disabled. Set "isActive": true for it in ~/.yaw-mcp/bundles.json and restart this MCP client to activate.`
13690
- };
13691
- }
13692
14283
  const serverConfig = anyMatch;
13693
- if (!profileAllows(this.profile, namespace)) {
13694
- return {
13695
- ok: false,
13696
- isChanged: false,
13697
- message: `"${namespace}" is not allowed by the project profile at ${this.profile?.path}.`
13698
- };
14284
+ const gateRefusal = this.spawnGateRefusal(serverConfig, "activate");
14285
+ if (gateRefusal) {
14286
+ return { ok: false, isChanged: false, message: gateRefusal };
13699
14287
  }
13700
- const minCompliance = resolveMinCompliance();
13701
- if (minCompliance !== null && !passesMinCompliance(serverConfig.complianceGrade, minCompliance)) {
13702
- return {
13703
- ok: false,
13704
- isChanged: false,
13705
- message: `Refused to load "${namespace}": ${complianceRefusalReason(serverConfig.complianceGrade, minCompliance)}. Unset YAW_MCP_MIN_COMPLIANCE (or lower it) to override.`
13706
- };
13707
- }
13708
- if (!fromPrewarm) {
14288
+ if (!fromPrewarm && !skipCap) {
13709
14289
  const capDecision = this.evaluateCapFor(namespace);
13710
14290
  if (!capDecision.allow) {
13711
14291
  return {
@@ -13753,11 +14333,11 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
13753
14333
  if (attempt === 0) {
13754
14334
  const msg = err instanceof Error ? err.message : String(err);
13755
14335
  log("warn", "Activation attempt failed, retrying", { namespace, error: msg });
13756
- await new Promise((r) => setTimeout(r, 1e3 * 2 ** attempt));
14336
+ await new Promise((r) => setTimeout(r, this.activationRetryDelayMs));
13757
14337
  }
13758
14338
  }
13759
14339
  }
13760
- const elicitedRetry = await this.maybeElicitAndRetry(namespace, lastError, progress, fromPrewarm);
14340
+ const elicitedRetry = await this.maybeElicitAndRetry(namespace, lastError, progress, fromPrewarm, isElicitRetry);
13761
14341
  if (elicitedRetry) return elicitedRetry;
13762
14342
  log("error", "Failed to activate upstream", {
13763
14343
  namespace,
@@ -13779,7 +14359,7 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
13779
14359
  // the values inline and retry activation once. Returns the retry result
13780
14360
  // on success, or null when we can't/shouldn't elicit. Single-round only —
13781
14361
  // we don't want to pester the user with a loop on every retry failure.
13782
- async maybeElicitAndRetry(namespace, lastError, progress, fromPrewarm = false) {
14362
+ async maybeElicitAndRetry(namespace, lastError, progress, fromPrewarm = false, isElicitRetry = false) {
13783
14363
  if (lastError instanceof VaultPassphraseRequiredError) {
13784
14364
  return this.elicitVaultPassphraseAndRetry(namespace, lastError, progress, fromPrewarm);
13785
14365
  }
@@ -13788,8 +14368,34 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
13788
14368
  const haystack = [stderr, errMessage].filter(Boolean).join("\n");
13789
14369
  const missing = detectMissingCredentials(haystack).filter((k) => !INTERNAL_SECRET_ENV_KEYS.has(k.toUpperCase()));
13790
14370
  if (missing.length === 0) return null;
13791
- const alreadyElicited = this.elicitedEnv.get(namespace);
13792
- if (alreadyElicited && missing.every((k) => k in alreadyElicited)) return null;
14371
+ const supplied = this.elicitedEnv.get(namespace) ?? {};
14372
+ if (isElicitRetry && missing.every((k) => k in supplied)) {
14373
+ log("info", "Credentials still missing after the elicited retry \u2014 not re-asking inside the same activation", {
14374
+ namespace,
14375
+ missing
14376
+ });
14377
+ this.activationFailures.set(namespace, {
14378
+ at: Date.now(),
14379
+ message: lastError instanceof Error ? lastError.message : String(lastError)
14380
+ });
14381
+ this.invalidateDiscoverCache();
14382
+ const promptsSoFar = this.credentialPrompts.get(namespace) ?? 0;
14383
+ const retryHint = promptsSoFar >= MAX_CREDENTIAL_PROMPTS ? ` No further prompts for "${namespace}" this session: set ${missing.join(", ")} in its "env" in ~/.yaw-mcp/bundles.json and restart this MCP client.` : ` Activate "${namespace}" again to try new ones.`;
14384
+ return {
14385
+ ok: false,
14386
+ isChanged: false,
14387
+ message: `Could not load "${namespace}": it still reports ${missing.join(", ")} missing, so the values just provided were not accepted.${retryHint}`
14388
+ };
14389
+ }
14390
+ const asked = this.credentialPrompts.get(namespace) ?? 0;
14391
+ if (asked >= MAX_CREDENTIAL_PROMPTS) {
14392
+ log("info", "Missing credentials persist after the prompt budget; not asking again", {
14393
+ namespace,
14394
+ missing,
14395
+ prompts: asked
14396
+ });
14397
+ return null;
14398
+ }
13793
14399
  const caps = this.server.getClientCapabilities();
13794
14400
  if (!caps?.elicitation) {
13795
14401
  log("info", "Detected missing credentials but client does not support elicitation", {
@@ -13807,6 +14413,7 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
13807
14413
  };
13808
14414
  }
13809
14415
  progress?.(`Asking for ${missing.length === 1 ? "credential" : "credentials"}: ${missing.join(", ")}`);
14416
+ this.credentialPrompts.set(namespace, asked + 1);
13810
14417
  let result;
13811
14418
  try {
13812
14419
  result = await this.server.elicitInput({
@@ -13834,9 +14441,17 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
13834
14441
  if (typeof v === "string" && v.length > 0) values[key] = v;
13835
14442
  }
13836
14443
  if (Object.keys(values).length === 0) return null;
13837
- this.elicitedEnv.set(namespace, { ...alreadyElicited, ...values });
14444
+ this.elicitedEnv.set(namespace, { ...supplied, ...values });
13838
14445
  progress?.("Got credentials \u2014 retrying load");
13839
- return this.runActivateOne(namespace, progress, fromPrewarm);
14446
+ return this.runActivateOne(
14447
+ namespace,
14448
+ progress,
14449
+ fromPrewarm,
14450
+ /* skipCap */
14451
+ true,
14452
+ /* isElicitRetry */
14453
+ true
14454
+ );
13840
14455
  }
13841
14456
  // The vault-passphrase counterpart to maybeElicitAndRetry. Split out
13842
14457
  // rather than folded in because almost nothing about the generic path
@@ -13852,7 +14467,26 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
13852
14467
  // rejected without ever becoming the session passphrase, and the user gets
13853
14468
  // MAX_VAULT_PASSPHRASE_PROMPTS tries in total across every server. A
13854
14469
  // decline still ends it immediately -- that is an answer, not a typo.
14470
+ //
14471
+ // Concurrency: the prompt itself is deduped through vaultElicitInflight.
14472
+ // Prewarm runs three activations at once, so several namespaces can reach a
14473
+ // locked vault in the same instant -- and they are all asking the ONE
14474
+ // question this vault has. Followers await the winner's prompt instead of
14475
+ // opening a second modal for it.
13855
14476
  async elicitVaultPassphraseAndRetry(namespace, lastError, progress, fromPrewarm = false) {
14477
+ const joined = this.vaultElicitInflight;
14478
+ if (joined) {
14479
+ progress?.("Waiting for the vault passphrase prompt already in flight");
14480
+ const outcome2 = await joined;
14481
+ if (outcome2 !== "unlocked") return null;
14482
+ return this.runActivateOne(
14483
+ namespace,
14484
+ progress,
14485
+ fromPrewarm,
14486
+ /* skipCap */
14487
+ true
14488
+ );
14489
+ }
13856
14490
  if (this.vaultPassphraseElicited) return null;
13857
14491
  const caps = this.server.getClientCapabilities();
13858
14492
  if (!caps?.elicitation) {
@@ -13863,6 +14497,42 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
13863
14497
  });
13864
14498
  return null;
13865
14499
  }
14500
+ const prompt = this.promptForVaultPassphrase(namespace, lastError, progress);
14501
+ this.vaultElicitInflight = prompt;
14502
+ let outcome;
14503
+ try {
14504
+ outcome = await prompt;
14505
+ } finally {
14506
+ if (this.vaultElicitInflight === prompt) this.vaultElicitInflight = null;
14507
+ }
14508
+ if (outcome === "unlocked") {
14509
+ progress?.("Got the passphrase -- retrying load");
14510
+ return this.runActivateOne(
14511
+ namespace,
14512
+ progress,
14513
+ fromPrewarm,
14514
+ /* skipCap */
14515
+ true
14516
+ );
14517
+ }
14518
+ if (outcome === "rejected") {
14519
+ const retryHint = this.vaultPassphraseElicited ? " No further prompts this session: set YAW_MCP_VAULT_PASSPHRASE in yaw-mcp's own env and restart this MCP client." : ` Activate "${namespace}" again to try another passphrase.`;
14520
+ return {
14521
+ ok: false,
14522
+ isChanged: false,
14523
+ message: `Could not load "${namespace}": the passphrase entered does not unlock your local secret vault, which its env (${lastError.refKeys.join(", ")}) references.${retryHint}`
14524
+ };
14525
+ }
14526
+ return null;
14527
+ }
14528
+ // The prompt half of the vault path, split out so concurrent callers can
14529
+ // await ONE of them (see vaultElicitInflight). Owns the ask budget, the
14530
+ // latch, verification, and storing the verified value; tells the caller
14531
+ // which of the three things happened, because they need different words:
14532
+ // "unlocked" -- verified and stored; retry the activation.
14533
+ // "rejected" -- the user typed a passphrase and it did not verify.
14534
+ // "unavailable" -- declined, empty, or the elicitation request failed.
14535
+ async promptForVaultPassphrase(namespace, lastError, progress) {
13866
14536
  this.vaultPassphrasePrompts++;
13867
14537
  if (this.vaultPassphrasePrompts >= MAX_VAULT_PASSPHRASE_PROMPTS) this.vaultPassphraseElicited = true;
13868
14538
  progress?.("Vault is locked -- asking for the passphrase");
@@ -13888,27 +14558,26 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
13888
14558
  namespace,
13889
14559
  error: err instanceof Error ? err.message : String(err)
13890
14560
  });
13891
- return null;
14561
+ return "unavailable";
13892
14562
  }
13893
14563
  if (result.action !== "accept" || !result.content) {
13894
14564
  this.vaultPassphraseElicited = true;
13895
14565
  log("info", "User declined vault passphrase elicitation", { namespace, action: result.action });
13896
- return null;
14566
+ return "unavailable";
13897
14567
  }
13898
14568
  const value = result.content.YAW_MCP_VAULT_PASSPHRASE;
13899
- if (typeof value !== "string" || value.length === 0) return null;
14569
+ if (typeof value !== "string" || value.length === 0) return "unavailable";
13900
14570
  if (!await verifyVaultPassphrase(value)) {
13901
14571
  log("info", "Elicited vault passphrase did not unlock the vault", {
13902
14572
  namespace,
13903
14573
  attempt: this.vaultPassphrasePrompts
13904
14574
  });
13905
14575
  progress?.("That passphrase did not unlock the vault");
13906
- return null;
14576
+ return "rejected";
13907
14577
  }
13908
14578
  setSessionVaultPassphrase(value);
13909
14579
  this.vaultPassphraseElicited = true;
13910
- progress?.("Got the passphrase -- retrying load");
13911
- return this.runActivateOne(namespace, progress, fromPrewarm);
14580
+ return "unlocked";
13912
14581
  }
13913
14582
  async handleActivate(namespaces, progress, toolsFilter) {
13914
14583
  if (namespaces.length === 0) {
@@ -14131,6 +14800,23 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
14131
14800
  isError: anyError || anyCapped && !anyChanged ? true : void 0
14132
14801
  };
14133
14802
  }
14803
+ // Drop every per-namespace bit of session state after its connection has
14804
+ // been closed. Called by BOTH teardown sites -- explicit deactivate and the
14805
+ // idle reaper -- which used to carry identical copies of this list, so a
14806
+ // new piece of per-namespace state had to be remembered in two places to
14807
+ // avoid leaking into the next load of the same server.
14808
+ //
14809
+ // Deliberately NOT cleared here: toolCache / toolCacheLearnedAt (what the
14810
+ // server offers survives an unload -- that is what makes it deferred
14811
+ // rather than invisible), activationFailures (a health signal with its own
14812
+ // TTL), and learning counters (cross-session by design).
14813
+ forgetNamespace(namespace) {
14814
+ this.connections.delete(namespace);
14815
+ this.idleCallCounts.delete(namespace);
14816
+ this.adaptiveSkipLogged.delete(namespace);
14817
+ this.toolFilters.delete(namespace);
14818
+ this.sessionActivated.delete(namespace);
14819
+ }
14134
14820
  async handleDeactivate(namespaces) {
14135
14821
  if (namespaces.length === 0) {
14136
14822
  return {
@@ -14146,12 +14832,16 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
14146
14832
  results.push(`"${namespace}" wasn't loaded.`);
14147
14833
  continue;
14148
14834
  }
14835
+ const inflight2 = this.inflightCalls.get(namespace) ?? 0;
14836
+ if (inflight2 > 0) {
14837
+ log("info", "Skipping deactivation \u2014 tool call in flight", { namespace, inflight: inflight2 });
14838
+ results.push(
14839
+ `"${namespace}" still has ${inflight2} tool call${inflight2 === 1 ? "" : "s"} in flight \u2014 not unloaded. Call mcp_connect_deactivate again once they finish.`
14840
+ );
14841
+ continue;
14842
+ }
14149
14843
  await disconnectFromUpstream(connection);
14150
- this.connections.delete(namespace);
14151
- this.idleCallCounts.delete(namespace);
14152
- this.adaptiveSkipLogged.delete(namespace);
14153
- this.toolFilters.delete(namespace);
14154
- this.sessionActivated.delete(namespace);
14844
+ this.forgetNamespace(namespace);
14155
14845
  anyChanged = true;
14156
14846
  results.push(`Unloaded "${namespace}". Tools removed from context.`);
14157
14847
  }
@@ -14220,11 +14910,7 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
14220
14910
  }
14221
14911
  log("info", "Auto-deactivating idle server", { namespace: ns, idleCalls: this.idleCallCounts.get(ns) });
14222
14912
  await disconnectFromUpstream(connection);
14223
- this.connections.delete(ns);
14224
- this.idleCallCounts.delete(ns);
14225
- this.adaptiveSkipLogged.delete(ns);
14226
- this.toolFilters.delete(ns);
14227
- this.sessionActivated.delete(ns);
14913
+ this.forgetNamespace(ns);
14228
14914
  deactivated++;
14229
14915
  }
14230
14916
  if (deactivated > 0) {
@@ -14269,39 +14955,9 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
14269
14955
  isError: true
14270
14956
  };
14271
14957
  }
14272
- if (!serverConfig.isActive) {
14273
- return {
14274
- content: [
14275
- {
14276
- type: "text",
14277
- text: `"${serverArg}" is installed but disabled. Set "isActive": true for it in ~/.yaw-mcp/bundles.json and restart this MCP client to inspect its tools.`
14278
- }
14279
- ],
14280
- isError: true
14281
- };
14282
- }
14283
- if (!profileAllows(this.profile, serverArg)) {
14284
- return {
14285
- content: [
14286
- {
14287
- type: "text",
14288
- text: `"${serverArg}" is not allowed by the project profile at ${this.profile?.path}.`
14289
- }
14290
- ],
14291
- isError: true
14292
- };
14293
- }
14294
- const minCompliance = resolveMinCompliance();
14295
- if (minCompliance !== null && !passesMinCompliance(serverConfig.complianceGrade, minCompliance)) {
14296
- return {
14297
- content: [
14298
- {
14299
- type: "text",
14300
- text: `Refused to load "${serverArg}": ${complianceRefusalReason(serverConfig.complianceGrade, minCompliance)}. Unset YAW_MCP_MIN_COMPLIANCE (or lower it) to override.`
14301
- }
14302
- ],
14303
- isError: true
14304
- };
14958
+ const gateRefusal = this.spawnGateRefusal(serverConfig, "inspect its tools");
14959
+ if (gateRefusal) {
14960
+ return { content: [{ type: "text", text: gateRefusal }], isError: true };
14305
14961
  }
14306
14962
  const existing = this.connections.get(serverArg);
14307
14963
  if (existing && existing.status === "connected") {
@@ -14329,7 +14985,7 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
14329
14985
  const transientConfig = elicitedForTransient ? { ...serverConfig, env: { ...serverConfig.env, ...elicitedForTransient } } : serverConfig;
14330
14986
  transient = await connectToUpstream(transientConfig, void 0, void 0, this.clientBridge);
14331
14987
  } catch (err) {
14332
- const message = err instanceof ActivationError ? err.message : err instanceof Error ? err.message : String(err);
14988
+ const message = err instanceof Error ? err.message : String(err);
14333
14989
  return {
14334
14990
  content: [
14335
14991
  {
@@ -14378,6 +15034,11 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
14378
15034
  if (serverArg) servers = servers.filter((s) => s.namespace === serverArg);
14379
15035
  const rows = computeSecretsReport(servers, vaultKeys);
14380
15036
  if (serverArg && servers.length === 0) {
15037
+ const configured = this.config?.servers.find((s) => s.namespace === serverArg);
15038
+ if (configured) {
15039
+ const refusal = this.spawnGateRefusal(configured, "inspect its tools") ?? `"${serverArg}" is installed but not visible to this report.`;
15040
+ return { content: [{ type: "text", text: refusal }], isError: true };
15041
+ }
14381
15042
  return {
14382
15043
  content: [
14383
15044
  {
@@ -14443,7 +15104,9 @@ ${activeCount} loaded in this session, ${totalTools} tools in context${tokenSumm
14443
15104
  5
14444
15105
  );
14445
15106
  if (flaky.length > 0) {
14446
- lines.push("\nCross-session reliability (dormant, <80% success):");
15107
+ const flakyPct = Math.round(PENALTY_RATE_THRESHOLD * 100);
15108
+ lines.push(`
15109
+ Cross-session reliability (dormant, <${flakyPct}% success):`);
14447
15110
  for (const { namespace, usage } of flaky) {
14448
15111
  const rate = Math.round(usage.succeeded / usage.dispatched * 100);
14449
15112
  const age = formatRelativeAge(now - usage.lastUsedAt);
@@ -14597,41 +15260,60 @@ To load the top pack in one step, call \`mcp_connect_activate\` with namespaces=
14597
15260
  args: s.args ?? {}
14598
15261
  }));
14599
15262
  const explicitReturn = typeof args.return === "string" ? args.return : void 0;
15263
+ for (let i = 0; i < steps.length; i++) {
15264
+ const step = steps[i];
15265
+ if (!META_TOOL_NAMES.has(step.tool)) continue;
15266
+ const key = stepBindingKey(step, i);
15267
+ return {
15268
+ content: [
15269
+ {
15270
+ type: "text",
15271
+ text: `exec: step "${key}": meta-tool "${step.tool}" cannot be called from exec; call it directly`
15272
+ }
15273
+ ],
15274
+ isError: true
15275
+ };
15276
+ }
15277
+ const refCheck = validateExecRefs(steps);
15278
+ if (!refCheck.ok) {
15279
+ return {
15280
+ content: [{ type: "text", text: `exec: ${refCheck.message}` }],
15281
+ isError: true
15282
+ };
15283
+ }
14600
15284
  const bindings = {};
14601
15285
  const stepKeys = [];
14602
15286
  const stepNamespaces = /* @__PURE__ */ new Map();
14603
15287
  const touchedNamespaces = /* @__PURE__ */ new Set();
15288
+ const pinned = /* @__PURE__ */ new Set();
15289
+ const pinNamespace = (ns) => {
15290
+ if (pinned.has(ns)) return;
15291
+ pinned.add(ns);
15292
+ this.inflightCalls.set(ns, (this.inflightCalls.get(ns) ?? 0) + 1);
15293
+ };
15294
+ const releasePins = () => {
15295
+ for (const ns of pinned) {
15296
+ const remaining = (this.inflightCalls.get(ns) ?? 1) - 1;
15297
+ if (remaining > 0) this.inflightCalls.set(ns, remaining);
15298
+ else this.inflightCalls.delete(ns);
15299
+ }
15300
+ pinned.clear();
15301
+ };
14604
15302
  const settleIdleTracking = async () => {
15303
+ releasePins();
14605
15304
  if (touchedNamespaces.size === 0) return;
14606
15305
  const used = [...touchedNamespaces];
14607
15306
  touchedNamespaces.clear();
14608
15307
  await this.trackUsageForNamespaces(used);
14609
15308
  };
15309
+ for (const step of steps) {
15310
+ const ns = this.toolRoutes.get(step.tool)?.namespace;
15311
+ if (ns) pinNamespace(ns);
15312
+ }
14610
15313
  for (let i = 0; i < steps.length; i++) {
14611
15314
  const step = steps[i];
14612
15315
  const key = stepBindingKey(step, i);
14613
15316
  stepKeys.push(key);
14614
- if (META_TOOL_NAMES.has(step.tool)) {
14615
- await settleIdleTracking();
14616
- return {
14617
- content: [
14618
- {
14619
- type: "text",
14620
- text: JSON.stringify(
14621
- {
14622
- ok: false,
14623
- failedStep: key,
14624
- error: `step "${key}": meta-tool "${step.tool}" cannot be called from exec; call it directly`,
14625
- partial: bindings
14626
- },
14627
- null,
14628
- 2
14629
- )
14630
- }
14631
- ],
14632
- isError: true
14633
- };
14634
- }
14635
15317
  let resolvedArgs;
14636
15318
  try {
14637
15319
  const resolved = resolveArgs(step.args, bindings);
@@ -14684,11 +15366,18 @@ To load the top pack in one step, call \`mcp_connect_activate\` with namespaces=
14684
15366
  if (stepNs) {
14685
15367
  stepNamespaces.set(key, stepNs);
14686
15368
  touchedNamespaces.add(stepNs);
15369
+ pinNamespace(stepNs);
15370
+ }
15371
+ let stepResult;
15372
+ try {
15373
+ stepResult = await this.handleToolCall(step.tool, resolvedArgs, void 0, {
15374
+ deferLearning: true,
15375
+ deferIdleTracking: true
15376
+ });
15377
+ } catch (err) {
15378
+ await settleIdleTracking();
15379
+ throw err;
14687
15380
  }
14688
- const stepResult = await this.handleToolCall(step.tool, resolvedArgs, void 0, {
14689
- deferLearning: true,
14690
- deferIdleTracking: true
14691
- });
14692
15381
  if (stepResult.isError) {
14693
15382
  const errText = stepResult.content?.[0]?.text ?? "unknown error";
14694
15383
  const routingFault = isRoutingFaultResult(stepResult);
@@ -14851,17 +15540,14 @@ var SERVERS_DEPRECATED_MESSAGE = "yaw-mcp servers: account mode has been removed
14851
15540
  async function runServersCommand(opts = {}) {
14852
15541
  const write = opts.out ?? ((s) => process.stdout.write(s));
14853
15542
  const writeErr = opts.err ?? ((s) => process.stderr.write(s));
14854
- const lines = [];
14855
- lines.push(SERVERS_DEPRECATED_MESSAGE);
14856
15543
  writeErr(`${SERVERS_DEPRECATED_MESSAGE}
14857
15544
  `);
14858
15545
  if (opts.json) {
14859
15546
  const payload = JSON.stringify({ ok: false, deprecated: true, error: SERVERS_DEPRECATED_MESSAGE });
14860
- lines.push(payload);
14861
15547
  write(`${payload}
14862
15548
  `);
14863
15549
  }
14864
- return { exitCode: 1, lines };
15550
+ return { exitCode: 1 };
14865
15551
  }
14866
15552
 
14867
15553
  // src/subcommands.ts
@@ -15143,12 +15829,28 @@ if (subcommand === "compliance") {
15143
15829
  MCP elicitation prompts for it instead, for
15144
15830
  that session only. Manage entries with
15145
15831
  \`yaw-mcp secrets\`.
15832
+ YAW_MCP_VAULT_PASSPHRASE_NEW The NEW passphrase for \`yaw-mcp secrets
15833
+ rotate\`, so a re-wrap can run without a TTY.
15834
+ Read only by \`rotate\`; without it (and
15835
+ without a TTY to confirm on) rotate fails
15836
+ rather than picking one for you.
15146
15837
  YAW_MCP_TRUST_PROJECT Set to \`1\` to skip the consent check on a
15147
15838
  project-local .yaw-mcp/bundles.json and load
15148
15839
  it unconditionally. FOR CI/AUTOMATION ONLY --
15149
15840
  it lets any repo you run yaw-mcp inside spawn
15150
15841
  arbitrary commands as you. Default: the file
15151
15842
  must be approved with \`yaw-mcp trust\`.
15843
+ YAW_MCP_ALLOW_UNOWNED_PROJECT_DIRS
15844
+ Set to \`1\` to accept a .yaw-mcp/ directory
15845
+ found outside $HOME whose owner cannot be
15846
+ verified (every win32 checkout, since there
15847
+ is no cheap ownership probe there). FOR
15848
+ CI/AUTOMATION ONLY -- an unowned directory
15849
+ on a writable volume lets a third party
15850
+ inject YAW-MCP.md guidance into your model
15851
+ context and apply config.json allow/block
15852
+ lists. Default: such candidates are skipped
15853
+ with a warning.
15152
15854
  YAW_MCP_DISABLE_PERSISTENCE Disable cross-session learning state.
15153
15855
  YAW_MCP_FOUNDRY Set to \`1\` to OPT IN to harvesting dispatch
15154
15856
  traces to ~/.yaw-mcp/foundry.jsonl for routing
@@ -15177,6 +15879,24 @@ if (subcommand === "compliance") {
15177
15879
  MCP_LIST_TIMEOUT Milliseconds to wait for a server's tool/
15178
15880
  resource/prompt inventory calls after the
15179
15881
  handshake (default 15000).
15882
+ MCP_CALL_TIMEOUT Milliseconds to wait for a single proxied
15883
+ tools/call (default 60000, the SDK's own
15884
+ bound) -- the last leg of a request that had
15885
+ no override. Raise it for a server that is
15886
+ legitimately slow (browser automation, a
15887
+ large query, a cold first call): a timeout is
15888
+ booked as an upstream error, so a healthy but
15889
+ slow server is otherwise down-ranked in the
15890
+ reliability lines \`discover\` renders.
15891
+ CLAUDE_CONFIG_DIR Claude Code's config directory, honored by
15892
+ \`yaw-mcp install claude-code\` so a non-default
15893
+ location is written instead of ~/.claude. Read
15894
+ only at install time; it is Claude Code's knob,
15895
+ not yaw-mcp's.
15896
+ LOG_LEVEL Verbosity of yaw-mcp's own JSON log lines on
15897
+ stderr: \`debug\` | \`info\` | \`warn\` | \`error\`
15898
+ (default info). \`debug\` is what to set when
15899
+ asking why a server did not load.
15180
15900
 
15181
15901
  Config resolution (highest precedence first) -- for the \`servers\` allow-list
15182
15902
  and \`blocked\` deny-list:
@@ -15198,10 +15918,10 @@ if (subcommand === "compliance") {
15198
15918
  `);
15199
15919
  process.exitCode = 0;
15200
15920
  } else if (subcommand === "--version" || subcommand === "-V") {
15201
- process.stdout.write(`yaw-mcp ${true ? "0.79.0" : "dev"}
15921
+ process.stdout.write(`yaw-mcp ${true ? "0.79.2" : "dev"}
15202
15922
  `);
15203
15923
  process.exitCode = 0;
15204
- } else if (subcommand && !subcommand.startsWith("-")) {
15924
+ } else if (subcommand !== void 0 && !subcommand.startsWith("-")) {
15205
15925
  const suggestions = suggestSubcommand(subcommand);
15206
15926
  const hint = suggestions.length > 0 ? ` Did you mean: ${suggestions.join(", ")}?` : " Run `yaw-mcp --help` for the list of subcommands.";
15207
15927
  process.stderr.write(`yaw-mcp: unknown subcommand "${subcommand}".${hint}
@@ -15238,8 +15958,7 @@ async function runServer() {
15238
15958
  const shutdown = async () => {
15239
15959
  if (shuttingDown) return;
15240
15960
  shuttingDown = true;
15241
- const forceExit = setTimeout(() => process.exit(1), 1e4);
15242
- if (forceExit.unref) forceExit.unref();
15961
+ setTimeout(() => process.exit(1), 1e4);
15243
15962
  await server.shutdown();
15244
15963
  process.exit(0);
15245
15964
  };