@yawlabs/mcp 1.0.12 → 1.0.15

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
@@ -7,7 +7,6 @@ import {
7
7
  CURRENT_OS,
8
8
  ENTRY_NAME,
9
9
  INSTALL_TARGETS,
10
- INTERNAL_SECRET_ENV_KEYS,
11
10
  LEGACY_ENTRY_NAMES,
12
11
  MIN_OAM_VERSION,
13
12
  POSIX_SHELL,
@@ -43,6 +42,7 @@ import {
43
42
  guidePath,
44
43
  importViewOf,
45
44
  isFeatureDisabled,
45
+ isInternalSecretEnvKey,
46
46
  isOamCommand,
47
47
  isOamLaunch,
48
48
  isProjectLocalEntry,
@@ -101,7 +101,7 @@ import {
101
101
  unparseableConfigFix,
102
102
  userConfigDir,
103
103
  yawModeOverlay
104
- } from "./chunk-HRHGAT5G.js";
104
+ } from "./chunk-RCDMJJCW.js";
105
105
 
106
106
  // src/audit-cmd.ts
107
107
  import { homedir as homedir6 } from "os";
@@ -261,7 +261,10 @@ function killTree(child) {
261
261
  if (pid !== void 0) {
262
262
  if (process.platform === "win32") {
263
263
  try {
264
- const killer = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore" });
264
+ const killer = spawn("taskkill", ["/pid", String(pid), "/T", "/F"], {
265
+ stdio: "ignore",
266
+ env: stripInternalSecretsFromEnv(process.env)
267
+ });
265
268
  killer.on("error", () => {
266
269
  });
267
270
  return;
@@ -1631,6 +1634,7 @@ function isValidKdfParams(v) {
1631
1634
  if (r < 1 || r > MAX_KDF_R) return false;
1632
1635
  if (p < 1 || p > MAX_KDF_P) return false;
1633
1636
  if (kdfMemoryBytes(N, r) > MAX_KDF_MEMORY_BYTES) return false;
1637
+ if (r < 4 && N >= 2 ** (16 * r)) return false;
1634
1638
  return true;
1635
1639
  }
1636
1640
  function generateSalt() {
@@ -1687,21 +1691,11 @@ var SECRETS_SCHEMA_VERSION = 2;
1687
1691
  var LEGACY_SCHEMA_VERSION = 1;
1688
1692
  var VAULT_CHECK_AAD = "yaw-mcp:vault-check";
1689
1693
  var VAULT_CHECK_PLAINTEXT = "yaw-mcp-vault-v1";
1690
- var VAULT_CHECK_CORRUPT_ERROR = 'vault verification token ("check") is corrupt -- the passphrase is correct, but the check marker does not decrypt';
1694
+ var VAULT_CHECK_CORRUPT_ERROR = 'vault verification token ("check") is corrupt -- the passphrase is correct, but the check marker does not verify';
1691
1695
  var VAULT_WRONG_PASSPHRASE_ERROR = "wrong passphrase for this vault (decryption failed)";
1692
1696
  function vaultPath(home = homedir4()) {
1693
1697
  return join5(home, CONFIG_DIRNAME, SECRETS_FILENAME);
1694
1698
  }
1695
- function emptyVault() {
1696
- return {
1697
- version: SECRETS_SCHEMA_VERSION,
1698
- salt: generateSalt().toString("base64"),
1699
- // Recorded, never assumed: see KdfParams. A vault that carries its own
1700
- // cost factor keeps opening after the default is raised.
1701
- kdf: { ...DEFAULT_KDF },
1702
- entries: {}
1703
- };
1704
- }
1705
1699
  var VaultEntryCorruptError = class extends Error {
1706
1700
  entryName;
1707
1701
  constructor(entryName) {
@@ -1710,28 +1704,33 @@ var VaultEntryCorruptError = class extends Error {
1710
1704
  this.entryName = entryName;
1711
1705
  }
1712
1706
  };
1713
- async function loadVault(path5) {
1707
+ async function loadVault(path5, opts) {
1708
+ const onWarning = opts?.onWarning;
1714
1709
  let raw;
1715
1710
  try {
1716
1711
  raw = await readFile5(path5, "utf8");
1717
1712
  } catch (err) {
1718
1713
  const code = err.code;
1719
1714
  if (code === "ENOENT") return null;
1720
- log("warn", "Failed to read vault", { path: path5, error: err instanceof Error ? err.message : String(err), code });
1715
+ if (!onWarning) {
1716
+ log("warn", "Failed to read vault", { path: path5, error: err instanceof Error ? err.message : String(err), code });
1717
+ }
1721
1718
  throw err;
1722
1719
  }
1723
1720
  let parsed;
1724
1721
  try {
1725
1722
  parsed = JSON.parse(raw);
1726
1723
  } catch (err) {
1727
- log("warn", "Vault file is not valid JSON", { path: path5, error: err instanceof Error ? err.message : String(err) });
1724
+ if (!onWarning) {
1725
+ log("warn", "Vault file is not valid JSON", { path: path5, error: err instanceof Error ? err.message : String(err) });
1726
+ }
1728
1727
  throw new Error(`vault at ${path5} is not valid JSON: ${err instanceof Error ? err.message : String(err)}`);
1729
1728
  }
1730
1729
  if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
1731
1730
  throw new Error(`vault at ${path5} is corrupt: root must be a JSON object`);
1732
1731
  }
1733
1732
  const obj = parsed;
1734
- if (typeof obj.salt !== "string" || !obj.entries || typeof obj.entries !== "object") {
1733
+ if (typeof obj.salt !== "string" || !obj.entries || typeof obj.entries !== "object" || Array.isArray(obj.entries)) {
1735
1734
  throw new Error(`vault at ${path5} is corrupt: missing or invalid salt/entries`);
1736
1735
  }
1737
1736
  if (Buffer.from(obj.salt, "base64").length !== SALT_LEN) {
@@ -1755,7 +1754,9 @@ async function loadVault(path5) {
1755
1754
  }
1756
1755
  }
1757
1756
  if (obj.check !== void 0 && !isEncryptedEntry(obj.check)) {
1758
- log("warn", "Vault verification token is malformed; ignoring it (the next write re-stamps it)", { path: path5 });
1757
+ const message = "Vault verification token is malformed; ignoring it (the next `yaw-mcp secrets set` re-stamps it)";
1758
+ if (onWarning) onWarning({ kind: "check-malformed", path: path5, message });
1759
+ else log("warn", message, { path: path5 });
1759
1760
  }
1760
1761
  const check = isEncryptedEntry(obj.check) ? obj.check : void 0;
1761
1762
  return {
@@ -1876,14 +1877,17 @@ async function checkVaultPassphrase(vault, passphrase) {
1876
1877
  (await unlock(vault, passphrase)).fill(0);
1877
1878
  return "opens";
1878
1879
  } catch (err) {
1879
- return (err instanceof Error ? err.message : String(err)) === VAULT_CHECK_CORRUPT_ERROR ? "marker-corrupt" : "wrong";
1880
+ const msg = err instanceof Error ? err.message : String(err);
1881
+ if (msg === VAULT_CHECK_CORRUPT_ERROR) return "marker-corrupt";
1882
+ if (msg === VAULT_WRONG_PASSPHRASE_ERROR) return "wrong";
1883
+ throw err;
1880
1884
  }
1881
1885
  }
1882
1886
  function vaultCheckCorruptHint(path5) {
1883
1887
  return `Your entries are intact: delete the "check" key from ${path5} by hand and re-run -- the next \`yaw-mcp secrets set\` re-stamps it.`;
1884
1888
  }
1885
1889
  async function createEmptyVault(passphrase) {
1886
- const vault = emptyVault();
1890
+ const vault = newVault();
1887
1891
  const key = await deriveKey(passphrase, Buffer.from(vault.salt, "base64"), DEFAULT_KDF);
1888
1892
  try {
1889
1893
  return ensureCheck(vault, key);
@@ -1901,6 +1905,11 @@ async function rotateVault(vault, oldKey, newPassphrase) {
1901
1905
  plaintext.set(name, decryptBound(vault, entry, oldKey, name));
1902
1906
  } catch {
1903
1907
  plaintext.clear();
1908
+ if (vault.check) {
1909
+ throw new Error(
1910
+ `rotate aborted: entry "${name}" failed to decrypt, but the passphrase is right (the vault's check marker verifies under it) -- the entry is corrupt, or was written under a different passphrase than the rest of the vault. Remove it (\`yaw-mcp secrets remove ${name}\`), set it again, and re-run rotate.`
1911
+ );
1912
+ }
1904
1913
  throw new Error(`rotate aborted: entry "${name}" failed to decrypt under the current passphrase`);
1905
1914
  }
1906
1915
  }
@@ -1959,7 +1968,14 @@ function getSecret(vault, key, name) {
1959
1968
  return decryptBound(vault, entry, key, name);
1960
1969
  }
1961
1970
  function newVault() {
1962
- return emptyVault();
1971
+ return {
1972
+ version: SECRETS_SCHEMA_VERSION,
1973
+ salt: generateSalt().toString("base64"),
1974
+ // Recorded, never assumed: see KdfParams. A vault that carries its own
1975
+ // cost factor keeps opening after the default is raised.
1976
+ kdf: { ...DEFAULT_KDF },
1977
+ entries: {}
1978
+ };
1963
1979
  }
1964
1980
  var SECRET_REF_RE = new RegExp(`\\$\\{secret:(${SECRET_NAME_CLASS})\\}`, "g");
1965
1981
  function resolveSecretRefs(env, vault, key) {
@@ -2081,12 +2097,28 @@ import {
2081
2097
  ToolListChangedNotificationSchema
2082
2098
  } from "@modelcontextprotocol/sdk/types.js";
2083
2099
 
2100
+ // src/bundles-hint.ts
2101
+ function bundlesFileHint(which) {
2102
+ const file = which === "defines-it" ? "the bundles.json that defines it" : "the bundles.json in effect";
2103
+ return `${file} (~/.yaw-mcp/bundles.json, or a trusted project-local .yaw-mcp/bundles.json)`;
2104
+ }
2105
+
2084
2106
  // src/credentials.ts
2107
+ var NAME = "[A-Z_][A-Z0-9_]{2,}";
2108
+ var GAP = "[^\\S\\r\\n]+";
2109
+ var SEP = "(?:[^\\S\\r\\n]*:\\s+|[^\\S\\r\\n]+)";
2110
+ var QUOTE = "[\"'`]?";
2111
+ var ENV_WORDS = `(?:(?:env|environment)${GAP})?(?:(?:variable|var)${GAP})?`;
2112
+ var LEADING_ENV_WORDS = `(?:(?:env|environment)${SEP})?(?:(?:variables?|vars?)${SEP})?`;
2085
2113
  var MISSING_PATTERNS = [
2086
- /\bmissing\s*:?\s+(?:required\s+)?(?:(?:env|environment)\s*:?\s+)?(?:(?:variable|var)\s*:?\s+)?([A-Z_][A-Z0-9_]{2,})\b/gi,
2087
- /\b([A-Z_][A-Z0-9_]{2,})\s+is\s+(?:required|not\s+set|missing|empty|undefined)\b/gi,
2088
- /\b([A-Z_][A-Z0-9_]{2,})\s+must\s+be\s+set\b/gi,
2089
- /\bplease\s+set\s+(?:env\s+(?:var\s+|variable\s+)?)?([A-Z_][A-Z0-9_]{2,})\b/gi
2114
+ new RegExp(`\\bmissing${SEP}(?:required${GAP})?${LEADING_ENV_WORDS}${QUOTE}(${NAME})\\b`, "gi"),
2115
+ new RegExp(
2116
+ `\\b(${NAME})${QUOTE}${GAP}${ENV_WORDS}(?:is${GAP}(?:required|missing|empty|undefined)|(?:is${GAP})?(?:not${GAP}set|unset|not${GAP}provided))\\b`,
2117
+ "gi"
2118
+ ),
2119
+ new RegExp(`\\b(${NAME})${QUOTE}${GAP}${ENV_WORDS}must${GAP}be${GAP}set\\b`, "gi"),
2120
+ new RegExp(`\\bplease${GAP}set${GAP}(?:the${GAP})?${LEADING_ENV_WORDS}${QUOTE}(${NAME})\\b`, "gi"),
2121
+ new RegExp(`\\bno${GAP}${QUOTE}(${NAME})${QUOTE}${GAP}${ENV_WORDS}(?:provided|set)\\b`, "gi")
2090
2122
  ];
2091
2123
  var CREDENTIAL_SEGMENTS = /* @__PURE__ */ new Set([
2092
2124
  "TOKEN",
@@ -2122,6 +2154,7 @@ var CREDENTIAL_SEGMENTS = /* @__PURE__ */ new Set([
2122
2154
  ]);
2123
2155
  var CREDENTIAL_NOUN_SUFFIXES = ["TOKEN", "SECRET", "PASSWORD", "PASSPHRASE", "CREDENTIAL"];
2124
2156
  var CREDENTIAL_SUBSTRINGS = ["TOKEN", "SECRET", "PASSWORD", "PASSPHRASE", "APIKEY", "CREDENTIAL"];
2157
+ var LOCATOR_SEGMENTS = /* @__PURE__ */ new Set(["PATH", "FILE", "DIR", "HOST", "PORT", "PREFIX", "SIZE"]);
2125
2158
  var IGNORED = /* @__PURE__ */ new Set([
2126
2159
  "PATH",
2127
2160
  "HOME",
@@ -2158,11 +2191,14 @@ var IGNORED = /* @__PURE__ */ new Set([
2158
2191
  "VALUE",
2159
2192
  "VAR"
2160
2193
  ]);
2194
+ var ALL_CAPS_NAME = new RegExp(`^${NAME}$`);
2161
2195
  function isAllCaps(name) {
2162
- return /^[A-Z_][A-Z0-9_]{2,}$/.test(name);
2196
+ return ALL_CAPS_NAME.test(name);
2163
2197
  }
2164
2198
  function isCredentialShaped(name) {
2165
- for (const segment of name.split("_")) {
2199
+ const segments = name.split("_");
2200
+ if (LOCATOR_SEGMENTS.has(segments[segments.length - 1] ?? "")) return false;
2201
+ for (const segment of segments) {
2166
2202
  if (CREDENTIAL_SEGMENTS.has(segment)) return true;
2167
2203
  if (CREDENTIAL_NOUN_SUFFIXES.some((noun) => segment.length > noun.length && segment.endsWith(noun))) {
2168
2204
  return true;
@@ -2939,10 +2975,9 @@ async function verifyVaultPassphrase(passphrase) {
2939
2975
  }
2940
2976
  if (!vault) return true;
2941
2977
  try {
2942
- await unlock(vault, passphrase);
2943
- return true;
2944
- } catch (err) {
2945
- return (err instanceof Error ? err.message : String(err)) === VAULT_CHECK_CORRUPT_ERROR;
2978
+ return await checkVaultPassphrase(vault, passphrase) !== "wrong";
2979
+ } catch {
2980
+ return false;
2946
2981
  }
2947
2982
  }
2948
2983
  function vaultPassphrase() {
@@ -3137,7 +3172,7 @@ function redactSecretsInOutput(text, env) {
3137
3172
  }
3138
3173
  function withConfigPointer(message, config) {
3139
3174
  if (!config.namespace) return message;
3140
- return `${message} -> Fix in ~/.yaw-mcp/bundles.json under "${config.namespace}", then activate it again -- the edit is picked up on the next mcp_connect_* call, with no client restart.`;
3175
+ return `${message} -> Fix "${config.namespace}" in ${bundlesFileHint("defines-it")}, then activate it again -- the edit is picked up on the next mcp_connect_* call, with no client restart.`;
3141
3176
  }
3142
3177
  function categorizeSpawnError(err) {
3143
3178
  const msg = err instanceof Error ? err.message : String(err);
@@ -3230,7 +3265,7 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge
3230
3265
  if (downstreamCaps?.sampling) capabilities.sampling = downstreamCaps.sampling;
3231
3266
  if (downstreamCaps?.roots) capabilities.roots = {};
3232
3267
  const client = new Client(
3233
- { name: "yaw-mcp", version: true ? "1.0.12" : "dev" },
3268
+ { name: "yaw-mcp", version: true ? "1.0.15" : "dev" },
3234
3269
  { capabilities }
3235
3270
  );
3236
3271
  if (bridge && capabilities.elicitation) {
@@ -4810,6 +4845,47 @@ import { readFile as readFile9, stat as stat4 } from "fs/promises";
4810
4845
  import { homedir as homedir9 } from "os";
4811
4846
  import { basename as basename2, isAbsolute, join as join9, resolve as resolve4 } from "path";
4812
4847
 
4848
+ // src/readline-question.ts
4849
+ import { createInterface } from "readline/promises";
4850
+ var QUESTION_CANCELLED = /* @__PURE__ */ Symbol("yaw-mcp:question-cancelled");
4851
+ async function questionOrEmpty(rl, prompt) {
4852
+ if (rl.closed === true) return "";
4853
+ const ac = new AbortController();
4854
+ let cancelled = false;
4855
+ const onClose = () => ac.abort();
4856
+ const onSigint = () => {
4857
+ cancelled = true;
4858
+ ac.abort();
4859
+ };
4860
+ rl.once("close", onClose);
4861
+ rl.once("SIGINT", onSigint);
4862
+ try {
4863
+ return await rl.question(prompt, { signal: ac.signal });
4864
+ } catch (err) {
4865
+ if (cancelled) return QUESTION_CANCELLED;
4866
+ if (ac.signal.aborted) return "";
4867
+ throw err;
4868
+ } finally {
4869
+ rl.off("close", onClose);
4870
+ rl.off("SIGINT", onSigint);
4871
+ }
4872
+ }
4873
+ async function readlineAnswer(input, output, question, terminal) {
4874
+ const rl = createInterface({ input, output, terminal });
4875
+ try {
4876
+ return await questionOrEmpty(rl, question);
4877
+ } finally {
4878
+ rl.close();
4879
+ }
4880
+ }
4881
+ async function askYesNo(opts, question, read = readlineAnswer) {
4882
+ if (opts.promptAnswer !== void 0) return opts.promptAnswer.trim().toLowerCase();
4883
+ const input = opts.io?.stdin ?? process.stdin;
4884
+ const output = opts.io?.stdout ?? process.stdout;
4885
+ const raw = await read(input, output, question, opts.io?.terminal);
4886
+ return raw === QUESTION_CANCELLED ? raw : raw.trim().toLowerCase();
4887
+ }
4888
+
4813
4889
  // src/secrets-cmd.ts
4814
4890
  import { createHash as createHash4 } from "crypto";
4815
4891
  import { chmod as chmod5, copyFile, constants as fsConstants, readFile as readFile8, unlink } from "fs/promises";
@@ -4819,12 +4895,13 @@ var SECRETS_USAGE = `Usage: yaw-mcp secrets <action> [args]
4819
4895
  Manage your encrypted secret vault at ~/.yaw-mcp/secrets.json.
4820
4896
 
4821
4897
  Actions:
4822
- set <name> Store a secret. Reads value from stdin (one
4823
- line, no echo). Override with --value <v> or
4824
- --stdin (raw, multi-line) for scripting. Setting
4825
- a name that already exists REPLACES it (confirmed
4826
- first on a TTY; scripted runs proceed and say
4827
- "Replaced" instead of "Stored").
4898
+ set <name> Store a secret. At a terminal, prompts for the
4899
+ value (one line, no echo; a bare Enter asks
4900
+ again). A piped stdin is read whole instead,
4901
+ minus one trailing newline. Or pass --value <v>.
4902
+ Setting a name that already exists REPLACES it
4903
+ (confirmed first on a TTY; scripted runs proceed
4904
+ and say "Replaced" instead of "Stored").
4828
4905
  get <name> Decrypt and print one secret value to stdout.
4829
4906
  NOTE: this prints the secret in CLEARTEXT (with
4830
4907
  or without --json). Redirect to a file or pipe
@@ -4882,22 +4959,27 @@ Actions:
4882
4959
  string, not the bare name.
4883
4960
 
4884
4961
  Flags:
4885
- --json Machine-readable output (where applicable). stdout
4886
- carries the result envelope; stderr carries one
4887
- JSON object per line: {"warning":...} lines (a
4888
- schema-behind file, a short passphrase, a vault
4889
- just created or reset) and, on failure, the
4890
- {"ok":false,"error":...} envelope last. Key on
4891
- "warning" vs "ok", never on line position.
4962
+ --json Machine-readable output. stdout carries the result
4963
+ envelope, one JSON line; stderr carries one JSON
4964
+ object per line: {"warning":...} lines (a
4965
+ schema-behind file, a malformed check marker, a
4966
+ short passphrase, a vault just created or reset,
4967
+ a value printed in cleartext to a terminal) and,
4968
+ on failure, the {"ok":false,"error":...} envelope
4969
+ last -- an argument error too (exit 2, no usage
4970
+ text). Key on "warning" vs "ok", never on line
4971
+ position.
4892
4972
  --value <v> Inline secret value (set only). The value sits in
4893
4973
  this process's argv, so it is visible to every
4894
4974
  other local user via ps / /proc/<pid>/cmdline for
4895
4975
  the whole run (which includes the ~100ms key
4896
4976
  derivation), and it lands in your shell history.
4897
- For scripting use --stdin; interactively use the
4898
- default no-echo prompt.
4899
- --stdin Read the secret from raw stdin (set only). The
4900
- scripting-safe alternative to --value: the value
4977
+ For scripting pipe the value in on stdin;
4978
+ interactively use the default no-echo prompt.
4979
+ --stdin Read the value from stdin even when stdin is a
4980
+ terminal (set only): raw, multi-line, until EOF,
4981
+ and the terminal echoes it. A piped stdin is read
4982
+ that way without the flag. Either way the value
4901
4983
  never appears in argv.
4902
4984
  --force Skip the destructive-action confirmation
4903
4985
  (remove, reset, and a set that overwrites an
@@ -4922,8 +5004,19 @@ Forgot the passphrase?
4922
5004
  moves the old file aside (kept, in case the passphrase turns up), lists
4923
5005
  the entry names you have to set again, and starts an empty vault under a
4924
5006
  new passphrase.`;
5007
+ var SECRETS_ACTIONS = ["set", "get", "list", "remove", "lock", "rotate", "reset", "audit"];
5008
+ function isSecretsAction(a) {
5009
+ return typeof a === "string" && SECRETS_ACTIONS.includes(a);
5010
+ }
4925
5011
  function parseSecretsArgs(argv) {
5012
+ const json = argv.includes("--json");
4926
5013
  const opts = {};
5014
+ const refuse = (msg) => ({
5015
+ ok: false,
5016
+ error: json ? JSON.stringify({ ok: false, error: msg }) : `yaw-mcp secrets${opts.action ? ` ${opts.action}` : ""}: ${msg}
5017
+
5018
+ ${SECRETS_USAGE}`
5019
+ });
4927
5020
  for (let i = 0; i < argv.length; i++) {
4928
5021
  const a = argv[i];
4929
5022
  if (a === "--help" || a === "-h") return { ok: false, error: SECRETS_USAGE, help: true };
@@ -4942,12 +5035,7 @@ function parseSecretsArgs(argv) {
4942
5035
  if (a === "--value") {
4943
5036
  const v = argv[++i];
4944
5037
  if (v === void 0 || v.startsWith("-")) {
4945
- return {
4946
- ok: false,
4947
- error: `yaw-mcp secrets: --value requires a value (for a dash-leading value use --stdin)
4948
-
4949
- ${SECRETS_USAGE}`
4950
- };
5038
+ return refuse("--value requires a value (for a dash-leading value use --stdin)");
4951
5039
  }
4952
5040
  opts.value = v;
4953
5041
  continue;
@@ -4955,25 +5043,17 @@ ${SECRETS_USAGE}`
4955
5043
  if (a === "--secret" || a === "--server") {
4956
5044
  const v = argv[++i];
4957
5045
  if (v === void 0 || v.startsWith("-")) {
4958
- return { ok: false, error: `yaw-mcp secrets: ${a} requires a value
4959
-
4960
- ${SECRETS_USAGE}` };
5046
+ return refuse(`${a} requires a value`);
4961
5047
  }
4962
5048
  if (a === "--secret") opts.secretFilter = v;
4963
5049
  else opts.serverFilter = v;
4964
5050
  continue;
4965
5051
  }
4966
5052
  if (a.startsWith("-")) {
4967
- return { ok: false, error: `yaw-mcp secrets: unknown flag "${a}"
4968
-
4969
- ${SECRETS_USAGE}` };
5053
+ return refuse(`unknown flag "${a}"`);
4970
5054
  }
4971
5055
  if (!opts.action) {
4972
- if (a !== "set" && a !== "get" && a !== "list" && a !== "remove" && a !== "lock" && a !== "rotate" && a !== "reset" && a !== "audit") {
4973
- return { ok: false, error: `yaw-mcp secrets: unknown action "${a}"
4974
-
4975
- ${SECRETS_USAGE}` };
4976
- }
5056
+ if (!isSecretsAction(a)) return refuse(`unknown action "${a}"`);
4977
5057
  opts.action = a;
4978
5058
  continue;
4979
5059
  }
@@ -4981,69 +5061,69 @@ ${SECRETS_USAGE}` };
4981
5061
  opts.name = a;
4982
5062
  continue;
4983
5063
  }
4984
- return { ok: false, error: `yaw-mcp secrets: unexpected positional argument "${a}"
4985
-
4986
- ${SECRETS_USAGE}` };
5064
+ return refuse(`unexpected positional argument "${a}"`);
4987
5065
  }
4988
- if (!opts.action) return { ok: false, error: `yaw-mcp secrets: missing action
4989
-
4990
- ${SECRETS_USAGE}` };
5066
+ if (!opts.action) return refuse("missing action");
4991
5067
  if (opts.name !== void 0 && opts.action !== "set" && opts.action !== "get" && opts.action !== "remove") {
4992
5068
  const hint = opts.action === "audit" ? ` -- audit takes no <name>; filter with \`--secret ${opts.name}\` or \`--server ${opts.name}\`` : ` -- ${opts.action} takes no <name>`;
4993
- return {
4994
- ok: false,
4995
- error: `yaw-mcp secrets ${opts.action}: unexpected argument "${opts.name}"${hint}
4996
-
4997
- ${SECRETS_USAGE}`
4998
- };
5069
+ return refuse(`unexpected argument "${opts.name}"${hint}`);
4999
5070
  }
5000
5071
  if (opts.action !== "set" && (opts.value !== void 0 || opts.fromStdin)) {
5001
5072
  const flag = opts.value !== void 0 ? "--value" : "--stdin";
5002
- return { ok: false, error: `yaw-mcp secrets ${opts.action}: ${flag} applies to \`set\` only
5003
-
5004
- ${SECRETS_USAGE}` };
5073
+ return refuse(`${flag} applies to \`set\` only`);
5005
5074
  }
5006
5075
  if (opts.value !== void 0 && opts.value.length === 0) {
5007
- return { ok: false, error: `yaw-mcp secrets set: Secret value cannot be empty.
5008
-
5009
- ${SECRETS_USAGE}` };
5076
+ return refuse("Secret value cannot be empty.");
5010
5077
  }
5011
5078
  if (opts.action !== "audit" && (opts.secretFilter !== void 0 || opts.serverFilter !== void 0)) {
5012
5079
  const flag = opts.secretFilter !== void 0 ? "--secret" : "--server";
5013
- return {
5014
- ok: false,
5015
- error: `yaw-mcp secrets ${opts.action}: ${flag} applies to \`audit\` only
5016
-
5017
- ${SECRETS_USAGE}`
5018
- };
5080
+ return refuse(`${flag} applies to \`audit\` only`);
5019
5081
  }
5020
5082
  if ((opts.action === "set" || opts.action === "get" || opts.action === "remove") && !opts.name) {
5021
- return { ok: false, error: `yaw-mcp secrets ${opts.action}: <name> is required
5022
-
5023
- ${SECRETS_USAGE}` };
5083
+ return refuse("<name> is required");
5024
5084
  }
5025
5085
  if (opts.action === "set" && opts.name !== void 0 && !SECRET_NAME_RE.test(opts.name)) {
5026
- return {
5027
- ok: false,
5028
- error: `yaw-mcp secrets set: invalid secret name "${opts.name}" -- use letters, digits, "_", "." or "-" only; other characters can never be referenced as \${secret:NAME}
5029
-
5030
- ${SECRETS_USAGE}`
5031
- };
5086
+ return refuse(
5087
+ `invalid secret name "${opts.name}" -- use letters, digits, "_", "." or "-" only; other characters can never be referenced as \${secret:NAME}`
5088
+ );
5032
5089
  }
5033
5090
  return { ok: true, options: opts };
5034
5091
  }
5092
+ function failResult(io, json, action, msg, opts = {}) {
5093
+ const { exitCode = 1, detail, detailAsHint = false, fields } = opts;
5094
+ if (json) {
5095
+ const error = detail !== void 0 && !detailAsHint ? `${msg} ${detail}` : msg;
5096
+ const hint = detail !== void 0 && detailAsHint ? { hint: detail } : {};
5097
+ io.err(`${JSON.stringify({ ok: false, error, ...hint, ...fields })}
5098
+ `);
5099
+ } else {
5100
+ io.err(`yaw-mcp secrets${action ? ` ${action}` : ""}: ${msg}
5101
+ ${detail !== void 0 ? ` ${detail}
5102
+ ` : ""}`);
5103
+ }
5104
+ return { exitCode };
5105
+ }
5106
+ function vaultLoadWarningNotice(io, warning, json) {
5107
+ if (json) {
5108
+ io.err(`${JSON.stringify({ warning: warning.kind, path: warning.path, message: warning.message })}
5109
+ `);
5110
+ return;
5111
+ }
5112
+ io.err(`yaw-mcp secrets: warning -- ${warning.path}: ${warning.message}.
5113
+ `);
5114
+ }
5115
+ function vaultUnreadableMessage(path5, error) {
5116
+ return `could not read the vault file at ${path5} (${error.code ?? error.message}) -- fix that and re-run.`;
5117
+ }
5035
5118
  async function safeLoadVault(path5, io, json, action) {
5036
5119
  try {
5037
- return { ok: true, vault: await loadVault(path5) };
5120
+ return { ok: true, vault: await loadVault(path5, { onWarning: (w) => vaultLoadWarningNotice(io, w, json) }) };
5038
5121
  } catch (err) {
5039
5122
  const raw = err instanceof Error ? err.message : String(err);
5040
5123
  const name = err instanceof VaultEntryCorruptError ? err.entryName : void 0;
5041
- const msg = name ? `secret entry ${name} is corrupt, and every secrets command fails until it is gone. Delete the "${name}" key from ${path5} by hand (or run \`yaw-mcp secrets reset\` to start the vault over -- it keeps the old file), then re-add it with \`yaw-mcp secrets set ${name}\`.` : raw;
5042
- if (json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5043
- `);
5044
- else io.err(`yaw-mcp secrets${action ? ` ${action}` : ""}: ${msg}
5045
- `);
5046
- return { ok: false, result: { exitCode: 1 } };
5124
+ const readError = err instanceof Error && typeof err.code === "string" ? err : void 0;
5125
+ const msg = name ? `secret entry ${name} is corrupt, and every secrets command fails until it is gone. Delete the "${name}" key from ${path5} by hand (or run \`yaw-mcp secrets reset\` to start the vault over -- it keeps the old file), then re-add it with \`yaw-mcp secrets set ${name}\`.` : readError ? vaultUnreadableMessage(path5, readError) : raw;
5126
+ return { ok: false, result: failResult(io, json, action, msg) };
5047
5127
  }
5048
5128
  }
5049
5129
  function isVaultUnreadable(fp) {
@@ -5063,13 +5143,7 @@ async function vaultChangedSinceLoad(path5, baseline) {
5063
5143
  return now !== baseline;
5064
5144
  }
5065
5145
  function vaultUnreadableResult(io, json, action, path5, fp) {
5066
- const cause = fp.error.code ?? fp.error.message;
5067
- const msg = `could not read the vault file at ${path5} (${cause}) -- fix that and re-run. Nothing was written.`;
5068
- if (json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5069
- `);
5070
- else io.err(`yaw-mcp secrets${action ? ` ${action}` : ""}: ${msg}
5071
- `);
5072
- return { exitCode: 1 };
5146
+ return failResult(io, json, action, `${vaultUnreadableMessage(path5, fp.error)} Nothing was written.`);
5073
5147
  }
5074
5148
  async function trySaveVault(path5, vault) {
5075
5149
  try {
@@ -5083,20 +5157,15 @@ async function trySaveVault(path5, vault) {
5083
5157
  async function saveVaultOrReport(path5, vault, io, json, action) {
5084
5158
  const cause = await trySaveVault(path5, vault);
5085
5159
  if (cause === null) return null;
5086
- const msg = `could not write the vault file at ${path5} (${cause}) -- nothing was saved.`;
5087
- if (json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5088
- `);
5089
- else io.err(`yaw-mcp secrets${action ? ` ${action}` : ""}: ${msg}
5090
- `);
5091
- return { exitCode: 1 };
5160
+ return failResult(io, json, action, `could not write the vault file at ${path5} (${cause}) -- nothing was saved.`);
5092
5161
  }
5093
5162
  function vaultChangedResult(io, json, action) {
5094
- const msg = "the vault changed on disk while this command was waiting for input -- nothing was written. Re-run to work from the current vault.";
5095
- if (json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5096
- `);
5097
- else io.err(`yaw-mcp secrets${action ? ` ${action}` : ""}: ${msg}
5098
- `);
5099
- return { exitCode: 1 };
5163
+ return failResult(
5164
+ io,
5165
+ json,
5166
+ action,
5167
+ "the vault changed on disk while this command was waiting for input -- nothing was written. Re-run to work from the current vault."
5168
+ );
5100
5169
  }
5101
5170
  function unlockErrorMessage(err, path5) {
5102
5171
  const msg = err instanceof Error ? err.message : String(err);
@@ -5109,21 +5178,11 @@ function unlockErrorMessage(err, path5) {
5109
5178
  return msg;
5110
5179
  }
5111
5180
  var CANCELLED = /* @__PURE__ */ Symbol("yaw-mcp:passphrase-cancelled");
5112
- function cancelledResult(io, json) {
5113
- const msg = "Cancelled.";
5114
- if (json) io.err(`${JSON.stringify({ ok: false, error: msg, cancelled: true })}
5115
- `);
5116
- else io.err(`yaw-mcp secrets: ${msg}
5117
- `);
5118
- return { exitCode: 130 };
5181
+ function cancelledResult(io, json, action) {
5182
+ return failResult(io, json, action, "Cancelled.", { exitCode: 130, fields: { cancelled: true } });
5119
5183
  }
5120
5184
  function abortedResult(io, json, action) {
5121
- const msg = "Aborted.";
5122
- if (json) io.err(`${JSON.stringify({ ok: false, error: msg, aborted: true })}
5123
- `);
5124
- else io.err(`yaw-mcp secrets ${action}: ${msg}
5125
- `);
5126
- return { exitCode: 1 };
5185
+ return failResult(io, json, action, "Aborted.", { fields: { aborted: true } });
5127
5186
  }
5128
5187
  function ttyEnds(opts) {
5129
5188
  const stdin = opts.io?.stdin ?? process.stdin;
@@ -5296,13 +5355,14 @@ var MAX_PASSPHRASE_PROMPTS = 3;
5296
5355
  var MIN_PASSPHRASE_WARN_LEN = 12;
5297
5356
  var CTRL_C = "";
5298
5357
  var CTRL_D = "";
5358
+ var TAB = " ";
5299
5359
  var DEL = "\x7F";
5300
5360
  var ESC = "\x1B";
5301
5361
  var NO_ECHO = /* @__PURE__ */ Symbol("yaw-mcp:no-echo-unavailable");
5302
5362
  function noEchoRefusal(required, remedy) {
5303
5363
  return `${required} Refusing to prompt: this terminal would not turn echo off, so what you type would be shown on screen. ${remedy}`;
5304
5364
  }
5305
- function readLineFromTTY(stdin, stdout, prompt = "Vault passphrase: ", echo = false) {
5365
+ function readLineFromTTY(stdin, stdout, prompt = "Vault passphrase: ", echo = false, keepTab = false) {
5306
5366
  return new Promise((resolve8) => {
5307
5367
  const chunks = [];
5308
5368
  const wasRaw = stdin.isRaw === true;
@@ -5378,7 +5438,7 @@ function readLineFromTTY(stdin, stdout, prompt = "Vault passphrase: ", echo = fa
5378
5438
  }
5379
5439
  continue;
5380
5440
  }
5381
- if (ch < " ") continue;
5441
+ if (ch < " " && !(keepTab && ch === TAB)) continue;
5382
5442
  chunks.push(ch);
5383
5443
  if (echo) stdout.write(ch);
5384
5444
  }
@@ -5398,7 +5458,12 @@ async function readStdinValue(io, forceRaw) {
5398
5458
  const stdoutIsTTY = stdout.isTTY === true;
5399
5459
  if (stdinIsTTY && !forceRaw) {
5400
5460
  if (!stdoutIsTTY) return PROMPT_IMPOSSIBLE;
5401
- return readLineFromTTY(stdin, stdout, "Secret value: ");
5461
+ for (let attempt = 0; attempt < MAX_PASSPHRASE_PROMPTS; attempt++) {
5462
+ const entered = await readLineFromTTY(stdin, stdout, "Secret value: ", false, true);
5463
+ if (entered === CANCELLED || entered === NO_ECHO || entered.length > 0) return entered;
5464
+ stdout.write("Secret value cannot be empty.\n");
5465
+ }
5466
+ return "";
5402
5467
  }
5403
5468
  const chunks = [];
5404
5469
  stdin.setEncoding("utf8");
@@ -5411,6 +5476,9 @@ async function runSecrets(opts, io = {
5411
5476
  }) {
5412
5477
  const home = opts.home ?? homedir8();
5413
5478
  const path5 = vaultPath(home);
5479
+ if (!isSecretsAction(opts.action)) {
5480
+ return failResult(io, opts.json, "", `unknown action ${String(opts.action)}`, { exitCode: 2 });
5481
+ }
5414
5482
  if (opts.action === "lock") {
5415
5483
  lock();
5416
5484
  if (opts.json) {
@@ -5440,7 +5508,7 @@ async function runSecrets(opts, io = {
5440
5508
  const vault2 = loaded2.vault;
5441
5509
  if (vault2) schemaBehindNotice(io, vault2, path5, opts.json);
5442
5510
  const keys = vault2 ? listKeys(vault2) : [];
5443
- if (opts.json) io.out(`${JSON.stringify({ ok: true, vault: vault2 !== null, keys }, null, 2)}
5511
+ if (opts.json) io.out(`${JSON.stringify({ ok: true, vault: vault2 !== null, keys })}
5444
5512
  `);
5445
5513
  else if (!vault2) io.out(`No vault at ${path5}. Run \`yaw-mcp secrets set <name>\` to create one.
5446
5514
  `);
@@ -5455,36 +5523,30 @@ async function runSecrets(opts, io = {
5455
5523
  return { exitCode: 0 };
5456
5524
  }
5457
5525
  const baseline = opts.action === "get" ? null : await vaultFingerprint(path5);
5458
- if (isVaultUnreadable(baseline)) return vaultUnreadableResult(io, opts.json, opts.action ?? "", path5, baseline);
5459
- const loaded = await safeLoadVault(path5, io, opts.json, opts.action ?? "");
5526
+ if (isVaultUnreadable(baseline)) return vaultUnreadableResult(io, opts.json, opts.action, path5, baseline);
5527
+ const loaded = await safeLoadVault(path5, io, opts.json, opts.action);
5460
5528
  if (!loaded.ok) return loaded.result;
5461
5529
  if (loaded.vault) schemaBehindNotice(io, loaded.vault, path5, opts.json);
5462
5530
  if (opts.action === "get" || opts.action === "remove") {
5463
5531
  const name = opts.name;
5464
5532
  if (!loaded.vault || !Object.hasOwn(loaded.vault.entries, name)) {
5465
- const msg = `No secret named "${name}" in the vault.`;
5466
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5467
- `);
5468
- else io.err(`yaw-mcp secrets: ${msg}
5469
- `);
5470
- return { exitCode: 1 };
5533
+ return failResult(io, opts.json, opts.action, `No secret named "${name}" in the vault.`);
5471
5534
  }
5472
5535
  }
5473
5536
  const replacing = opts.action === "set" && loaded.vault !== null && Object.hasOwn(loaded.vault.entries, opts.name);
5474
5537
  if (opts.action === "remove" && !opts.force) {
5475
5538
  if (isInteractiveTTY(opts)) {
5476
5539
  const confirmed = await promptYesNo(opts, `Permanently delete secret "${opts.name}"? This cannot be undone.`);
5477
- if (confirmed === CANCELLED) return cancelledResult(io, opts.json);
5540
+ if (confirmed === CANCELLED) return cancelledResult(io, opts.json, "remove");
5478
5541
  if (!confirmed) return abortedResult(io, opts.json, "remove");
5479
5542
  } else {
5480
- const msg = `refusing to delete "${opts.name}" without confirmation and ${nonTTYEnds(opts)}.`;
5481
- const hint = "Re-run with --force to delete it. This cannot be undone.";
5482
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: `${msg} ${hint}` })}
5483
- `);
5484
- else io.err(`yaw-mcp secrets remove: ${msg}
5485
- ${hint}
5486
- `);
5487
- return { exitCode: 2 };
5543
+ return failResult(
5544
+ io,
5545
+ opts.json,
5546
+ "remove",
5547
+ `refusing to delete "${opts.name}" without confirmation and ${nonTTYEnds(opts)}.`,
5548
+ { exitCode: 2, detail: "Re-run with --force to delete it. This cannot be undone." }
5549
+ );
5488
5550
  }
5489
5551
  }
5490
5552
  if (replacing && !opts.force && isInteractiveTTY(opts)) {
@@ -5492,40 +5554,35 @@ async function runSecrets(opts, io = {
5492
5554
  opts,
5493
5555
  `Secret "${opts.name}" already exists. Replace it? The stored value is overwritten.`
5494
5556
  );
5495
- if (confirmed === CANCELLED) return cancelledResult(io, opts.json);
5557
+ if (confirmed === CANCELLED) return cancelledResult(io, opts.json, "set");
5496
5558
  if (!confirmed) return abortedResult(io, opts.json, "set");
5497
5559
  }
5498
5560
  let vault = loaded.vault ?? newVault();
5499
5561
  const isFresh = loaded.vault === null;
5500
5562
  const creatingVault = opts.action === "set" && !vault.check && Object.keys(vault.entries).length === 0;
5501
5563
  const passphrase = await resolvePassphrase(opts, io, creatingVault);
5502
- if (passphrase === CANCELLED) return cancelledResult(io, opts.json);
5564
+ if (passphrase === CANCELLED) return cancelledResult(io, opts.json, opts.action);
5503
5565
  if (passphrase === NO_ECHO) {
5504
- const msg = noEchoRefusal("Passphrase required.", "Set YAW_MCP_VAULT_PASSPHRASE instead.");
5505
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5506
- `);
5507
- else io.err(`yaw-mcp secrets: ${msg}
5508
- `);
5509
- return { exitCode: 1 };
5566
+ return failResult(
5567
+ io,
5568
+ opts.json,
5569
+ opts.action,
5570
+ noEchoRefusal("Passphrase required.", "Set YAW_MCP_VAULT_PASSPHRASE instead.")
5571
+ );
5510
5572
  }
5511
5573
  if (passphrase === null) {
5512
- const msg = promptUnavailableMessage(opts, "Passphrase required.", "YAW_MCP_VAULT_PASSPHRASE");
5513
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5514
- `);
5515
- else io.err(`yaw-mcp secrets: ${msg}
5516
- `);
5517
- return { exitCode: 1 };
5574
+ return failResult(
5575
+ io,
5576
+ opts.json,
5577
+ opts.action,
5578
+ promptUnavailableMessage(opts, "Passphrase required.", "YAW_MCP_VAULT_PASSPHRASE")
5579
+ );
5518
5580
  }
5519
5581
  let key;
5520
5582
  try {
5521
5583
  key = await unlock(vault, passphrase);
5522
5584
  } catch (err) {
5523
- const msg = unlockErrorMessage(err, path5);
5524
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5525
- `);
5526
- else io.err(`yaw-mcp secrets: ${msg}
5527
- `);
5528
- return { exitCode: 1 };
5585
+ return failResult(io, opts.json, opts.action, unlockErrorMessage(err, path5));
5529
5586
  }
5530
5587
  if (opts.action === "set") {
5531
5588
  const name = opts.name;
@@ -5533,42 +5590,30 @@ async function runSecrets(opts, io = {
5533
5590
  if (opts.value !== void 0) value = opts.value;
5534
5591
  else {
5535
5592
  const entered = await readStdinValue(opts.io, opts.fromStdin);
5536
- if (entered === CANCELLED) return cancelledResult(io, opts.json);
5593
+ if (entered === CANCELLED) return cancelledResult(io, opts.json, "set");
5537
5594
  if (entered === NO_ECHO) {
5538
- const msg = noEchoRefusal("Secret value required.", "Pipe the value in with --stdin instead.");
5539
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5540
- `);
5541
- else io.err(`yaw-mcp secrets set: ${msg}
5542
- `);
5543
- return { exitCode: 1 };
5595
+ return failResult(
5596
+ io,
5597
+ opts.json,
5598
+ "set",
5599
+ noEchoRefusal("Secret value required.", "Pipe the value in with --stdin instead.")
5600
+ );
5544
5601
  }
5545
5602
  if (entered === PROMPT_IMPOSSIBLE) {
5546
- const msg = "cannot prompt for the value: stdin is a TTY but stdout is not, so the prompt would be written into the redirect instead of shown. Pass --value <v>, or pipe the value in with --stdin.";
5547
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5548
- `);
5549
- else io.err(`yaw-mcp secrets set: ${msg}
5550
- `);
5551
- return { exitCode: 1 };
5603
+ return failResult(
5604
+ io,
5605
+ opts.json,
5606
+ "set",
5607
+ "cannot prompt for the value: stdin is a TTY but stdout is not, so the prompt would be written into the redirect instead of shown. Pass --value <v>, or pipe the value in with --stdin."
5608
+ );
5552
5609
  }
5553
5610
  value = entered;
5554
5611
  }
5555
- if (!value) {
5556
- const msg = "Secret value cannot be empty.";
5557
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5558
- `);
5559
- else io.err(`yaw-mcp secrets: ${msg}
5560
- `);
5561
- return { exitCode: 1 };
5562
- }
5612
+ if (!value) return failResult(io, opts.json, "set", "Secret value cannot be empty.");
5563
5613
  try {
5564
5614
  vault = setSecret(vault, key, name, value);
5565
5615
  } catch (err) {
5566
- const msg = err instanceof Error ? err.message : String(err);
5567
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5568
- `);
5569
- else io.err(`yaw-mcp secrets set: ${msg}
5570
- `);
5571
- return { exitCode: 1 };
5616
+ return failResult(io, opts.json, "set", err instanceof Error ? err.message : String(err));
5572
5617
  }
5573
5618
  if (await vaultChangedSinceLoad(path5, baseline)) return vaultChangedResult(io, opts.json, "set");
5574
5619
  const failed = await saveVaultOrReport(path5, vault, io, opts.json, "set");
@@ -5588,10 +5633,14 @@ async function runSecrets(opts, io = {
5588
5633
  const value = getSecret(vault, key, name);
5589
5634
  const outStream = opts.io?.stdout ?? process.stdout;
5590
5635
  if (outStream.isTTY === true) {
5591
- io.err(
5592
- `yaw-mcp secrets: warning -- printing "${name}" in cleartext to your terminal; it will remain in scrollback.
5636
+ if (opts.json) io.err(`${JSON.stringify({ warning: "cleartext-on-tty", name })}
5637
+ `);
5638
+ else {
5639
+ io.err(
5640
+ `yaw-mcp secrets: warning -- printing "${name}" in cleartext to your terminal; it will remain in scrollback.
5593
5641
  `
5594
- );
5642
+ );
5643
+ }
5595
5644
  }
5596
5645
  if (opts.json) io.out(`${JSON.stringify({ ok: true, name, value })}
5597
5646
  `);
@@ -5599,14 +5648,10 @@ async function runSecrets(opts, io = {
5599
5648
  `);
5600
5649
  return { exitCode: 0 };
5601
5650
  } catch (err) {
5602
- const msg = err instanceof Error ? err.message : String(err);
5603
- const hint = `Entry "${name}" failed to decrypt: it is corrupt, or it was written under a different passphrase than the rest of the vault. Remove it and set it again.`;
5604
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg, hint })}
5605
- `);
5606
- else io.err(`yaw-mcp secrets: ${msg}
5607
- ${hint}
5608
- `);
5609
- return { exitCode: 1 };
5651
+ return failResult(io, opts.json, "get", err instanceof Error ? err.message : String(err), {
5652
+ detail: `Entry "${name}" failed to decrypt: it is corrupt, or it was written under a different passphrase than the rest of the vault. Remove it and set it again.`,
5653
+ detailAsHint: true
5654
+ });
5610
5655
  }
5611
5656
  }
5612
5657
  if (opts.action === "remove") {
@@ -5621,9 +5666,8 @@ async function runSecrets(opts, io = {
5621
5666
  `);
5622
5667
  return { exitCode: 0 };
5623
5668
  }
5624
- io.err(`yaw-mcp secrets: unknown action ${opts.action}
5625
- `);
5626
- return { exitCode: 2 };
5669
+ const unhandled = opts.action;
5670
+ return failResult(io, opts.json, "", `unknown action ${String(unhandled)}`, { exitCode: 2 });
5627
5671
  }
5628
5672
  async function runSecretsRotate(opts, io) {
5629
5673
  const home = opts.home ?? homedir8();
@@ -5634,75 +5678,65 @@ async function runSecretsRotate(opts, io) {
5634
5678
  if (!loaded.ok) return loaded.result;
5635
5679
  const vault = loaded.vault;
5636
5680
  if (!vault) {
5637
- const msg = `No vault at ${path5} to rotate. Run \`yaw-mcp secrets set <name>\` first.`;
5638
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5639
- `);
5640
- else io.err(`yaw-mcp secrets rotate: ${msg}
5641
- `);
5642
- return { exitCode: 1 };
5681
+ return failResult(
5682
+ io,
5683
+ opts.json,
5684
+ "rotate",
5685
+ `No vault at ${path5} to rotate. Run \`yaw-mcp secrets set <name>\` first.`
5686
+ );
5643
5687
  }
5644
5688
  const currentPassphrase = await resolvePassphrase(opts, io);
5645
- if (currentPassphrase === CANCELLED) return cancelledResult(io, opts.json);
5689
+ if (currentPassphrase === CANCELLED) return cancelledResult(io, opts.json, "rotate");
5646
5690
  if (currentPassphrase === NO_ECHO) {
5647
- const msg = noEchoRefusal("Current passphrase required.", "Set YAW_MCP_VAULT_PASSPHRASE instead.");
5648
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5649
- `);
5650
- else io.err(`yaw-mcp secrets rotate: ${msg}
5651
- `);
5652
- return { exitCode: 1 };
5691
+ return failResult(
5692
+ io,
5693
+ opts.json,
5694
+ "rotate",
5695
+ noEchoRefusal("Current passphrase required.", "Set YAW_MCP_VAULT_PASSPHRASE instead.")
5696
+ );
5653
5697
  }
5654
5698
  if (currentPassphrase === null) {
5655
- const msg = promptUnavailableMessage(opts, "Current passphrase required.", "YAW_MCP_VAULT_PASSPHRASE");
5656
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5657
- `);
5658
- else io.err(`yaw-mcp secrets rotate: ${msg}
5659
- `);
5660
- return { exitCode: 1 };
5699
+ return failResult(
5700
+ io,
5701
+ opts.json,
5702
+ "rotate",
5703
+ promptUnavailableMessage(opts, "Current passphrase required.", "YAW_MCP_VAULT_PASSPHRASE")
5704
+ );
5661
5705
  }
5662
5706
  let oldKey;
5663
5707
  try {
5664
5708
  oldKey = await unlock(vault, currentPassphrase);
5665
5709
  } catch (err) {
5666
- const msg = unlockErrorMessage(err, path5);
5667
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5668
- `);
5669
- else io.err(`yaw-mcp secrets rotate: ${msg}
5670
- `);
5671
- return { exitCode: 1 };
5710
+ return failResult(io, opts.json, "rotate", unlockErrorMessage(err, path5));
5672
5711
  }
5673
5712
  const newPassphrase = await resolveNewPassphrase(opts, io);
5674
- if (newPassphrase === CANCELLED) return cancelledResult(io, opts.json);
5713
+ if (newPassphrase === CANCELLED) return cancelledResult(io, opts.json, "rotate");
5675
5714
  if (newPassphrase === NO_ECHO) {
5676
- const msg = noEchoRefusal("New passphrase required.", "Set YAW_MCP_VAULT_PASSPHRASE_NEW instead.");
5677
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5678
- `);
5679
- else io.err(`yaw-mcp secrets rotate: ${msg}
5680
- `);
5681
- return { exitCode: 1 };
5715
+ return failResult(
5716
+ io,
5717
+ opts.json,
5718
+ "rotate",
5719
+ noEchoRefusal("New passphrase required.", "Set YAW_MCP_VAULT_PASSPHRASE_NEW instead.")
5720
+ );
5682
5721
  }
5683
5722
  if (newPassphrase === null) {
5684
- const msg = promptUnavailableMessage(
5685
- opts,
5686
- "New passphrase required (and must be confirmed).",
5687
- "YAW_MCP_VAULT_PASSPHRASE_NEW"
5723
+ return failResult(
5724
+ io,
5725
+ opts.json,
5726
+ "rotate",
5727
+ promptUnavailableMessage(
5728
+ opts,
5729
+ "New passphrase required (and must be confirmed).",
5730
+ "YAW_MCP_VAULT_PASSPHRASE_NEW"
5731
+ )
5688
5732
  );
5689
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5690
- `);
5691
- else io.err(`yaw-mcp secrets rotate: ${msg}
5692
- `);
5693
- return { exitCode: 1 };
5694
5733
  }
5695
5734
  let rotated;
5696
5735
  try {
5697
5736
  rotated = await rotateVault(vault, oldKey, newPassphrase);
5698
5737
  } catch (err) {
5699
- const msg = err instanceof Error ? err.message : String(err);
5700
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5701
- `);
5702
- else io.err(`yaw-mcp secrets rotate: ${msg}
5703
- `);
5704
5738
  lock();
5705
- return { exitCode: 1 };
5739
+ return failResult(io, opts.json, "rotate", err instanceof Error ? err.message : String(err));
5706
5740
  }
5707
5741
  if (await vaultChangedSinceLoad(path5, baseline)) {
5708
5742
  lock();
@@ -5773,6 +5807,18 @@ function alreadyOpensMessage(verdict, subject, path5) {
5773
5807
  }
5774
5808
  return `${subject} already opens the vault at ${path5} -- nothing to reset, and the vault was not touched. ${RESET_ALTERNATIVES}`;
5775
5809
  }
5810
+ async function resetGuardVerdict(vault, candidate) {
5811
+ try {
5812
+ return await checkVaultPassphrase(vault, candidate);
5813
+ } catch (err) {
5814
+ return { failed: err instanceof Error ? err.message : String(err) };
5815
+ } finally {
5816
+ lock();
5817
+ }
5818
+ }
5819
+ function guardFailedMessage(subject, path5, cause) {
5820
+ return `could not check ${subject} against the vault at ${path5} (${cause}) -- nothing was changed.`;
5821
+ }
5776
5822
  function resetPreamble(path5, backup, names, envKeyed) {
5777
5823
  const lines = [];
5778
5824
  if ("names" in names) {
@@ -5820,13 +5866,7 @@ async function runSecretsReset(opts, io) {
5820
5866
  const home = opts.home ?? homedir8();
5821
5867
  const path5 = vaultPath(home);
5822
5868
  const json = opts.json;
5823
- const fail = (msg, exitCode = 1) => {
5824
- if (json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5825
- `);
5826
- else io.err(`yaw-mcp secrets reset: ${msg}
5827
- `);
5828
- return { exitCode };
5829
- };
5869
+ const fail = (msg) => failResult(io, json, "reset", msg);
5830
5870
  const baseline = await vaultFingerprint(path5);
5831
5871
  if (isVaultUnreadable(baseline)) return vaultUnreadableResult(io, json, "reset", path5, baseline);
5832
5872
  if (baseline === null) {
@@ -5836,7 +5876,7 @@ async function runSecretsReset(opts, io) {
5836
5876
  let vault = null;
5837
5877
  if ("names" in names) {
5838
5878
  try {
5839
- vault = await loadVault(path5);
5879
+ vault = await loadVault(path5, { onWarning: (w) => vaultLoadWarningNotice(io, w, json) });
5840
5880
  } catch {
5841
5881
  vault = null;
5842
5882
  }
@@ -5844,8 +5884,8 @@ async function runSecretsReset(opts, io) {
5844
5884
  const guardable = vault !== null && vaultVerifiesPassphrases(vault);
5845
5885
  const scripted = opts.passphrase ?? process.env.YAW_MCP_VAULT_PASSPHRASE ?? "";
5846
5886
  if (guardable && vault !== null && scripted.length > 0) {
5847
- const verdict = await checkVaultPassphrase(vault, scripted);
5848
- lock();
5887
+ const verdict = await resetGuardVerdict(vault, scripted);
5888
+ if (typeof verdict === "object") return fail(guardFailedMessage("YAW_MCP_VAULT_PASSPHRASE", path5, verdict.failed));
5849
5889
  if (verdict !== "wrong") return fail(alreadyOpensMessage(verdict, "YAW_MCP_VAULT_PASSPHRASE", path5));
5850
5890
  }
5851
5891
  const at = /* @__PURE__ */ new Date();
@@ -5856,21 +5896,23 @@ async function runSecretsReset(opts, io) {
5856
5896
  const stdout = opts.io?.stdout ?? process.stdout;
5857
5897
  stdout.write(resetPreamble(path5, resetBackupPath(path5, at), names, envKeyed));
5858
5898
  const answer = await readLineFromTTY(stdin, stdout, "Type RESET to continue: ", true);
5859
- if (answer === CANCELLED) return cancelledResult(io, json);
5899
+ if (answer === CANCELLED) return cancelledResult(io, json, "reset");
5860
5900
  if (answer.trim().toLowerCase() !== "reset") return abortedResult(io, json, "reset");
5861
5901
  } else {
5862
- const msg = `refusing to reset the vault without confirmation and ${nonTTYEnds(opts)}.`;
5863
- const hint = "Re-run with --force to reset it. The old vault is moved aside, not deleted, and every entry has to be set again.";
5864
- if (json) io.err(`${JSON.stringify({ ok: false, error: `${msg} ${hint}` })}
5865
- `);
5866
- else io.err(`yaw-mcp secrets reset: ${msg}
5867
- ${hint}
5868
- `);
5869
- return { exitCode: 2 };
5902
+ return failResult(
5903
+ io,
5904
+ json,
5905
+ "reset",
5906
+ `refusing to reset the vault without confirmation and ${nonTTYEnds(opts)}.`,
5907
+ {
5908
+ exitCode: 2,
5909
+ detail: "Re-run with --force to reset it. The old vault is moved aside, not deleted, and every entry has to be set again."
5910
+ }
5911
+ );
5870
5912
  }
5871
5913
  }
5872
5914
  const passphrase = await resolvePassphrase(opts, io, true, NEW_PASSPHRASE_LABELS);
5873
- if (passphrase === CANCELLED) return cancelledResult(io, json);
5915
+ if (passphrase === CANCELLED) return cancelledResult(io, json, "reset");
5874
5916
  if (passphrase === NO_ECHO) {
5875
5917
  return fail(noEchoRefusal("New passphrase required.", "Set YAW_MCP_VAULT_PASSPHRASE instead."));
5876
5918
  }
@@ -5880,8 +5922,8 @@ async function runSecretsReset(opts, io) {
5880
5922
  );
5881
5923
  }
5882
5924
  if (guardable && vault !== null && scripted.length === 0) {
5883
- const verdict = await checkVaultPassphrase(vault, passphrase);
5884
- lock();
5925
+ const verdict = await resetGuardVerdict(vault, passphrase);
5926
+ if (typeof verdict === "object") return fail(guardFailedMessage("that passphrase", path5, verdict.failed));
5885
5927
  if (verdict !== "wrong") return fail(alreadyOpensMessage(verdict, "that passphrase", path5));
5886
5928
  }
5887
5929
  let fresh;
@@ -5954,15 +5996,10 @@ async function runSecretsAudit(opts, io) {
5954
5996
  home
5955
5997
  );
5956
5998
  } catch (err) {
5957
- const msg = err instanceof Error ? err.message : String(err);
5958
- if (opts.json) io.err(`${JSON.stringify({ ok: false, error: msg })}
5959
- `);
5960
- else io.err(`yaw-mcp secrets audit: ${msg}
5961
- `);
5962
- return { exitCode: 1 };
5999
+ return failResult(io, opts.json, "audit", err instanceof Error ? err.message : String(err));
5963
6000
  }
5964
6001
  if (opts.json) {
5965
- io.out(`${JSON.stringify({ ok: true, count: events.length, events }, null, 2)}
6002
+ io.out(`${JSON.stringify({ ok: true, count: events.length, events })}
5966
6003
  `);
5967
6004
  return { exitCode: 0 };
5968
6005
  }
@@ -6181,7 +6218,7 @@ async function runTrustGrant(opts) {
6181
6218
  return { exitCode: 1 };
6182
6219
  }
6183
6220
  const question = serverCount === 0 ? " Approve this file? It defines no servers. [y/N] " : ` Read ${serverCount === 1 ? "the 1 command" : `all ${serverCount} commands`} above. Approve this file? [y/N] `;
6184
- const answer = await askYesNo(opts, question);
6221
+ const answer = await askYesNo(opts, question, readTrustAnswer);
6185
6222
  if (answer !== "y" && answer !== "yes") {
6186
6223
  printErr("yaw-mcp trust: Aborted. Nothing was approved.");
6187
6224
  return { exitCode: 1 };
@@ -6509,12 +6546,8 @@ function isInteractive(opts) {
6509
6546
  if (opts.promptAnswer !== void 0) return true;
6510
6547
  return Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY);
6511
6548
  }
6512
- async function askYesNo(opts, question) {
6513
- if (opts.promptAnswer !== void 0) return opts.promptAnswer.trim().toLowerCase();
6514
- const input = opts.io?.stdin ?? process.stdin;
6515
- const output = opts.io?.stdout ?? process.stdout;
6516
- const answer = await readAnswerFromTTY(input, output, question);
6517
- return (answer ?? "").trim().toLowerCase();
6549
+ async function readTrustAnswer(input, output, question) {
6550
+ return await readAnswerFromTTY(input, output, question) ?? "";
6518
6551
  }
6519
6552
 
6520
6553
  // src/call-cmd.ts
@@ -8382,7 +8415,6 @@ import { existsSync as existsSync5 } from "fs";
8382
8415
  import { chmod as chmod6, mkdir as mkdir4, readdir, readFile as readFile12, unlink as unlink2 } from "fs/promises";
8383
8416
  import { homedir as homedir14 } from "os";
8384
8417
  import { join as join13, resolve as resolve6 } from "path";
8385
- import { createInterface as createInterface2 } from "readline/promises";
8386
8418
 
8387
8419
  // src/catalog-search.ts
8388
8420
  var str = (v) => typeof v === "string" ? v : void 0;
@@ -8605,34 +8637,7 @@ function normalizeCatalogGrade(raw) {
8605
8637
  import { readFile as readFile11, stat as stat5 } from "fs/promises";
8606
8638
  import { homedir as homedir13 } from "os";
8607
8639
  import { dirname as dirname7, join as join12, resolve as resolve5, sep } from "path";
8608
- import { createInterface } from "readline/promises";
8609
-
8610
- // src/readline-question.ts
8611
- var QUESTION_CANCELLED = /* @__PURE__ */ Symbol("yaw-mcp:question-cancelled");
8612
- async function questionOrEmpty(rl, prompt) {
8613
- if (rl.closed === true) return "";
8614
- const ac = new AbortController();
8615
- let cancelled = false;
8616
- const onClose = () => ac.abort();
8617
- const onSigint = () => {
8618
- cancelled = true;
8619
- ac.abort();
8620
- };
8621
- rl.once("close", onClose);
8622
- rl.once("SIGINT", onSigint);
8623
- try {
8624
- return await rl.question(prompt, { signal: ac.signal });
8625
- } catch (err) {
8626
- if (cancelled) return QUESTION_CANCELLED;
8627
- if (ac.signal.aborted) return "";
8628
- throw err;
8629
- } finally {
8630
- rl.off("close", onClose);
8631
- rl.off("SIGINT", onSigint);
8632
- }
8633
- }
8634
-
8635
- // src/install-cmd.ts
8640
+ import { createInterface as createInterface2 } from "readline/promises";
8636
8641
  function oamAbsentNote(os, publishesBinary = oamPublishesBinaryForThisMachine) {
8637
8642
  const head = "Runtime: node (oam is not installed, which is fine -- node is the supported default. ";
8638
8643
  if (os === CURRENT_OS && !publishesBinary()) {
@@ -9350,7 +9355,7 @@ function sameFingerprint(a, b) {
9350
9355
  async function promptCollision(path5, diff, io, keptEnvKeys) {
9351
9356
  const stdin = io?.stdin ?? process.stdin;
9352
9357
  const stdout = io?.stdout ?? process.stdout;
9353
- const rl = createInterface({ input: stdin, output: stdout, terminal: io?.terminal });
9358
+ const rl = createInterface2({ input: stdin, output: stdout, terminal: io?.terminal });
9354
9359
  try {
9355
9360
  const raw = await questionOrEmpty(
9356
9361
  rl,
@@ -9944,7 +9949,7 @@ function entryEnvKeys(entry) {
9944
9949
  async function promptUninstall(question, io) {
9945
9950
  const stdin = io?.stdin ?? process.stdin;
9946
9951
  const stdout = io?.stdout ?? process.stdout;
9947
- const rl = createInterface({ input: stdin, output: stdout, terminal: io?.terminal });
9952
+ const rl = createInterface2({ input: stdin, output: stdout, terminal: io?.terminal });
9948
9953
  try {
9949
9954
  const raw = await questionOrEmpty(rl, question);
9950
9955
  if (raw === QUESTION_CANCELLED) return "cancelled";
@@ -10965,18 +10970,6 @@ function isInteractive2(opts) {
10965
10970
  if (opts.promptAnswer !== void 0) return true;
10966
10971
  return Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY);
10967
10972
  }
10968
- async function askYesNo2(opts, question) {
10969
- if (opts.promptAnswer !== void 0) return opts.promptAnswer.trim().toLowerCase();
10970
- const input = opts.io?.stdin ?? process.stdin;
10971
- const output = opts.io?.stdout ?? process.stdout;
10972
- const rl = createInterface2({ input, output, terminal: opts.io?.terminal });
10973
- try {
10974
- const raw = await questionOrEmpty(rl, question);
10975
- return raw === QUESTION_CANCELLED ? raw : raw.trim().toLowerCase();
10976
- } finally {
10977
- rl.close();
10978
- }
10979
- }
10980
10973
  async function runTryCleanup(opts) {
10981
10974
  const out = opts.out ?? createStreamWriter(process.stdout);
10982
10975
  const err = opts.err ?? createStreamWriter(process.stderr);
@@ -11032,7 +11025,7 @@ async function runTryCleanup(opts) {
11032
11025
  printErr(" Re-run with --force (or -y) to remove it.");
11033
11026
  return { exitCode: 2, written: [] };
11034
11027
  }
11035
- const answer = await askYesNo2(opts, ` Remove "${marker.entryName}"? [y/N] `);
11028
+ const answer = await askYesNo(opts, ` Remove "${marker.entryName}"? [y/N] `);
11036
11029
  if (answer === QUESTION_CANCELLED) {
11037
11030
  printErr("yaw-mcp try-cleanup: Cancelled. Nothing was removed.");
11038
11031
  return { exitCode: 130, written: [] };
@@ -11436,7 +11429,7 @@ function foldBundleWarnings(warnings, probe) {
11436
11429
  const prefix = `${probe.path}:`;
11437
11430
  return warnings.filter((w) => !w.startsWith(prefix));
11438
11431
  }
11439
- var VERSION = true ? "1.0.12" : "dev";
11432
+ var VERSION = true ? "1.0.15" : "dev";
11440
11433
  var DOCTOR_USAGE = `Usage: yaw-mcp doctor [--json]
11441
11434
 
11442
11435
  Print a diagnostic of your yaw-mcp setup.
@@ -11933,10 +11926,14 @@ async function collectVaultStatus(opts) {
11933
11926
  let passphraseUnlocks = null;
11934
11927
  let checkMarkerCorrupt = false;
11935
11928
  if (passphrase !== "" && vault !== null && vaultVerifiesPassphrases(vault)) {
11936
- const verdict = await checkVaultPassphrase(vault, passphrase);
11937
- lock();
11938
- passphraseUnlocks = verdict === "opens";
11939
- checkMarkerCorrupt = verdict === "marker-corrupt";
11929
+ try {
11930
+ const verdict = await checkVaultPassphrase(vault, passphrase);
11931
+ passphraseUnlocks = verdict === "opens";
11932
+ checkMarkerCorrupt = verdict === "marker-corrupt";
11933
+ } catch {
11934
+ } finally {
11935
+ lock();
11936
+ }
11940
11937
  }
11941
11938
  const refs = [];
11942
11939
  const malformed = [];
@@ -12983,15 +12980,15 @@ function touch(cache, key, value) {
12983
12980
  cache.delete(key);
12984
12981
  cache.set(key, value);
12985
12982
  }
12986
- var SEP = "\0";
12983
+ var SEP2 = "\0";
12987
12984
  var ESC2 = String.fromCharCode(1);
12988
12985
  function esc(text) {
12989
- return text.includes(ESC2) || text.includes(SEP) ? text.replaceAll(ESC2, ESC2 + ESC2).replaceAll(SEP, ESC2 + SEP) : text;
12986
+ return text.includes(ESC2) || text.includes(SEP2) ? text.replaceAll(ESC2, ESC2 + ESC2).replaceAll(SEP2, ESC2 + SEP2) : text;
12990
12987
  }
12991
12988
  function serverSignature(server) {
12992
- let sig = `${esc(server.namespace)}${SEP}${esc(server.name)}${SEP}${esc(server.description ?? "")}`;
12989
+ let sig = `${esc(server.namespace)}${SEP2}${esc(server.name)}${SEP2}${esc(server.description ?? "")}`;
12993
12990
  for (const tool of server.tools) {
12994
- sig += `${SEP}${esc(tool.name)}${SEP}${esc(tool.description ?? "")}`;
12991
+ sig += `${SEP2}${esc(tool.name)}${SEP2}${esc(tool.description ?? "")}`;
12995
12992
  }
12996
12993
  return sig;
12997
12994
  }
@@ -13671,7 +13668,6 @@ Run \`yaw-mcp doctor\` for what each one needs.
13671
13668
  // src/import-cmd.ts
13672
13669
  import { homedir as homedir18 } from "os";
13673
13670
  import { basename as basename3, resolve as resolvePath } from "path";
13674
- import { createInterface as createInterface3 } from "readline/promises";
13675
13671
  var IMPORT_USAGE = `Usage: yaw-mcp import <client> [flags]
13676
13672
 
13677
13673
  Read the MCP servers a client already has configured and add them to your
@@ -13974,18 +13970,6 @@ function isInteractive3(opts) {
13974
13970
  if (opts.promptAnswer !== void 0) return true;
13975
13971
  return Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY);
13976
13972
  }
13977
- async function askYesNo3(opts, question) {
13978
- if (opts.promptAnswer !== void 0) return opts.promptAnswer.trim().toLowerCase();
13979
- const input = opts.io?.stdin ?? process.stdin;
13980
- const output = opts.io?.stdout ?? process.stdout;
13981
- const rl = createInterface3({ input, output, terminal: opts.io?.terminal });
13982
- try {
13983
- const raw = await questionOrEmpty(rl, question);
13984
- return raw === QUESTION_CANCELLED ? raw : raw.trim().toLowerCase();
13985
- } finally {
13986
- rl.close();
13987
- }
13988
- }
13989
13973
  async function runImport(opts) {
13990
13974
  const out = opts.out ?? createStreamWriter(process.stdout);
13991
13975
  const errOut = opts.err ?? createStreamWriter(process.stderr);
@@ -14257,7 +14241,7 @@ If the previous entry was a different server you meant to keep, restore it from
14257
14241
  );
14258
14242
  return { exitCode: 0, written };
14259
14243
  }
14260
- const answer = await askYesNo3(
14244
+ const answer = await askYesNo(
14261
14245
  opts,
14262
14246
  ` Remove ${imported.length === 1 ? "it" : `those ${imported.length} entries`} from ${resolved.absolute}? [y/N] `
14263
14247
  );
@@ -14314,7 +14298,6 @@ If the previous entry was a different server you meant to keep, restore it from
14314
14298
  // src/local-add-cmd.ts
14315
14299
  import { readFile as readFile14 } from "fs/promises";
14316
14300
  import { homedir as homedir19 } from "os";
14317
- import { createInterface as createInterface4 } from "readline/promises";
14318
14301
  var ADD_USAGE = `Usage: yaw-mcp add <slug> [flags]
14319
14302
  yaw-mcp add <name> --command "<launch line>" [flags]
14320
14303
  yaw-mcp add <name> --url <https://...> [flags]
@@ -14973,18 +14956,6 @@ function isInteractive4(opts) {
14973
14956
  if (opts.promptAnswer !== void 0) return true;
14974
14957
  return Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY);
14975
14958
  }
14976
- async function askYesNo4(opts, question) {
14977
- if (opts.promptAnswer !== void 0) return opts.promptAnswer.trim().toLowerCase();
14978
- const input = opts.io?.stdin ?? process.stdin;
14979
- const output = opts.io?.stdout ?? process.stdout;
14980
- const rl = createInterface4({ input, output, terminal: opts.io?.terminal });
14981
- try {
14982
- const raw = await questionOrEmpty(rl, question);
14983
- return raw === QUESTION_CANCELLED ? raw : raw.trim().toLowerCase();
14984
- } finally {
14985
- rl.close();
14986
- }
14987
- }
14988
14959
  async function runRemove(opts) {
14989
14960
  const out = opts.out ?? createStreamWriter(process.stdout);
14990
14961
  const err = opts.err ?? createStreamWriter(process.stderr);
@@ -15020,7 +14991,7 @@ async function runRemove(opts) {
15020
14991
  printErr(" Re-run with --force (or -y) to remove it.");
15021
14992
  return { exitCode: 2, written: [] };
15022
14993
  }
15023
- const answer = await askYesNo4(opts, ` Remove "${doomed.namespace}"? [y/N] `);
14994
+ const answer = await askYesNo(opts, ` Remove "${doomed.namespace}"? [y/N] `);
15024
14995
  if (answer === QUESTION_CANCELLED) {
15025
14996
  printErr("yaw-mcp remove: Cancelled. Nothing was removed.");
15026
14997
  return { exitCode: 130, written: [] };
@@ -15187,7 +15158,6 @@ ${servers.length} server${servers.length === 1 ? "" : "s"} in ${loaded.path}`);
15187
15158
  import { existsSync as existsSync7 } from "fs";
15188
15159
  import { readFile as readFile15 } from "fs/promises";
15189
15160
  import { homedir as homedir20 } from "os";
15190
- import { createInterface as createInterface5 } from "readline/promises";
15191
15161
  var SET_USAGE = `Usage: yaw-mcp set <slug-or-namespace> <key=value> [<key=value> ...] [flags]
15192
15162
 
15193
15163
  Change per-server fields in your local ~/.yaw-mcp/bundles.json without
@@ -15355,18 +15325,6 @@ function isInteractive5(opts) {
15355
15325
  if (opts.promptAnswer !== void 0) return true;
15356
15326
  return Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY);
15357
15327
  }
15358
- async function askYesNo5(opts, question) {
15359
- if (opts.promptAnswer !== void 0) return opts.promptAnswer.trim().toLowerCase();
15360
- const input = opts.io?.stdin ?? process.stdin;
15361
- const output = opts.io?.stdout ?? process.stdout;
15362
- const rl = createInterface5({ input, output, terminal: opts.io?.terminal });
15363
- try {
15364
- const raw = await questionOrEmpty(rl, question);
15365
- return raw === QUESTION_CANCELLED ? raw : raw.trim().toLowerCase();
15366
- } finally {
15367
- rl.close();
15368
- }
15369
- }
15370
15328
  function render(value) {
15371
15329
  return value === void 0 ? "unset" : JSON.stringify(value);
15372
15330
  }
@@ -15537,7 +15495,7 @@ async function runSet(opts) {
15537
15495
  }
15538
15496
  return { exitCode: 2, written: [] };
15539
15497
  }
15540
- const answer = await askYesNo5(opts, `${phrase[0].toUpperCase()}${phrase.slice(1)} on "${namespace}"? [y/N] `);
15498
+ const answer = await askYesNo(opts, `${phrase[0].toUpperCase()}${phrase.slice(1)} on "${namespace}"? [y/N] `);
15541
15499
  if (answer === QUESTION_CANCELLED) {
15542
15500
  if (opts.json) printErr(JSON.stringify({ ok: false, error: "Cancelled.", cancelled: true, path: path5, namespace }));
15543
15501
  else printErr("Aborted.");
@@ -15653,7 +15611,6 @@ async function runEnableDisable(opts) {
15653
15611
  import { existsSync as existsSync8 } from "fs";
15654
15612
  import { unlink as unlink3 } from "fs/promises";
15655
15613
  import { homedir as homedir21 } from "os";
15656
- import { createInterface as createInterface6 } from "readline/promises";
15657
15614
  var RESET_LEARNING_USAGE = `Usage: yaw-mcp reset-learning
15658
15615
 
15659
15616
  Delete ~/.yaw-mcp/state.json so cross-session learning starts fresh.
@@ -15699,18 +15656,6 @@ function isInteractive6(opts) {
15699
15656
  if (opts.promptAnswer !== void 0) return true;
15700
15657
  return Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY);
15701
15658
  }
15702
- async function askYesNo6(opts, question) {
15703
- if (opts.promptAnswer !== void 0) return opts.promptAnswer.trim().toLowerCase();
15704
- const input = opts.io?.stdin ?? process.stdin;
15705
- const output = opts.io?.stdout ?? process.stdout;
15706
- const rl = createInterface6({ input, output, terminal: opts.io?.terminal });
15707
- try {
15708
- const raw = await questionOrEmpty(rl, question);
15709
- return raw === QUESTION_CANCELLED ? raw : raw.trim().toLowerCase();
15710
- } finally {
15711
- rl.close();
15712
- }
15713
- }
15714
15659
  async function runResetLearning(opts = {}) {
15715
15660
  const home = opts.home ?? homedir21();
15716
15661
  const env = opts.env ?? process.env;
@@ -15754,7 +15699,7 @@ async function runResetLearning(opts = {}) {
15754
15699
  printErr(" Re-run with --force (or -y).");
15755
15700
  return { exitCode: 2, lines, removed: false, path: filePath };
15756
15701
  }
15757
- const answer = await askYesNo6(opts, "Delete it? [y/N] ");
15702
+ const answer = await askYesNo(opts, "Delete it? [y/N] ");
15758
15703
  if (answer === QUESTION_CANCELLED) {
15759
15704
  printErr("yaw-mcp reset-learning: Cancelled. Nothing was deleted.");
15760
15705
  return { exitCode: 130, lines, removed: false, path: filePath };
@@ -18146,6 +18091,9 @@ function openInSystemBrowser(url, spawnLauncher = spawn4) {
18146
18091
  }
18147
18092
  function openSecretEntryPage(opts) {
18148
18093
  if (opts.fields.length === 0) return Promise.reject(new Error("a secret entry page needs at least one field"));
18094
+ if (new Set(opts.fields.map((f) => f.name)).size !== opts.fields.length) {
18095
+ return Promise.reject(new Error("secret entry page field names must be unique"));
18096
+ }
18149
18097
  const ttlMs = opts.ttlMs ?? SECRET_ENTRY_PAGE_TTL_MS;
18150
18098
  const token = randomBytes3(32).toString("hex");
18151
18099
  const expectedPath = Buffer.from(`/${token}`, "utf8");
@@ -18401,6 +18349,10 @@ function isPrewarmEnabled() {
18401
18349
  }
18402
18350
  var exposureWarnedFor = null;
18403
18351
  var LITE_BY_DEFAULT_CLIENTS = /* @__PURE__ */ new Set(["typed-cli"]);
18352
+ var NO_RELIST_CLIENTS = /* @__PURE__ */ new Set(["codex-mcp-client", "continue-client"]);
18353
+ function clientRelistsTools(clientInfo) {
18354
+ return !(clientInfo?.name !== void 0 && NO_RELIST_CLIENTS.has(clientInfo.name));
18355
+ }
18404
18356
  function resolveToolExposure(clientInfo) {
18405
18357
  const fallback = clientInfo?.name !== void 0 && LITE_BY_DEFAULT_CLIENTS.has(clientInfo.name) ? "lite" : "gateway";
18406
18358
  const raw = process.env.YAW_MCP_TOOL_EXPOSURE?.trim().toLowerCase();
@@ -18537,6 +18489,12 @@ function computeToolOverlaps(connections) {
18537
18489
  });
18538
18490
  return overlaps;
18539
18491
  }
18492
+ function newExplicitLoadTally() {
18493
+ return { anyChanged: false, anyError: false, anyCapped: false, advertisedGrew: false };
18494
+ }
18495
+ function explicitLoadIsError(tally) {
18496
+ return tally.anyError || tally.anyCapped && !tally.anyChanged ? true : void 0;
18497
+ }
18540
18498
  var ConnectServer = class _ConnectServer {
18541
18499
  server;
18542
18500
  clientBridge;
@@ -18576,6 +18534,14 @@ var ConnectServer = class _ConnectServer {
18576
18534
  * would see an unchanged file and skip the reconcile that never finished,
18577
18535
  * leaving a connection running on config the user has already replaced. */
18578
18536
  bundlesReconcilePending = false;
18537
+ /** The startup pre-warm while it is still running, else null. find_tool
18538
+ * and exec read only LEARNED tool lists, and on a fresh install the
18539
+ * pre-warm is what learns them -- fire-and-forget from `oninitialized`,
18540
+ * so a first call can land before it: find_tool said "No configured
18541
+ * server has a tool matching" a configured server's tool, and exec said
18542
+ * "Unknown tool". Both now wait for this (bounded, STARTUP_PREWARM_WAIT_MS)
18543
+ * when the answer would otherwise be "nothing". */
18544
+ startupPrewarm = null;
18579
18545
  toolRoutes = /* @__PURE__ */ new Map();
18580
18546
  resourceRoutes = /* @__PURE__ */ new Map();
18581
18547
  promptRoutes = /* @__PURE__ */ new Map();
@@ -18649,9 +18615,12 @@ var ConnectServer = class _ConnectServer {
18649
18615
  // Short-term memory of activation failures; used by dispatch to
18650
18616
  // down-rank recently-flaky servers. Cleared on successful activation.
18651
18617
  activationFailures = /* @__PURE__ */ new Map();
18652
- // Session-scoped credential overrides supplied by the user via MCP
18653
- // elicitation when a server's stderr indicated a missing env var.
18654
- // Cleared on shutdown — persistence belongs in the Yaw MCP
18618
+ // Session-scoped credential values the user typed on the masked-entry page
18619
+ // when a server's stderr named a missing env var (maybeElicitAndRetry).
18620
+ // They fill in keys the server's bundles.json env leaves unset or empty; a
18621
+ // non-empty value in the file wins (see effectiveEntry), and a value the
18622
+ // child still rejects after the retry is dropped rather than kept to shadow
18623
+ // a later fix. Cleared on shutdown — persistence belongs in the Yaw MCP
18655
18624
  // bundles.json, these are a "get me running now" shortcut.
18656
18625
  elicitedEnv = /* @__PURE__ */ new Map();
18657
18626
  // Stop-asking latch for the VAULT PASSPHRASE elicitation. Not keyed by
@@ -18688,7 +18657,31 @@ var ConnectServer = class _ConnectServer {
18688
18657
  // credentials. Per-namespace (unlike the vault counter) because these are
18689
18658
  // the child's own secrets. Bounds the re-ask that replaced the old
18690
18659
  // "already elicited, never ask again" latch -- see MAX_CREDENTIAL_PROMPTS.
18660
+ // An expired page spends its ask like any other; what sets an expiry apart
18661
+ // is that it does not latch (below), so the next activate asks again while
18662
+ // this count allows.
18691
18663
  credentialPrompts = /* @__PURE__ */ new Map();
18664
+ // Latch: namespaces whose prompt has ended the asking for the session,
18665
+ // keyed by the REASON so a follow-up activate can surface the right
18666
+ // refusal. The vault uses a single boolean (`vaultPassphraseElicited`)
18667
+ // and the same shaped message regardless of why; here, "declined" is a
18668
+ // user decision (return the raw spawn error, the user knows what they
18669
+ // did), "empty" is the defensive twin of it (a page result with no
18670
+ // non-empty value, which the shipped page cannot produce -- see the
18671
+ // submitted branch of maybeElicitAndRetry), and "no-page" / "no-browser"
18672
+ // are wall-shaped failures a follow-up activate would hit identically,
18673
+ // so the user gets the bundles.json hint on every attempt. An expired page
18674
+ // never latches: the user may simply have been away.
18675
+ //
18676
+ // There is no reset for either prompt's latch short of a new ConnectServer.
18677
+ // This one is cleared only by shutdown(); the vault's
18678
+ // (`vaultPassphraseElicited`) is never cleared at all, and
18679
+ // `clearSessionVaultPassphrase` -- called only from shutdown() and tests --
18680
+ // clears the vault PASSPHRASE, not a latch. `yaw-mcp secrets reset` runs in
18681
+ // its own process and cannot reach this one's state; it tells the user to
18682
+ // restart a running server instead. Not worth building a reset until a verb
18683
+ // that needs one (e.g. a per-server "forget I asked") actually lands.
18684
+ credentialElicited = /* @__PURE__ */ new Map();
18692
18685
  // In-flight activation promises, keyed by namespace. Dedupes
18693
18686
  // concurrent activation attempts for the same namespace so that two
18694
18687
  // tool calls landing on a disconnected upstream don't each spawn
@@ -18757,8 +18750,8 @@ var ConnectServer = class _ConnectServer {
18757
18750
  // Short-TTL dedup cache for discover output. Agents often call
18758
18751
  // discover twice in quick succession (e.g. once to list, again after
18759
18752
  // a failed activate) — the second call returns the same text if
18760
- // nothing has changed. Keyed on (configVersion, context, autoWarmed,
18761
- // active-namespace-set) so activate/deactivate naturally invalidates.
18753
+ // nothing has changed. See discoverCacheKey for the key's components; the
18754
+ // connected set is one, so activate/deactivate naturally invalidates.
18762
18755
  discoverCache = null;
18763
18756
  static DISCOVER_CACHE_TTL_MS = 3e3;
18764
18757
  // Baseline idle-call threshold lives in resolveIdleThreshold() (module
@@ -18798,7 +18791,7 @@ var ConnectServer = class _ConnectServer {
18798
18791
  static SHUTDOWN_DRAIN_MS = 2e3;
18799
18792
  constructor() {
18800
18793
  this.server = new Server(
18801
- { name: "yaw-mcp", version: true ? "1.0.12" : "dev" },
18794
+ { name: "yaw-mcp", version: true ? "1.0.15" : "dev" },
18802
18795
  {
18803
18796
  capabilities: {
18804
18797
  tools: { listChanged: true },
@@ -18924,6 +18917,63 @@ var ConnectServer = class _ConnectServer {
18924
18917
  });
18925
18918
  });
18926
18919
  };
18920
+ /** Wait for the startup pre-warm, if it is still running, for at most
18921
+ * STARTUP_PREWARM_WAIT_MS, or until `signal` aborts. Resolves either way:
18922
+ * past the bound the caller answers from what is known, exactly as it did
18923
+ * before this existed, and on an abort the caller checks the signal. */
18924
+ async settleStartupPrewarm(signal) {
18925
+ const pending2 = this.startupPrewarm;
18926
+ if (!pending2 || signal?.aborted) return;
18927
+ let timer;
18928
+ let onAbort;
18929
+ const bound = new Promise((resolve8) => {
18930
+ timer = setTimeout(resolve8, _ConnectServer.STARTUP_PREWARM_WAIT_MS);
18931
+ timer.unref?.();
18932
+ onAbort = () => resolve8();
18933
+ signal?.addEventListener("abort", onAbort, { once: true });
18934
+ });
18935
+ try {
18936
+ await Promise.race([pending2, bound]);
18937
+ } finally {
18938
+ clearTimeout(timer);
18939
+ if (onAbort) signal?.removeEventListener("abort", onAbort);
18940
+ }
18941
+ }
18942
+ /** How long find_tool / exec wait on a still-running startup pre-warm.
18943
+ * Measured on a loaded Windows ARM64 box, a fresh install's pre-warm of
18944
+ * two npx/oam servers finished 4-6 s after initialize; this leaves room
18945
+ * for a larger bundle without holding a call anywhere near a client's
18946
+ * tool timeout (Codex: 300 s). Not readonly, so a test can shrink it. */
18947
+ static STARTUP_PREWARM_WAIT_MS = 2e4;
18948
+ /** The line a load reply needs for a client that never re-lists tools
18949
+ * (NO_RELIST_CLIENTS), or null for every other client.
18950
+ *
18951
+ * The reply above it enumerates the tools just loaded as if they were now
18952
+ * callable, which is true for a client that re-lists and false for this
18953
+ * one: its tool list is the startup one, so the model's direct call fails
18954
+ * inside the client. The example names a tool that is really reachable --
18955
+ * a served, not shadowed, tool of the first namespace that loaded -- and,
18956
+ * where the server has one, a tool that needs no arguments (read-only
18957
+ * first), so `args: {}` runs as written. When every tool needs arguments
18958
+ * the line says to fill them in rather than show a call that would fail. */
18959
+ execHintForNonRelistingClient(loaded) {
18960
+ if (clientRelistsTools(this.server.getClientVersion())) return null;
18961
+ const needsNoArgs = (t) => {
18962
+ const required = t.inputSchema?.required;
18963
+ return !Array.isArray(required) || required.length === 0;
18964
+ };
18965
+ for (const ns of loaded) {
18966
+ const conn = this.connections.get(ns);
18967
+ if (!conn) continue;
18968
+ const served = this.splitShadowedTools(ns, conn.tools).served;
18969
+ const example = served.find((t) => needsNoArgs(t) && t.annotations?.readOnlyHint === true) ?? served.find(needsNoArgs) ?? served[0];
18970
+ if (example === void 0) continue;
18971
+ const call = JSON.stringify({ steps: [{ tool: example.namespacedName, args: {} }] });
18972
+ const fill = needsNoArgs(example) ? "" : ` (with the tool's own arguments in "args"; mcp_connect_read_tool shows a tool's arguments)`;
18973
+ return `This client keeps the tool list it read at startup, so the tools just loaded are not in it and a direct call to one fails. Call them through mcp_connect_exec instead, e.g. ${call}${fill}`;
18974
+ }
18975
+ return null;
18976
+ }
18927
18977
  rebuildRoutes() {
18928
18978
  this.toolRoutes = buildToolRoutes(this.connections, this.getDeferredServers());
18929
18979
  this.resourceRoutes = buildResourceRoutes(this.connections);
@@ -18981,11 +19031,16 @@ var ConnectServer = class _ConnectServer {
18981
19031
  // show, so a curated list is still worth rendering over it.
18982
19032
  //
18983
19033
  // This is the ONE precedence rule for a cold server's tool list. Every
18984
- // reader goes through it -- getProfiledActiveServers merges once and the
18985
- // discover body reads the merged `server.toolCache`; rankableFor calls it
18986
- // for the BM25 corpus. Two more copies of the resolution used to live in
18987
- // those readers with `??` semantics (empty learned list WINS), so discover
18988
- // could rank a server on an empty list while listing its curated tools.
19034
+ // reader of the LIST goes through it: getProfiledActiveServers merges once,
19035
+ // and what reads its result (the discover body, getDeferredServers and so
19036
+ // the deferred routes and tools/list, dispatch's sampling tiebreak) sees the
19037
+ // merged `server.toolCache`; rankableFor (the BM25 corpus),
19038
+ // estimateTokensFor, coldStartHint and unmatchedFilterNames call it
19039
+ // directly. Copies of the resolution used to live in readers with `??`
19040
+ // semantics (empty learned list WINS), so discover could rank a server on
19041
+ // an empty list while listing its curated tools. hasKnownTools and
19042
+ // isLearnedCacheStale read this.toolCache raw on purpose: they ask whether
19043
+ // a list was OBSERVED, and an empty one was.
18989
19044
  //
18990
19045
  // Identity preservation: when both sides resolve to the same array
18991
19046
  // reference — which in practice means BOTH are undefined (server.ts
@@ -19227,18 +19282,46 @@ var ConnectServer = class _ConnectServer {
19227
19282
  return changed;
19228
19283
  }
19229
19284
  /** The entry as a fresh activation would actually launch it: the config
19230
- * file's entry with any session-elicited credentials merged over its env.
19285
+ * file's entry with any session-elicited credentials filling in the env
19286
+ * keys the file leaves unset or empty.
19231
19287
  *
19232
- * ONE copy, reached from both the activation path (which builds the child
19233
- * from it) and the staleness check below (which compares a live child
19234
- * against it). Two copies drifted the moment elicitation existed: a
19235
- * connection is launched from the MERGED shape and remembers it as
19236
- * connection.config, so comparing a freshly-parsed entry against it
19237
- * directly reads every elicited server as "launch config changed" and
19238
- * reaps a healthy child on the next unrelated edit. */
19288
+ * The FILE wins for a key it sets to a non-empty value. The give-up and
19289
+ * refusal messages tell the user to set the key in bundles.json and
19290
+ * activate again, and that edit has to be what the next launch uses:
19291
+ * with the elicited value merged on top, a value typed this session
19292
+ * shadowed the file for the rest of it, so the recommended fix did
19293
+ * nothing until a client restart -- and the staleness check below, which
19294
+ * compares through this same function, never saw the edit either, so it
19295
+ * left the child running on the typed value. With the file winning, a
19296
+ * file value that differs from the typed one moves the launch identity
19297
+ * like any other env edit, and reconcileConfig reaps the child so the next
19298
+ * activate launches it from the file.
19299
+ *
19300
+ * ONE copy, reached from the activation path (which builds the child from
19301
+ * it), the staleness check below (which compares a live child against it)
19302
+ * and handleReadTool's transient connect (which must inspect the server
19303
+ * under the env an activation would give it). Copies drifted the moment
19304
+ * elicitation existed: a connection is launched from the MERGED shape and
19305
+ * remembers it as connection.config, so comparing a freshly-parsed entry
19306
+ * against it directly reads every elicited server as "launch config
19307
+ * changed" and reaps a healthy child on the next unrelated edit. */
19239
19308
  effectiveEntry(entry) {
19240
19309
  const elicited = this.elicitedEnv.get(entry.namespace);
19241
- return elicited ? { ...entry, env: { ...entry.env, ...elicited } } : entry;
19310
+ if (!elicited) return entry;
19311
+ const fillIns = {};
19312
+ for (const [key, value] of Object.entries(elicited)) {
19313
+ if (!this.entrySetsEnv(entry, key)) fillIns[key] = value;
19314
+ }
19315
+ return Object.keys(fillIns).length === 0 ? entry : { ...entry, env: { ...entry.env, ...fillIns } };
19316
+ }
19317
+ /** Does the config entry itself set `key` to a non-empty value? Such a key
19318
+ * belongs to the file: effectiveEntry never lets an elicited value replace
19319
+ * it, and maybeElicitAndRetry therefore never asks for it (the answer would
19320
+ * be ignored). An empty string counts as unset -- a `"GITHUB_TOKEN": ""`
19321
+ * placeholder is exactly the gap the prompt exists to fill. */
19322
+ entrySetsEnv(entry, key) {
19323
+ const value = entry?.env?.[key];
19324
+ return typeof value === "string" && value.length > 0;
19242
19325
  }
19243
19326
  /** Is this namespace exempt from the idle reaper (types.ts `pinned`)?
19244
19327
  *
@@ -19407,12 +19490,16 @@ var ConnectServer = class _ConnectServer {
19407
19490
  serverCount: this.config?.servers.length ?? 0
19408
19491
  });
19409
19492
  await this.hydrateComplianceGrades();
19493
+ this.rebuildRoutes();
19410
19494
  if (this.getProfiledActiveServers().some((s) => s.command !== void 0 && uvLaunchKind(s.command) !== null)) {
19411
19495
  ensureUv().catch((err) => log("warn", "uv prewarm failed", { error: err?.message }));
19412
19496
  }
19413
19497
  const transport = new StdioServerTransport();
19414
19498
  this.server.oninitialized = () => {
19415
- this.prewarmDormantServers().catch((err) => log("warn", "Pre-warm failed", { error: err?.message }));
19499
+ const prewarm = this.prewarmDormantServers().catch((err) => log("warn", "Pre-warm failed", { error: err?.message })).finally(() => {
19500
+ if (this.startupPrewarm === prewarm) this.startupPrewarm = null;
19501
+ });
19502
+ this.startupPrewarm = prewarm;
19416
19503
  if (isAutoLoadEnabled()) {
19417
19504
  if (this.persistenceReady) {
19418
19505
  this.autoLoadRecurringPack().catch((err) => log("warn", "Auto-load failed", { error: err?.message }));
@@ -19657,7 +19744,7 @@ var ConnectServer = class _ConnectServer {
19657
19744
  if (name === META_TOOLS.findTool.name) {
19658
19745
  const q = typeof args.query === "string" ? args.query : "";
19659
19746
  const limit = typeof args.limit === "number" && Number.isFinite(args.limit) ? args.limit : void 0;
19660
- return this.observed(this.attachGuideNudge(this.handleFindTool(q, limit)));
19747
+ return this.observed(this.attachGuideNudge(await this.handleFindTool(q, limit)));
19661
19748
  }
19662
19749
  if (name === META_TOOLS.exec.name) {
19663
19750
  const result2 = await this.handleExec(args, extra?.signal);
@@ -20063,10 +20150,9 @@ var ConnectServer = class _ConnectServer {
20063
20150
  ]
20064
20151
  };
20065
20152
  }
20066
- // Drop the memoized discover body. The cache key only covers
20067
- // (configVersion, context, warmedNamespace, connected set, tool filters,
20068
- // advertised set), so state that
20069
- // discover RENDERS but the key does not see -- activation failures
20153
+ // Drop the memoized discover body. The cache key covers only the components
20154
+ // discoverCacheKey (below) lists and explains, so state that discover
20155
+ // RENDERS but the key does not see -- activation failures
20070
20156
  // (formatHealthWarning) and learning counters (usage:/reliability: lines)
20071
20157
  // -- has to invalidate explicitly. Without this the exact case the cache
20072
20158
  // was built for ("discover, failed activate, discover again") replays the
@@ -20141,7 +20227,7 @@ var ConnectServer = class _ConnectServer {
20141
20227
  }
20142
20228
  if (disabled.length > 0) {
20143
20229
  parts.push(
20144
- `Set "isActive": true for a server in the bundles.json that defines it (~/.yaw-mcp/bundles.json, or a trusted project-local .yaw-mcp/bundles.json); mcp_connect_discover lists what is installed but disabled. The edit is picked up on the next mcp_connect_* call, with no client restart.`
20230
+ `Set "isActive": true for a server in ${bundlesFileHint("defines-it")}; mcp_connect_discover lists what is installed but disabled. The edit is picked up on the next mcp_connect_* call, with no client restart.`
20145
20231
  );
20146
20232
  }
20147
20233
  return parts.join(" ");
@@ -20162,7 +20248,10 @@ var ConnectServer = class _ConnectServer {
20162
20248
  return { content: [{ type: "text", text: this.emptyStateText() }] };
20163
20249
  }
20164
20250
  const allProfiled = this.getProfiledActiveServers();
20165
- const warmPrefix = warmedNamespace ? `Auto-loaded "${warmedNamespace}" \u2014 top match for your query.
20251
+ const warmExecHint = warmedNamespace ? this.execHintForNonRelistingClient([warmedNamespace]) : null;
20252
+ const warmBanner = warmedNamespace ? `Auto-loaded "${warmedNamespace}" \u2014 top match for your query.${warmExecHint ? `
20253
+ ${warmExecHint}` : ""}` : "";
20254
+ const warmPrefix = warmBanner ? `${warmBanner}
20166
20255
 
20167
20256
  ` : "";
20168
20257
  const focusMiss = (text) => ({
@@ -20175,7 +20264,7 @@ var ConnectServer = class _ConnectServer {
20175
20264
  const configured = this.config.servers.find((srv) => srv.namespace === focusNamespace);
20176
20265
  if (configured && configured.isActive === false) {
20177
20266
  return focusMiss(
20178
- `"${focusNamespace}" is installed but disabled ("isActive": false in ~/.yaw-mcp/bundles.json). Call mcp_connect_discover with no arguments to list what is available.`
20267
+ `"${focusNamespace}" is installed but disabled -- "isActive": false in ${bundlesFileHint("defines-it")}. Call mcp_connect_discover with no arguments to list what is available.`
20179
20268
  );
20180
20269
  }
20181
20270
  if (configured) {
@@ -20187,7 +20276,7 @@ var ConnectServer = class _ConnectServer {
20187
20276
  1
20188
20277
  )[0];
20189
20278
  return focusMiss(
20190
- near ? `"${focusNamespace}" is not in ~/.yaw-mcp/bundles.json. Did you mean: ${near}?` : `"${focusNamespace}" is not in ~/.yaw-mcp/bundles.json. Call mcp_connect_discover with no arguments to list what is available.`
20279
+ near ? `"${focusNamespace}" is not in ${bundlesFileHint("in-effect")}. Did you mean: ${near}?` : `"${focusNamespace}" is not in ${bundlesFileHint("in-effect")}. Call mcp_connect_discover with no arguments to list what is available.`
20191
20280
  );
20192
20281
  }
20193
20282
  }
@@ -20219,8 +20308,8 @@ var ConnectServer = class _ConnectServer {
20219
20308
  allProfiled.length === 0 ? `${this.noServersEnabledText()}
20220
20309
  ` : context ? "Servers ranked by relevance:\n" : "Installed MCP servers:\n"
20221
20310
  );
20222
- if (warmedNamespace) {
20223
- lines.push(`Auto-loaded "${warmedNamespace}" \u2014 top match for your query.
20311
+ if (warmBanner) {
20312
+ lines.push(`${warmBanner}
20224
20313
  `);
20225
20314
  }
20226
20315
  const minCompliance = resolveMinCompliance();
@@ -20610,7 +20699,7 @@ ${activeCount} loaded in this session, ${totalTools} ${totalTools === 1 ? "tool"
20610
20699
  if (!refusal) return null;
20611
20700
  switch (refusal.kind) {
20612
20701
  case "disabled":
20613
- return `"${refusal.namespace}" is installed but disabled. Set "isActive": true for it in ~/.yaw-mcp/bundles.json and try again to ${purpose} -- the edit is picked up on the next mcp_connect_* call, with no client restart.`;
20702
+ return `"${refusal.namespace}" is installed but disabled. Set "isActive": true for it in ${bundlesFileHint("defines-it")} and try again to ${purpose} -- the edit is picked up on the next mcp_connect_* call, with no client restart.`;
20614
20703
  case "profile":
20615
20704
  return `"${refusal.namespace}" is not allowed by the project profile at ${refusal.profilePath}.`;
20616
20705
  case "compliance":
@@ -20732,7 +20821,7 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
20732
20821
  */
20733
20822
  coldStartHint(server) {
20734
20823
  if (server.type !== "local" || server.command === void 0) return "";
20735
- const cached = this.toolCache.get(server.namespace) ?? server.toolCache;
20824
+ const cached = this.mergeToolCache(server).toolCache;
20736
20825
  if (cached && cached.length > 0) return "";
20737
20826
  const base = (server.command.split(/[\\/]/).pop() ?? server.command).replace(/\.(exe|cmd|bat|ps1)$/i, "");
20738
20827
  const fetches = COLD_START_LAUNCHERS[base.toLowerCase()];
@@ -20849,9 +20938,14 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
20849
20938
  }
20850
20939
  // If the activation error names a missing credential (e.g. "GITHUB_TOKEN
20851
20940
  // is required") AND the client supports elicitation, ask the user for
20852
- // the values inline and retry activation once. Returns the retry result
20853
- // on success, or null when we can't/shouldn't elicit. Single-round only —
20854
- // we don't want to pester the user with a loop on every retry failure.
20941
+ // the values on the masked loopback page and retry the activation with
20942
+ // them. Returns the retry's result; a refusal that says what went wrong
20943
+ // (the page could not start, could not be shown or expired; the values
20944
+ // just typed were not accepted; shutdown); or null when we can't/shouldn't
20945
+ // elicit and the caller's give-up path should report the raw spawn error.
20946
+ // Bounded rather than single-round: inside the retry an ask bought, only a
20947
+ // key nobody has typed yet gets another ask, and every ask spends one of
20948
+ // the namespace's MAX_CREDENTIAL_PROMPTS for the session.
20855
20949
  async maybeElicitAndRetry(namespace, lastError, progress, fromPrewarm = false, isElicitRetry = false) {
20856
20950
  if (lastError instanceof VaultPassphraseRequiredError) {
20857
20951
  return this.elicitVaultPassphraseAndRetry(namespace, lastError, progress, fromPrewarm);
@@ -20859,7 +20953,10 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
20859
20953
  const stderr = lastError instanceof ActivationError ? lastError.stderrTail : void 0;
20860
20954
  const errMessage = lastError instanceof Error ? lastError.message : String(lastError);
20861
20955
  const haystack = [stderr, errMessage].filter(Boolean).join("\n");
20862
- const missing = detectMissingCredentials(haystack).filter((k) => !INTERNAL_SECRET_ENV_KEYS.has(k.toUpperCase()));
20956
+ const liveEntry = this.config?.servers.find((s) => s.namespace === namespace);
20957
+ const missing = detectMissingCredentials(haystack).filter(
20958
+ (k) => !isInternalSecretEnvKey(k) && !this.entrySetsEnv(liveEntry, k)
20959
+ );
20863
20960
  if (missing.length === 0) return null;
20864
20961
  const supplied = this.elicitedEnv.get(namespace) ?? {};
20865
20962
  if (isElicitRetry && missing.every((k) => k in supplied)) {
@@ -20872,14 +20969,30 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
20872
20969
  message: lastError instanceof Error ? lastError.message : String(lastError)
20873
20970
  });
20874
20971
  this.invalidateDiscoverCache();
20972
+ const kept = { ...supplied };
20973
+ for (const key of missing) delete kept[key];
20974
+ if (Object.keys(kept).length === 0) this.elicitedEnv.delete(namespace);
20975
+ else this.elicitedEnv.set(namespace, kept);
20875
20976
  const promptsSoFar = this.credentialPrompts.get(namespace) ?? 0;
20876
- 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 activate again -- the edit is picked up on the next mcp_connect_* call, with no client restart.` : ` Activate "${namespace}" again to try new ones.`;
20977
+ const retryHint = promptsSoFar >= MAX_CREDENTIAL_PROMPTS ? this.noFurtherCredentialPromptsHint(namespace, missing) : ` Activate "${namespace}" again to try new ones.`;
20877
20978
  return {
20878
20979
  ok: false,
20879
20980
  isChanged: false,
20880
20981
  message: `Could not load "${namespace}": it still reports ${missing.join(", ")} missing, so the values just provided were not accepted.${retryHint}`
20881
20982
  };
20882
20983
  }
20984
+ if (this.credentialElicited.has(namespace)) {
20985
+ const reason = this.credentialElicited.get(namespace);
20986
+ log("debug", "Namespace already declined or unreachable for credential prompt; not asking again", {
20987
+ namespace,
20988
+ missing,
20989
+ reason
20990
+ });
20991
+ if (reason === "no-page" || reason === "no-browser") {
20992
+ return this.credentialUnreachableRefusal(namespace, missing, reason);
20993
+ }
20994
+ return null;
20995
+ }
20883
20996
  const asked = this.credentialPrompts.get(namespace) ?? 0;
20884
20997
  if (asked >= MAX_CREDENTIAL_PROMPTS) {
20885
20998
  log("info", "Missing credentials persist after the prompt budget; not asking again", {
@@ -20897,43 +21010,59 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
20897
21010
  });
20898
21011
  return null;
20899
21012
  }
20900
- const properties = {};
20901
- for (const key of missing) {
20902
- properties[key] = {
20903
- type: "string",
20904
- title: key,
20905
- description: `The value for ${key} required by "${namespace}". Stored only for this yaw-mcp session.`
20906
- };
20907
- }
20908
21013
  progress?.(`Asking for ${missing.length === 1 ? "credential" : "credentials"}: ${missing.join(", ")}`);
20909
21014
  this.credentialPrompts.set(namespace, asked + 1);
20910
- let result;
20911
- try {
20912
- result = await this.server.elicitInput({
20913
- message: `"${namespace}" can't start without ${missing.join(", ")}. Provide ${missing.length === 1 ? "it" : "them"} to retry, or decline to cancel.`,
20914
- requestedSchema: {
20915
- type: "object",
20916
- properties,
20917
- required: missing
20918
- }
20919
- });
20920
- } catch (err) {
20921
- log("warn", "Elicitation request failed", {
20922
- namespace,
20923
- error: err instanceof Error ? err.message : String(err)
20924
- });
21015
+ const isPlural = missing.length !== 1;
21016
+ const what = isPlural ? "them" : "it";
21017
+ const fixHint = `Set ${what} in this server's "env" in ${bundlesFileHint("defines-it")} to skip this prompt in future sessions.`;
21018
+ const why = `"${namespace}" cannot start: it reports ${missing.join(", ")} missing. ${fixHint}`;
21019
+ const entry = await this.collectSecretOnLoopbackPage({
21020
+ namespace,
21021
+ why,
21022
+ secretNoun: isPlural ? `the values of ${missing.join(", ")}` : `the value of ${missing[0]}`,
21023
+ page: {
21024
+ title: `"${namespace}" needs ${isPlural ? "credentials" : "a credential"} to start`,
21025
+ // "its" in both slots: the subject is the one server, however many
21026
+ // keys it named.
21027
+ intro: `"${namespace}" cannot start without ${missing.join(", ")} and reported its missing key${isPlural ? "s" : ""} on its own. Type ${isPlural ? "each value" : "the value"} below. yaw-mcp keeps ${what} in memory for this session only -- never written to disk, and never passed to anything other than "${namespace}". ${fixHint}`,
21028
+ fields: missing.map((name) => ({ name, label: name })),
21029
+ doneMessage: "Received. You can close this tab and return to your MCP client."
21030
+ },
21031
+ progress
21032
+ });
21033
+ if (entry.kind === "failed") {
21034
+ log("info", "Credential elicitation did not complete", { namespace, missing });
21035
+ if (this.shuttingDown) return this.shuttingDownRefusal(namespace);
20925
21036
  return null;
20926
21037
  }
20927
- if (result.action !== "accept" || !result.content) {
20928
- log("info", "User declined credential elicitation", { namespace, action: result.action });
21038
+ if (entry.kind === "declined") {
21039
+ log("info", "User declined credential elicitation", { namespace });
21040
+ if (this.shuttingDown) return this.shuttingDownRefusal(namespace);
21041
+ this.credentialElicited.set(namespace, "declined");
20929
21042
  return null;
20930
21043
  }
21044
+ if (entry.kind === "unreachable") {
21045
+ log("info", "Credential masked-entry page was unreachable", {
21046
+ namespace,
21047
+ missing,
21048
+ reason: entry.reason
21049
+ });
21050
+ if (this.shuttingDown) return this.shuttingDownRefusal(namespace);
21051
+ if (entry.reason !== "expired") {
21052
+ this.credentialElicited.set(namespace, entry.reason);
21053
+ }
21054
+ return this.credentialUnreachableRefusal(namespace, missing, entry.reason);
21055
+ }
20931
21056
  const values = {};
20932
21057
  for (const key of missing) {
20933
- const v = result.content[key];
21058
+ const v = entry.values[key];
20934
21059
  if (typeof v === "string" && v.length > 0) values[key] = v;
20935
21060
  }
20936
- if (Object.keys(values).length === 0) return null;
21061
+ if (Object.keys(values).length === 0) {
21062
+ log("info", "Credential masked-entry page returned no values", { namespace, missing });
21063
+ this.credentialElicited.set(namespace, "empty");
21064
+ return null;
21065
+ }
20937
21066
  this.elicitedEnv.set(namespace, { ...supplied, ...values });
20938
21067
  progress?.("Got credentials \u2014 retrying load");
20939
21068
  return this.runActivateOne(
@@ -21059,6 +21188,53 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
21059
21188
  message: `Could not load "${namespace}": ${what}, so your local secret vault, which its env (${lastError.refKeys.join(", ")}) references, is still locked.${retryHint}`
21060
21189
  };
21061
21190
  }
21191
+ // The result for a missing-credential prompt whose masked-entry page never
21192
+ // took a value: it could not start, no browser could be opened for it, or
21193
+ // it expired with nothing submitted. The shape mirrors
21194
+ // vaultPassphraseUnreachable so a user who saw the vault message once
21195
+ // recognises this one: explain what could not happen, then say whether
21196
+ // activating again will open a new page, and point at the bundles.json env
21197
+ // path either way.
21198
+ //
21199
+ // The retry hint reads the latch and the budget, as the vault's reads its
21200
+ // latch, because the two outcomes differ. No-page and no-browser latch the
21201
+ // namespace before this runs (and the early check in maybeElicitAndRetry
21202
+ // re-renders this same refusal on every follow-up activate), so for them a
21203
+ // new page is never coming this session. An expired page does not latch:
21204
+ // the next activate opens a new page if the namespace has an ask left under
21205
+ // MAX_CREDENTIAL_PROMPTS, and returns the raw spawn error if it does not.
21206
+ credentialUnreachableRefusal(namespace, missing, reason) {
21207
+ const isPlural = missing.length !== 1;
21208
+ const noun = isPlural ? "credentials" : "credential";
21209
+ let what;
21210
+ switch (reason) {
21211
+ case "no-browser":
21212
+ what = `yaw-mcp could not open a browser on this machine for the page that takes the ${noun} in a masked field`;
21213
+ break;
21214
+ case "no-page":
21215
+ what = `yaw-mcp could not start the local page that takes the ${noun} in a masked field`;
21216
+ break;
21217
+ case "expired":
21218
+ what = `the page that takes the ${noun} in a masked field expired with nothing submitted`;
21219
+ break;
21220
+ }
21221
+ const newPageComing = !this.credentialElicited.has(namespace) && (this.credentialPrompts.get(namespace) ?? 0) < MAX_CREDENTIAL_PROMPTS;
21222
+ const retryHint = newPageComing ? ` Activate "${namespace}" again for a new page, or set ${missing.join(", ")} in its "env" in ${bundlesFileHint("defines-it")} -- the edit is picked up on the next mcp_connect_* call, with no client restart.` : this.noFurtherCredentialPromptsHint(namespace, missing);
21223
+ return {
21224
+ ok: false,
21225
+ isChanged: false,
21226
+ message: `Could not load "${namespace}": ${what}, so ${missing.join(", ")} ${isPlural ? "are" : "is"} still missing.${retryHint}`
21227
+ };
21228
+ }
21229
+ // The retry hint for a namespace this session will not prompt for again
21230
+ // (latched, or MAX_CREDENTIAL_PROMPTS spent). One copy for every message
21231
+ // that ends the asking, so they cannot drift. The bundles.json edit it
21232
+ // recommends does get through: bundles.json is re-read at meta-tool
21233
+ // boundaries, effectiveEntry lets the file's value win over any elicited
21234
+ // one, and a spawn that succeeds never reaches the prompt or its latch.
21235
+ noFurtherCredentialPromptsHint(namespace, missing) {
21236
+ return ` No further prompts for "${namespace}" this session: set ${missing.join(", ")} in its "env" in ${bundlesFileHint("defines-it")} and activate again -- the edit is picked up on the next mcp_connect_* call, with no client restart.`;
21237
+ }
21062
21238
  // Collect secret values WITHOUT them ever being typed into the client's
21063
21239
  // own dialog. They are typed into masked fields on a one-shot page this
21064
21240
  // process serves on 127.0.0.1 (secret-entry-page.ts, which carries the
@@ -21081,8 +21257,8 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
21081
21257
  // that is exactly the exposure this replaces.
21082
21258
  //
21083
21259
  // Nothing here is vault-specific. The missing-credential prompt
21084
- // (maybeElicitAndRetry, which still asks in a visible form field) can move
21085
- // onto it by supplying its own words and fields.
21260
+ // (maybeElicitAndRetry) supplies its own words and fields and goes through
21261
+ // the same page.
21086
21262
  async collectSecretOnLoopbackPage(request2) {
21087
21263
  const { namespace, why, secretNoun, progress } = request2;
21088
21264
  const modes = getSupportedElicitationModes(this.server.getClientCapabilities()?.elicitation);
@@ -21136,7 +21312,7 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
21136
21312
  },
21137
21313
  () => page.result
21138
21314
  );
21139
- if (mode === "url" && outcome.kind !== "closed") this.notifyElicitationComplete(page.elicitationId, namespace);
21315
+ if (mode === "url" && !this.shuttingDown) this.notifyElicitationComplete(page.elicitationId, namespace);
21140
21316
  if (outcome.kind === "submitted") return { kind: "submitted", values: outcome.values };
21141
21317
  if (outcome.kind === "expired") return { kind: "unreachable", reason: "expired" };
21142
21318
  return { kind: "failed" };
@@ -21167,7 +21343,9 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
21167
21343
  // which of these happened, because they need different words:
21168
21344
  // unlocked -- verified and stored; retry the activation.
21169
21345
  // rejected -- the user typed a passphrase and it did not verify.
21170
- // unavailable -- declined, empty, or the elicitation request failed.
21346
+ // unavailable -- declined; no answer (the elicitation request failed,
21347
+ // or the page closed under the wait); or, from a drifted
21348
+ // page only, an empty submission.
21171
21349
  // unreachable -- the masked-entry page never took a passphrase.
21172
21350
  async promptForVaultPassphrase(namespace, lastError, progress) {
21173
21351
  this.vaultPassphrasePrompts++;
@@ -21212,6 +21390,51 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
21212
21390
  this.vaultPassphraseElicited = true;
21213
21391
  return { kind: "unlocked" };
21214
21392
  }
21393
+ // The bookkeeping the two meta-tools that load what the client ASKED for
21394
+ // share -- handleActivate (by name) and handleDispatch (by intent). One
21395
+ // copy, so a new per-namespace flag or notify condition cannot reach one of
21396
+ // them and miss the other, which is how two hand-kept "mirrors
21397
+ // handleActivate" loops drift. autoLoadRecurringPack and discover's
21398
+ // auto-warm also add to sessionActivated but are deliberately not routed
21399
+ // through here: they report no cap/error split and no isError. What each
21400
+ // handler does beyond this -- activate's filter rollback and upstream
21401
+ // `instructions`, dispatch's scored result lines, and the list of loaded
21402
+ // namespaces each passes to execHintForNonRelistingClient -- stays in the
21403
+ // handler.
21404
+ //
21405
+ // Gateway mode advertises a namespace only on a signal of what the user
21406
+ // wants -- by name or by intent here, by discover's auto-warm and by replay
21407
+ // of their recurring pack at those two sites -- never in activateOne, which
21408
+ // the deferred first-call path and prewarm also route through: surfacing a
21409
+ // whole namespace off those would grow the tool list as a side effect of
21410
+ // one call. So the sessionActivated add lives here, on success only. A cap
21411
+ // refusal is booked apart from every other refusal (its message says what
21412
+ // to unload); explicitLoadIsError says what each means for the reply.
21413
+ recordExplicitLoad(tally, namespace, r) {
21414
+ if (r.isChanged) tally.anyChanged = true;
21415
+ if (r.ok) {
21416
+ if (!this.sessionActivated.has(namespace)) tally.advertisedGrew = true;
21417
+ this.sessionActivated.add(namespace);
21418
+ } else if (r.capped) {
21419
+ tally.anyCapped = true;
21420
+ } else {
21421
+ tally.anyError = true;
21422
+ }
21423
+ }
21424
+ // After the batch: a new connection needs the routes rebuilt AND the
21425
+ // client told. An advertised set that grew with no new connection (a
21426
+ // winner already connected but never advertised) -- or, for activate, a
21427
+ // `tools` filter change on a connected server -- leaves the routes current
21428
+ // but moves the tools/list surface, so the client still has to re-list.
21429
+ // Without that arm a gateway client is told tools are "now callable" while
21430
+ // its tools/list never learns they exist.
21431
+ async announceExplicitLoads(tally, surfaceMoved = false) {
21432
+ if (tally.anyChanged) {
21433
+ await this.refreshRoutesAndNotify();
21434
+ } else if (surfaceMoved || tally.advertisedGrew) {
21435
+ await this.notifyAllListsChanged();
21436
+ }
21437
+ }
21215
21438
  async handleActivate(namespaces, progress, toolsFilter) {
21216
21439
  if (namespaces.length === 0) {
21217
21440
  return {
@@ -21249,21 +21472,18 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
21249
21472
  }
21250
21473
  const results = [];
21251
21474
  const upstreamInstructions = [];
21252
- let anyChanged = false;
21253
- let anyError = false;
21254
- let anyCapped = false;
21255
- let advertisedGrew = false;
21475
+ const tally = newExplicitLoadTally();
21256
21476
  const total = namespaces.length;
21477
+ const loadedOk = [];
21257
21478
  let i = 0;
21258
21479
  for (const namespace of namespaces) {
21259
21480
  i += 1;
21260
21481
  progress?.(`Loading ${namespace} (${i}/${total})`, i - 1, total);
21261
21482
  const r = await this.activateOne(namespace, progress);
21262
21483
  results.push(r.message);
21263
- if (r.isChanged) anyChanged = true;
21484
+ this.recordExplicitLoad(tally, namespace, r);
21485
+ if (r.ok) loadedOk.push(namespace);
21264
21486
  if (r.ok) {
21265
- if (!this.sessionActivated.has(namespace)) advertisedGrew = true;
21266
- this.sessionActivated.add(namespace);
21267
21487
  const captured = this.connections.get(namespace)?.instructions;
21268
21488
  if (captured && !this.instructionsShown.has(namespace)) {
21269
21489
  this.instructionsShown.add(namespace);
@@ -21271,8 +21491,6 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
21271
21491
  }
21272
21492
  }
21273
21493
  if (!r.ok) {
21274
- if (r.capped) anyCapped = true;
21275
- else anyError = true;
21276
21494
  if (installedFilter && installedFilter.namespace === namespace) {
21277
21495
  if (installedFilter.prev) this.toolFilters.set(namespace, installedFilter.prev);
21278
21496
  else this.toolFilters.delete(namespace);
@@ -21282,11 +21500,7 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
21282
21500
  }
21283
21501
  }
21284
21502
  }
21285
- if (anyChanged) {
21286
- await this.refreshRoutesAndNotify();
21287
- } else if (filtersChanged || advertisedGrew) {
21288
- await this.notifyAllListsChanged();
21289
- }
21503
+ await this.announceExplicitLoads(tally, filtersChanged);
21290
21504
  if (filterRequestedFor) {
21291
21505
  const ns = filterRequestedFor;
21292
21506
  const unmatched = this.unmatchedFilterNames(ns);
@@ -21299,10 +21513,12 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
21299
21513
  results.push(lead + fix);
21300
21514
  }
21301
21515
  }
21516
+ const execHint = this.execHintForNonRelistingClient(loadedOk);
21517
+ if (execHint) results.push(execHint);
21302
21518
  results.push(...upstreamInstructions);
21303
21519
  return {
21304
21520
  content: [{ type: "text", text: results.join("\n") }],
21305
- isError: anyError || anyCapped && !anyChanged ? true : void 0
21521
+ isError: explicitLoadIsError(tally)
21306
21522
  };
21307
21523
  }
21308
21524
  /** Filter names for `namespace` that match no tool the server actually
@@ -21313,7 +21529,14 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
21313
21529
  const filter = this.toolFilters.get(namespace);
21314
21530
  if (!filter || filter.size === 0) return [];
21315
21531
  const conn = this.connections.get(namespace);
21316
- const known = conn && conn.status === "connected" ? conn.tools.map((t) => t.name) : (this.toolCache.get(namespace) ?? []).map((t) => t.name);
21532
+ let known;
21533
+ if (conn && conn.status === "connected") {
21534
+ known = conn.tools.map((t) => t.name);
21535
+ } else {
21536
+ const config = this.config?.servers.find((s) => s.namespace === namespace);
21537
+ const cache = config ? this.mergeToolCache(config).toolCache : this.toolCache.get(namespace);
21538
+ known = (cache ?? []).map((t) => t.name);
21539
+ }
21317
21540
  if (known.length === 0) return [];
21318
21541
  const have = new Set(known);
21319
21542
  return [...filter].filter((n) => !have.has(n)).sort();
@@ -21353,9 +21576,9 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
21353
21576
  //
21354
21577
  // The three empty-state messages below are the fresh-install path (dispatch
21355
21578
  // is the documented first call), so each names the LOCAL fix -- `yaw-mcp
21356
- // add <slug>`, `"isActive": true` in ~/.yaw-mcp/bundles.json -- rather than
21357
- // the retired hosted add/enable UI at yaw.sh/mcp that discover and bundles
21358
- // were already migrated away from.
21579
+ // add <slug>`, `"isActive": true` in the bundles.json that defines the
21580
+ // server -- rather than the retired hosted add/enable UI at yaw.sh/mcp that
21581
+ // discover and bundles were already migrated away from.
21359
21582
  async handleDispatch(intent, budget, progress, routeEffortOverride) {
21360
21583
  const trimmed = intent?.trim?.() ?? "";
21361
21584
  if (trimmed.length === 0) {
@@ -21399,7 +21622,8 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
21399
21622
  if (safeBudget === 1 && shouldSample(ranked, effort)) {
21400
21623
  progress?.("Top candidates close \u2014 asking LLM to pick\u2026");
21401
21624
  const serversByNamespace = new Map(activeServers.map((s) => [s.namespace, s]));
21402
- const candidates = buildCandidates(ranked.slice(0, 3), serversByNamespace, this.toolCache);
21625
+ const mergedTools = new Map(activeServers.map((s) => [s.namespace, s.toolCache ?? []]));
21626
+ const candidates = buildCandidates(ranked.slice(0, 3), serversByNamespace, mergedTools);
21403
21627
  const samples = sampleCountForEffort(effort);
21404
21628
  const picked = await bestOfNViaSampling(this.server, trimmed, candidates, samples);
21405
21629
  if (picked) {
@@ -21435,43 +21659,33 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
21435
21659
  }
21436
21660
  }
21437
21661
  const results = [];
21438
- let anyChanged = false;
21439
- let anyError = false;
21440
- let anyCapped = false;
21441
- let advertisedGrew = false;
21662
+ const tally = newExplicitLoadTally();
21663
+ const dispatchedOk = [];
21442
21664
  let i = 0;
21443
21665
  for (const winner of winners) {
21444
21666
  i += 1;
21445
21667
  progress?.(`Loading ${winner.namespace} (${i}/${winners.length})`, i - 1, winners.length);
21446
21668
  const r = await this.activateOne(winner.namespace, progress);
21447
21669
  results.push(`${winner.namespace} (score ${winner.score.toFixed(2)}): ${r.message}`);
21448
- if (r.isChanged) anyChanged = true;
21449
- if (r.ok) {
21450
- if (!this.sessionActivated.has(winner.namespace)) advertisedGrew = true;
21451
- this.sessionActivated.add(winner.namespace);
21452
- }
21453
- if (!r.ok) {
21454
- if (r.capped) anyCapped = true;
21455
- else anyError = true;
21456
- }
21457
- }
21458
- if (anyChanged) {
21459
- await this.refreshRoutesAndNotify();
21460
- } else if (advertisedGrew) {
21461
- await this.notifyAllListsChanged();
21670
+ this.recordExplicitLoad(tally, winner.namespace, r);
21671
+ if (r.ok) dispatchedOk.push(winner.namespace);
21462
21672
  }
21673
+ await this.announceExplicitLoads(tally);
21674
+ const execHint = this.execHintForNonRelistingClient(dispatchedOk);
21675
+ if (execHint) results.push(execHint);
21463
21676
  const header = `Dispatched "${trimmed}" \u2014 loaded top ${winners.length} of ${ranked.length} matching server${ranked.length === 1 ? "" : "s"}.
21464
21677
  `;
21465
21678
  return {
21466
21679
  content: [{ type: "text", text: header + results.join("\n") }],
21467
- isError: anyError || anyCapped && !anyChanged ? true : void 0
21680
+ isError: explicitLoadIsError(tally)
21468
21681
  };
21469
21682
  }
21470
21683
  // Drop every per-namespace bit of session state after its connection has
21471
- // been closed. Called by BOTH teardown sites -- explicit deactivate and the
21472
- // idle reaper -- which used to carry identical copies of this list, so a
21473
- // new piece of per-namespace state had to be remembered in two places to
21474
- // avoid leaking into the next load of the same server.
21684
+ // been closed. Called by all three teardown sites -- explicit deactivate,
21685
+ // the idle reaper, and reconcileConfig's unload of a server a bundles.json
21686
+ // reload changed or removed. The first two used to carry identical copies
21687
+ // of this list, so a new piece of per-namespace state had to be remembered
21688
+ // in each place to avoid leaking into the next load of the same server.
21475
21689
  //
21476
21690
  // Deliberately NOT cleared here: toolCache / toolCacheLearnedAt (what the
21477
21691
  // server offers survives an unload -- that is what makes it deferred
@@ -21652,7 +21866,7 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
21652
21866
  content: [
21653
21867
  {
21654
21868
  type: "text",
21655
- text: `"${serverArg}" is not in ~/.yaw-mcp/bundles.json.${hint}`
21869
+ text: `"${serverArg}" is not in ${bundlesFileHint("in-effect")}.${hint}`
21656
21870
  }
21657
21871
  ],
21658
21872
  isError: true
@@ -21683,8 +21897,7 @@ Name collision: ${subject} of "${namespace}" cannot be called. ${entries}${more}
21683
21897
  };
21684
21898
  }
21685
21899
  progress?.(`Inspecting "${serverArg}" (transient \u2014 not loading into session)\u2026`);
21686
- const elicitedForTransient = this.elicitedEnv.get(serverArg);
21687
- const transientConfig = elicitedForTransient ? { ...serverConfig, env: { ...serverConfig.env, ...elicitedForTransient } } : serverConfig;
21900
+ const transientConfig = this.effectiveEntry(serverConfig);
21688
21901
  try {
21689
21902
  return await withTransientUpstream(
21690
21903
  transientConfig,
@@ -21829,10 +22042,6 @@ Cross-session reliability (dormant, <${flakyPct}% success):`);
21829
22042
  }
21830
22043
  return { content: [{ type: "text", text: lines.join("\n") }] };
21831
22044
  }
21832
- // Pack suggestion. Surfaces recurring multi-server tool-call sequences
21833
- // observed in this session. Observation only — never activates
21834
- // anything. Ranked by frequency primarily, with recency as a tiebreak
21835
- // so the hottest-most-recent pattern sits at the top.
21836
22045
  /** Cap on what find_tool returns when the caller names no limit.
21837
22046
  *
21838
22047
  * A number, not "everything that matched": the point of the tool is to
@@ -21854,7 +22063,7 @@ Cross-session reliability (dormant, <${flakyPct}% success):`);
21854
22063
  * match rather than leaving the model to infer it -- a silently absent
21855
22064
  * schema reads as "this tool takes no arguments", which is a worse answer
21856
22065
  * than "activate it to see". */
21857
- handleFindTool(query, limit) {
22066
+ async handleFindTool(query, limit) {
21858
22067
  const servers = this.getProfiledActiveServers();
21859
22068
  if (servers.length === 0) {
21860
22069
  const configured = this.config?.servers.length ?? 0;
@@ -21876,10 +22085,17 @@ Cross-session reliability (dormant, <${flakyPct}% success):`);
21876
22085
  1,
21877
22086
  Math.min(limit ?? _ConnectServer.FIND_TOOL_DEFAULT_LIMIT, _ConnectServer.FIND_TOOL_MAX_LIMIT)
21878
22087
  );
21879
- const ranked = rankTools(
22088
+ let ranked = rankTools(
21880
22089
  query,
21881
22090
  servers.map((s) => this.rankableFor(s))
21882
22091
  );
22092
+ if (ranked.length === 0 && this.startupPrewarm) {
22093
+ await this.settleStartupPrewarm();
22094
+ ranked = rankTools(
22095
+ query,
22096
+ this.getProfiledActiveServers().map((s) => this.rankableFor(s))
22097
+ );
22098
+ }
21883
22099
  if (ranked.length === 0) {
21884
22100
  return {
21885
22101
  content: [
@@ -21915,6 +22131,11 @@ Cross-session reliability (dormant, <${flakyPct}% success):`);
21915
22131
  );
21916
22132
  return { content: [{ type: "text", text: lines.join("\n") }] };
21917
22133
  }
22134
+ // Pack suggestion. Surfaces recurring multi-server tool-call sequences from
22135
+ // the pack history, which persists across restarts (see persistence.ts).
22136
+ // Observation only — never activates anything. Ranked by frequency
22137
+ // primarily, with recency as a tiebreak so the hottest-most-recent pattern
22138
+ // sits at the top.
21918
22139
  handleSuggest() {
21919
22140
  const detected = this.packDetector.detectChains();
21920
22141
  if (detected.length === 0) {
@@ -22091,6 +22312,13 @@ To load the top pack in one step, call \`mcp_connect_activate\` with namespaces=
22091
22312
  isError: true
22092
22313
  };
22093
22314
  }
22315
+ if (this.startupPrewarm && steps.some((s) => !this.toolRoutes.has(s.tool))) {
22316
+ await this.settleStartupPrewarm(signal);
22317
+ if (signal?.aborted) {
22318
+ return { content: [{ type: "text", text: "exec: cancelled before step 0 ran." }], isError: true };
22319
+ }
22320
+ if (steps.some((s) => !this.toolRoutes.has(s.tool))) this.rebuildRoutes();
22321
+ }
22094
22322
  for (let i = 0; i < steps.length; i++) {
22095
22323
  const step = steps[i];
22096
22324
  const route = this.toolRoutes.get(step.tool);
@@ -22306,6 +22534,7 @@ To load the top pack in one step, call \`mcp_connect_activate\` with namespaces=
22306
22534
  await Promise.allSettled(disconnects);
22307
22535
  this.connections.clear();
22308
22536
  this.elicitedEnv.clear();
22537
+ this.credentialElicited.clear();
22309
22538
  clearSessionVaultPassphrase();
22310
22539
  this.inflightCalls.clear();
22311
22540
  await this.server.close();
@@ -22350,7 +22579,7 @@ function registerShutdownTriggers(shutdown, targets) {
22350
22579
  // src/status-cmd.ts
22351
22580
  import { existsSync as existsSync10 } from "fs";
22352
22581
  import { homedir as homedir23 } from "os";
22353
- var VERSION2 = true ? "1.0.12" : "dev";
22582
+ var VERSION2 = true ? "1.0.15" : "dev";
22354
22583
  var STATUS_SCHEMA_VERSION = 1;
22355
22584
  var STATUS_USAGE = `Usage: yaw-mcp status [--json]
22356
22585
 
@@ -23130,7 +23359,7 @@ if (subcommand === "compliance") {
23130
23359
  `);
23131
23360
  process.exitCode = 0;
23132
23361
  } else if (subcommand === "--version" || subcommand === "-V") {
23133
- process.stdout.write(`yaw-mcp ${true ? "1.0.12" : "dev"}
23362
+ process.stdout.write(`yaw-mcp ${true ? "1.0.15" : "dev"}
23134
23363
  `);
23135
23364
  process.exitCode = 0;
23136
23365
  } else if (subcommand !== void 0 && !subcommand.startsWith("-")) {