@yawlabs/mcp 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -11,17 +11,30 @@ import {
11
11
  LEGACY_ENTRY_NAMES,
12
12
  MIN_OAM_VERSION,
13
13
  acquireUpgradeLock,
14
+ applyClientConfigEdits,
15
+ blockedContainerFix,
14
16
  buildLaunchEntry,
15
17
  buildUpgradePlan,
16
18
  cacheDir,
19
+ classifyClientConfig,
20
+ claudeCodeContainerPathVariants,
21
+ claudeCodeContainerPaths,
17
22
  compareVersions,
23
+ composeEntry,
24
+ containerKeysAt,
18
25
  createStreamWriter,
26
+ describeJsonShape,
27
+ describeValueShape,
19
28
  detectInstallMethod,
20
29
  detectSea,
30
+ editJsoncPath,
31
+ effectiveConfigFormat,
21
32
  fetchLatestVersion,
33
+ findBlockedContainerSegment,
22
34
  findLegacyEntry,
23
35
  findProjectConfigDir,
24
36
  guidePath,
37
+ importViewOf,
25
38
  isOamCommand,
26
39
  isOamLaunch,
27
40
  isProjectLocalEntry,
@@ -40,24 +53,42 @@ import {
40
53
  oamNoBinaryReason,
41
54
  oamPublishesBinaryForThisMachine,
42
55
  packageName,
56
+ parseJsonc,
43
57
  parseUpgradeArgs,
58
+ prepareClaudeCodeSettingsPatch,
44
59
  probeOam,
60
+ readClientConfigFile,
61
+ readClientEnv,
62
+ readStrictJson,
45
63
  realpathOrSelf,
46
64
  refineInstallMethod,
65
+ reloadDoneClause,
66
+ reloadRemovalClause,
67
+ resolveAlsoReadSites,
47
68
  resolveAppDataDir,
48
69
  resolveClaudeCodeSettingsPath,
49
70
  resolveInstallPath,
71
+ resolveInstallSites,
50
72
  resolveOamSpawn,
73
+ resolveProgramProbe,
51
74
  resolveStableNpmEntry,
52
75
  runUpgrade,
53
76
  scrubInternalSecretsFromProcessEnv,
77
+ selectSites,
54
78
  setLogSurface,
55
79
  sidecarsNodeModules,
56
80
  sidecarsRoot,
81
+ siteAt,
57
82
  specConstraint,
58
83
  stripInternalSecretsFromEnv,
59
- userConfigDir
60
- } from "./chunk-PZMKIDQV.js";
84
+ terminateWithNewline,
85
+ tildePath,
86
+ unloadableConfigFix,
87
+ unloadableConfigProblem,
88
+ unparseableConfigFix,
89
+ userConfigDir,
90
+ yawModeOverlay
91
+ } from "./chunk-PAUBVL2N.js";
61
92
 
62
93
  // src/audit-cmd.ts
63
94
  import { homedir as homedir6 } from "os";
@@ -499,135 +530,6 @@ function setJsonKey(target, key, value) {
499
530
  target[key] = value;
500
531
  }
501
532
 
502
- // src/jsonc.ts
503
- import { applyEdits, modify } from "jsonc-parser";
504
- function stripJsoncComments(src) {
505
- let out = "";
506
- let i = 0;
507
- const len = src.length;
508
- let inString = false;
509
- let stringChar = "";
510
- while (i < len) {
511
- const c = src[i];
512
- if (inString) {
513
- out += c;
514
- if (c === "\\" && i + 1 < len) {
515
- out += src[i + 1];
516
- i += 2;
517
- continue;
518
- }
519
- if (c === stringChar) inString = false;
520
- i++;
521
- continue;
522
- }
523
- if (c === '"' || c === "'") {
524
- inString = true;
525
- stringChar = c;
526
- out += c;
527
- i++;
528
- continue;
529
- }
530
- const next = src[i + 1];
531
- if (c === "/" && next === "/") {
532
- while (i < len && src[i] !== "\n") i++;
533
- continue;
534
- }
535
- if (c === "/" && next === "*") {
536
- i += 2;
537
- while (i < len && !(src[i] === "*" && src[i + 1] === "/")) {
538
- if (src[i] === "\n") out += "\n";
539
- i++;
540
- }
541
- i += 2;
542
- continue;
543
- }
544
- out += c;
545
- i++;
546
- }
547
- return out;
548
- }
549
- function stripTrailingCommas(src) {
550
- let out = "";
551
- let i = 0;
552
- const len = src.length;
553
- let inString = false;
554
- let stringChar = "";
555
- while (i < len) {
556
- const c = src[i];
557
- if (inString) {
558
- out += c;
559
- if (c === "\\" && i + 1 < len) {
560
- out += src[i + 1];
561
- i += 2;
562
- continue;
563
- }
564
- if (c === stringChar) inString = false;
565
- i++;
566
- continue;
567
- }
568
- if (c === '"' || c === "'") {
569
- inString = true;
570
- stringChar = c;
571
- out += c;
572
- i++;
573
- continue;
574
- }
575
- if (c === ",") {
576
- let j = i + 1;
577
- while (j < len && (src[j] === " " || src[j] === " " || src[j] === "\r" || src[j] === "\n")) j++;
578
- if (j < len && (src[j] === "]" || src[j] === "}")) {
579
- out += " ";
580
- i++;
581
- continue;
582
- }
583
- }
584
- out += c;
585
- i++;
586
- }
587
- return out;
588
- }
589
- function parseJsonc(src) {
590
- const debommed = src.charCodeAt(0) === 65279 ? src.slice(1) : src;
591
- const stripped = stripTrailingCommas(stripJsoncComments(debommed));
592
- return JSON.parse(stripped);
593
- }
594
- var FORMATTING_OPTIONS = {
595
- insertSpaces: true,
596
- tabSize: 2,
597
- eol: "\n"
598
- };
599
- function editJsoncEntry(src, containerPath, entryName, value) {
600
- if (entryName === "") {
601
- throw new Error("editJsoncEntry: entryName must be a non-empty key");
602
- }
603
- const debommed = src.charCodeAt(0) === 65279 ? src.slice(1) : src;
604
- const targetPath = [...containerPath, entryName];
605
- const edits = modify(debommed, targetPath, value, { formattingOptions: FORMATTING_OPTIONS });
606
- return applyEdits(debommed, edits);
607
- }
608
- function removeJsoncEntry(src, containerPath, entryName) {
609
- if (entryName === "") {
610
- throw new Error("removeJsoncEntry: entryName must be a non-empty key");
611
- }
612
- const debommed = src.charCodeAt(0) === 65279 ? src.slice(1) : src;
613
- const targetPath = [...containerPath, entryName];
614
- const edits = modify(debommed, targetPath, void 0, { formattingOptions: FORMATTING_OPTIONS });
615
- if (edits.length === 0) return src;
616
- return applyEdits(debommed, edits);
617
- }
618
- function editJsoncPath(src, path6, value) {
619
- if (path6.length === 0) {
620
- throw new Error("editJsoncPath: path must not be empty");
621
- }
622
- if (path6.some((seg) => seg === "")) {
623
- throw new Error("editJsoncPath: path segments must be non-empty");
624
- }
625
- const debommed = src.charCodeAt(0) === 65279 ? src.slice(1) : src;
626
- const edits = modify(debommed, path6, value, { formattingOptions: FORMATTING_OPTIONS });
627
- if (edits.length === 0) return src;
628
- return applyEdits(debommed, edits);
629
- }
630
-
631
533
  // src/grades-cache.ts
632
534
  var GRADES_FILENAME = "grades.json";
633
535
  var GRADE_LETTERS = /* @__PURE__ */ new Set(["A", "B", "C", "D", "F"]);
@@ -885,12 +787,12 @@ var SECRET_PATTERNS = [
885
787
  `\\b((?:[A-Za-z0-9]{1,32}[-_]){0,8}(?:${SECRET_KEY_NAMES}))(["']?\\s*[=:][ \\t]*)(?:'([^'\\n]*)'|"([^"\\n]*)"|([^\\s,;&"'}\\]<]+)((?:[ \\t]+(?!-)(?![A-Za-z0-9_-]+["']?[ \\t]*[=:])[^\\s,;&"'}\\]<]+)*))`,
886
788
  "gi"
887
789
  ),
888
- replace: (_match, name, sep, single, double, bare, tail) => {
889
- if (single !== void 0) return `${name}${sep}'${REDACTED}'`;
890
- if (double !== void 0) return `${name}${sep}"${REDACTED}"`;
891
- if (ABSENCE_VALUE.test(bare)) return `${name}${sep}${bare}${tail}`;
892
- if (!/[ \t]$/.test(sep)) return `${name}${sep}${REDACTED}${tail}`;
893
- return `${name}${sep}${REDACTED}`;
790
+ replace: (_match, name, sep2, single, double, bare, tail) => {
791
+ if (single !== void 0) return `${name}${sep2}'${REDACTED}'`;
792
+ if (double !== void 0) return `${name}${sep2}"${REDACTED}"`;
793
+ if (ABSENCE_VALUE.test(bare)) return `${name}${sep2}${bare}${tail}`;
794
+ if (!/[ \t]$/.test(sep2)) return `${name}${sep2}${REDACTED}${tail}`;
795
+ return `${name}${sep2}${REDACTED}`;
894
796
  }
895
797
  },
896
798
  // 3. A vendor-prefixed key carrying no name for rule 2 to anchor on.
@@ -3363,7 +3265,7 @@ async function connectToUpstreamOnce(config, onDisconnect, onListChanged, bridge
3363
3265
  if (downstreamCaps?.sampling) capabilities.sampling = downstreamCaps.sampling;
3364
3266
  if (downstreamCaps?.roots) capabilities.roots = {};
3365
3267
  const client = new Client(
3366
- { name: "yaw-mcp", version: true ? "1.0.0" : "dev" },
3268
+ { name: "yaw-mcp", version: true ? "1.0.2" : "dev" },
3367
3269
  { capabilities }
3368
3270
  );
3369
3271
  if (bridge && capabilities.elicitation) {
@@ -6572,6 +6474,47 @@ ${CALL_USAGE}`);
6572
6474
  }
6573
6475
  }
6574
6476
 
6477
+ // src/client-aliases.ts
6478
+ var CLIENT_ALIASES = [
6479
+ // `mcp` is Claude Code's PROJECT scope under a second name: the same
6480
+ // `<project>/.mcp.json`, the same `mcpServers` container and the same launch
6481
+ // entry `install claude-code --scope project` writes. Claude Code's docs
6482
+ // call that scope "a `.mcp.json` file at your project's root directory" with
6483
+ // the root key `mcpServers` (code.claude.com/docs/en/mcp, "Project scope").
6484
+ //
6485
+ // Pinning the scope is what makes it name that file at all: claude-code's
6486
+ // three scopes include `user`, and `resolveInstallSite` prefers `user` when
6487
+ // no `--scope` is given, so an alias that pinned nothing would resolve
6488
+ // `install mcp` to `~/.claude.json` -- the wrong file under the right name.
6489
+ //
6490
+ // Nothing claude-code's project scope does is re-implemented here, because
6491
+ // the alias is gone before any of it runs: the row's
6492
+ // `hooks.permissionsPatch` (the `permissions.allow += ["mcp__mcp__*"]` patch
6493
+ // of `<project>/.claude/settings.json`), the approve-on-restart Done line,
6494
+ // and whatever strictness that scope declares through `strictJson` all key
6495
+ // off the resolved (client, scope) and never off the spelling. The tests
6496
+ // drive BOTH spellings through the same assertions rather than assume it.
6497
+ {
6498
+ id: "mcp",
6499
+ clientId: "claude-code",
6500
+ scope: "project",
6501
+ label: "Claude Code's project scope -- the project-root .mcp.json"
6502
+ }
6503
+ ];
6504
+ function clientChoices(verb = "install") {
6505
+ const ids = INSTALL_TARGETS.map((t) => t.clientId);
6506
+ if (verb === "try") return ids;
6507
+ return [...ids, ...CLIENT_ALIASES.map((a) => a.id)];
6508
+ }
6509
+ function resolveClientArg(verb, arg) {
6510
+ const target = INSTALL_TARGETS.find((t) => t.clientId === arg);
6511
+ if (target) return { clientId: target.clientId, via: null };
6512
+ if (verb === "try") return null;
6513
+ const alias = CLIENT_ALIASES.find((a) => a.id === arg);
6514
+ if (!alias) return null;
6515
+ return { clientId: alias.clientId, scope: alias.scope, via: alias.id };
6516
+ }
6517
+
6575
6518
  // src/completion-cmd.ts
6576
6519
  var COMPLETION_USAGE = `Usage: yaw-mcp completion <bash|zsh|fish|powershell>
6577
6520
 
@@ -6582,7 +6525,7 @@ var COMPLETION_USAGE = `Usage: yaw-mcp completion <bash|zsh|fish|powershell>
6582
6525
  zsh yaw-mcp completion zsh > "\${fpath[1]}/_yaw-mcp" (must be on $fpath)
6583
6526
  fish yaw-mcp completion fish > ~/.config/fish/completions/yaw-mcp.fish
6584
6527
  powershell yaw-mcp completion powershell >> $PROFILE`;
6585
- var INSTALL_CLIENTS = INSTALL_TARGETS.map((t) => t.clientId);
6528
+ var INSTALL_CLIENTS = clientChoices("install");
6586
6529
  var SUBCOMMAND_SPEC = [
6587
6530
  // Setup -- connect a client to yaw-mcp.
6588
6531
  {
@@ -6721,12 +6664,10 @@ var SUBCOMMAND_SPEC = [
6721
6664
  flags: ["--json", "--help"]
6722
6665
  },
6723
6666
  { name: "doctor", description: "Print diagnostic of yaw-mcp setup", flags: ["--json", "--help"] },
6724
- // `servers` is deliberately NOT here. It is still dispatched -- Yaw Terminal
6725
- // shells out to `yaw-mcp servers --json` and reads signedIn:false from its
6726
- // always-non-zero exit -- but it is a deprecation stub, and completing a
6727
- // deprecated thing teaches it to new users: the same rule that hides
6728
- // --token above. completion-cmd.test.ts's drift guard carries the matching
6729
- // exemption.
6667
+ // `servers` is not here because it no longer exists: it was deleted in
6668
+ // 1.0.0, and typing it gets the retired-verb hint from RETIRED_SUBCOMMANDS
6669
+ // in subcommands.ts. completion-cmd.test.ts pins it out of both this spec
6670
+ // and KNOWN_SUBCOMMANDS.
6730
6671
  {
6731
6672
  name: "bundles",
6732
6673
  description: "Browse curated multi-server bundles",
@@ -6990,7 +6931,7 @@ ${caseBranches}
6990
6931
  import { closeSync, existsSync as existsSync6, fstatSync, openSync, readFileSync as readFileSync3, readSync } from "fs";
6991
6932
  import { readFile as readFile13 } from "fs/promises";
6992
6933
  import { homedir as homedir15 } from "os";
6993
- import { join as join13, posix, resolve as resolve7, win32 } from "path";
6934
+ import { join as join14, posix, resolve as resolve7, win32 } from "path";
6994
6935
 
6995
6936
  // src/cli-shadows.ts
6996
6937
  var EMPTY = [];
@@ -8126,7 +8067,7 @@ import { createHash as createHash5 } from "crypto";
8126
8067
  import { existsSync as existsSync5 } from "fs";
8127
8068
  import { chmod as chmod6, mkdir as mkdir5, readdir, readFile as readFile12, unlink as unlink2 } from "fs/promises";
8128
8069
  import { homedir as homedir14 } from "os";
8129
- import { join as join12, resolve as resolve6 } from "path";
8070
+ import { join as join13, resolve as resolve6 } from "path";
8130
8071
  import { createInterface as createInterface2 } from "readline/promises";
8131
8072
 
8132
8073
  // src/catalog-search.ts
@@ -8339,9 +8280,8 @@ function normalizeCatalogGrade(raw) {
8339
8280
  // src/install-cmd.ts
8340
8281
  import { readFile as readFile11, stat as stat6 } from "fs/promises";
8341
8282
  import { homedir as homedir13 } from "os";
8342
- import { resolve as resolve5 } from "path";
8283
+ import { dirname as dirname7, join as join12, resolve as resolve5, sep } from "path";
8343
8284
  import { createInterface } from "readline/promises";
8344
- import { Writable } from "stream";
8345
8285
 
8346
8286
  // src/readline-question.ts
8347
8287
  var QUESTION_CANCELLED = /* @__PURE__ */ Symbol("yaw-mcp:question-cancelled");
@@ -8386,11 +8326,6 @@ async function summarizeBundles(opts) {
8386
8326
  const state = loaded.config === null && loaded.path !== null ? "unreadable" : count > 0 ? "servers" : "empty";
8387
8327
  return { state, count, path: loaded.path ?? localBundlesPath(userConfigDir(home)), warnings: loaded.warnings };
8388
8328
  }
8389
- function directClientEntries(container) {
8390
- if (typeof container !== "object" || container === null || Array.isArray(container)) return [];
8391
- const skip = /* @__PURE__ */ new Set([ENTRY_NAME, ...LEGACY_ENTRY_NAMES]);
8392
- return Object.entries(container).filter(([k, v]) => !skip.has(k) && typeof v === "object" && v !== null && !Array.isArray(v)).map(([k]) => k);
8393
- }
8394
8329
  function describeContainer(file, containerPath) {
8395
8330
  if (containerPath.length <= 1) return file;
8396
8331
  const tail = containerPath.slice(2).map((k) => `.${k}`).join("");
@@ -8424,7 +8359,22 @@ function logInstallTail(log2, err, direct, bundles) {
8424
8359
  function resolveAppData(opts) {
8425
8360
  return resolveAppDataDir({ appData: opts.appData, home: opts.home });
8426
8361
  }
8427
- var USAGE = "Usage: yaw-mcp install <claude-code|claude-desktop|cursor|vscode|windsurf|gemini-cli> [--scope user|project|local]\n [--project-dir <path>] [--os macos|linux|windows]\n [--force | --repair | --skip] [--keep-legacy] [--dry-run]\n yaw-mcp install --list (detect clients; no writes)\n yaw-mcp install --all (install into every client available on this OS)\n\n Re-running install over an entry that already matches is a no-op (exit 0, no prompt).\n Undo it with `yaw-mcp uninstall <client>`.\n\n When a different `" + ENTRY_NAME + "` entry is already in the config, install asks on a TTY\n and refuses without one. Answer up front with:\n --force Overwrite whatever is there.\n --repair Replace an entry that has DRIFTED from what install writes; a\n no-op when it already matches, so a fixup script can run it\n unconditionally.\n --skip Leave the existing entry untouched and exit 0.\n --dry-run Print the entry (and any permissions patch) that WOULD be\n written, and exit 0 without touching a file.\n\n Deprecated (accepted, ignored, warns): --token <mcp_pat_...>, --no-yaw-mcp-config.\n yaw-mcp is local-only -- it stores no token and never writes ~/.yaw-mcp/config.json.\n Configure servers in ~/.yaw-mcp/bundles.json (see `yaw-mcp add <slug>`).";
8362
+ var USAGE = (
8363
+ // DERIVED, never a hand-kept list: `parseInstallArgs` validates against
8364
+ // `clientChoices("install")`, so a literal synopsis is a promise the parser
8365
+ // stops keeping the moment a client or an alias lands -- it reads as a
8366
+ // refusal that never happens.
8367
+ `Usage: yaw-mcp install <${clientChoices("install").join("|")}> [--scope user|project|local]
8368
+ [--project-dir <path>] [--os macos|linux|windows]
8369
+ [--force | --repair | --skip] [--keep-legacy] [--dry-run]
8370
+ yaw-mcp install --list (detect clients; no writes)
8371
+ yaw-mcp install --all (install into every client yaw-mcp supports on this OS)
8372
+
8373
+ Re-running install over an entry that already matches is a no-op (exit 0, no prompt).
8374
+ Undo it with \`yaw-mcp uninstall <client>\`.
8375
+
8376
+ When a different \`` + ENTRY_NAME + "` entry is already in the config, install asks on a TTY\n and refuses without one, showing what differs (exit 2; a real failure, such\n as a malformed config, exits 1). Under --all the run exits 2 when every\n client that did not succeed was refused this way, and 1 if any one failed.\n Answer up front with:\n --force Overwrite whatever is there, env included: the new entry keeps\n none of the old entry's env, and install names each key it drops.\n --repair Replace an entry that has DRIFTED from what install writes,\n keeping the old entry's string-valued env; a no-op when it\n already matches, so a fixup script can run it unconditionally.\n --skip Leave the existing entry untouched and exit 0.\n --dry-run Print the entry (and any permissions patch) that WOULD be\n written, and exit 0 without touching a file.\n\n Deprecated (accepted, ignored, warns): --token <mcp_pat_...>, --no-yaw-mcp-config.\n yaw-mcp is local-only -- it stores no token and never writes ~/.yaw-mcp/config.json.\n Configure servers in ~/.yaw-mcp/bundles.json (see `yaw-mcp add <slug>`)."
8377
+ );
8428
8378
  function describeUnreadableConfig(cmd, path6, err) {
8429
8379
  if (err.code === "EISDIR") {
8430
8380
  return `yaw-mcp ${cmd}: ${path6} is a directory, not a file -- move or remove it, then re-run.`;
@@ -8432,8 +8382,31 @@ function describeUnreadableConfig(cmd, path6, err) {
8432
8382
  return `yaw-mcp ${cmd}: cannot read ${path6}: ${err.message}`;
8433
8383
  }
8434
8384
  function clientUnavailableMessage(cmd, target, os, genericFix) {
8435
- const fix = target.clientId === "claude-desktop" && os === "linux" ? "Anthropic ships Claude Desktop on macOS and Windows only. Install Claude Code or Cursor instead." : genericFix;
8436
- return `yaw-mcp ${cmd}: ${target.label} is not available on ${os}.
8385
+ const reason = target.notConfigurableOn?.[os];
8386
+ if (reason === void 0) return `yaw-mcp ${cmd}: ${target.label} is not available on ${os}.
8387
+ ${genericFix}`;
8388
+ const alternatives = INSTALL_TARGETS.filter(
8389
+ (t) => t.clientId !== target.clientId && t.availableOn.includes(os) && t.notConfigurableOn?.[os] === void 0
8390
+ ).slice(0, 2);
8391
+ const orList = (parts) => parts.join(" or ");
8392
+ let fix;
8393
+ switch (cmd) {
8394
+ case "uninstall":
8395
+ fix = "Remove the entry by hand if you added one.";
8396
+ break;
8397
+ case "import":
8398
+ fix = 'Add those servers to yaw-mcp yourself instead: `yaw-mcp add <slug>` for a catalog server, or `yaw-mcp add <name> --command "<launch line>"` for any other.';
8399
+ break;
8400
+ case "try":
8401
+ fix = `Pick another client, such as ${orList(
8402
+ alternatives.map((t) => `--client ${t.clientId}`)
8403
+ )}, or add the entry by hand.`;
8404
+ break;
8405
+ default:
8406
+ fix = `Install into ${orList(alternatives.map((t) => t.label))} instead, or add the entry by hand.`;
8407
+ }
8408
+ return `yaw-mcp ${cmd}: ${target.label} on ${os} is not supported yet.
8409
+ ${reason}.
8437
8410
  ${fix}`;
8438
8411
  }
8439
8412
  var TOKEN_FLAG_DEPRECATION = "yaw-mcp install: --token is deprecated and ignored -- yaw-mcp is local-only and no longer stores a token. Drop the flag, and revoke that PAT at its source -- dropping it here does not deactivate it.";
@@ -8456,7 +8429,8 @@ ${USAGE}`);
8456
8429
  // NOT "pass --os to override": install resolves paths against THIS
8457
8430
  // machine, so a cross-OS --os write is refused at the flag boundary
8458
8431
  // (see parseInstallArgs) — only the --dry-run preview is offered.
8459
- "Pick a different client, or preview another OS's config with --os <os> --dry-run."
8432
+ // `import` has no --os flag at all, so it must not advertise one.
8433
+ cmd === "import" ? "Pick a different client." : "Pick a different client, or preview another OS's config with --os <os> --dry-run."
8460
8434
  )
8461
8435
  );
8462
8436
  return null;
@@ -8481,22 +8455,26 @@ ${USAGE}`);
8481
8455
  return null;
8482
8456
  }
8483
8457
  const projectDir = scopeSpec.requiresProjectDir ? resolve5(opts.cwd ?? process.cwd(), opts.projectDir ?? ".") : void 0;
8484
- let resolved;
8458
+ let sites;
8485
8459
  try {
8486
- resolved = resolveInstallPath({
8460
+ sites = resolveInstallSites({
8487
8461
  clientId: target.clientId,
8488
8462
  scope,
8489
8463
  os,
8490
8464
  home: opts.home,
8491
8465
  appData: resolveAppDataDir({ appData: opts.appData, home: opts.home }),
8492
8466
  projectDir,
8493
- claudeConfigDir: opts.claudeConfigDir
8467
+ claudeConfigDir: opts.claudeConfigDir,
8468
+ // A MODULAR row resolves its own path from these (Zed's
8469
+ // $XDG_CONFIG_HOME, Cline's three knobs, Continue's global dir). Read
8470
+ // once by the dispatcher; a row never reads process.env itself.
8471
+ clientEnv: opts.clientEnv
8494
8472
  });
8495
8473
  } catch (e) {
8496
8474
  err(`yaw-mcp ${cmd}: ${e.message}`);
8497
8475
  return null;
8498
8476
  }
8499
- return { target, os, scope, projectDir, resolved };
8477
+ return { target, os, scope, projectDir, resolved: sites[0].resolved, sites };
8500
8478
  }
8501
8479
  async function runInstall(opts) {
8502
8480
  const stdout = opts.io?.stdout ?? process.stdout;
@@ -8526,6 +8504,12 @@ async function runInstall(opts) {
8526
8504
  err("yaw-mcp install: --repair and --skip are mutually exclusive");
8527
8505
  return { written: [], wouldWrite: [], messages, exitCode: 2 };
8528
8506
  }
8507
+ if (opts.force && opts.repair) {
8508
+ err(
8509
+ "yaw-mcp install: --force and --repair are mutually exclusive -- --force drops the existing entry's env, --repair keeps its string values. Pass one."
8510
+ );
8511
+ return { written: [], wouldWrite: [], messages, exitCode: 2 };
8512
+ }
8529
8513
  if (opts.listOnly) return runInstallList(opts, log2, messages);
8530
8514
  if (opts.all) return runInstallAll(opts, log2, err, messages);
8531
8515
  if (!opts.clientId) {
@@ -8533,53 +8517,57 @@ async function runInstall(opts) {
8533
8517
  ${USAGE}`);
8534
8518
  return { written: [], wouldWrite: [], messages, exitCode: 2 };
8535
8519
  }
8536
- const site = resolveInstallSite("install", opts, err);
8537
- if (!site) return { written: [], wouldWrite: [], messages, exitCode: 2 };
8538
- const { target, os, scope, projectDir, resolved } = site;
8520
+ const plan = resolveInstallSite("install", opts, err);
8521
+ if (!plan) return { written: [], wouldWrite: [], messages, exitCode: 2 };
8522
+ const { target, os, scope, projectDir, resolved } = plan;
8539
8523
  log2(`Target: ${target.label} (${scope})`);
8540
8524
  log2(`File: ${resolved.absolute}`);
8541
8525
  const containerPath = resolved.containerPath;
8542
- let existing = {};
8543
- let rawClient = null;
8544
- let existingHasEntry = false;
8545
- let storedEntry;
8546
- let legacyEntry = null;
8547
- let directEntryNames = [];
8526
+ const selectedSites = selectSites(plan.sites);
8527
+ const site = selectedSites[0];
8528
+ const extraSites = selectedSites.slice(1);
8529
+ const driveCaseSiblings = [];
8548
8530
  const fingerprintBefore = await fileFingerprint(resolved.absolute);
8549
- if (fingerprintBefore !== null) {
8550
- let raw;
8551
- try {
8552
- raw = await readFile11(resolved.absolute, "utf8");
8553
- } catch (e) {
8554
- err(describeUnreadableConfig("install", resolved.absolute, e));
8555
- return { written: [], wouldWrite: [], messages, exitCode: 1 };
8556
- }
8557
- if (raw.trim().length > 0) {
8558
- try {
8559
- const parsed = parseJsonc(raw);
8560
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
8561
- err(
8562
- `yaw-mcp install: ${resolved.absolute} is not a JSON object -- refusing to overwrite. Edit by hand or rename the file and re-run.`
8563
- );
8564
- return { written: [], wouldWrite: [], messages, exitCode: 1 };
8565
- }
8566
- existing = parsed;
8567
- rawClient = raw;
8568
- } catch (e) {
8569
- err(
8570
- `yaw-mcp install: ${resolved.absolute} is not valid JSON (${e.message}). Refusing to overwrite. Fix the file or rename it and re-run.`
8571
- );
8572
- return { written: [], wouldWrite: [], messages, exitCode: 1 };
8573
- }
8574
- }
8575
- const container = readNested(existing, containerPath);
8576
- if (typeof container === "object" && container !== null && !Array.isArray(container)) {
8577
- const c = container;
8578
- existingHasEntry = ENTRY_NAME in c;
8579
- storedEntry = c[ENTRY_NAME];
8580
- legacyEntry = findLegacyEntry(c);
8581
- directEntryNames = directClientEntries(c);
8582
- }
8531
+ const view = await readClientConfigFile(site, { transform: target.entry });
8532
+ const read = view.read;
8533
+ if (read.kind === "unreadable") {
8534
+ err(describeUnreadableConfig("install", resolved.absolute, { code: read.code, message: read.message }));
8535
+ return { written: [], wouldWrite: [], messages, exitCode: 1 };
8536
+ }
8537
+ if (read.kind === "malformed") {
8538
+ err(
8539
+ read.reason === "root" ? `yaw-mcp install: ${resolved.absolute} is not a ${read.syntax} object -- refusing to overwrite it; ${unparseableConfigFix("re-run")}.` : `yaw-mcp install: ${resolved.absolute} is not valid ${read.syntax} (${read.detail}) -- refusing to overwrite it; ${unparseableConfigFix("re-run")}.`
8540
+ );
8541
+ return { written: [], wouldWrite: [], messages, exitCode: 1 };
8542
+ }
8543
+ const unloadable = view.unloadable();
8544
+ if (unloadable !== null && !(read.kind === "blocked" && !read.reparable)) {
8545
+ err(
8546
+ `yaw-mcp install: ${resolved.absolute} ${unloadableConfigProblem(unloadable)} -- refusing to write into it; ${unloadableConfigFix("re-run")}.`
8547
+ );
8548
+ return { written: [], wouldWrite: [], messages, exitCode: 1 };
8549
+ }
8550
+ const variantPaths = claudeCodeContainerPathVariants(
8551
+ containerPath,
8552
+ (prefix) => containerKeysAt(view.raw, site, prefix)
8553
+ );
8554
+ for (const variantPath of variantPaths.slice(1)) {
8555
+ const sibling = classifyClientConfig(view.raw, siteAt(site, variantPath), { transform: target.entry });
8556
+ if (sibling.read.kind !== "ok" || !sibling.read.containerPresent) continue;
8557
+ const siblingLegacy = sibling.legacyKey();
8558
+ const siblingHasEntry = sibling.entry() !== void 0;
8559
+ if (!siblingHasEntry && siblingLegacy === null) continue;
8560
+ driveCaseSiblings.push({ key: variantPath[1], hasEntry: siblingHasEntry, legacy: siblingLegacy });
8561
+ }
8562
+ const existingHasEntry = view.entry() !== void 0;
8563
+ const storedEntry = view.normalized();
8564
+ const legacyEntry = view.legacyKey();
8565
+ const directEntryNames = view.otherServerKeys();
8566
+ for (const sibling of driveCaseSiblings) {
8567
+ const what = sibling.hasEntry ? sibling.legacy !== null ? `"${ENTRY_NAME}" and legacy "${sibling.legacy}" entries` : `a "${ENTRY_NAME}" entry` : `a legacy "${sibling.legacy}" entry`;
8568
+ log2(
8569
+ `Note: ${resolved.absolute} also has ${what} under projects[${JSON.stringify(sibling.key)}] -- the same directory spelled with the other drive-letter case. Left alone: only a Claude Code whose cwd is spelled that way reads it, and that session cannot see the entry this command writes. \`yaw-mcp uninstall ${target.clientId} --scope ${scope}\` removes both spellings.`
8570
+ );
8583
8571
  }
8584
8572
  if (existingHasEntry && opts.skip) {
8585
8573
  log2(
@@ -8591,7 +8579,12 @@ ${USAGE}`);
8591
8579
  const resolveEntry = opts.resolveOamEntry ?? resolveStableNpmEntry;
8592
8580
  const oamBinPath = oamProbeResult.binPath;
8593
8581
  const oamEntry = oamBinPath ? resolveEntry("@yawlabs/mcp") : null;
8594
- const newEntry = buildLaunchEntry({ os, oamBinPath, oamEntry });
8582
+ const newEntry = buildLaunchEntry({
8583
+ os,
8584
+ oamBinPath,
8585
+ oamEntry,
8586
+ windowsWrap: target.entry?.windowsLaunch?.broker !== "bare"
8587
+ });
8595
8588
  const runtimeLines = [];
8596
8589
  const oamVersion = oamProbeResult.version ? ` ${oamProbeResult.version}` : "";
8597
8590
  if (oamBinPath && oamEntry && newEntry.command === oamBinPath) {
@@ -8624,13 +8617,48 @@ ${USAGE}`);
8624
8617
  } else if (!opts.suppressOamAbsentNote) {
8625
8618
  runtimeLines.push(oamAbsentNote(os, opts.oamPublishesBinary));
8626
8619
  }
8627
- const previousEntry = readEntryAt(existing, containerPath, ENTRY_NAME);
8628
- const previousEnv = previousEntry?.env;
8629
- const entryToWrite = newEntry.env === void 0 && previousEnv && Object.keys(previousEnv).length > 0 ? { ...newEntry, env: previousEnv } : newEntry;
8630
- if (entryToWrite !== newEntry) {
8631
- runtimeLines.push(`Kept existing env on the ${ENTRY_NAME} entry: ${Object.keys(previousEnv ?? {}).join(", ")}`);
8620
+ const previousEnv = view.carryableEnv();
8621
+ const carryableEnv = newEntry.env === void 0 && previousEnv && Object.keys(previousEnv).length > 0 ? previousEnv : void 0;
8622
+ const envCarried = carryableEnv !== void 0 && !opts.force;
8623
+ const carriedFields = opts.force ? {} : view.carried();
8624
+ const entryToWrite = composeEntry({
8625
+ base: newEntry,
8626
+ transform: target.entry,
8627
+ os,
8628
+ purpose: "broker",
8629
+ env: opts.force ? void 0 : carryableEnv,
8630
+ carried: carriedFields
8631
+ });
8632
+ const carriedKeys = carryableEnv ? Object.keys(carryableEnv).sort() : [];
8633
+ if (carryableEnv) {
8634
+ const keys = carriedKeys.join(", ");
8635
+ if (opts.force) {
8636
+ runtimeLines.push(
8637
+ `${opts.dryRun ? "Would drop" : "Dropping"} existing env on the ${ENTRY_NAME} entry (--force): ${keys}. (--repair would keep ${carriedKeys.length === 1 ? "it" : "them"}; --force does not.)`
8638
+ );
8639
+ } else {
8640
+ runtimeLines.push(`Kept existing env on the ${ENTRY_NAME} entry: ${keys}`);
8641
+ }
8642
+ }
8643
+ const home = opts.home ?? homedir13();
8644
+ const rowArgs = {
8645
+ os,
8646
+ home,
8647
+ appData: resolveAppDataDir({ appData: opts.appData, home: opts.home }),
8648
+ projectDir,
8649
+ claudeConfigDir: opts.claudeConfigDir,
8650
+ clientEnv: opts.clientEnv
8651
+ };
8652
+ if (launchesViaNpx(entryToWrite)) {
8653
+ const shadowed = await shadowedLocalLaunch(target, scope, rowArgs);
8654
+ if (shadowed !== null) {
8655
+ runtimeLines.push(
8656
+ `Note: ${target.label} ranks ${resolved.absolute} above ${shadowed}, whose "${ENTRY_NAME}" entry launches yaw-mcp locally -- so this npx entry replaces that local launch for ${target.label}, and npx resolves @yawlabs/mcp@latest on every ${target.label} start: slow, and it can exceed ${target.label}'s MCP connect timeout. For a fast absolute-path entry, install yaw-mcp globally (\`npm i -g @yawlabs/mcp\`) with oam available and re-run \`yaw-mcp install ${target.clientId}\`, or raise MCP_TIMEOUT.`
8657
+ );
8658
+ }
8632
8659
  }
8633
8660
  const entryState = !existingHasEntry ? "absent" : deepEqualJson(storedEntry, entryToWrite) ? "identical" : "differs";
8661
+ let overwriteAuthorised = opts.force === true || opts.repair === true;
8634
8662
  if (entryState === "differs") {
8635
8663
  const diff = describeEntryDiff(storedEntry, entryToWrite);
8636
8664
  const diffBlock = indentDiff(diff, " ");
@@ -8643,20 +8671,23 @@ ${USAGE}`);
8643
8671
  return { written: [], wouldWrite: [], messages, exitCode: 0 };
8644
8672
  } else if (opts.promptAnswer) decision = opts.promptAnswer;
8645
8673
  else if (opts.io?.isTTY ?? (Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY))) {
8646
- const answer = await promptCollision(resolved.absolute, diff, opts.io);
8674
+ const answer = await promptCollision(resolved.absolute, diff, opts.io, envCarried ? carriedKeys : []);
8647
8675
  if (answer === "skip") {
8648
8676
  log2(`Existing "${ENTRY_NAME}" entry left untouched. Nothing to do.`);
8649
8677
  return { written: [], wouldWrite: [], messages, exitCode: 0 };
8650
8678
  }
8651
8679
  decision = answer;
8652
8680
  } else {
8681
+ const differs = ` It differs from the entry install would write:
8682
+ ${diffBlock}`;
8683
+ const flagHint = carryableEnv ? ` Re-run with --repair to bring it up to date (keeping env: ${carriedKeys.join(", ")}), --force to overwrite it outright (dropping its env), --skip to leave it, or --dry-run to preview.` : " Re-run with --repair to bring it up to date, --force to overwrite, --skip to leave it, or --dry-run to preview.";
8653
8684
  err(
8654
- `yaw-mcp install: ${resolved.absolute} already has a "${ENTRY_NAME}" entry and stdin is not a TTY.
8655
- It differs from the entry install would write:
8656
- ${diffBlock}
8657
- Re-run with --repair to bring it up to date, --force to overwrite, --skip to leave it, or --dry-run to preview.`
8685
+ opts.deferCollisionHint ? `yaw-mcp install: ${resolved.absolute} already has a "${ENTRY_NAME}" entry -- left untouched.
8686
+ ${differs}` : `yaw-mcp install: ${resolved.absolute} already has a "${ENTRY_NAME}" entry and stdin is not a TTY.
8687
+ ${differs}
8688
+ ` + flagHint
8658
8689
  );
8659
- return { written: [], wouldWrite: [], messages, exitCode: 2 };
8690
+ return { written: [], wouldWrite: [], messages, exitCode: 2, collisionRefused: true };
8660
8691
  }
8661
8692
  if (decision === "abort") {
8662
8693
  err("Aborted.");
@@ -8666,6 +8697,7 @@ ${diffBlock}
8666
8697
  err("Cancelled.");
8667
8698
  return { written: [], wouldWrite: [], messages, exitCode: 130 };
8668
8699
  }
8700
+ overwriteAuthorised = true;
8669
8701
  log2(
8670
8702
  opts.dryRun ? `Would overwrite existing "${ENTRY_NAME}" entry.` : `Overwriting existing "${ENTRY_NAME}" entry.`
8671
8703
  );
@@ -8679,99 +8711,129 @@ ${diffBlock}
8679
8711
  for (const line of runtimeLines) log2(line);
8680
8712
  }
8681
8713
  let clientJson = null;
8714
+ let repairedContainer = null;
8682
8715
  if (skipEntryWrite && !trimLegacy) {
8683
8716
  clientJson = null;
8684
- } else if (skipEntryWrite && rawClient !== null) {
8685
- try {
8686
- const next = removeJsoncEntry(rawClient, containerPath, legacyEntry);
8687
- clientJson = next.endsWith("\n") ? next : `${next}
8688
- `;
8689
- } catch (e) {
8690
- err(
8691
- `yaw-mcp install: failed to remove the legacy "${legacyEntry}" entry from ${resolved.absolute} (${e.message}). Refusing to overwrite.`
8692
- );
8693
- return { written: [], wouldWrite: [], messages, exitCode: 1 };
8694
- }
8695
- } else if (rawClient !== null) {
8696
- let spliceSource = rawClient;
8697
- const blocked = findBlockedContainerSegment(existing, containerPath);
8698
- if (blocked) {
8699
- const keyPath = blocked.path.join(".");
8700
- if (!blocked.reparable) {
8701
- err(
8702
- `yaw-mcp install: "${keyPath}" in ${resolved.absolute} is ${describeJsonShape(blocked.value)}, not a JSON object -- refusing to overwrite. Make it an object (or remove the key) and re-run.`
8703
- );
8704
- return { written: [], wouldWrite: [], messages, exitCode: 1 };
8705
- }
8706
- try {
8707
- spliceSource = editJsoncEntry(
8708
- spliceSource,
8709
- blocked.path.slice(0, -1),
8710
- blocked.path[blocked.path.length - 1],
8711
- {}
8712
- );
8713
- } catch (e) {
8717
+ } else {
8718
+ const edits = [];
8719
+ if (read.kind === "blocked") {
8720
+ const keyPath = read.path.join(".");
8721
+ if (!read.reparable) {
8714
8722
  err(
8715
- `yaw-mcp install: failed to replace the non-object "${keyPath}" key in ${resolved.absolute} (${e.message}). Refusing to overwrite.`
8723
+ `yaw-mcp install: "${keyPath}" in ${resolved.absolute} is ${read.shape}, not a JSON object -- refusing to overwrite it; ${blockedContainerFix("re-run")}.`
8716
8724
  );
8717
8725
  return { written: [], wouldWrite: [], messages, exitCode: 1 };
8718
8726
  }
8719
- log2(
8720
- `Note: "${keyPath}" in ${resolved.absolute} is ${describeJsonShape(blocked.value)}, not an object -- ${opts.dryRun ? "would replace" : "replaced"} it with an empty object so the "${ENTRY_NAME}" entry has somewhere to live.`
8721
- );
8727
+ edits.push({ op: "repair", path: read.path });
8728
+ repairedContainer = { keyPath, shape: read.shape };
8722
8729
  }
8730
+ if (!skipEntryWrite) edits.push({ op: "upsert", key: ENTRY_NAME, entry: entryToWrite });
8731
+ if (trimLegacy) edits.push({ op: "remove", key: legacyEntry });
8723
8732
  try {
8724
- let next = editJsoncEntry(spliceSource, containerPath, ENTRY_NAME, entryToWrite);
8725
- if (trimLegacy) next = removeJsoncEntry(next, containerPath, legacyEntry);
8726
- clientJson = next.endsWith("\n") ? next : `${next}
8727
- `;
8733
+ clientJson = terminateWithNewline(applyClientConfigEdits(view, edits, site));
8728
8734
  } catch (e) {
8729
8735
  err(
8730
- `yaw-mcp install: failed to splice the "${ENTRY_NAME}" entry into ${resolved.absolute} (${e.message}). Refusing to overwrite.`
8736
+ skipEntryWrite ? `yaw-mcp install: failed to remove the legacy "${legacyEntry}" entry from ${resolved.absolute} (${e.message}). Refusing to overwrite.` : `yaw-mcp install: failed to splice the "${ENTRY_NAME}" entry into ${resolved.absolute} (${e.message}). Refusing to overwrite.`
8731
8737
  );
8732
8738
  return { written: [], wouldWrite: [], messages, exitCode: 1 };
8733
8739
  }
8734
- } else {
8735
- const merged = mergeClientConfig(existing, containerPath, entryToWrite);
8736
- clientJson = `${JSON.stringify(merged, null, 2)}
8737
- `;
8738
8740
  }
8739
- const home = opts.home ?? homedir13();
8740
- const settingsPatch = opts.clientId === "claude-code" ? await prepareClaudeCodeSettingsPatch({
8741
+ const containerRepairNote = (what, tense) => `Note: "${what.keyPath}" in ${resolved.absolute} is ${what.shape}, not an object -- ${tense} it with an empty object so the "${ENTRY_NAME}" entry has somewhere to live.`;
8742
+ const grant = await prepareGrantPatches({
8743
+ target,
8741
8744
  scope,
8742
8745
  home,
8743
8746
  projectDir,
8744
- claudeConfigDir: opts.claudeConfigDir
8745
- }) : null;
8746
- if (settingsPatch?.malformed) {
8747
+ claudeConfigDir: opts.claudeConfigDir,
8748
+ yawMode: opts.clientEnv?.yawMode,
8749
+ op: "add"
8750
+ });
8751
+ const settingsPatches = grant.patches;
8752
+ for (const settingsPatch of settingsPatches) {
8753
+ if (!settingsPatch.malformed) continue;
8747
8754
  err(
8748
8755
  `yaw-mcp install: warning -- could not patch ${settingsPatch.path} (${settingsPatch.malformedReason}); left unchanged. Add "${CLAUDE_CODE_ALLOW_PATTERN}" to permissions.allow by hand, or you may be re-prompted for each yaw-mcp tool call.`
8749
8756
  );
8750
8757
  }
8758
+ const primaryPatch = settingsPatches.find((p) => !p.yawHome) ?? null;
8759
+ const scopedGrantNote = grant.overlay !== null || primaryPatch === null || primaryPatch.malformed ? null : configDirScopedGrantNote({
8760
+ cmd: "install",
8761
+ dryRun: opts.dryRun === true,
8762
+ target,
8763
+ scope,
8764
+ where: rowArgs,
8765
+ entryFile: resolved.absolute,
8766
+ settingsPath: primaryPatch.path
8767
+ });
8768
+ const staleProgram = await staleProgramWarning({
8769
+ clientId: target.clientId,
8770
+ scope,
8771
+ os,
8772
+ home,
8773
+ appData: resolveAppData(opts),
8774
+ projectDir,
8775
+ claudeConfigDir: opts.claudeConfigDir,
8776
+ clientEnv: opts.clientEnv
8777
+ });
8778
+ if (staleProgram !== null) err(`yaw-mcp install: warning -- ${staleProgram}`);
8751
8779
  const bundles = opts.suppressBundlesNote ? null : await Promise.resolve((opts.bundlesSummary ?? summarizeBundles)({ home: opts.home, cwd: opts.cwd })).catch(
8752
8780
  () => null
8753
8781
  );
8754
8782
  if (opts.dryRun) {
8755
- if (clientJson === null && !settingsPatch?.changed) {
8783
+ const extraPreview = [];
8784
+ const extraWouldWrite = await applyToExtraSites({
8785
+ cmd: "install",
8786
+ sites: extraSites,
8787
+ transform: target.entry,
8788
+ // The BASE entry, not `entryToWrite`: each copy composes its own from
8789
+ // its own carry. See applyToExtraSites.
8790
+ compose: { base: newEntry, os, force: opts.force === true },
8791
+ keepLegacy: opts.keepLegacy === true,
8792
+ authorised: overwriteAuthorised,
8793
+ dryRun: true,
8794
+ log: (s) => extraPreview.push([log2, s]),
8795
+ err: (s) => extraPreview.push([err, s])
8796
+ });
8797
+ const flushExtraPreview = () => {
8798
+ for (const [sink, line] of extraPreview) sink(line);
8799
+ };
8800
+ if (clientJson === null && !settingsPatches.some((p) => p.changed) && extraWouldWrite.length === 0) {
8801
+ flushExtraPreview();
8756
8802
  log2(`
8757
8803
  Nothing to do: ${target.label} (${scope}) is already configured.`);
8758
8804
  return { written: [], wouldWrite: [], messages, exitCode: 0 };
8759
8805
  }
8806
+ if (repairedContainer) log2(containerRepairNote(repairedContainer, "would replace"));
8760
8807
  log2("\n--- dry run: would add the following (the rest of each file is left as-is) ---");
8761
8808
  if (clientJson !== null && !skipEntryWrite) {
8762
- const previewEntry = entryToWrite !== newEntry && entryToWrite.env ? {
8809
+ const previewEntry = envCarried && entryToWrite.env ? {
8763
8810
  ...entryToWrite,
8764
8811
  env: Object.fromEntries(Object.keys(entryToWrite.env).map((k) => [k, DRY_RUN_ENV_PLACEHOLDER]))
8765
8812
  } : entryToWrite;
8766
- const preview = mergeClientConfig({}, containerPath, previewEntry);
8767
- log2(`
8813
+ log2(
8814
+ `
8768
8815
  # ${resolved.absolute}
8769
- ${JSON.stringify(preview, null, 2)}`);
8816
+ ${view.adapter.renderPreview(view.address, ENTRY_NAME, previewEntry, read.kind === "absent")}`
8817
+ );
8770
8818
  }
8771
- if (settingsPatch?.changed) {
8772
- log2(`# ${settingsPatch.path}
8819
+ for (const settingsPatch of settingsPatches) {
8820
+ if (settingsPatch.changed) {
8821
+ log2(`# ${settingsPatch.path}
8773
8822
  permissions.allow += ${JSON.stringify(settingsPatch.added)}`);
8823
+ }
8774
8824
  }
8825
+ const freshNote2 = yawFreshPaneNote({
8826
+ grant,
8827
+ target,
8828
+ claudeConfigDir: opts.claudeConfigDir,
8829
+ entryFile: resolved.absolute,
8830
+ wrote: [
8831
+ ...clientJson !== null ? [resolved.absolute] : [],
8832
+ ...settingsPatches.filter((p) => p.changed).map((p) => p.path)
8833
+ ]
8834
+ });
8835
+ if (freshNote2 !== null) log2(freshNote2);
8836
+ if (scopedGrantNote !== null) log2(scopedGrantNote);
8775
8837
  if (legacyEntry) {
8776
8838
  log2(
8777
8839
  trimLegacy ? `Would also remove the legacy "${legacyEntry}" entry at ${resolved.absolute} (pass --keep-legacy to leave it).` : `Note: legacy "${legacyEntry}" entry at ${resolved.absolute} would remain (--keep-legacy) -- remove it to avoid running yaw-mcp twice.`
@@ -8788,7 +8850,11 @@ permissions.allow += ${JSON.stringify(settingsPatch.added)}`);
8788
8850
  bundles
8789
8851
  );
8790
8852
  const wouldWrite = clientJson !== null ? [resolved.absolute] : [];
8791
- if (settingsPatch?.changed) wouldWrite.push(settingsPatch.path);
8853
+ flushExtraPreview();
8854
+ wouldWrite.push(...extraWouldWrite);
8855
+ for (const settingsPatch of settingsPatches) {
8856
+ if (settingsPatch.changed) wouldWrite.push(settingsPatch.path);
8857
+ }
8792
8858
  return { written: [], wouldWrite, messages, exitCode: 0 };
8793
8859
  }
8794
8860
  const written = [];
@@ -8806,12 +8872,29 @@ permissions.allow += ${JSON.stringify(settingsPatch.added)}`);
8806
8872
  return { written, wouldWrite: [], messages, exitCode: 1 };
8807
8873
  }
8808
8874
  log2(`Wrote ${resolved.absolute}`);
8875
+ if (repairedContainer) log2(containerRepairNote(repairedContainer, "replaced"));
8809
8876
  written.push(resolved.absolute);
8810
8877
  if (trimLegacy) {
8811
8878
  log2(`Removed the legacy "${legacyEntry}" entry -- it would have run yaw-mcp a second time.`);
8812
8879
  }
8813
8880
  }
8814
- if (settingsPatch?.changed) {
8881
+ written.push(
8882
+ ...await applyToExtraSites({
8883
+ cmd: "install",
8884
+ sites: extraSites,
8885
+ transform: target.entry,
8886
+ // The BASE entry, not `entryToWrite`: each copy composes its own from
8887
+ // its own carry. See applyToExtraSites.
8888
+ compose: { base: newEntry, os, force: opts.force === true },
8889
+ keepLegacy: opts.keepLegacy === true,
8890
+ authorised: overwriteAuthorised,
8891
+ dryRun: false,
8892
+ log: log2,
8893
+ err
8894
+ })
8895
+ );
8896
+ for (const settingsPatch of settingsPatches) {
8897
+ if (!settingsPatch.changed) continue;
8815
8898
  if (!sameFingerprint(settingsPatch.fingerprint, await fileFingerprint(settingsPatch.path))) {
8816
8899
  err(
8817
8900
  `yaw-mcp install: warning -- ${settingsPatch.path} changed while install was running (another process wrote it); left unchanged. Add "${CLAUDE_CODE_ALLOW_PATTERN}" to permissions.allow by hand, or you may be re-prompted for each yaw-mcp tool call.`
@@ -8819,7 +8902,9 @@ permissions.allow += ${JSON.stringify(settingsPatch.added)}`);
8819
8902
  } else {
8820
8903
  try {
8821
8904
  await atomicWriteFile(settingsPatch.path, settingsPatch.nextJson);
8822
- log2(`Wrote ${settingsPatch.path} (added ${CLAUDE_CODE_ALLOW_PATTERN} to permissions.allow)`);
8905
+ log2(
8906
+ `Wrote ${settingsPatch.path} (added ${CLAUDE_CODE_ALLOW_PATTERN} to permissions.allow${settingsPatch.yawHome ? YAW_HOME_GRANT_REASON : ""})`
8907
+ );
8823
8908
  written.push(settingsPatch.path);
8824
8909
  } catch (e) {
8825
8910
  err(
@@ -8828,12 +8913,23 @@ permissions.allow += ${JSON.stringify(settingsPatch.added)}`);
8828
8913
  }
8829
8914
  }
8830
8915
  }
8916
+ const freshNote = yawFreshPaneNote({
8917
+ grant,
8918
+ target,
8919
+ claudeConfigDir: opts.claudeConfigDir,
8920
+ entryFile: resolved.absolute,
8921
+ wrote: written
8922
+ });
8923
+ if (freshNote !== null) log2(freshNote);
8831
8924
  if (written.length === 0) {
8832
8925
  log2(`
8833
8926
  Nothing to do: ${target.label} is already configured.`);
8834
8927
  return { written, wouldWrite: [], messages, exitCode: 0 };
8835
8928
  }
8836
8929
  if (target.notes) log2(`Note: ${target.notes}`);
8930
+ if (scopedGrantNote !== null && primaryPatch !== null) {
8931
+ if (!primaryPatch.changed || written.includes(primaryPatch.path)) log2(scopedGrantNote);
8932
+ }
8837
8933
  if (legacyEntry && !trimLegacy) {
8838
8934
  log2(
8839
8935
  `Note: legacy "${legacyEntry}" entry remains at ${resolved.absolute} (--keep-legacy). Remove it to avoid running yaw-mcp twice.`
@@ -8847,120 +8943,64 @@ Nothing to do: ${target.label} is already configured.`);
8847
8943
  );
8848
8944
  log2(
8849
8945
  target.clientId === "claude-code" && scope === "project" ? `
8850
- Done: ${target.label} is configured. Restart it in this project and approve the .mcp.json server when prompted -- Claude Code keeps project-scope (.mcp.json) servers disabled until you approve them.` : `
8851
- Done: ${target.label} is configured. Restart it to pick up the new MCP server.`
8946
+ Done: ${target.label} is configured. Restart it in this project and approve the .mcp.json server when prompted -- Claude Code keeps project-scope (.mcp.json) servers disabled until you approve them.` : (
8947
+ // How the client picks the change up is the ROW's fact, not this
8948
+ // line's: a client that watches its config file must not be told to
8949
+ // restart, and one that needs a window reload must not be told the
8950
+ // editor. `reload` defaults to "restart", whose clause is what every
8951
+ // pre-existing row printed, byte for byte.
8952
+ `
8953
+ Done: ${target.label} is configured. ${reloadDoneClause(target.reload, target.label)}`
8954
+ )
8852
8955
  );
8853
8956
  return { written, wouldWrite: [], messages, exitCode: 0 };
8854
8957
  }
8855
- async function prepareClaudeCodeSettingsPatch(opts) {
8856
- const path6 = resolveClaudeCodeSettingsPath(opts.scope, {
8857
- home: opts.home,
8858
- projectDir: opts.projectDir,
8859
- claudeConfigDir: opts.claudeConfigDir
8860
- });
8861
- if (!path6) return null;
8862
- let existing = {};
8863
- let rawSettings = null;
8864
- const fingerprint = await fileFingerprint(path6);
8865
- if (fingerprint !== null) {
8866
- try {
8867
- const raw = await readFile11(path6, "utf8");
8868
- if (raw.trim().length > 0) {
8869
- const parsed = parseJsonc(raw);
8870
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
8871
- existing = parsed;
8872
- rawSettings = raw;
8873
- } else {
8874
- return {
8875
- path: path6,
8876
- nextJson: "",
8877
- changed: false,
8878
- added: [],
8879
- removed: [],
8880
- malformed: true,
8881
- malformedReason: "not a JSON object",
8882
- fingerprint
8883
- };
8884
- }
8885
- }
8886
- } catch (e) {
8887
- return {
8888
- path: path6,
8889
- nextJson: "",
8890
- changed: false,
8891
- added: [],
8892
- removed: [],
8893
- malformed: true,
8894
- malformedReason: e.message,
8895
- fingerprint
8896
- };
8897
- }
8898
- }
8899
- const op = opts.op ?? "add";
8900
- const merged = op === "remove" ? removePermissionsAllow(existing, [CLAUDE_CODE_ALLOW_PATTERN]) : mergePermissionsAllow(existing, [CLAUDE_CODE_ALLOW_PATTERN]);
8901
- const before = JSON.stringify(existing);
8902
- const after = JSON.stringify(merged);
8903
- if (before === after) return { path: path6, nextJson: "", changed: false, added: [], removed: [], fingerprint };
8904
- const prevAllow = existing.permissions?.allow;
8905
- const prevAllowList = Array.isArray(prevAllow) ? prevAllow : [];
8906
- const added = op === "add" ? [CLAUDE_CODE_ALLOW_PATTERN].filter((p) => !prevAllowList.includes(p)) : [];
8907
- const removed = op === "remove" ? [CLAUDE_CODE_ALLOW_PATTERN].filter((p) => prevAllowList.includes(p)) : [];
8908
- if (rawSettings !== null) {
8909
- const blockedPermissions = findBlockedContainerSegment(existing, ["permissions"]);
8910
- if (blockedPermissions) {
8911
- return {
8912
- path: path6,
8913
- nextJson: "",
8914
- changed: false,
8915
- added: [],
8916
- removed: [],
8917
- malformed: true,
8918
- malformedReason: `"permissions" is ${describeJsonShape(blockedPermissions.value)}, not a JSON object`,
8919
- fingerprint
8920
- };
8921
- }
8922
- const nextAllow = merged.permissions.allow;
8923
- try {
8924
- const next = editJsoncEntry(rawSettings, ["permissions"], "allow", nextAllow);
8925
- return { path: path6, nextJson: next.endsWith("\n") ? next : `${next}
8926
- `, changed: true, added, removed, fingerprint };
8927
- } catch (e) {
8928
- return {
8929
- path: path6,
8930
- nextJson: "",
8931
- changed: false,
8932
- added: [],
8933
- removed: [],
8934
- malformed: true,
8935
- malformedReason: `could not splice permissions.allow (${e.message})`,
8936
- fingerprint
8937
- };
8938
- }
8939
- }
8940
- return { path: path6, nextJson: `${JSON.stringify(merged, null, 2)}
8941
- `, changed: true, added, removed, fingerprint };
8942
- }
8943
- function mergePermissionsAllow(existing, patterns) {
8944
- const out = { ...existing };
8945
- const prev = out.permissions;
8946
- const perms = typeof prev === "object" && prev !== null && !Array.isArray(prev) ? { ...prev } : {};
8947
- const prevAllow = perms.allow;
8948
- const allow = Array.isArray(prevAllow) ? [...prevAllow] : [];
8949
- for (const p of patterns) {
8950
- if (!allow.includes(p)) allow.push(p);
8958
+ async function prepareGrantPatches(args) {
8959
+ if (args.target.hooks?.permissionsPatch !== "claude-code") return { patches: [], overlay: null };
8960
+ const overlay = args.scope === "user" ? yawModeOverlay({ yawMode: args.yawMode, claudeConfigDir: args.claudeConfigDir }) : null;
8961
+ const patches = [];
8962
+ const dirs = [
8963
+ { claudeConfigDir: args.claudeConfigDir, yawHome: false }
8964
+ ];
8965
+ if (overlay === "augment") dirs.push({ claudeConfigDir: void 0, yawHome: true });
8966
+ for (const { claudeConfigDir, yawHome } of dirs) {
8967
+ const patch = await prepareClaudeCodeSettingsPatch({
8968
+ scope: args.scope,
8969
+ home: args.home,
8970
+ projectDir: args.projectDir,
8971
+ claudeConfigDir,
8972
+ op: args.op
8973
+ });
8974
+ if (patch !== null) patches.push({ ...patch, claudeConfigDir, yawHome });
8975
+ }
8976
+ return { patches, overlay };
8977
+ }
8978
+ var YAW_HOME_GRANT_REASON = " -- a Yaw Mode pane's own settings.json does not outlive the pane";
8979
+ function yawFreshPaneNote(args) {
8980
+ const overlayPatch = args.grant.patches.find((p) => !p.yawHome);
8981
+ const cfg = args.claudeConfigDir;
8982
+ if (args.grant.overlay !== "fresh" || overlayPatch === void 0 || cfg === void 0) return null;
8983
+ const entryInOverlay = samePathKey(args.entryFile).startsWith(`${samePathKey(cfg)}${sep}`);
8984
+ const grantWritten = args.wrote.includes(overlayPatch.path);
8985
+ const entryWritten = entryInOverlay && args.wrote.includes(args.entryFile);
8986
+ if (!grantWritten && !entryWritten) return null;
8987
+ const { label, clientId } = args.target;
8988
+ const again = `Run \`yaw-mcp install ${clientId}\` from a normal shell to keep`;
8989
+ if (!entryInOverlay) {
8990
+ return `Note: a fresh Yaw Mode pane does not keep its settings.json, so the ${CLAUDE_CODE_ALLOW_PATTERN} grant in ${overlayPatch.path} goes when this pane closes. ${again} it.`;
8991
+ }
8992
+ return overlayPatch.malformed ? `Note: a fresh Yaw Mode pane does not keep its config dir, so the ${label} entry in ${args.entryFile} goes when this pane closes. ${again} it.` : `Note: a fresh Yaw Mode pane does not keep its config dir, so the ${label} entry in ${args.entryFile} and the ${CLAUDE_CODE_ALLOW_PATTERN} grant in ${overlayPatch.path} go when this pane closes. ${again} them.`;
8993
+ }
8994
+ async function staleProgramWarning(opts) {
8995
+ const probe = resolveProgramProbe(opts);
8996
+ if (probe === null) return null;
8997
+ let bytes;
8998
+ try {
8999
+ bytes = await readFile11(probe.file);
9000
+ } catch {
9001
+ return null;
8951
9002
  }
8952
- perms.allow = allow;
8953
- out.permissions = perms;
8954
- return out;
8955
- }
8956
- function removePermissionsAllow(existing, patterns) {
8957
- const prev = existing.permissions;
8958
- if (typeof prev !== "object" || prev === null || Array.isArray(prev)) return existing;
8959
- const prevAllow = prev.allow;
8960
- if (!Array.isArray(prevAllow)) return existing;
8961
- const allow = prevAllow.filter((p) => !(typeof p === "string" && patterns.includes(p)));
8962
- if (allow.length === prevAllow.length) return existing;
8963
- return { ...existing, permissions: { ...prev, allow } };
9003
+ return probe.markers.some((marker) => bytes.includes(marker)) ? null : probe.warning;
8964
9004
  }
8965
9005
  async function fileFingerprint(path6) {
8966
9006
  try {
@@ -8974,7 +9014,7 @@ function sameFingerprint(a, b) {
8974
9014
  if (a === null || b === null) return a === b;
8975
9015
  return a.mtimeMs === b.mtimeMs && a.size === b.size;
8976
9016
  }
8977
- async function promptCollision(path6, diff, io) {
9017
+ async function promptCollision(path6, diff, io, keptEnvKeys) {
8978
9018
  const stdin = io?.stdin ?? process.stdin;
8979
9019
  const stdout = io?.stdout ?? process.stdout;
8980
9020
  const rl = createInterface({ input: stdin, output: stdout, terminal: io?.terminal });
@@ -8983,7 +9023,7 @@ async function promptCollision(path6, diff, io) {
8983
9023
  rl,
8984
9024
  `${path6} already has an "${ENTRY_NAME}" entry that differs from the one install would write:
8985
9025
  ${indentDiff(diff, " ")}
8986
- [o]verwrite, [s]kip, or [a]bort? (default: skip) `
9026
+ [o]verwrite${keptEnvKeys.length > 0 ? ` (keeping env: ${keptEnvKeys.join(", ")})` : ""}, [s]kip, or [a]bort? (default: skip) `
8987
9027
  );
8988
9028
  if (raw === QUESTION_CANCELLED) return "cancelled";
8989
9029
  const answer = raw.trim().toLowerCase();
@@ -8994,36 +9034,6 @@ ${indentDiff(diff, " ")}
8994
9034
  rl.close();
8995
9035
  }
8996
9036
  }
8997
- function readNested(root, containerPath) {
8998
- let cur = root;
8999
- for (const key of containerPath) {
9000
- if (typeof cur !== "object" || cur === null || Array.isArray(cur)) return void 0;
9001
- cur = cur[key];
9002
- }
9003
- return cur;
9004
- }
9005
- function findBlockedContainerSegment(root, containerPath) {
9006
- let node = root;
9007
- for (let i = 0; i < containerPath.length; i++) {
9008
- const value = node[containerPath[i]];
9009
- if (value === void 0) return null;
9010
- if (typeof value === "object" && value !== null && !Array.isArray(value)) {
9011
- node = value;
9012
- continue;
9013
- }
9014
- return {
9015
- path: containerPath.slice(0, i + 1),
9016
- value,
9017
- reparable: value === null || !Array.isArray(value) || value.length === 0
9018
- };
9019
- }
9020
- return null;
9021
- }
9022
- function describeJsonShape(value) {
9023
- if (value === null) return "null";
9024
- if (Array.isArray(value)) return value.length === 0 ? "an empty array" : `an array of ${value.length}`;
9025
- return `a ${typeof value}`;
9026
- }
9027
9037
  function deepEqualJson(a, b) {
9028
9038
  if (a === b) return true;
9029
9039
  if (a === null || b === null) return false;
@@ -9044,7 +9054,7 @@ function indentDiff(diff, indent) {
9044
9054
  }
9045
9055
  function describeEntryDiff(stored, nextEntry) {
9046
9056
  if (typeof stored !== "object" || stored === null || Array.isArray(stored)) {
9047
- return [`the stored entry is ${describeJsonShape(stored)}, not an object`];
9057
+ return [`the stored entry is ${describeValueShape(stored)}, not an object`];
9048
9058
  }
9049
9059
  const prev = stored;
9050
9060
  const next = nextEntry;
@@ -9076,38 +9086,103 @@ function describeEntryDiff(stored, nextEntry) {
9076
9086
  }
9077
9087
  return lines.length > 0 ? lines : ["the entries differ in key order only"];
9078
9088
  }
9079
- function readEntryAt(existing, containerPath, entryName = ENTRY_NAME) {
9080
- const node = readNested(existing, containerPath);
9081
- if (typeof node !== "object" || node === null || Array.isArray(node)) return null;
9082
- const entry = node[entryName];
9083
- if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return null;
9084
- const result = { ...entry };
9085
- const env = entry.env;
9086
- if (typeof env === "object" && env !== null && !Array.isArray(env)) {
9087
- const kept = Object.fromEntries(Object.entries(env).filter(([, v]) => typeof v === "string"));
9088
- result.env = Object.keys(kept).length > 0 ? kept : void 0;
9089
- } else {
9090
- result.env = void 0;
9089
+ async function applyToExtraSites(args) {
9090
+ const { cmd, compose, log: log2, err } = args;
9091
+ const touched = [];
9092
+ for (const site of args.sites) {
9093
+ const where = site.resolved.absolute;
9094
+ const named = `${where} (${site.label})`;
9095
+ const view = await readClientConfigFile(site, { transform: args.transform });
9096
+ const read = view.read;
9097
+ if (read.kind === "unreadable" || read.kind === "malformed" || read.kind === "unspliceable") {
9098
+ err(`yaw-mcp ${cmd}: warning -- ${named} could not be edited; left unchanged. Edit it by hand.`);
9099
+ continue;
9100
+ }
9101
+ const legacy = view.legacyKey();
9102
+ const trimLegacy = legacy !== null && !args.keepLegacy;
9103
+ const hasEntry = view.entry() !== void 0;
9104
+ if (compose === void 0) {
9105
+ if (!hasEntry && !trimLegacy) continue;
9106
+ const edits2 = [];
9107
+ if (hasEntry) edits2.push({ op: "remove", key: ENTRY_NAME });
9108
+ if (trimLegacy) edits2.push({ op: "remove", key: legacy });
9109
+ const removed = [];
9110
+ if (hasEntry) removed.push(`the "${ENTRY_NAME}" entry`);
9111
+ if (trimLegacy) removed.push(`the legacy "${legacy}" entry`);
9112
+ if (args.dryRun) {
9113
+ for (const what of removed) log2(`Would also remove ${what} from ${named}.`);
9114
+ touched.push(where);
9115
+ continue;
9116
+ }
9117
+ try {
9118
+ await atomicWriteFile(where, terminateWithNewline(applyClientConfigEdits(view, edits2, site)));
9119
+ for (const what of removed) log2(`Removed ${what} from ${named}.`);
9120
+ touched.push(where);
9121
+ } catch (e) {
9122
+ err(
9123
+ `yaw-mcp ${cmd}: warning -- failed to remove ${removed.join(" and ")} from ${named} (${e.message}); left unchanged. Remove ${removed.length > 1 ? "them" : "it"} by hand.`
9124
+ );
9125
+ }
9126
+ continue;
9127
+ }
9128
+ const previousEnv = view.carryableEnv();
9129
+ const carryableEnv = compose.base.env === void 0 && previousEnv && Object.keys(previousEnv).length > 0 ? previousEnv : void 0;
9130
+ const entry = composeEntry({
9131
+ base: compose.base,
9132
+ transform: args.transform,
9133
+ os: compose.os,
9134
+ purpose: "broker",
9135
+ env: compose.force ? void 0 : carryableEnv,
9136
+ carried: compose.force ? {} : view.carried()
9137
+ });
9138
+ const stored = view.normalized();
9139
+ if (hasEntry && deepEqualJson(stored, entry) && !trimLegacy) {
9140
+ log2(`The "${ENTRY_NAME}" entry in ${named} is already correct.`);
9141
+ continue;
9142
+ }
9143
+ if (hasEntry && !deepEqualJson(stored, entry) && !args.authorised) {
9144
+ err(
9145
+ `yaw-mcp ${cmd}: warning -- ${named} already has a differing "${ENTRY_NAME}" entry; left untouched. Re-run with --repair to bring every copy up to date, or --force to overwrite them.`
9146
+ );
9147
+ continue;
9148
+ }
9149
+ const edits = [];
9150
+ if (read.kind === "blocked") {
9151
+ if (!read.reparable) {
9152
+ err(
9153
+ `yaw-mcp ${cmd}: warning -- "${read.path.join(".")}" in ${named} is ${read.shape}, not an object; left unchanged. Fix it by hand.`
9154
+ );
9155
+ continue;
9156
+ }
9157
+ edits.push({ op: "repair", path: read.path });
9158
+ }
9159
+ edits.push({ op: "upsert", key: ENTRY_NAME, entry });
9160
+ if (trimLegacy) edits.push({ op: "remove", key: legacy });
9161
+ let next;
9162
+ try {
9163
+ next = terminateWithNewline(applyClientConfigEdits(view, edits, site));
9164
+ } catch (e) {
9165
+ err(
9166
+ `yaw-mcp ${cmd}: warning -- ${args.dryRun ? `${named} cannot be written` : `failed to write ${named}`} (${e.message}); left unchanged. That copy of the client will not see yaw-mcp.`
9167
+ );
9168
+ continue;
9169
+ }
9170
+ if (args.dryRun) {
9171
+ log2(`Would also write the "${ENTRY_NAME}" entry to ${named}.`);
9172
+ touched.push(where);
9173
+ continue;
9174
+ }
9175
+ try {
9176
+ await atomicWriteFile(where, next);
9177
+ log2(`Wrote ${named}`);
9178
+ touched.push(where);
9179
+ } catch (e) {
9180
+ err(
9181
+ `yaw-mcp ${cmd}: warning -- failed to write ${named} (${e.message}); left unchanged. That copy of the client will not see yaw-mcp.`
9182
+ );
9183
+ }
9091
9184
  }
9092
- return result;
9093
- }
9094
- function mergeClientConfig(existing, containerPath, entry, entryName = ENTRY_NAME) {
9095
- if (containerPath.length === 0) throw new Error("mergeClientConfig: containerPath cannot be empty");
9096
- const out = { ...existing };
9097
- let parent = out;
9098
- for (let i = 0; i < containerPath.length - 1; i++) {
9099
- const key = containerPath[i];
9100
- const child = parent[key];
9101
- const cloned = typeof child === "object" && child !== null && !Array.isArray(child) ? { ...child } : {};
9102
- parent[key] = cloned;
9103
- parent = cloned;
9104
- }
9105
- const leafKey = containerPath[containerPath.length - 1];
9106
- const prev = parent[leafKey];
9107
- const container = typeof prev === "object" && prev !== null && !Array.isArray(prev) ? { ...prev } : {};
9108
- container[entryName] = entry;
9109
- parent[leafKey] = container;
9110
- return out;
9185
+ return touched;
9111
9186
  }
9112
9187
  function looksLikeFlag(value) {
9113
9188
  return value.startsWith("-");
@@ -9232,14 +9307,15 @@ ${USAGE}`
9232
9307
  if (positional.length !== 1)
9233
9308
  return { ok: false, error: `Expected exactly one client argument, got ${positional.length}.
9234
9309
  ${USAGE}` };
9235
- const clientId = positional[0];
9236
- if (!INSTALL_TARGETS.some((t) => t.clientId === clientId)) {
9310
+ const resolved = resolveClientArg("install", positional[0]);
9311
+ if (!resolved) {
9237
9312
  return {
9238
9313
  ok: false,
9239
- error: `Unknown client: ${clientId}. Choose: ${INSTALL_TARGETS.map((t) => t.clientId).join(", ")}`
9314
+ error: `Unknown client: ${positional[0]}. Choose: ${clientChoices("install").join(", ")}`
9240
9315
  };
9241
9316
  }
9242
- opts.clientId = clientId;
9317
+ opts.clientId = resolved.clientId;
9318
+ if (resolved.scope !== void 0 && opts.scope === void 0) opts.scope = resolved.scope;
9243
9319
  return { ok: true, options: opts };
9244
9320
  }
9245
9321
  async function runInstallList(opts, log2, messages) {
@@ -9251,6 +9327,10 @@ async function runInstallList(opts, log2, messages) {
9251
9327
  os,
9252
9328
  cwd,
9253
9329
  claudeConfigDir: opts.claudeConfigDir,
9330
+ // `--list` must resolve each row's path the way INSTALL does, or it
9331
+ // reports on a file install never writes: an env-redirected client would
9332
+ // show "not installed" beside an entry sitting at the redirected path.
9333
+ clientEnv: opts.clientEnv,
9254
9334
  appData: resolveAppData(opts)
9255
9335
  });
9256
9336
  const rows = probes.map((p) => ({
@@ -9259,7 +9339,7 @@ async function runInstallList(opts, log2, messages) {
9259
9339
  path: displayPath(p.path, home, os),
9260
9340
  status: statusFor(p)
9261
9341
  }));
9262
- const installed = probes.filter((p) => p.hasMcpEntry).length;
9342
+ const installed = probes.filter((p) => p.hasMcpEntry && p.unloadable === null).length;
9263
9343
  const available = probes.filter((p) => !p.unavailable).length;
9264
9344
  log2(`${installed}/${available} client scopes have yaw-mcp configured on ${os}.`);
9265
9345
  log2("");
@@ -9277,40 +9357,45 @@ async function runInstallList(opts, log2, messages) {
9277
9357
  );
9278
9358
  }
9279
9359
  log2("");
9360
+ for (const p of probes) {
9361
+ if (!p.entryProjectKey) continue;
9362
+ const label = INSTALL_TARGETS.find((t) => t.clientId === p.clientId)?.label ?? p.clientId;
9363
+ log2(
9364
+ `Note: the ${label} (${p.scope}) entry is under projects[${JSON.stringify(p.entryProjectKey)}] in ${displayPath(p.path, home, os)} -- the same directory spelled with the other drive-letter case. Only a Claude Code whose cwd is spelled that way reads it. \`yaw-mcp install ${p.clientId} --scope ${p.scope}\` writes the canonical key; \`yaw-mcp uninstall ${p.clientId} --scope ${p.scope}\` removes both spellings.`
9365
+ );
9366
+ log2("");
9367
+ }
9280
9368
  log2("Install into a specific client: `yaw-mcp install <client> [--scope user|project|local]`");
9281
- log2("Install into every available client (user scope where supported): `yaw-mcp install --all`");
9369
+ log2("Install into every supported client (user scope where supported): `yaw-mcp install --all`");
9282
9370
  return { written: [], wouldWrite: [], messages, exitCode: 0 };
9283
9371
  }
9284
9372
  function statusFor(p) {
9285
- if (p.unavailable) return "unavailable";
9373
+ if (p.unavailable) return p.unavailableReason !== void 0 ? "not supported yet" : "unavailable";
9286
9374
  if (p.malformed) return "malformed";
9287
9375
  if (p.unreadable) return `unreadable: ${p.unreadable}`;
9288
- if (p.hasMcpEntry) return "installed";
9289
- if (p.hasLegacyEntry) return `legacy: ${p.legacyEntryName ?? "unknown"}`;
9290
- if (p.exists) return "other-entries";
9291
- return "not installed";
9376
+ if (p.unloadable) return "not loading (comments or trailing commas)";
9377
+ const keySuffix = p.entryProjectKey ? " (other drive case)" : "";
9378
+ if (p.hasMcpEntry) return `installed${keySuffix}`;
9379
+ if (p.hasLegacyEntry) return `legacy: ${p.legacyEntryName ?? "unknown"}${keySuffix}`;
9380
+ if (!p.exists) return "not installed";
9381
+ return p.containerEntries > 0 ? "other-entries" : "no-entries";
9292
9382
  }
9293
9383
  function displayPath(abs, home, os) {
9294
- if (abs === "(n/a)") return abs;
9295
- const afterHome = abs.slice(home.length, home.length + 1);
9296
- const endsAtBoundary = afterHome === "" || afterHome === "/" || afterHome === "\\" || /[\\/]$/.test(home);
9297
- if (home && abs.startsWith(home) && endsAtBoundary) {
9298
- const sep = os === "windows" ? "\\" : "/";
9299
- const hostSep = process.platform === "win32" ? /[\\/]/g : /\//g;
9300
- const tail = abs.slice(home.length).replace(/^[\\/]/, "").replace(hostSep, sep);
9301
- return `~${sep}${tail}`;
9302
- }
9303
- return abs;
9384
+ return tildePath(abs, home, os === "windows" ? "\\" : "/");
9304
9385
  }
9305
9386
  async function runInstallAll(opts, log2, err, messages) {
9306
9387
  const os = opts.os ?? CURRENT_OS;
9307
- const targets = INSTALL_TARGETS.filter((t) => t.availableOn.includes(os));
9388
+ const targets = (opts.targets ?? INSTALL_TARGETS).filter((t) => t.availableOn.includes(os));
9308
9389
  if (targets.length === 0) {
9309
9390
  err(`yaw-mcp install --all: no installable clients on ${os}.`);
9310
9391
  return { written: [], wouldWrite: [], messages, exitCode: 1 };
9311
9392
  }
9312
9393
  const plans = [];
9313
9394
  const skipped = [];
9395
+ for (const t of INSTALL_TARGETS) {
9396
+ const why = t.notConfigurableOn?.[os];
9397
+ if (why !== void 0) skipped.push({ clientId: t.clientId, reason: why });
9398
+ }
9314
9399
  for (const t of targets) {
9315
9400
  const userScope = t.scopes.find((s) => s.scope === "user");
9316
9401
  if (userScope) {
@@ -9340,26 +9425,9 @@ async function runInstallAll(opts, log2, err, messages) {
9340
9425
  const aggregateWouldWrite = [];
9341
9426
  let failed = 0;
9342
9427
  let succeeded = 0;
9343
- const collisionClients = [];
9344
- const realStderr = opts.io?.stderr ?? process.stderr;
9345
- const isCollisionRefusal = (s) => s.includes(`already has a "${ENTRY_NAME}" entry and stdin is not a TTY`);
9428
+ const refusedClients = [];
9346
9429
  for (const plan of plans) {
9347
9430
  log2(`-- ${plan.clientId} (${plan.scope}) --`);
9348
- let sawCollision = false;
9349
- const subStderr = new Writable({
9350
- write(chunk, _enc, cb) {
9351
- const text = chunk.toString();
9352
- if (isCollisionRefusal(text)) sawCollision = true;
9353
- else realStderr.write(text);
9354
- cb();
9355
- }
9356
- });
9357
- const baseIo = opts.io ?? {
9358
- stdin: process.stdin,
9359
- stdout: process.stdout,
9360
- stderr: process.stderr,
9361
- isTTY: Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY)
9362
- };
9363
9431
  const result = await runInstall({
9364
9432
  ...opts,
9365
9433
  listOnly: false,
@@ -9372,6 +9440,8 @@ async function runInstallAll(opts, log2, err, messages) {
9372
9440
  // Same consolidation, one line down: printed once after the loop.
9373
9441
  suppressOamAbsentNote: true,
9374
9442
  suppressBundlesNote: true,
9443
+ // And the collision refusal's shared half, printed once after the loop.
9444
+ deferCollisionHint: true,
9375
9445
  clientId: plan.clientId,
9376
9446
  scope: plan.scope,
9377
9447
  // Only the plans whose scope actually resolves a path from --project-dir
@@ -9379,14 +9449,13 @@ async function runInstallAll(opts, log2, err, messages) {
9379
9449
  // passing the parent's copy to every client would fail each user-scope
9380
9450
  // one the moment --project-dir was passed to pull the project-only
9381
9451
  // client (vscode) into the run.
9382
- projectDir: plan.usesProjectDir ? opts.projectDir : void 0,
9383
- io: { ...baseIo, stderr: subStderr }
9452
+ projectDir: plan.usesProjectDir ? opts.projectDir : void 0
9384
9453
  });
9385
- if (sawCollision) collisionClients.push(plan.clientId);
9386
- aggregateWritten.push(...result.written);
9387
- aggregateWouldWrite.push(...result.wouldWrite);
9388
- messages.push(...result.messages.filter((m) => !isCollisionRefusal(m)));
9454
+ for (const path6 of result.written) if (!aggregateWritten.includes(path6)) aggregateWritten.push(path6);
9455
+ for (const path6 of result.wouldWrite) if (!aggregateWouldWrite.includes(path6)) aggregateWouldWrite.push(path6);
9456
+ messages.push(...result.messages);
9389
9457
  if (result.exitCode === 0) succeeded += 1;
9458
+ else if (result.collisionRefused) refusedClients.push(plan.clientId);
9390
9459
  else failed += 1;
9391
9460
  log2("");
9392
9461
  }
@@ -9398,43 +9467,55 @@ async function runInstallAll(opts, log2, err, messages) {
9398
9467
  ).catch(() => null);
9399
9468
  logInstallTail(log2, err, { names: [], where: "", clientLabel: "" }, bundles);
9400
9469
  }
9401
- if (collisionClients.length > 0) {
9470
+ const refused = refusedClients.length;
9471
+ const them = refused === 1 ? "it" : "them";
9472
+ const theirEnv = refused === 1 ? "in its env" : "in each entry's env";
9473
+ if (refused > 0) {
9402
9474
  err(
9403
- `yaw-mcp install --all: ${collisionClients.length} client${collisionClients.length === 1 ? "" : "s"} already have a "${ENTRY_NAME}" entry (${collisionClients.join(", ")}) and stdin is not a TTY.
9404
- Re-run \`yaw-mcp install --all --force\` to overwrite them, or \`--skip\` to leave them untouched.`
9475
+ `yaw-mcp install --all: ${refused} client${refused === 1 ? " already has" : "s already have"} a differing "${ENTRY_NAME}" entry (${refusedClients.join(", ")}) and stdin is not a TTY.
9476
+ Re-run \`yaw-mcp install --all --repair\` to bring ${them} up to date (keeping the string values ${theirEnv}), \`--force\` to overwrite ${them} outright (dropping all of it), \`--skip\` to leave ${them} untouched, or \`--dry-run\` to preview.`
9405
9477
  );
9406
9478
  }
9407
9479
  const totalPlanned = plans.length;
9408
- if (failed === 0) {
9409
- log2(`Done: ${succeeded}/${totalPlanned} clients installed successfully.`);
9410
- return {
9411
- written: aggregateWritten,
9412
- wouldWrite: aggregateWouldWrite,
9413
- messages,
9414
- exitCode: 0
9415
- };
9416
- }
9417
- err(`${failed}/${totalPlanned} client install${failed === 1 ? "" : "s"} failed. ${succeeded} succeeded.`);
9480
+ const plural = (n) => n === 1 ? "" : "s";
9481
+ if (failed === 0 && refused === 0) {
9482
+ log2(
9483
+ opts.dryRun ? `Dry run: ${succeeded}/${totalPlanned} client${plural(totalPlanned)} would be installed; nothing written.` : `Done: ${succeeded}/${totalPlanned} client${plural(totalPlanned)} installed successfully.`
9484
+ );
9485
+ return { written: aggregateWritten, wouldWrite: aggregateWouldWrite, messages, exitCode: 0 };
9486
+ }
9487
+ const noun = opts.dryRun ? "preview" : "install";
9488
+ const whatFailed = `${failed}/${totalPlanned} client ${noun}${plural(failed)} failed`;
9489
+ const whatRefused = `${refused === 1 ? "was" : "were"} refused (see the flags above)`;
9490
+ const notDone = failed === 0 ? `${refused}/${totalPlanned} client ${noun}${plural(refused)} ${whatRefused}.` : refused === 0 ? `${whatFailed}.` : `${whatFailed} and ${refused} ${whatRefused}.`;
9491
+ const tail = opts.dryRun ? `${succeeded} would be installed; nothing written.` : `${succeeded} succeeded.`;
9492
+ err(`${opts.dryRun ? "Dry run: " : ""}${notDone} ${tail}`);
9418
9493
  return {
9419
9494
  written: aggregateWritten,
9420
9495
  wouldWrite: aggregateWouldWrite,
9421
9496
  messages,
9422
- exitCode: 1
9497
+ exitCode: failed > 0 ? 1 : 2
9423
9498
  };
9424
9499
  }
9425
9500
  var INSTALL_USAGE = USAGE;
9501
+ function grantSharingLabels() {
9502
+ const labels = INSTALL_TARGETS.filter((t) => t.hooks?.permissionsPatch === "claude-code").map((t) => t.label);
9503
+ return labels.length <= 1 ? labels.join("") : `${labels.slice(0, -1).join(", ")} and ${labels[labels.length - 1]}`;
9504
+ }
9426
9505
  var UNINSTALL_USAGE = (
9427
- // Every client INSTALL_TARGETS carries, because that array is what the
9428
- // parser validates against -- uninstall has accepted windsurf and gemini-cli
9429
- // since they were added to it, and a usage line naming only the first four
9430
- // reads as a refusal that never happens.
9431
- `Usage: yaw-mcp uninstall <${INSTALL_TARGETS.map((t) => t.clientId).join("|")}> [--scope user|project|local]
9506
+ // Every name the parser accepts, because `clientChoices` is what it
9507
+ // validates against -- uninstall has accepted windsurf and gemini-cli since
9508
+ // they were added to the table, and a usage line naming only the first four
9509
+ // reads as a refusal that never happens. Aliases ride along for the same
9510
+ // reason, at the end, after the real clients.
9511
+ `Usage: yaw-mcp uninstall <${clientChoices("uninstall").join("|")}> [--scope user|project|local]
9432
9512
  [--project-dir <path>] [--os macos|linux|windows]
9433
9513
  [--force | -y] [--keep-legacy] [--dry-run]
9434
9514
 
9435
- Removes the "${ENTRY_NAME}" entry from the client's config, and for Claude Code drops
9436
- ${CLAUDE_CODE_ALLOW_PATTERN} from permissions.allow. A pre-rename entry (${LEGACY_ENTRY_NAMES.join(", ")})
9437
- goes with it unless --keep-legacy is passed.
9515
+ Removes the "${ENTRY_NAME}" entry from the client's config, and for ${grantSharingLabels()} drops
9516
+ ${CLAUDE_CODE_ALLOW_PATTERN} from permissions.allow -- unless another of them still has its entry and
9517
+ reads the same settings.json, which keeps the grant and says so.
9518
+ A pre-rename entry (${LEGACY_ENTRY_NAMES.join(", ")}) goes with it unless --keep-legacy is passed.
9438
9519
 
9439
9520
  Nothing to remove is exit 0, not an error. Comments and every unrelated key in the
9440
9521
  file are preserved. Local servers in ~/.yaw-mcp/bundles.json are untouched --
@@ -9500,19 +9581,20 @@ ${UNINSTALL_USAGE}` };
9500
9581
  if (positional.length !== 1)
9501
9582
  return { ok: false, error: `Expected exactly one client argument, got ${positional.length}.
9502
9583
  ${UNINSTALL_USAGE}` };
9503
- const clientId = positional[0];
9504
- if (!INSTALL_TARGETS.some((t) => t.clientId === clientId)) {
9584
+ const resolved = resolveClientArg("uninstall", positional[0]);
9585
+ if (!resolved) {
9505
9586
  return {
9506
9587
  ok: false,
9507
- error: `Unknown client: ${clientId}. Choose: ${INSTALL_TARGETS.map((t) => t.clientId).join(", ")}`
9588
+ error: `Unknown client: ${positional[0]}. Choose: ${clientChoices("uninstall").join(", ")}`
9508
9589
  };
9509
9590
  }
9510
- opts.clientId = clientId;
9591
+ opts.clientId = resolved.clientId;
9592
+ if (resolved.scope !== void 0 && opts.scope === void 0) opts.scope = resolved.scope;
9511
9593
  return { ok: true, options: opts };
9512
9594
  }
9513
9595
  function renderEntryLaunch(entry) {
9514
9596
  if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
9515
- return `(${describeJsonShape(entry)})`;
9597
+ return `(${describeValueShape(entry)})`;
9516
9598
  }
9517
9599
  const e = entry;
9518
9600
  const command = typeof e.command === "string" ? e.command : "";
@@ -9538,6 +9620,107 @@ async function promptUninstall(question, io) {
9538
9620
  rl.close();
9539
9621
  }
9540
9622
  }
9623
+ function samePathKey(p) {
9624
+ const abs = resolve5(p);
9625
+ return process.platform === "win32" ? abs.toLowerCase() : abs;
9626
+ }
9627
+ function clientLoadsEntry(view) {
9628
+ return view.read.kind === "ok" && view.read.unloadable === null && view.entry() !== void 0;
9629
+ }
9630
+ function launchesViaNpx(entry) {
9631
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) return false;
9632
+ const { command, args } = entry;
9633
+ if (typeof command !== "string") return false;
9634
+ if (nodeLaunchKind(command) === "npx") return true;
9635
+ const launcher = (command.split(/[\\/]/).pop() ?? command).toLowerCase();
9636
+ return (launcher === "cmd" || launcher === "cmd.exe") && Array.isArray(args) && typeof args[0] === "string" && args[0].toLowerCase() === "/c" && typeof args[1] === "string" && nodeLaunchKind(args[1]) === "npx";
9637
+ }
9638
+ async function shadowedLocalLaunch(target, scope, where) {
9639
+ if (!target.hooks?.alsoReads) return null;
9640
+ let sites;
9641
+ try {
9642
+ sites = resolveAlsoReadSites({ clientId: target.clientId, scope, ...where });
9643
+ } catch {
9644
+ return null;
9645
+ }
9646
+ for (const site of sites) {
9647
+ const view = await readClientConfigFile(site, { transform: target.entry });
9648
+ if (clientLoadsEntry(view) && !launchesViaNpx(view.entry()?.value)) return site.resolved.absolute;
9649
+ }
9650
+ return null;
9651
+ }
9652
+ function configDirScopedGrantNote(args) {
9653
+ const cfg = args.where.claudeConfigDir;
9654
+ if (cfg === void 0 || cfg.length === 0) return null;
9655
+ if (samePathKey(dirname7(args.settingsPath)) !== samePathKey(cfg)) return null;
9656
+ const homeSettings = resolveClaudeCodeSettingsPath("user", { home: args.where.home });
9657
+ if (homeSettings === null || samePathKey(homeSettings) === samePathKey(args.settingsPath)) return null;
9658
+ let unredirected;
9659
+ try {
9660
+ unredirected = resolveInstallPath({
9661
+ clientId: args.target.clientId,
9662
+ scope: args.scope,
9663
+ ...args.where,
9664
+ claudeConfigDir: void 0,
9665
+ clientEnv: { ...args.where.clientEnv, claudeConfigDir: void 0 }
9666
+ }).absolute;
9667
+ } catch {
9668
+ return null;
9669
+ }
9670
+ if (samePathKey(unredirected) !== samePathKey(args.entryFile)) return null;
9671
+ const { label } = args.target;
9672
+ if (args.cmd === "install") {
9673
+ return `Note: the ${CLAUDE_CODE_ALLOW_PATTERN} grant ${label} reads ${args.dryRun ? "would go" : "is"} in ${args.settingsPath}, under CLAUDE_CONFIG_DIR, so it is scoped to that config dir: a ${label} started without it reads ${homeSettings} instead, while ${args.entryFile} does not follow the variable.`;
9674
+ }
9675
+ return `Note: this run looks for the ${CLAUDE_CODE_ALLOW_PATTERN} grant only in ${args.settingsPath}, under CLAUDE_CONFIG_DIR; ${homeSettings}, which a ${label} started without that variable reads, is left as it is.`;
9676
+ }
9677
+ async function sharedGrantHolder(args) {
9678
+ const settingsKey = samePathKey(args.settingsPath);
9679
+ const onlyKey = args.only === void 0 ? null : samePathKey(args.only);
9680
+ const isSelfSite = (site) => args.self.sites.some(
9681
+ (own) => samePathKey(own.resolved.absolute) === samePathKey(site.resolved.absolute) && JSON.stringify(own.resolved.containerPath) === JSON.stringify(site.resolved.containerPath)
9682
+ );
9683
+ for (const peer of INSTALL_TARGETS) {
9684
+ if (peer.hooks?.permissionsPatch !== "claude-code") continue;
9685
+ if (!peer.availableOn.includes(args.os)) continue;
9686
+ for (const spec of peer.scopes) {
9687
+ const isSelf = peer.clientId === args.self.clientId && spec.scope === args.self.scope;
9688
+ const peerProjectDir = spec.requiresProjectDir ? args.projectDir ?? args.home : void 0;
9689
+ const peerSettings = resolveClaudeCodeSettingsPath(spec.scope, {
9690
+ home: args.home,
9691
+ projectDir: peerProjectDir,
9692
+ claudeConfigDir: args.claudeConfigDir
9693
+ });
9694
+ if (peerSettings === null || samePathKey(peerSettings) !== settingsKey) continue;
9695
+ const where = {
9696
+ clientId: peer.clientId,
9697
+ scope: spec.scope,
9698
+ os: args.os,
9699
+ home: args.home,
9700
+ appData: args.appData,
9701
+ projectDir: peerProjectDir,
9702
+ claudeConfigDir: args.claudeConfigDir,
9703
+ clientEnv: args.clientEnv
9704
+ };
9705
+ let candidates;
9706
+ try {
9707
+ candidates = [...isSelf ? [] : selectSites(resolveInstallSites(where)), ...resolveAlsoReadSites(where)];
9708
+ } catch {
9709
+ continue;
9710
+ }
9711
+ for (const site of candidates) {
9712
+ if (isSelfSite(site)) continue;
9713
+ if (onlyKey !== null && samePathKey(site.resolved.absolute) !== onlyKey) continue;
9714
+ const view = await readClientConfigFile(site, { transform: peer.entry });
9715
+ const unreadable = view.read.kind === "unreadable";
9716
+ if (unreadable || clientLoadsEntry(view)) {
9717
+ return { label: peer.label, scope: spec.scope, file: site.resolved.absolute, unreadable };
9718
+ }
9719
+ }
9720
+ }
9721
+ }
9722
+ return null;
9723
+ }
9541
9724
  async function runUninstall(opts) {
9542
9725
  const stdout = opts.io?.stdout ?? process.stdout;
9543
9726
  const stderr = opts.io?.stderr ?? process.stderr;
@@ -9557,94 +9740,201 @@ async function runUninstall(opts) {
9557
9740
  ${UNINSTALL_USAGE}`);
9558
9741
  return { written: [], wouldWrite: [], messages, exitCode: 2 };
9559
9742
  }
9560
- const site = resolveInstallSite("uninstall", opts, err);
9561
- if (!site) return { written: [], wouldWrite: [], messages, exitCode: 2 };
9562
- const { target, scope, projectDir, resolved } = site;
9743
+ const plan = resolveInstallSite("uninstall", opts, err);
9744
+ if (!plan) return { written: [], wouldWrite: [], messages, exitCode: 2 };
9745
+ const { target, os, scope, projectDir, resolved } = plan;
9563
9746
  log2(`Target: ${target.label} (${scope})`);
9564
9747
  log2(`File: ${resolved.absolute}`);
9565
9748
  const containerPath = resolved.containerPath;
9566
- let existing = {};
9567
- let rawClient = null;
9568
- let storedEntry;
9569
- let hasEntry = false;
9570
- let legacyEntry = null;
9749
+ const selectedSites = selectSites(plan.sites);
9750
+ const site = selectedSites[0];
9751
+ const extraSites = selectedSites.slice(1);
9752
+ const sites = [];
9571
9753
  const fingerprintBefore = await fileFingerprint(resolved.absolute);
9572
- if (fingerprintBefore !== null) {
9573
- let raw;
9574
- try {
9575
- raw = await readFile11(resolved.absolute, "utf8");
9576
- } catch (e) {
9577
- err(describeUnreadableConfig("uninstall", resolved.absolute, e));
9578
- return { written: [], wouldWrite: [], messages, exitCode: 1 };
9579
- }
9580
- if (raw.trim().length > 0) {
9581
- try {
9582
- const parsed = parseJsonc(raw);
9583
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
9584
- err(
9585
- `yaw-mcp uninstall: ${resolved.absolute} is not a JSON object -- refusing to edit. Remove the "${ENTRY_NAME}" entry by hand.`
9586
- );
9587
- return { written: [], wouldWrite: [], messages, exitCode: 1 };
9588
- }
9589
- existing = parsed;
9590
- rawClient = raw;
9591
- } catch (e) {
9592
- err(
9593
- `yaw-mcp uninstall: ${resolved.absolute} is not valid JSON (${e.message}). Refusing to edit. Fix the file and re-run.`
9594
- );
9595
- return { written: [], wouldWrite: [], messages, exitCode: 1 };
9596
- }
9597
- }
9598
- const container = readNested(existing, containerPath);
9599
- if (typeof container === "object" && container !== null && !Array.isArray(container)) {
9600
- const c = container;
9601
- hasEntry = ENTRY_NAME in c;
9602
- storedEntry = c[ENTRY_NAME];
9603
- legacyEntry = findLegacyEntry(c);
9604
- }
9754
+ const view = await readClientConfigFile(site, { transform: target.entry });
9755
+ const read = view.read;
9756
+ if (read.kind === "unreadable") {
9757
+ err(describeUnreadableConfig("uninstall", resolved.absolute, { code: read.code, message: read.message }));
9758
+ return { written: [], wouldWrite: [], messages, exitCode: 1 };
9605
9759
  }
9606
- const trimLegacy = legacyEntry !== null && !opts.keepLegacy;
9760
+ if (read.kind === "malformed") {
9761
+ err(
9762
+ read.reason === "root" ? `yaw-mcp uninstall: ${resolved.absolute} is not a ${read.syntax} object -- refusing to edit. Remove the "${ENTRY_NAME}" entry by hand.` : `yaw-mcp uninstall: ${resolved.absolute} is not valid ${read.syntax} (${read.detail}). Refusing to edit. Fix the file and re-run.`
9763
+ );
9764
+ return { written: [], wouldWrite: [], messages, exitCode: 1 };
9765
+ }
9766
+ const variantPaths = claudeCodeContainerPathVariants(
9767
+ containerPath,
9768
+ (prefix) => containerKeysAt(view.raw, site, prefix)
9769
+ );
9770
+ for (let i = 0; i < variantPaths.length; i++) {
9771
+ const variantPath = variantPaths[i];
9772
+ const sibling = i > 0;
9773
+ const at = sibling ? classifyClientConfig(view.raw, siteAt(site, variantPath), { transform: target.entry }) : view;
9774
+ if (at.read.kind !== "ok" || !at.read.containerPresent) continue;
9775
+ const entryHere = at.entry() !== void 0;
9776
+ const legacyHere = at.legacyKey();
9777
+ if (sibling && !entryHere && legacyHere === null) continue;
9778
+ sites.push({
9779
+ containerPath: variantPath,
9780
+ projectKey: containerPath[0] === "projects" ? variantPath[1] : null,
9781
+ sibling,
9782
+ hasEntry: entryHere,
9783
+ storedEntry: at.entry()?.value,
9784
+ legacyEntry: legacyHere
9785
+ });
9786
+ }
9787
+ const trimsLegacy = (s) => s.legacyEntry !== null && !opts.keepLegacy;
9788
+ const where = (s) => s.sibling ? ` under projects[${JSON.stringify(s.projectKey)}]` : "";
9789
+ const removals = sites.filter((s) => s.hasEntry || trimsLegacy(s));
9607
9790
  const home = opts.home ?? homedir13();
9608
- const settingsPatch = opts.clientId === "claude-code" ? await prepareClaudeCodeSettingsPatch({
9791
+ const grant = await prepareGrantPatches({
9792
+ target,
9609
9793
  scope,
9610
9794
  home,
9611
9795
  projectDir,
9612
9796
  claudeConfigDir: opts.claudeConfigDir,
9797
+ yawMode: opts.clientEnv?.yawMode,
9613
9798
  op: "remove"
9614
- }) : null;
9615
- if (settingsPatch?.malformed) {
9799
+ });
9800
+ for (const settingsPatch of grant.patches) {
9801
+ if (!settingsPatch.malformed) continue;
9616
9802
  err(
9617
9803
  `yaw-mcp uninstall: warning -- could not patch ${settingsPatch.path} (${settingsPatch.malformedReason}); left unchanged. Remove "${CLAUDE_CODE_ALLOW_PATTERN}" from permissions.allow by hand.`
9618
9804
  );
9619
9805
  }
9620
- if (!hasEntry && !trimLegacy && !settingsPatch?.changed) {
9621
- log2(`
9622
- Nothing to do: ${target.label} (${scope}) has no yaw-mcp entry.`);
9806
+ const rowArgs = {
9807
+ os,
9808
+ home,
9809
+ appData: resolveAppDataDir({ appData: opts.appData, home: opts.home }),
9810
+ projectDir,
9811
+ claudeConfigDir: opts.claudeConfigDir,
9812
+ clientEnv: opts.clientEnv
9813
+ };
9814
+ const primaryPatch = grant.patches.find((p) => !p.yawHome) ?? null;
9815
+ const scopedGrantNote = grant.overlay !== null || primaryPatch === null ? null : configDirScopedGrantNote({
9816
+ cmd: "uninstall",
9817
+ dryRun: opts.dryRun === true,
9818
+ target,
9819
+ scope,
9820
+ where: rowArgs,
9821
+ entryFile: resolved.absolute,
9822
+ settingsPath: primaryPatch.path
9823
+ });
9824
+ const settingsPatches = [];
9825
+ for (const settingsPatch of grant.patches) {
9826
+ if (settingsPatch.changed) {
9827
+ const askUnder = [];
9828
+ if (settingsPatch.yawHome) {
9829
+ askUnder.push({
9830
+ ...rowArgs,
9831
+ settingsPath: settingsPatch.path,
9832
+ claudeConfigDir: void 0,
9833
+ clientEnv: { ...opts.clientEnv, claudeConfigDir: void 0 },
9834
+ carriedHome: null
9835
+ });
9836
+ if (primaryPatch !== null && opts.claudeConfigDir !== void 0) {
9837
+ askUnder.push({
9838
+ ...rowArgs,
9839
+ settingsPath: primaryPatch.path,
9840
+ carriedHome: join12(opts.claudeConfigDir, ".claude.json")
9841
+ });
9842
+ }
9843
+ } else {
9844
+ askUnder.push({
9845
+ ...rowArgs,
9846
+ settingsPath: settingsPatch.path,
9847
+ claudeConfigDir: settingsPatch.claudeConfigDir,
9848
+ carriedHome: null
9849
+ });
9850
+ }
9851
+ let holder = null;
9852
+ let carried = false;
9853
+ for (const { carriedHome, ...under } of askUnder) {
9854
+ holder = await sharedGrantHolder({
9855
+ self: { clientId: target.clientId, scope, sites: selectedSites },
9856
+ ...under,
9857
+ only: carriedHome ?? void 0
9858
+ });
9859
+ carried = carriedHome !== null;
9860
+ if (holder !== null) break;
9861
+ }
9862
+ if (holder !== null) {
9863
+ log2(
9864
+ holder.unreadable ? `Keeping ${CLAUDE_CODE_ALLOW_PATTERN} in ${settingsPatch.path}: could not read ${holder.file} to tell whether ${holder.label} (${holder.scope}) still uses it.` : carried ? `Keeping ${CLAUDE_CODE_ALLOW_PATTERN} in ${settingsPatch.path}: ${holder.label} (${holder.scope}) still launches yaw-mcp from ${holder.file}, which Yaw carries home when the pane closes.` : `Keeping ${CLAUDE_CODE_ALLOW_PATTERN} in ${settingsPatch.path}: ${holder.label} (${holder.scope}) still launches yaw-mcp from ${holder.file} and reads that grant.`
9865
+ );
9866
+ continue;
9867
+ }
9868
+ }
9869
+ settingsPatches.push(settingsPatch);
9870
+ }
9871
+ if (scopedGrantNote !== null) log2(scopedGrantNote);
9872
+ const extraPreview = [];
9873
+ const extraWouldRemove = await applyToExtraSites({
9874
+ cmd: "uninstall",
9875
+ sites: extraSites,
9876
+ transform: target.entry,
9877
+ compose: void 0,
9878
+ keepLegacy: opts.keepLegacy === true,
9879
+ authorised: true,
9880
+ dryRun: true,
9881
+ log: (line) => extraPreview.push({ stream: "log", line }),
9882
+ err: (line) => extraPreview.push({ stream: "err", line })
9883
+ });
9884
+ const flushExtraPreview = (warnings) => {
9885
+ for (const { stream, line } of extraPreview) {
9886
+ if (stream === "err" && !warnings) continue;
9887
+ (stream === "log" ? log2 : err)(line);
9888
+ }
9889
+ };
9890
+ if (removals.length === 0 && extraWouldRemove.length === 0 && !settingsPatches.some((p) => p.changed)) {
9891
+ flushExtraPreview(true);
9892
+ const kept = sites.filter((s) => s.legacyEntry !== null).map((s) => `"${s.legacyEntry}"${where(s)}`);
9893
+ log2(
9894
+ kept.length > 0 ? `
9895
+ Nothing to do: ${target.label} (${scope}) has no "${ENTRY_NAME}" entry, and the legacy ${kept.join(" and ")} entr${kept.length === 1 ? "y" : "ies"} you asked to keep (--keep-legacy) still launch yaw-mcp.` : `
9896
+ Nothing to do: ${target.label} (${scope}) has no yaw-mcp entry.`
9897
+ );
9623
9898
  return { written: [], wouldWrite: [], messages, exitCode: 0 };
9624
9899
  }
9625
9900
  const preview = [];
9626
- if (hasEntry) {
9627
- preview.push(`entry: "${ENTRY_NAME}"`);
9628
- preview.push(`launch: ${renderEntryLaunch(storedEntry)}`);
9629
- const envKeys = entryEnvKeys(storedEntry);
9630
- if (envKeys.length > 0) preview.push(`env keys: ${envKeys.join(", ")} (values go with the entry)`);
9631
- }
9632
- if (trimLegacy) preview.push(`legacy: "${legacyEntry}" (also removed; --keep-legacy leaves it)`);
9633
- if (settingsPatch?.changed) preview.push(`grant: ${CLAUDE_CODE_ALLOW_PATTERN} from ${settingsPatch.path}`);
9901
+ for (const s of sites) {
9902
+ if (s.hasEntry) {
9903
+ preview.push(`entry: "${ENTRY_NAME}"${where(s)}`);
9904
+ preview.push(`launch: ${renderEntryLaunch(s.storedEntry)}`);
9905
+ const envKeys = entryEnvKeys(s.storedEntry);
9906
+ if (envKeys.length > 0) preview.push(`env keys: ${envKeys.join(", ")} (values go with the entry)`);
9907
+ }
9908
+ if (trimsLegacy(s)) {
9909
+ preview.push(`legacy: "${s.legacyEntry}"${where(s)} (also removed; --keep-legacy leaves it)`);
9910
+ }
9911
+ }
9912
+ for (const settingsPatch of settingsPatches) {
9913
+ if (settingsPatch.changed) preview.push(`grant: ${CLAUDE_CODE_ALLOW_PATTERN} from ${settingsPatch.path}`);
9914
+ }
9634
9915
  if (opts.dryRun) {
9635
9916
  log2(`
9636
9917
  --- dry run: would remove the following (the rest of each file is left as-is) ---`);
9637
9918
  for (const line of preview) log2(` ${line}`);
9919
+ flushExtraPreview(true);
9638
9920
  const wouldWrite = [];
9639
- if (hasEntry || trimLegacy) wouldWrite.push(resolved.absolute);
9640
- if (settingsPatch?.changed) wouldWrite.push(settingsPatch.path);
9921
+ if (removals.length > 0) wouldWrite.push(resolved.absolute);
9922
+ wouldWrite.push(...extraWouldRemove);
9923
+ for (const settingsPatch of settingsPatches) {
9924
+ if (settingsPatch.changed) wouldWrite.push(settingsPatch.path);
9925
+ }
9641
9926
  return { written: [], wouldWrite, messages, exitCode: 0 };
9642
9927
  }
9643
9928
  if (!opts.force) {
9644
- log2(`
9929
+ if (preview.length > 0) {
9930
+ log2(`
9645
9931
  Remove from ${resolved.absolute}:`);
9646
- log2("");
9647
- for (const line of preview) log2(` ${line}`);
9932
+ log2("");
9933
+ for (const line of preview) log2(` ${line}`);
9934
+ } else {
9935
+ log2("");
9936
+ }
9937
+ flushExtraPreview(false);
9648
9938
  log2("");
9649
9939
  const interactive = opts.promptAnswer !== void 0 || (opts.io?.isTTY ?? (Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY)));
9650
9940
  if (!interactive) {
@@ -9665,13 +9955,17 @@ Nothing to do: ${target.label} (${scope}) has no yaw-mcp entry.`);
9665
9955
  }
9666
9956
  }
9667
9957
  let clientJson = null;
9668
- if (rawClient !== null && (hasEntry || trimLegacy)) {
9958
+ if (view.raw !== null && removals.length > 0) {
9669
9959
  try {
9670
- let next = rawClient;
9671
- if (hasEntry) next = removeJsoncEntry(next, containerPath, ENTRY_NAME);
9672
- if (trimLegacy) next = removeJsoncEntry(next, containerPath, legacyEntry);
9673
- clientJson = next.endsWith("\n") ? next : `${next}
9674
- `;
9960
+ let next = view.raw;
9961
+ for (const s of removals) {
9962
+ const edits = [];
9963
+ if (s.hasEntry) edits.push({ op: "remove", key: ENTRY_NAME });
9964
+ if (trimsLegacy(s)) edits.push({ op: "remove", key: s.legacyEntry });
9965
+ const at = classifyClientConfig(next, siteAt(site, s.containerPath), { transform: target.entry });
9966
+ next = applyClientConfigEdits(at, edits, site);
9967
+ }
9968
+ clientJson = terminateWithNewline(next);
9675
9969
  } catch (e) {
9676
9970
  err(
9677
9971
  `yaw-mcp uninstall: failed to remove the "${ENTRY_NAME}" entry from ${resolved.absolute} (${e.message}). Refusing to overwrite.`
@@ -9695,10 +9989,26 @@ Nothing to do: ${target.label} (${scope}) has no yaw-mcp entry.`);
9695
9989
  }
9696
9990
  log2(`Wrote ${resolved.absolute}`);
9697
9991
  written.push(resolved.absolute);
9698
- if (hasEntry) log2(`Removed the "${ENTRY_NAME}" entry.`);
9699
- if (trimLegacy) log2(`Removed the legacy "${legacyEntry}" entry.`);
9700
- }
9701
- if (settingsPatch?.changed) {
9992
+ for (const s of removals) {
9993
+ if (s.hasEntry) log2(`Removed the "${ENTRY_NAME}" entry${where(s)}.`);
9994
+ if (trimsLegacy(s)) log2(`Removed the legacy "${s.legacyEntry}" entry${where(s)}.`);
9995
+ }
9996
+ }
9997
+ written.push(
9998
+ ...await applyToExtraSites({
9999
+ cmd: "uninstall",
10000
+ sites: extraSites,
10001
+ transform: target.entry,
10002
+ compose: void 0,
10003
+ keepLegacy: opts.keepLegacy === true,
10004
+ authorised: true,
10005
+ dryRun: false,
10006
+ log: log2,
10007
+ err
10008
+ })
10009
+ );
10010
+ for (const settingsPatch of settingsPatches) {
10011
+ if (!settingsPatch.changed) continue;
9702
10012
  if (!sameFingerprint(settingsPatch.fingerprint, await fileFingerprint(settingsPatch.path))) {
9703
10013
  err(
9704
10014
  `yaw-mcp uninstall: warning -- ${settingsPatch.path} changed while uninstall was running (another process wrote it); left unchanged. Remove "${CLAUDE_CODE_ALLOW_PATTERN}" from permissions.allow by hand.`
@@ -9715,12 +10025,24 @@ Nothing to do: ${target.label} (${scope}) has no yaw-mcp entry.`);
9715
10025
  }
9716
10026
  }
9717
10027
  }
9718
- log2(
9719
- `
9720
- Done: ${target.label} no longer launches yaw-mcp. Restart it to drop the server. Your servers in ~/.yaw-mcp/bundles.json are untouched -- \`yaw-mcp install ${target.clientId}\` wires it back.`
9721
- );
10028
+ const stillLaunching = sites.filter((s) => s.legacyEntry !== null && !trimsLegacy(s));
10029
+ if (stillLaunching.length > 0) {
10030
+ const kept = stillLaunching.map((s) => `"${s.legacyEntry}"${where(s)}`);
10031
+ log2(
10032
+ `
10033
+ ${target.label} still launches yaw-mcp through the legacy ${kept.join(" and ")} entr${kept.length === 1 ? "y" : "ies"} you asked to keep (--keep-legacy). Remove ${kept.length === 1 ? "it" : "them"} from ${resolved.absolute} to stop it. Your servers in ~/.yaw-mcp/bundles.json are untouched.`
10034
+ );
10035
+ return { written, wouldWrite: [], messages, exitCode: 0 };
10036
+ }
10037
+ log2(uninstallDoneLine(target, resolved.display));
9722
10038
  return { written, wouldWrite: [], messages, exitCode: 0 };
9723
10039
  }
10040
+ function uninstallDoneLine(target, display) {
10041
+ const note = target.uninstallNote;
10042
+ const head = note === void 0 ? `${target.label} no longer launches yaw-mcp.` : `${target.label} no longer launches yaw-mcp from ${display}.`;
10043
+ return `
10044
+ Done: ${head} ${reloadRemovalClause(target.reload, target.label)}${note === void 0 ? "" : ` ${note}`} Your servers in ~/.yaw-mcp/bundles.json are untouched -- \`yaw-mcp install ${target.clientId}\` wires it back.`;
10045
+ }
9724
10046
 
9725
10047
  // src/try-cmd.ts
9726
10048
  var USAGE_INDENT = " ".repeat(23);
@@ -9748,7 +10070,7 @@ var TRY_USAGE = `Usage: yaw-mcp try <slug> [flags]
9748
10070
  it on a timer -- once --ttl has elapsed it is removed by the next
9749
10071
  \`yaw-mcp doctor\` run. Run \`yaw-mcp try-cleanup <slug>\` to remove it now.
9750
10072
 
9751
- --client <name> ${wrapToUsageColumn(INSTALL_TARGETS.map((t) => t.clientId))}
10073
+ --client <name> ${wrapToUsageColumn(clientChoices("try"))}
9752
10074
  (default: auto-detect, prefers the first installed
9753
10075
  client in the order probed by \`yaw-mcp install --list\`)
9754
10076
  --ttl <duration> How long the trial lives before doctor GCs it
@@ -9799,13 +10121,14 @@ function parseTryArgs(argv) {
9799
10121
  switch (a) {
9800
10122
  case "--client": {
9801
10123
  const v = next();
9802
- if (!v || !INSTALL_TARGETS.some((t) => t.clientId === v)) {
10124
+ const resolved = v === void 0 ? null : resolveClientArg("try", v);
10125
+ if (!resolved) {
9803
10126
  return {
9804
10127
  ok: false,
9805
- error: `--client requires ${INSTALL_TARGETS.map((t) => t.clientId).join("|")}`
10128
+ error: `--client requires ${clientChoices("try").join("|")}`
9806
10129
  };
9807
10130
  }
9808
- opts.clientId = v;
10131
+ opts.clientId = resolved.clientId;
9809
10132
  break;
9810
10133
  }
9811
10134
  case "--ttl": {
@@ -9893,10 +10216,10 @@ function parseDurationMs(s) {
9893
10216
  return ms > MAX_TTL_MS ? null : ms;
9894
10217
  }
9895
10218
  function trialsDir(home = homedir14()) {
9896
- return join12(home, CONFIG_DIRNAME, TRIALS_DIRNAME);
10219
+ return join13(home, CONFIG_DIRNAME, TRIALS_DIRNAME);
9897
10220
  }
9898
10221
  function trialMarkerPath(slug, home = homedir14()) {
9899
- return join12(trialsDir(home), `${slug}.json`);
10222
+ return join13(trialsDir(home), `${slug}.json`);
9900
10223
  }
9901
10224
  function rejectUntrustedMarker(marker) {
9902
10225
  if (!marker.entryName.startsWith(TRIAL_ENTRY_PREFIX)) {
@@ -9929,46 +10252,40 @@ async function readTrialMarker(markerPath) {
9929
10252
  }
9930
10253
  }
9931
10254
  async function peelEntryFromConfig(clientPath, containerPath, entryName, dryRun = false, expectFingerprint) {
9932
- if (!existsSync5(clientPath)) return "absent";
9933
- const raw = await readFile12(clientPath, "utf8");
9934
- if (raw.trim().length === 0) return "absent";
9935
- const parsed = parseJsonc(raw);
9936
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return "not-object";
9937
- let container = parsed;
9938
- for (const segment of containerPath) {
9939
- const child = Object.hasOwn(container, segment) ? container[segment] : void 0;
9940
- if (typeof child !== "object" || child === null || Array.isArray(child)) return "absent";
9941
- container = child;
9942
- }
9943
- if (expectFingerprint !== void 0) {
9944
- const current = Object.hasOwn(container, entryName) ? container[entryName] : void 0;
9945
- if (current !== void 0 && typeof current === "object" && current !== null && trialLaunchFingerprint(current) !== expectFingerprint) {
9946
- return "replaced";
9947
- }
9948
- }
9949
- const next = removeJsoncEntry(raw, containerPath, entryName);
9950
- if (next === raw) return "absent";
10255
+ const site = markerSite(clientPath, containerPath);
10256
+ const view = await readClientConfigFile(site);
10257
+ const read = view.read;
10258
+ if (read.kind === "absent") return "absent";
10259
+ if (read.kind === "unreadable") throw new Error(read.message);
10260
+ if (read.kind === "malformed") {
10261
+ if (read.reason === "root") return "not-object";
10262
+ throw new Error(read.detail);
10263
+ }
10264
+ if (read.kind === "blocked") return "absent";
10265
+ if (read.kind === "unspliceable") throw new Error(`the "${read.key}" entry is ${read.reason}`);
10266
+ if (!read.containerPresent) return "absent";
10267
+ const current = view.entry(entryName);
10268
+ if (current === void 0) return "absent";
10269
+ if (expectFingerprint !== void 0 && typeof current.value === "object" && current.value !== null && trialLaunchFingerprint(current.value) !== expectFingerprint) {
10270
+ return "replaced";
10271
+ }
10272
+ const next = applyClientConfigEdits(view, [{ op: "remove", key: entryName }], site);
10273
+ if (next === view.raw) return "absent";
9951
10274
  if (dryRun) return "removed";
9952
- await atomicWriteFile(clientPath, next.endsWith("\n") ? next : `${next}
9953
- `);
10275
+ await atomicWriteFile(clientPath, terminateWithNewline(next));
9954
10276
  return "removed";
9955
10277
  }
9956
- function configHasEntry(raw, containerPath, entryName) {
9957
- if (raw === null || raw.trim().length === 0) return false;
9958
- let parsed;
9959
- try {
9960
- parsed = parseJsonc(raw);
9961
- } catch {
9962
- return false;
9963
- }
9964
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return false;
9965
- let container = parsed;
9966
- for (const segment of containerPath) {
9967
- const child = Object.hasOwn(container, segment) ? container[segment] : void 0;
9968
- if (typeof child !== "object" || child === null || Array.isArray(child)) return false;
9969
- container = child;
9970
- }
9971
- return Object.hasOwn(container, entryName);
10278
+ function markerSite(clientPath, containerPath) {
10279
+ return {
10280
+ id: "trial",
10281
+ label: "trial entry",
10282
+ resolved: { absolute: clientPath, display: clientPath, containerPath: [...containerPath] },
10283
+ format: "jsonc",
10284
+ detectDir: null
10285
+ };
10286
+ }
10287
+ function configHasEntry(raw, site, entryName) {
10288
+ return classifyClientConfig(raw, site).entry(entryName) !== void 0;
9972
10289
  }
9973
10290
  async function peelTrialEntry(marker, dryRun = false) {
9974
10291
  if (rejectUntrustedMarker(marker) !== null) return "failed";
@@ -10003,6 +10320,7 @@ async function autoDetectClient(opts) {
10003
10320
  os: opts.os,
10004
10321
  cwd: opts.cwd,
10005
10322
  claudeConfigDir: opts.claudeConfigDir,
10323
+ clientEnv: opts.clientEnv,
10006
10324
  appData: opts.appData
10007
10325
  });
10008
10326
  for (const p of probes) {
@@ -10043,7 +10361,8 @@ async function runTry(opts) {
10043
10361
  }
10044
10362
  ttlMs = parsedTtl;
10045
10363
  }
10046
- const claudeConfigDir = env.CLAUDE_CONFIG_DIR && env.CLAUDE_CONFIG_DIR.length > 0 ? env.CLAUDE_CONFIG_DIR : void 0;
10364
+ const clientEnv2 = readClientEnv(env);
10365
+ const claudeConfigDir = clientEnv2.claudeConfigDir;
10047
10366
  const appData = resolveAppDataDir({ home: opts.home, env });
10048
10367
  const fetchExplore = opts.fetchExplore ?? defaultFetchExplore;
10049
10368
  const catalogUrl = env.YAW_MCP_CATALOG_URL !== void 0 && env.YAW_MCP_CATALOG_URL.length > 0 ? env.YAW_MCP_CATALOG_URL : void 0;
@@ -10054,7 +10373,7 @@ async function runTry(opts) {
10054
10373
  printErr(`yaw-mcp try: ${e.message}`);
10055
10374
  return { exitCode: 1, written: [] };
10056
10375
  }
10057
- const detected = opts.clientId ? null : await autoDetectClient({ home, os, cwd, claudeConfigDir, appData });
10376
+ const detected = opts.clientId ? null : await autoDetectClient({ home, os, cwd, claudeConfigDir, clientEnv: clientEnv2, appData });
10058
10377
  const clientId = opts.clientId ?? detected.clientId;
10059
10378
  const tryTarget = INSTALL_TARGETS.find((t) => t.clientId === clientId);
10060
10379
  if (tryTarget && !tryTarget.availableOn.includes(os)) {
@@ -10065,21 +10384,25 @@ async function runTry(opts) {
10065
10384
  const hasUserScope = tryTarget?.scopes.some((sc) => sc.scope === "user") ?? false;
10066
10385
  const scope = hasUserScope ? "user" : detected?.scope ?? tryTarget?.scopes[0].scope ?? "user";
10067
10386
  const projectDir = scope === "project" ? resolve6(cwd) : void 0;
10068
- let resolved;
10387
+ let site;
10069
10388
  try {
10070
- resolved = resolveInstallPath({
10389
+ site = resolveInstallSites({
10071
10390
  clientId,
10072
10391
  scope,
10073
10392
  os,
10074
10393
  home,
10075
10394
  appData,
10076
10395
  projectDir,
10077
- claudeConfigDir
10078
- });
10396
+ claudeConfigDir,
10397
+ // A MODULAR row resolves its own path from these, so a trial written for
10398
+ // an env-redirected client lands where that client reads.
10399
+ clientEnv: clientEnv2
10400
+ })[0];
10079
10401
  } catch (e) {
10080
10402
  printErr(`yaw-mcp try: ${e.message}`);
10081
10403
  return { exitCode: 1, written: [] };
10082
10404
  }
10405
+ const resolved = site.resolved;
10083
10406
  const lookup = (k) => opts.envOverrides?.[k] ?? env[k];
10084
10407
  const missing = (server.requiredEnvVars ?? []).filter((k) => (lookup(k) ?? "").trim() === "");
10085
10408
  if (missing.length > 0) {
@@ -10114,6 +10437,7 @@ async function runTry(opts) {
10114
10437
  env: Object.keys(trialEnv).length > 0 ? trialEnv : void 0
10115
10438
  }
10116
10439
  });
10440
+ const entryToWrite = composeEntry({ base: entry, transform: tryTarget?.entry, os, purpose: "upstream" });
10117
10441
  const entryHasSecrets = entry.env !== void 0 && Object.keys(entry.env).length > 0;
10118
10442
  if (scope === "project" && entryHasSecrets) {
10119
10443
  const target = INSTALL_TARGETS.find((t) => t.clientId === clientId);
@@ -10148,49 +10472,36 @@ async function runTry(opts) {
10148
10472
  createdAt: now,
10149
10473
  // What this run is about to write, so a later sweep can tell this entry
10150
10474
  // from one the user has since put at the same name (see
10151
- // trialLaunchFingerprint). Taken from `entry` -- the object actually
10152
- // written -- not from `server`, so the Windows `cmd /c` wrap that
10475
+ // trialLaunchFingerprint). Taken from `entryToWrite` -- the object
10476
+ // actually written -- not from `server`, so the Windows `cmd /c` wrap that
10153
10477
  // buildLaunchEntry adds is inside the fingerprint, exactly as it will be
10154
10478
  // read back out of the config.
10155
- entryFingerprint: trialLaunchFingerprint(entry)
10479
+ entryFingerprint: trialLaunchFingerprint(entryToWrite)
10156
10480
  };
10157
- const readClientRaw = async () => {
10158
- if (!existsSync5(resolved.absolute)) return { ok: true, raw: null };
10159
- let raw;
10160
- try {
10161
- raw = await readFile12(resolved.absolute, "utf8");
10162
- } catch (e) {
10163
- const code = e.code;
10481
+ const readClientView = async () => {
10482
+ const view = await readClientConfigFile(site);
10483
+ const read = view.read;
10484
+ if (read.kind === "unreadable") {
10164
10485
  printErr(
10165
- code === "EISDIR" ? `${describeUnreadableConfig("try", resolved.absolute, e)} Refusing to overwrite.` : `yaw-mcp try: ${resolved.absolute} could not be read (${code ?? e.message}) -- check its permissions and ownership. Refusing to overwrite.`
10486
+ read.code === "EISDIR" ? `${describeUnreadableConfig("try", resolved.absolute, { code: read.code, message: read.message })} Refusing to overwrite.` : `yaw-mcp try: ${resolved.absolute} could not be read (${read.code ?? read.message}) -- check its permissions and ownership. Refusing to overwrite.`
10166
10487
  );
10167
10488
  return { ok: false };
10168
10489
  }
10169
- if (raw.trim().length === 0) return { ok: true, raw: null };
10170
- let parsed;
10171
- try {
10172
- parsed = parseJsonc(raw);
10173
- } catch (e) {
10174
- printErr(`yaw-mcp try: ${resolved.absolute} is not valid JSON (${e.message}). Refusing to overwrite.`);
10490
+ if (read.kind === "malformed") {
10491
+ printErr(
10492
+ read.reason === "root" ? `yaw-mcp try: ${resolved.absolute} is not a ${read.syntax} object \u2014 refusing to overwrite.` : `yaw-mcp try: ${resolved.absolute} is not valid ${read.syntax} (${read.detail}). Refusing to overwrite.`
10493
+ );
10175
10494
  return { ok: false };
10176
10495
  }
10177
- if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) return { ok: true, raw };
10178
- printErr(`yaw-mcp try: ${resolved.absolute} is not a JSON object \u2014 refusing to overwrite.`);
10179
- return { ok: false };
10496
+ return { ok: true, view };
10180
10497
  };
10181
- const firstRead = await readClientRaw();
10498
+ const firstRead = await readClientView();
10182
10499
  if (!firstRead.ok) return { exitCode: 1, written: [] };
10183
- const replacesEntryInPlace = configHasEntry(firstRead.raw, resolved.containerPath, entryName);
10184
- const buildClientJson = (raw) => {
10185
- if (raw === null) {
10186
- const merged = mergeClientConfig({}, resolved.containerPath, entry, entryName);
10187
- return { ok: true, json: `${JSON.stringify(merged, null, 2)}
10188
- ` };
10189
- }
10500
+ const replacesEntryInPlace = configHasEntry(firstRead.view.raw, site, entryName);
10501
+ const buildClientJson = (view) => {
10190
10502
  try {
10191
- const next = editJsoncEntry(raw, resolved.containerPath, entryName, entry);
10192
- return { ok: true, json: next.endsWith("\n") ? next : `${next}
10193
- ` };
10503
+ const edits = [{ op: "upsert", key: entryName, entry: entryToWrite }];
10504
+ return { ok: true, json: terminateWithNewline(applyClientConfigEdits(view, edits, site)) };
10194
10505
  } catch (e) {
10195
10506
  printErr(
10196
10507
  `yaw-mcp try: failed to splice entry into ${resolved.absolute} (${e.message}). Refusing to overwrite.`
@@ -10198,7 +10509,7 @@ async function runTry(opts) {
10198
10509
  return { ok: false };
10199
10510
  }
10200
10511
  };
10201
- const firstSplice = buildClientJson(firstRead.raw);
10512
+ const firstSplice = buildClientJson(firstRead.view);
10202
10513
  if (!firstSplice.ok) return { exitCode: 1, written: [] };
10203
10514
  let clientJson = firstSplice.json;
10204
10515
  const markerJson = `${JSON.stringify(marker, null, 2)}
@@ -10243,9 +10554,9 @@ async function runTry(opts) {
10243
10554
  if (outcome === "removed") {
10244
10555
  print(`Removed the previous ${slug} trial (${previousMarker.entryName}) from ${previousMarker.clientPath}`);
10245
10556
  if (previousMarker.clientPath === resolved.absolute) {
10246
- const reread = await readClientRaw();
10557
+ const reread = await readClientView();
10247
10558
  if (!reread.ok) return { exitCode: 1, written: [] };
10248
- const respliced = buildClientJson(reread.raw);
10559
+ const respliced = buildClientJson(reread.view);
10249
10560
  if (!respliced.ok) return { exitCode: 1, written: [] };
10250
10561
  clientJson = respliced.json;
10251
10562
  }
@@ -10447,7 +10758,7 @@ async function scanTrials(opts = {}) {
10447
10758
  }
10448
10759
  for (const filename of entries) {
10449
10760
  if (!filename.endsWith(".json")) continue;
10450
- const path6 = join12(dir, filename);
10761
+ const path6 = join13(dir, filename);
10451
10762
  try {
10452
10763
  const raw = await readFile12(path6, "utf8");
10453
10764
  const parsed = JSON.parse(raw);
@@ -10780,7 +11091,7 @@ function foldBundleWarnings(warnings, probe) {
10780
11091
  const prefix = `${probe.path}:`;
10781
11092
  return warnings.filter((w) => !w.startsWith(prefix));
10782
11093
  }
10783
- var VERSION = true ? "1.0.0" : "dev";
11094
+ var VERSION = true ? "1.0.2" : "dev";
10784
11095
  var DOCTOR_USAGE = `Usage: yaw-mcp doctor [--json]
10785
11096
 
10786
11097
  Print a diagnostic of your yaw-mcp setup.
@@ -10812,12 +11123,23 @@ async function collectDoctorBase(opts) {
10812
11123
  const trustProbe = await probeProjectTrust({ cwd, home, env }).catch(() => null);
10813
11124
  const trustWarning = projectTrustWarning(trustProbe);
10814
11125
  if (trustWarning) config.warnings = [...config.warnings, trustWarning];
10815
- const claudeConfigDir = env.CLAUDE_CONFIG_DIR && env.CLAUDE_CONFIG_DIR.length > 0 ? env.CLAUDE_CONFIG_DIR : void 0;
10816
- return { cwd, home, appData, os, env, timestamp, config, trustProbe, claudeConfigDir };
11126
+ const clientEnv2 = readClientEnv(env);
11127
+ return {
11128
+ cwd,
11129
+ home,
11130
+ appData,
11131
+ os,
11132
+ env,
11133
+ timestamp,
11134
+ config,
11135
+ trustProbe,
11136
+ claudeConfigDir: clientEnv2.claudeConfigDir,
11137
+ clientEnv: clientEnv2
11138
+ };
10817
11139
  }
10818
11140
  async function collectStateStatus(opts) {
10819
11141
  const disabled = isPersistenceDisabled(opts.env);
10820
- const filePath = join13(userConfigDir(opts.home), STATE_FILENAME);
11142
+ const filePath = join14(userConfigDir(opts.home), STATE_FILENAME);
10821
11143
  const peek = disabled ? null : await peekStateFile(filePath);
10822
11144
  const persisted = peek?.kind === "ok" ? await loadState(filePath) : null;
10823
11145
  return { disabled, filePath, peek, persisted };
@@ -10832,17 +11154,24 @@ function isTransientRead(c) {
10832
11154
  return c.unreadable !== null && c.unreadableCode !== null && TRANSIENT_READ_CODES.has(c.unreadableCode);
10833
11155
  }
10834
11156
  function probeUsable(c) {
10835
- return !c.unavailable && c.exists && !c.malformed && c.unreadable === null;
11157
+ return !c.unavailable && c.exists && !c.malformed && c.unreadable === null && c.unloadable === null;
10836
11158
  }
10837
11159
  function clientCannotLaunch(c) {
10838
- return c.unreadable !== null && !isTransientRead(c) || c.malformed || c.launchCommandMissing !== null || c.launchOamEntryMissing !== null || c.launchOamNotAbsolute !== null;
11160
+ return c.unreadable !== null && !isTransientRead(c) || c.malformed || // Only WITH our entry in it. The file's client loads no server from it
11161
+ // either way, but a strict file yaw-mcp was never installed to is the
11162
+ // blocked-container case ("install refuses this file" is advice, and a
11163
+ // commented `.mcp.json` in a checkout must not drag a working machine to
11164
+ // exit 2); a strict file that HOLDS the "mcp" entry is the state this
11165
+ // fold exists for -- the CLIENTS row says the entry is not loading while
11166
+ // DIAGNOSIS said "All good", on --json too.
11167
+ c.unloadable !== null && c.hasMcpEntry || c.launchCommandMissing !== null || c.launchOamEntryMissing !== null || c.launchOamNotAbsolute !== null;
10839
11168
  }
10840
11169
  function clientLaunchWarnings(clients) {
10841
11170
  const grouped = /* @__PURE__ */ new Map();
10842
11171
  for (const c of clients) {
10843
11172
  if (!clientCannotLaunch(c)) continue;
10844
11173
  const { client, status } = describeClient(c);
10845
- const key = `${c.path}\0${client}\0${status}`;
11174
+ const key = `${c.path}\0${client}\0${c.malformed ? "malformed" : status}`;
10846
11175
  const seen = grouped.get(key);
10847
11176
  if (seen) seen.scopes.push(c.scope);
10848
11177
  else grouped.set(key, { path: c.path, client, scopes: [c.scope], status });
@@ -10858,7 +11187,7 @@ async function runDoctor(opts = {}) {
10858
11187
  write(`${s}
10859
11188
  `);
10860
11189
  };
10861
- const { cwd, home, appData, os, env, timestamp, config, trustProbe, claudeConfigDir } = await collectDoctorBase(opts);
11190
+ const { cwd, home, appData, os, env, timestamp, config, trustProbe, claudeConfigDir, clientEnv: clientEnv2 } = await collectDoctorBase(opts);
10862
11191
  print(`yaw-mcp doctor -- ${timestamp}`);
10863
11192
  print(`yaw-mcp version: ${VERSION}`);
10864
11193
  print(`platform: ${os}`);
@@ -10906,6 +11235,7 @@ async function runDoctor(opts = {}) {
10906
11235
  os,
10907
11236
  cwd,
10908
11237
  claudeConfigDir,
11238
+ clientEnv: clientEnv2,
10909
11239
  appData,
10910
11240
  platform: opts.platform,
10911
11241
  readClientConfig: opts.readClientConfig
@@ -10988,7 +11318,7 @@ async function runDoctor(opts = {}) {
10988
11318
  async function runDoctorJson(opts) {
10989
11319
  const lines = [];
10990
11320
  const write = opts.out ?? createStreamWriter(process.stdout);
10991
- const { cwd, home, appData, os, env, timestamp, config, trustProbe, claudeConfigDir } = await collectDoctorBase(opts);
11321
+ const { cwd, home, appData, os, env, timestamp, config, trustProbe, claudeConfigDir, clientEnv: clientEnv2 } = await collectDoctorBase(opts);
10992
11322
  const trialScan = await scanTrials({ home, now: opts.now });
10993
11323
  const trialGc = await gcExpiredTrials({
10994
11324
  home,
@@ -11000,6 +11330,7 @@ async function runDoctorJson(opts) {
11000
11330
  os,
11001
11331
  cwd,
11002
11332
  claudeConfigDir,
11333
+ clientEnv: clientEnv2,
11003
11334
  appData,
11004
11335
  platform: opts.platform,
11005
11336
  readClientConfig: opts.readClientConfig
@@ -11597,51 +11928,66 @@ function schemaSuffix(f) {
11597
11928
  return ` (schema v${f.version})`;
11598
11929
  }
11599
11930
  function renderClientStatus(c, installCmd) {
11600
- if (c.unavailable) return "unavailable on this OS";
11931
+ if (c.unavailable) {
11932
+ return c.unavailableReason !== void 0 ? `not supported on this OS yet -- ${c.unavailableReason}` : "unavailable on this OS";
11933
+ }
11601
11934
  if (c.unreadable !== null) {
11602
11935
  if (isTransientRead(c)) {
11603
11936
  return `exists but could not be read just now (${c.unreadable}) -- another process holds it; rerun doctor`;
11604
11937
  }
11605
11938
  return `exists but could not be read (${c.unreadable}) -- check the file and its permissions, then rerun doctor`;
11606
11939
  }
11607
- if (c.malformed) return "exists but JSON is malformed -- fix or rerun `yaw-mcp install`";
11608
- const legacy = c.hasLegacyEntry ? `; legacy "${c.legacyEntryName}" entry also present -- remove it once the working entry is back` : "";
11940
+ if (c.malformed) {
11941
+ return `exists but JSON is malformed -- install refuses to overwrite it; ${unparseableConfigFix(`run \`${installCmd}\``)}`;
11942
+ }
11943
+ if (c.containerBlocked !== null) {
11944
+ return `present, but ${c.containerBlocked}, not a JSON object -- install refuses to overwrite it; ${blockedContainerFix(`run \`${installCmd}\``)}`;
11945
+ }
11946
+ if (c.unloadable !== null) {
11947
+ return `exists but ${c.unloadable} -- install refuses to write into it; ${unloadableConfigFix(`run \`${installCmd}\``)}`;
11948
+ }
11949
+ const legacy = c.hasLegacyEntry ? `; legacy "${c.legacyEntryName}" entry also present -- install removes it as it writes the working entry` : "";
11950
+ const keyNote = c.entryProjectKey ? `; found under projects[${JSON.stringify(c.entryProjectKey)}], the same directory spelled with the other drive-letter case -- only a Claude Code whose cwd is spelled that way reads it, and \`${installCmd}\` writes the canonical key` : "";
11609
11951
  if (c.launchCommandMissing) {
11610
- return `has "${ENTRY_NAME}" entry, but its launch command does not exist: ${c.launchCommandMissing} -- the client cannot start yaw-mcp; rerun \`${installCmd}\`${legacy}`;
11952
+ return `has "${ENTRY_NAME}" entry, but its launch command does not exist: ${c.launchCommandMissing} -- the client cannot start yaw-mcp; rerun \`${installCmd}\`${legacy}${keyNote}`;
11611
11953
  }
11612
11954
  if (c.launchOamEntryMissing) {
11613
- return `has "${ENTRY_NAME}" entry running on oam, but its entry file does not exist: ${c.launchOamEntryMissing} -- oam cannot fetch it on demand the way npx would; rerun \`${installCmd}\`${legacy}`;
11955
+ return `has "${ENTRY_NAME}" entry running on oam, but its entry file does not exist: ${c.launchOamEntryMissing} -- oam cannot fetch it on demand the way npx would; rerun \`${installCmd}\`${legacy}${keyNote}`;
11614
11956
  }
11615
11957
  if (c.launchOamNotAbsolute) {
11616
- return `has "${ENTRY_NAME}" entry with a bare "${c.launchOamNotAbsolute}" command -- it resolves against the client's PATH, which a GUI-launched client does not inherit from your shell; rerun \`${installCmd}\` to write an absolute path, or set OAM_BIN${legacy}`;
11958
+ return `has "${ENTRY_NAME}" entry with a bare "${c.launchOamNotAbsolute}" command -- it resolves against the client's PATH, which a GUI-launched client does not inherit from your shell; rerun \`${installCmd}\` to write an absolute path (set OAM_BIN to oam's full path first if install cannot find it)${legacy}${keyNote}`;
11617
11959
  }
11618
11960
  if (c.launchForeignPath) {
11619
- return `has "${ENTRY_NAME}" entry${c.launchRuntime === "oam" ? " (runs on oam)" : ""} whose launch path is for another OS: ${c.launchForeignPath} -- not verified from here${c.hasLegacyEntry ? `; legacy "${c.legacyEntryName}" entry also present -- remove it to avoid running yaw-mcp twice` : ""}`;
11961
+ return `has "${ENTRY_NAME}" entry${c.launchRuntime === "oam" ? " (runs on oam)" : ""} whose launch path is for another OS: ${c.launchForeignPath} -- not verified from here${c.hasLegacyEntry ? `; legacy "${c.legacyEntryName}" entry also present -- remove it to avoid running yaw-mcp twice` : ""}${keyNote}`;
11620
11962
  }
11621
11963
  if (c.hasMcpEntry && c.hasLegacyEntry) {
11622
- return `OK -- has "${ENTRY_NAME}" entry${c.launchRuntime === "oam" ? " (runs on oam)" : ""}; legacy "${c.legacyEntryName}" entry also present -- remove it to avoid running yaw-mcp twice`;
11964
+ return `OK -- has "${ENTRY_NAME}" entry${c.launchRuntime === "oam" ? " (runs on oam)" : ""}; legacy "${c.legacyEntryName}" entry also present -- remove it to avoid running yaw-mcp twice${keyNote}`;
11623
11965
  }
11624
11966
  if (c.hasMcpEntry) {
11625
- return `OK -- has "${ENTRY_NAME}" entry${c.launchRuntime === "oam" ? " (runs on oam)" : ""}`;
11967
+ return `OK -- has "${ENTRY_NAME}" entry${c.launchRuntime === "oam" ? " (runs on oam)" : ""}${keyNote}`;
11626
11968
  }
11627
11969
  if (c.hasLegacyEntry) {
11628
- return `legacy "${c.legacyEntryName}" entry present -- run \`${installCmd}\` to migrate, then remove the legacy entry by hand`;
11970
+ return `legacy "${c.legacyEntryName}" entry present -- run \`${installCmd}\` to migrate; install removes the legacy entry as it writes the new one${keyNote}`;
11629
11971
  }
11630
11972
  if (c.exists) return `present, no "${ENTRY_NAME}" entry -- run \`${installCmd}\``;
11631
11973
  return `not configured -- run \`${installCmd}\``;
11632
11974
  }
11633
11975
  var EMPTY_PROBE = {
11634
11976
  hasMcpEntry: false,
11977
+ containerEntries: 0,
11635
11978
  hasLegacyEntry: false,
11636
11979
  legacyEntryName: null,
11637
11980
  malformed: false,
11981
+ unloadable: null,
11638
11982
  unreadable: null,
11639
11983
  unreadableCode: null,
11984
+ containerBlocked: null,
11640
11985
  launchCommandMissing: null,
11641
11986
  launchRuntime: null,
11642
11987
  launchOamNotAbsolute: null,
11643
11988
  launchOamEntryMissing: null,
11644
- launchForeignPath: null
11989
+ launchForeignPath: null,
11990
+ entryProjectKey: null
11645
11991
  };
11646
11992
  var MALFORMED = { ...EMPTY_PROBE, malformed: true };
11647
11993
  function unreadableProbe(err) {
@@ -11655,6 +12001,7 @@ function unreadableProbe(err) {
11655
12001
  function* enumerateProbeSlots(opts) {
11656
12002
  for (const target of INSTALL_TARGETS) {
11657
12003
  if (!target.availableOn.includes(opts.os)) {
12004
+ const why = target.notConfigurableOn?.[opts.os];
11658
12005
  yield {
11659
12006
  result: {
11660
12007
  clientId: target.clientId,
@@ -11662,7 +12009,8 @@ function* enumerateProbeSlots(opts) {
11662
12009
  path: "(n/a)",
11663
12010
  exists: false,
11664
12011
  unavailable: true,
11665
- ...EMPTY_PROBE
12012
+ ...EMPTY_PROBE,
12013
+ ...why !== void 0 ? { unavailableReason: why } : {}
11666
12014
  },
11667
12015
  read: null
11668
12016
  };
@@ -11678,7 +12026,8 @@ function* enumerateProbeSlots(opts) {
11678
12026
  home: opts.home,
11679
12027
  appData: opts.appData,
11680
12028
  projectDir: scope.requiresProjectDir ? opts.cwd : void 0,
11681
- claudeConfigDir: opts.claudeConfigDir
12029
+ claudeConfigDir: opts.claudeConfigDir,
12030
+ clientEnv: opts.clientEnv
11682
12031
  });
11683
12032
  } catch {
11684
12033
  continue;
@@ -11693,7 +12042,15 @@ function* enumerateProbeSlots(opts) {
11693
12042
  unavailable: false,
11694
12043
  ...EMPTY_PROBE
11695
12044
  },
11696
- read: exists2 ? { path: resolved.absolute, containerPath: resolved.containerPath } : null
12045
+ read: exists2 ? {
12046
+ path: resolved.absolute,
12047
+ containerPath: resolved.containerPath,
12048
+ // The scope's own strictness, resolved the one way the write
12049
+ // path resolves it -- claude-code's `.mcp.json` is the single
12050
+ // strict site today, and a row added to INSTALL_TARGETS is
12051
+ // picked up here without touching this file.
12052
+ strict: effectiveConfigFormat(target.config, scope) === "json"
12053
+ } : null
11697
12054
  };
11698
12055
  }
11699
12056
  }
@@ -11710,7 +12067,8 @@ function probeClients(opts) {
11710
12067
  } catch (err) {
11711
12068
  Object.assign(result, unreadableProbe(err));
11712
12069
  }
11713
- if (raw !== null) Object.assign(result, classifyProbeContent(raw, read.containerPath, existsSync6, platform));
12070
+ if (raw !== null)
12071
+ Object.assign(result, classifyProbeContent(raw, read.containerPath, read.strict, existsSync6, platform));
11714
12072
  }
11715
12073
  out.push(result);
11716
12074
  }
@@ -11752,19 +12110,46 @@ function oamRunEntryFromTokens(tokens) {
11752
12110
  if (sub < 0 || tokens[sub] !== "run") return null;
11753
12111
  return tokens.slice(sub + 1).find((t) => !t.startsWith("-")) ?? null;
11754
12112
  }
11755
- function classifyProbeContent(raw, containerPath, exists2 = existsSync6, platform = process.platform) {
12113
+ function classifyProbeContent(raw, containerPath, strict, exists2 = existsSync6, platform = process.platform) {
11756
12114
  const isAbsolute2 = platform === "win32" ? win32.isAbsolute : posix.isAbsolute;
11757
12115
  if (raw.trim().length === 0) {
11758
12116
  return { ...EMPTY_PROBE };
11759
12117
  }
12118
+ const client = strict ? readStrictJson(raw) : null;
12119
+ const unloadable = client !== null && !client.ok ? unloadableConfigProblem(client.violation) : null;
11760
12120
  try {
11761
12121
  const parsed = parseJsonc(raw);
11762
12122
  if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
11763
12123
  return { ...MALFORMED };
11764
12124
  }
11765
- const container = walkContainer(parsed, containerPath);
12125
+ const variantPaths = claudeCodeContainerPaths(parsed, containerPath);
12126
+ let container = null;
12127
+ let entryProjectKey = null;
12128
+ for (let i = 0; i < variantPaths.length; i++) {
12129
+ const found = walkContainer(parsed, variantPaths[i]);
12130
+ if (!found) continue;
12131
+ const wired = ENTRY_NAME in found || findLegacyEntry(found) !== null;
12132
+ if (container === null || wired) {
12133
+ container = found;
12134
+ entryProjectKey = i === 0 ? null : variantPaths[i][1];
12135
+ }
12136
+ if (wired) break;
12137
+ }
11766
12138
  if (!container) {
11767
- return { ...EMPTY_PROBE };
12139
+ const blocked = findBlockedContainerSegment(parsed, containerPath);
12140
+ if (blocked !== null && !blocked.reparable) {
12141
+ return {
12142
+ ...EMPTY_PROBE,
12143
+ // Both, when both are true: a strict file can be unloadable AND
12144
+ // hold a container install refuses, and dropping the strictness
12145
+ // here would leave the row silent about it the moment the user
12146
+ // fixed the container. Which one the ROW leads with is
12147
+ // renderClientStatus's business.
12148
+ unloadable,
12149
+ containerBlocked: `"${blocked.path.join(".")}" is ${describeJsonShape(blocked.value)}`
12150
+ };
12151
+ }
12152
+ return { ...EMPTY_PROBE, unloadable };
11768
12153
  }
11769
12154
  const legacyEntryName = findLegacyEntry(container);
11770
12155
  const entry = container[ENTRY_NAME];
@@ -11799,16 +12184,23 @@ function classifyProbeContent(raw, containerPath, exists2 = existsSync6, platfor
11799
12184
  }
11800
12185
  return {
11801
12186
  hasMcpEntry: ENTRY_NAME in container,
12187
+ containerEntries: Object.keys(container).length,
11802
12188
  hasLegacyEntry: legacyEntryName !== null,
11803
12189
  legacyEntryName,
11804
12190
  malformed: false,
12191
+ unloadable,
11805
12192
  unreadable: null,
11806
12193
  unreadableCode: null,
12194
+ containerBlocked: null,
11807
12195
  launchCommandMissing,
11808
12196
  launchRuntime,
11809
12197
  launchOamNotAbsolute,
11810
12198
  launchOamEntryMissing,
11811
- launchForeignPath
12199
+ launchForeignPath,
12200
+ // Only when something is actually wired there: a bare sibling container
12201
+ // is not news, and naming it would send the user after a key that holds
12202
+ // nothing.
12203
+ entryProjectKey: ENTRY_NAME in container || legacyEntryName !== null ? entryProjectKey : null
11812
12204
  };
11813
12205
  } catch {
11814
12206
  return { ...MALFORMED };
@@ -11825,7 +12217,8 @@ async function probeClientsAsync(opts) {
11825
12217
  } catch (err) {
11826
12218
  Object.assign(result, unreadableProbe(err));
11827
12219
  }
11828
- if (raw !== null) Object.assign(result, classifyProbeContent(raw, read.containerPath, existsSync6, platform));
12220
+ if (raw !== null)
12221
+ Object.assign(result, classifyProbeContent(raw, read.containerPath, read.strict, existsSync6, platform));
11829
12222
  }
11830
12223
  out.push(result);
11831
12224
  }
@@ -11859,9 +12252,9 @@ function scanShellHistoryForShadows(opts) {
11859
12252
  function shellHistorySources(opts) {
11860
12253
  const sources = [];
11861
12254
  const plain = (l) => l.trim() || null;
11862
- sources.push({ path: opts.env.HISTFILE || join13(opts.home, ".bash_history"), extractCommand: plain });
12255
+ sources.push({ path: opts.env.HISTFILE || join14(opts.home, ".bash_history"), extractCommand: plain });
11863
12256
  sources.push({
11864
- path: join13(opts.home, ".zsh_history"),
12257
+ path: join14(opts.home, ".zsh_history"),
11865
12258
  // Zsh extended-history lines look like `: 1700000000:0;npm audit`.
11866
12259
  // Strip the metadata prefix so we get just the command.
11867
12260
  extractCommand: (l) => {
@@ -11877,17 +12270,17 @@ function shellHistorySources(opts) {
11877
12270
  const appData = opts.env.APPDATA;
11878
12271
  if (appData) {
11879
12272
  sources.push({
11880
- path: join13(appData, "Microsoft", "Windows", "PowerShell", "PSReadLine", "ConsoleHost_history.txt"),
12273
+ path: join14(appData, "Microsoft", "Windows", "PowerShell", "PSReadLine", "ConsoleHost_history.txt"),
11881
12274
  extractCommand: plain
11882
12275
  });
11883
12276
  }
11884
- const xdgData = opts.env.XDG_DATA_HOME || join13(opts.home, ".local", "share");
12277
+ const xdgData = opts.env.XDG_DATA_HOME || join14(opts.home, ".local", "share");
11885
12278
  sources.push({
11886
- path: join13(xdgData, "powershell", "PSReadLine", "ConsoleHost_history.txt"),
12279
+ path: join14(xdgData, "powershell", "PSReadLine", "ConsoleHost_history.txt"),
11887
12280
  extractCommand: plain
11888
12281
  });
11889
12282
  sources.push({
11890
- path: join13(xdgData, "fish", "fish_history"),
12283
+ path: join14(xdgData, "fish", "fish_history"),
11891
12284
  extractCommand: (l) => {
11892
12285
  const trimmed = l.trim();
11893
12286
  if (!trimmed.startsWith("- cmd:")) return null;
@@ -12571,7 +12964,6 @@ async function runFoundryExport(opts) {
12571
12964
  }
12572
12965
 
12573
12966
  // src/import-cmd.ts
12574
- import { readFile as readFile14 } from "fs/promises";
12575
12967
  import { homedir as homedir18 } from "os";
12576
12968
  import { basename as basename3, resolve as resolvePath } from "path";
12577
12969
  import { createInterface as createInterface3 } from "readline/promises";
@@ -12581,7 +12973,7 @@ var IMPORT_USAGE = `Usage: yaw-mcp import <client> [flags]
12581
12973
  local ~/.yaw-mcp/bundles.json, so yaw-mcp serves the servers you already had
12582
12974
  instead of starting empty.
12583
12975
 
12584
- <client> is one of: ${INSTALL_TARGETS.map((t) => t.clientId).join(", ")}.
12976
+ <client> is one of: ${clientChoices("import").join(", ")}.
12585
12977
 
12586
12978
  yaw-mcp's own entry is never imported, under any of its names. Each server's
12587
12979
  command, args, url, headers and env come across as they are -- an import that
@@ -12700,10 +13092,18 @@ function toEntry(key, value, vars) {
12700
13092
  unresolved: [...unresolved]
12701
13093
  };
12702
13094
  }
12703
- function readVsCodeInputs(parsed) {
13095
+ function readVsCodeInputs(raw) {
12704
13096
  const out = /* @__PURE__ */ new Map();
12705
- if (!Array.isArray(parsed.inputs)) return out;
12706
- for (const item of parsed.inputs) {
13097
+ let parsed;
13098
+ try {
13099
+ parsed = parseJsonc(raw);
13100
+ } catch {
13101
+ return out;
13102
+ }
13103
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return out;
13104
+ const inputs = parsed.inputs;
13105
+ if (!Array.isArray(inputs)) return out;
13106
+ for (const item of inputs) {
12707
13107
  if (!item || typeof item !== "object" || Array.isArray(item)) continue;
12708
13108
  const r = item;
12709
13109
  if (typeof r.id !== "string" || r.id === "") continue;
@@ -12725,30 +13125,77 @@ function renderLaunch2(shape) {
12725
13125
  return shape.url ? `HTTP ${displaySafe(shape.url)}` : "(no launch command)";
12726
13126
  }
12727
13127
  function describeContainer2(ref) {
12728
- return `${displaySafe(ref.absolute)} (${ref.containerPath.join(".")})`;
13128
+ return `${displaySafe(ref.resolved.absolute)} (${ref.resolved.containerPath.join(".")})`;
12729
13129
  }
12730
- function hasYawMcpEntry(container) {
12731
- return ENTRY_NAME in container || LEGACY_ENTRY_NAMES.some((n) => n in container);
13130
+ function isWiredIn(view) {
13131
+ return view.entry() !== void 0 || view.legacyKey() !== null;
12732
13132
  }
12733
13133
  async function readContainer(ref) {
12734
- let raw;
12735
- try {
12736
- raw = await readFile14(ref.absolute, "utf8");
12737
- } catch {
12738
- return null;
13134
+ const where = displaySafe(ref.resolved.absolute);
13135
+ const view = await readClientConfigFile(ref);
13136
+ const read = view.read;
13137
+ if (read.kind === "absent") return { state: "none" };
13138
+ if (read.kind === "unreadable") {
13139
+ if (read.code === "EISDIR") {
13140
+ return {
13141
+ state: "refused",
13142
+ clause: `${where} is a directory, not a file`,
13143
+ installSays: `cannot read ${where}`,
13144
+ fix: (then) => `move or remove it, then ${then}`
13145
+ };
13146
+ }
13147
+ return {
13148
+ state: "refused",
13149
+ clause: `${where} could not be read (${displaySafe(read.message)})`,
13150
+ installSays: `cannot read ${where}`,
13151
+ fix: (then) => `check the file and its permissions, then ${then}`
13152
+ };
12739
13153
  }
12740
- let parsed;
12741
- try {
12742
- parsed = parseJsonc(raw);
12743
- } catch {
12744
- return null;
13154
+ if (read.kind === "malformed") {
13155
+ return {
13156
+ state: "refused",
13157
+ clause: read.reason === "root" ? `${where} is not a ${read.syntax} object` : `${where} is not valid ${read.syntax}`,
13158
+ installSays: `refuses to overwrite ${where}`,
13159
+ fix: unparseableConfigFix
13160
+ };
13161
+ }
13162
+ if (read.kind === "blocked") {
13163
+ if (!read.reparable) {
13164
+ const keyPath = `"${read.path.join(".")}" in ${where}`;
13165
+ return {
13166
+ state: "refused",
13167
+ clause: `${keyPath} is ${read.shape}, not a JSON object`,
13168
+ installSays: `refuses to overwrite ${keyPath}`,
13169
+ fix: blockedContainerFix
13170
+ };
13171
+ }
13172
+ return { state: "none" };
13173
+ }
13174
+ if (read.kind === "unspliceable") {
13175
+ const keyPath = `the "${read.key}" entry in ${where}`;
13176
+ return {
13177
+ state: "refused",
13178
+ clause: `${keyPath} is ${read.reason}`,
13179
+ installSays: `refuses to edit ${keyPath}`,
13180
+ fix: (then) => `rewrite that entry by hand, then ${then}`
13181
+ };
12745
13182
  }
12746
- let node = parsed;
12747
- for (const key of ref.containerPath) {
12748
- if (!node || typeof node !== "object" || Array.isArray(node)) return null;
12749
- node = node[key];
13183
+ const unloadable = view.unloadable();
13184
+ if (unloadable !== null) {
13185
+ return {
13186
+ state: "refused",
13187
+ clause: `${where} ${unloadableConfigProblem(unloadable)}`,
13188
+ installSays: `refuses to write into ${where}`,
13189
+ fix: unloadableConfigFix
13190
+ };
12750
13191
  }
12751
- return node && typeof node === "object" && !Array.isArray(node) ? node : null;
13192
+ const folded = classifyClientConfig(view.raw, ref, { containerPaths: driveCaseVariants(ref, view.raw) });
13193
+ const at = folded.read;
13194
+ if (at.kind !== "ok" || !at.containerPresent) return { state: "none" };
13195
+ return { state: "container", wired: isWiredIn(folded) };
13196
+ }
13197
+ function driveCaseVariants(site, raw) {
13198
+ return claudeCodeContainerPathVariants(site.resolved.containerPath, (prefix) => containerKeysAt(raw, site, prefix));
12752
13199
  }
12753
13200
  function parseImportArgs(argv) {
12754
13201
  if (argv.length === 0) return { ok: false, error: IMPORT_USAGE };
@@ -12805,14 +13252,15 @@ ${IMPORT_USAGE}`
12805
13252
  return { ok: false, error: `yaw-mcp import: expected exactly one client.
12806
13253
  ${IMPORT_USAGE}` };
12807
13254
  }
12808
- const clientId = positional[0];
12809
- if (!INSTALL_TARGETS.some((t) => t.clientId === clientId)) {
13255
+ const resolved = resolveClientArg("import", positional[0]);
13256
+ if (!resolved) {
12810
13257
  return {
12811
13258
  ok: false,
12812
- error: `yaw-mcp import: unknown client "${clientId}". Choose: ${INSTALL_TARGETS.map((t) => t.clientId).join(", ")}`
13259
+ error: `yaw-mcp import: unknown client "${positional[0]}". Choose: ${clientChoices("import").join(", ")}`
12813
13260
  };
12814
13261
  }
12815
- opts.clientId = clientId;
13262
+ opts.clientId = resolved.clientId;
13263
+ if (resolved.scope !== void 0 && opts.scope === void 0) opts.scope = resolved.scope;
12816
13264
  return { ok: true, options: opts };
12817
13265
  }
12818
13266
  function isInteractive3(opts) {
@@ -12851,53 +13299,58 @@ async function runImport(opts) {
12851
13299
  };
12852
13300
  print(`Source: ${target.label} (${site.scope})`);
12853
13301
  print(`File: ${displaySafe(resolved.absolute)}`);
12854
- let raw;
12855
- try {
12856
- raw = await readFile14(resolved.absolute, "utf8");
12857
- } catch (e) {
12858
- const code = e.code;
12859
- printErr(
12860
- code === "ENOENT" ? `yaw-mcp import: ${displaySafe(resolved.absolute)} does not exist -- ${target.label} has no MCP servers configured at this scope.` : `yaw-mcp import: cannot read ${displaySafe(resolved.absolute)}: ${e.message}`
12861
- );
13302
+ const targetSite = site.sites[0];
13303
+ const view = await readClientConfigFile(targetSite, { transform: target.entry });
13304
+ const read = view.read;
13305
+ if (read.kind === "unreadable") {
13306
+ printErr(`yaw-mcp import: cannot read ${displaySafe(resolved.absolute)}: ${read.message}`);
12862
13307
  return { exitCode: 1, written: [] };
12863
13308
  }
12864
- let parsed;
12865
- try {
12866
- parsed = parseJsonc(raw);
12867
- } catch (e) {
12868
- printErr(`yaw-mcp import: ${displaySafe(resolved.absolute)} is not valid JSON (${e.message}).`);
13309
+ if (read.kind === "absent") {
13310
+ printErr(
13311
+ view.raw === null ? `yaw-mcp import: ${displaySafe(resolved.absolute)} does not exist -- ${target.label} has no MCP servers configured at this scope.` : `yaw-mcp import: ${displaySafe(resolved.absolute)} is empty -- ${target.label} has no MCP servers configured at this scope.`
13312
+ );
12869
13313
  return { exitCode: 1, written: [] };
12870
13314
  }
12871
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
12872
- printErr(`yaw-mcp import: ${displaySafe(resolved.absolute)} is not a JSON object.`);
13315
+ if (read.kind === "malformed") {
13316
+ printErr(
13317
+ read.reason === "root" ? `yaw-mcp import: ${displaySafe(resolved.absolute)} is not a ${read.syntax} object.` : `yaw-mcp import: ${displaySafe(resolved.absolute)} is not valid ${read.syntax} (${read.detail}).`
13318
+ );
12873
13319
  return { exitCode: 1, written: [] };
12874
13320
  }
12875
- let container = parsed;
12876
- for (const key of resolved.containerPath) {
12877
- if (!container || typeof container !== "object" || Array.isArray(container)) {
12878
- container = void 0;
12879
- break;
13321
+ let source = null;
13322
+ let sourcePath = [...resolved.containerPath];
13323
+ for (const variantPath of driveCaseVariants(targetSite, view.raw)) {
13324
+ const at = classifyClientConfig(view.raw, siteAt(targetSite, variantPath), { transform: target.entry });
13325
+ if (at.read.kind !== "ok" || !at.read.containerPresent) continue;
13326
+ if (source === null || at.count() > 0) {
13327
+ source = at;
13328
+ sourcePath = variantPath;
12880
13329
  }
12881
- container = container[key];
13330
+ if (at.count() > 0) break;
12882
13331
  }
12883
- if (!container || typeof container !== "object" || Array.isArray(container)) {
13332
+ if (source === null) {
12884
13333
  print(`
12885
13334
  Nothing to import: no "${resolved.containerPath.join(".")}" object in ${displaySafe(resolved.absolute)}.`);
12886
13335
  return { exitCode: 0, written: [] };
12887
13336
  }
12888
13337
  const isVsCode = target.clientId === "vscode";
12889
13338
  const vars = isVsCode ? { workspaceFolder: site.projectDir } : null;
12890
- const inputs = isVsCode ? readVsCodeInputs(parsed) : /* @__PURE__ */ new Map();
13339
+ const inputs = isVsCode ? readVsCodeInputs(view.raw ?? "") : /* @__PURE__ */ new Map();
12891
13340
  const candidates = [];
12892
13341
  const skippedSelf = [];
12893
13342
  const unusable = [];
12894
13343
  const unresolvable = [];
12895
- for (const [key, value] of Object.entries(container)) {
13344
+ for (const { key, value } of source.entries()) {
12896
13345
  if (isSelfEntry(key)) {
12897
13346
  skippedSelf.push(key);
12898
13347
  continue;
12899
13348
  }
12900
- const built = toEntry(key, value, vars);
13349
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
13350
+ unusable.push(key);
13351
+ continue;
13352
+ }
13353
+ const built = toEntry(key, importViewOf(value, target.entry).entry, vars);
12901
13354
  if (!built) {
12902
13355
  unusable.push(key);
12903
13356
  continue;
@@ -13036,39 +13489,55 @@ If the previous entry was a different server you meant to keep, restore it from
13036
13489
  print(`Left ${displaySafe(resolved.absolute)} alone (--keep-originals).`);
13037
13490
  return { exitCode: 0, written };
13038
13491
  }
13039
- const searched = [{ absolute: resolved.absolute, containerPath: resolved.containerPath }];
13492
+ const searched = [siteAt(targetSite, sourcePath)];
13493
+ let installRef = site.scope === "user" ? searched[0] : null;
13040
13494
  for (const spec of target.scopes) {
13041
13495
  if (spec.scope === site.scope) continue;
13042
13496
  try {
13043
- const other = resolveInstallPath({
13497
+ const others = resolveInstallSites({
13044
13498
  clientId: target.clientId,
13045
13499
  scope: spec.scope,
13046
13500
  os: site.os,
13047
13501
  home,
13048
13502
  appData: resolveAppDataDir({ appData: opts.appData, home }),
13503
+ // Same env the target scope resolved with, so an env-redirected client
13504
+ // is searched at its REAL other-scope path rather than the default one.
13505
+ clientEnv: opts.clientEnv,
13049
13506
  // The project the user is standing in -- the same resolution
13050
13507
  // resolveInstallSite would have made had that scope been the target.
13051
13508
  projectDir: spec.requiresProjectDir ? site.projectDir ?? resolvePath(opts.cwd ?? process.cwd(), ".") : void 0,
13052
13509
  claudeConfigDir: opts.claudeConfigDir
13053
13510
  });
13054
- const already = searched.some(
13055
- (r) => r.absolute === other.absolute && r.containerPath.join(".") === other.containerPath.join(".")
13056
- );
13057
- if (!already) searched.push({ absolute: other.absolute, containerPath: other.containerPath });
13511
+ for (const other of others) {
13512
+ const already = searched.find(
13513
+ (r) => r.resolved.absolute === other.resolved.absolute && r.resolved.containerPath.join(".") === other.resolved.containerPath.join(".")
13514
+ );
13515
+ const ref = already ?? other;
13516
+ if (!already) searched.push(ref);
13517
+ if (spec.scope === "user" && installRef === null) installRef = ref;
13518
+ }
13058
13519
  } catch {
13059
13520
  }
13060
13521
  }
13061
13522
  let wiredIn = null;
13523
+ const refused = /* @__PURE__ */ new Map();
13062
13524
  for (let i = 0; i < searched.length; i++) {
13063
- const found = i === 0 ? container : await readContainer(searched[i]);
13064
- if (found && hasYawMcpEntry(found)) {
13525
+ const read2 = i === 0 ? { state: "container", wired: isWiredIn(source) } : await readContainer(searched[i]);
13526
+ if (read2.state === "container" && read2.wired) {
13065
13527
  wiredIn = searched[i];
13066
13528
  break;
13067
13529
  }
13530
+ if (read2.state === "refused") refused.set(searched[i], read2);
13068
13531
  }
13069
13532
  if (!wiredIn) {
13533
+ const noEntry = searched.filter((r) => !refused.has(r));
13534
+ const clauses = [`no yaw-mcp entry in ${noEntry.map(describeContainer2).join(" or ")}`];
13535
+ for (const r of refused.values()) if (!clauses.includes(r.clause)) clauses.push(r.clause);
13536
+ const installCmd = `yaw-mcp install ${target.clientId}`;
13537
+ const blocking = installRef ? refused.get(installRef) : void 0;
13538
+ const next2 = blocking ? `\`${installCmd}\` ${blocking.installSays}; ${blocking.fix(`run \`${installCmd}\` and re-run this with --remove-originals`)}.` : `Run \`${installCmd}\` first, then re-run this with --remove-originals.`;
13070
13539
  printErr(
13071
- `Not removing the originals: no yaw-mcp entry in ${searched.map(describeContainer2).join(" or ")}, so ${target.label} would be left with no way to reach them. Run \`yaw-mcp install ${target.clientId}\` first, then re-run this with --remove-originals.`
13540
+ `Not removing the originals: ${clauses.join(", and ")}, so ${target.label} would be left with no way to reach them. ${next2}`
13072
13541
  );
13073
13542
  return { exitCode: 0, written };
13074
13543
  }
@@ -13095,12 +13564,15 @@ If the previous entry was a different server you meant to keep, restore it from
13095
13564
  return { exitCode: 0, written };
13096
13565
  }
13097
13566
  }
13098
- let next = raw;
13567
+ const removalSite = siteAt(targetSite, sourcePath);
13568
+ let next = view.raw ?? "";
13099
13569
  let removed = 0;
13100
13570
  const unremovable = [];
13101
13571
  for (const r of imported) {
13102
13572
  try {
13103
- const after = removeJsoncEntry(next, resolved.containerPath, r.candidate.key);
13573
+ const at = classifyClientConfig(next, removalSite, { transform: target.entry });
13574
+ const edits = [{ op: "remove", key: r.candidate.key }];
13575
+ const after = applyClientConfigEdits(at, edits, removalSite);
13104
13576
  if (after !== next) removed++;
13105
13577
  next = after;
13106
13578
  } catch (e) {
@@ -13119,8 +13591,7 @@ If the previous entry was a different server you meant to keep, restore it from
13119
13591
  return { exitCode: 0, written };
13120
13592
  }
13121
13593
  try {
13122
- await atomicWriteFile(resolved.absolute, next.endsWith("\n") ? next : `${next}
13123
- `);
13594
+ await atomicWriteFile(resolved.absolute, terminateWithNewline(next));
13124
13595
  } catch (e) {
13125
13596
  printErr(
13126
13597
  `yaw-mcp import: could not write ${displaySafe(resolved.absolute)} (${e.message}). It was left unchanged; the servers are imported either way.`
@@ -13135,7 +13606,7 @@ If the previous entry was a different server you meant to keep, restore it from
13135
13606
  }
13136
13607
 
13137
13608
  // src/local-add-cmd.ts
13138
- import { readFile as readFile15 } from "fs/promises";
13609
+ import { readFile as readFile14 } from "fs/promises";
13139
13610
  import { homedir as homedir19 } from "os";
13140
13611
  import { createInterface as createInterface4 } from "readline/promises";
13141
13612
  var ADD_USAGE = `Usage: yaw-mcp add <slug> [flags]
@@ -13369,18 +13840,26 @@ async function printPostWriteNotes(printErr, opts) {
13369
13840
  }
13370
13841
  }
13371
13842
  async function anyClientWiredToYawMcp(home, cwd, env, appData) {
13843
+ const clientEnv2 = readClientEnv(env);
13372
13844
  try {
13373
13845
  const probes = await probeClientsAsync({
13374
13846
  home,
13375
13847
  os: CURRENT_OS,
13376
13848
  cwd,
13377
- // CLAUDE_CONFIG_DIR relocates claude-code's file; `appData` is resolved
13378
- // by the caller (see runAdd) because choosing between the ambient
13379
- // %APPDATA% and a home-derived one is a caller's job -- resolving it
13380
- // from the ALREADY-defaulted home here would pin every real run to
13381
- // <home>\AppData\Roaming and miss a redirected profile, which is the
13382
- // exact split resolveAppDataDir exists to prevent.
13383
- claudeConfigDir: env.CLAUDE_CONFIG_DIR && env.CLAUDE_CONFIG_DIR.length > 0 ? env.CLAUDE_CONFIG_DIR : void 0,
13849
+ // Every client env var comes from `readClientEnv`, the ONE reader of
13850
+ // those names -- not from a `process.env.X` of this module's own, which
13851
+ // is how two commands came to disagree about whether an EMPTY value
13852
+ // counts as set. CLAUDE_CONFIG_DIR relocates claude-code's file; the
13853
+ // rest are read for the clients that have one, so a Continue- or
13854
+ // Cline-only user stops getting a false "nothing is wired" nudge.
13855
+ //
13856
+ // `appData` stays resolved by the CALLER (see runAdd): choosing between
13857
+ // the ambient %APPDATA% and a home-derived one is a caller's job --
13858
+ // resolving it from the ALREADY-defaulted home here would pin every
13859
+ // real run to <home>\AppData\Roaming and miss a redirected profile,
13860
+ // which is the exact split resolveAppDataDir exists to prevent.
13861
+ claudeConfigDir: clientEnv2.claudeConfigDir,
13862
+ clientEnv: clientEnv2,
13384
13863
  appData
13385
13864
  });
13386
13865
  return probes.some((p) => p.hasMcpEntry);
@@ -13682,7 +14161,7 @@ ${REMOVE_USAGE}` };
13682
14161
  async function readRawServers(path6) {
13683
14162
  let raw;
13684
14163
  try {
13685
- raw = await readFile15(path6, "utf8");
14164
+ raw = await readFile14(path6, "utf8");
13686
14165
  } catch {
13687
14166
  return null;
13688
14167
  }
@@ -13954,7 +14433,7 @@ ${servers.length} server${servers.length === 1 ? "" : "s"} in ${loaded.path}`);
13954
14433
 
13955
14434
  // src/local-set-cmd.ts
13956
14435
  import { existsSync as existsSync7 } from "fs";
13957
- import { readFile as readFile16 } from "fs/promises";
14436
+ import { readFile as readFile15 } from "fs/promises";
13958
14437
  import { homedir as homedir20 } from "os";
13959
14438
  import { createInterface as createInterface5 } from "readline/promises";
13960
14439
  var SET_USAGE = `Usage: yaw-mcp set <slug-or-namespace> <key=value> [<key=value> ...] [flags]
@@ -14179,7 +14658,7 @@ async function runSet(opts) {
14179
14658
  return withBundlesLock(home, async () => {
14180
14659
  let rawText;
14181
14660
  try {
14182
- rawText = await readFile16(path6, "utf8");
14661
+ rawText = await readFile15(path6, "utf8");
14183
14662
  } catch (e) {
14184
14663
  if (e.code === "EISDIR") {
14185
14664
  printErr(`yaw-mcp ${verb}: ${path6} is a directory, not a file -- move or remove it, then re-run.`);
@@ -15220,12 +15699,12 @@ function pushToolCall(history, record, limit = HISTORY_LIMIT) {
15220
15699
 
15221
15700
  // src/install-nudge.ts
15222
15701
  import { existsSync as existsSync9, mkdirSync as mkdirSync3, readFileSync as readFileSync6, statSync as statSync3, writeFileSync as writeFileSync2 } from "fs";
15223
- import { dirname as dirname7, join as join14 } from "path";
15702
+ import { dirname as dirname8, join as join15 } from "path";
15224
15703
  var INSTALL_NUDGE_MIN_COUNT = 5;
15225
15704
  var INSTALL_NUDGE_COOLDOWN_MS = 7 * 24 * 60 * 60 * 1e3;
15226
15705
  var INSTALL_NUDGE_STATE_FILENAME = "install-nudge-state.json";
15227
15706
  function installNudgeStatePath(home) {
15228
- return join14(home, CONFIG_DIRNAME, INSTALL_NUDGE_STATE_FILENAME);
15707
+ return join15(home, CONFIG_DIRNAME, INSTALL_NUDGE_STATE_FILENAME);
15229
15708
  }
15230
15709
  function installNudgeEnabled(env, config) {
15231
15710
  if (env.YAW_MCP_INSTALL_NUDGE === "1") return true;
@@ -15282,7 +15761,7 @@ function recordNudges(clis, home, now = Date.now) {
15282
15761
  const kept = state.nudges.filter((n) => !recorded.has(n.cli) && at - clampToNow(n.nudgedAt, at) < INSTALL_NUDGE_COOLDOWN_MS).map((n) => ({ cli: n.cli, nudgedAt: clampToNow(n.nudgedAt, at) }));
15283
15762
  for (const cli of recorded) kept.push({ cli, nudgedAt: at });
15284
15763
  const path6 = installNudgeStatePath(home);
15285
- mkdirSync3(dirname7(path6), { recursive: true });
15764
+ mkdirSync3(dirname8(path6), { recursive: true });
15286
15765
  writeFileSync2(path6, `${JSON.stringify({ nudges: kept }, null, 2)}
15287
15766
  `, "utf8");
15288
15767
  try {
@@ -17243,7 +17722,7 @@ var ConnectServer = class _ConnectServer {
17243
17722
  static SHUTDOWN_DRAIN_MS = 2e3;
17244
17723
  constructor() {
17245
17724
  this.server = new Server(
17246
- { name: "yaw-mcp", version: true ? "1.0.0" : "dev" },
17725
+ { name: "yaw-mcp", version: true ? "1.0.2" : "dev" },
17247
17726
  {
17248
17727
  capabilities: {
17249
17728
  tools: { listChanged: true },
@@ -20646,7 +21125,7 @@ function registerShutdownTriggers(shutdown, targets) {
20646
21125
  // src/status-cmd.ts
20647
21126
  import { existsSync as existsSync10 } from "fs";
20648
21127
  import { homedir as homedir23 } from "os";
20649
- var VERSION2 = true ? "1.0.0" : "dev";
21128
+ var VERSION2 = true ? "1.0.2" : "dev";
20650
21129
  var STATUS_SCHEMA_VERSION = 1;
20651
21130
  var STATUS_USAGE = `Usage: yaw-mcp status [--json]
20652
21131
 
@@ -20866,6 +21345,25 @@ function suggestFlag(input, limit = 2) {
20866
21345
  }
20867
21346
 
20868
21347
  // src/index.ts
21348
+ var HELP_INDENT = " ".repeat(29);
21349
+ function wrapHelpList(parts, width = 80) {
21350
+ const lines = [];
21351
+ let current = "";
21352
+ parts.forEach((part, i) => {
21353
+ const last = i === parts.length - 1;
21354
+ const piece = last ? part : `${part},`;
21355
+ const candidate = current === "" ? piece : `${current} ${piece}`;
21356
+ if (HELP_INDENT.length + candidate.length + (last ? 1 : 0) > width && current !== "") {
21357
+ lines.push(current);
21358
+ current = piece;
21359
+ } else {
21360
+ current = candidate;
21361
+ }
21362
+ });
21363
+ lines.push(current);
21364
+ return lines.join(`
21365
+ ${HELP_INDENT}`);
21366
+ }
20869
21367
  function dispatch(cmd, p) {
20870
21368
  p.then((r) => {
20871
21369
  process.exitCode = typeof r === "number" ? r : r.exitCode;
@@ -20886,6 +21384,7 @@ function run(cmd, parsed, runner) {
20886
21384
  dispatch(cmd, runner(parsed.options));
20887
21385
  }
20888
21386
  var subcommand = process.argv[2];
21387
+ var clientEnv = readClientEnv(process.env);
20889
21388
  if (subcommand !== void 0) setLogSurface("cli");
20890
21389
  if (subcommand === "compliance") {
20891
21390
  dispatch("compliance", runComplianceCommand(process.argv.slice(3)));
@@ -20900,15 +21399,17 @@ if (subcommand === "compliance") {
20900
21399
  `);
20901
21400
  process.exitCode = 0;
20902
21401
  } else {
20903
- const claudeConfigDir = process.env.CLAUDE_CONFIG_DIR && process.env.CLAUDE_CONFIG_DIR.length > 0 ? process.env.CLAUDE_CONFIG_DIR : void 0;
20904
- run("install", parsed, (options) => runInstall({ ...options, claudeConfigDir }));
21402
+ run(
21403
+ "install",
21404
+ parsed,
21405
+ (options) => runInstall({ ...options, claudeConfigDir: clientEnv.claudeConfigDir, clientEnv })
21406
+ );
20905
21407
  }
20906
21408
  } else if (subcommand === "uninstall") {
20907
- const claudeConfigDir = process.env.CLAUDE_CONFIG_DIR && process.env.CLAUDE_CONFIG_DIR.length > 0 ? process.env.CLAUDE_CONFIG_DIR : void 0;
20908
21409
  run(
20909
21410
  "uninstall",
20910
21411
  parseUninstallArgs(process.argv.slice(3)),
20911
- (options) => runUninstall({ ...options, claudeConfigDir })
21412
+ (options) => runUninstall({ ...options, claudeConfigDir: clientEnv.claudeConfigDir, clientEnv })
20912
21413
  );
20913
21414
  } else if (subcommand === "doctor") {
20914
21415
  run("doctor", parseDoctorArgs(process.argv.slice(3)), runDoctor);
@@ -20942,8 +21443,11 @@ if (subcommand === "compliance") {
20942
21443
  } else if (subcommand === "remove") {
20943
21444
  run("remove", parseRemoveArgs(process.argv.slice(3)), runRemove);
20944
21445
  } else if (subcommand === "import") {
20945
- const claudeConfigDir = process.env.CLAUDE_CONFIG_DIR && process.env.CLAUDE_CONFIG_DIR.length > 0 ? process.env.CLAUDE_CONFIG_DIR : void 0;
20946
- run("import", parseImportArgs(process.argv.slice(3)), (options) => runImport({ ...options, claudeConfigDir }));
21446
+ run(
21447
+ "import",
21448
+ parseImportArgs(process.argv.slice(3)),
21449
+ (options) => runImport({ ...options, claudeConfigDir: clientEnv.claudeConfigDir, clientEnv })
21450
+ );
20947
21451
  } else if (subcommand === "call") {
20948
21452
  run("call", parseCallArgs(process.argv.slice(3)), runCall);
20949
21453
  } else if (subcommand === "search") {
@@ -20973,18 +21477,41 @@ if (subcommand === "compliance") {
20973
21477
  install <client> Connect one MCP client to yaw-mcp. This wires the
20974
21478
  aggregator into the client; it does NOT add a
20975
21479
  server (for that, see \`add\` below). <client> is
20976
- one of: claude-code, claude-desktop, cursor, vscode,
20977
- windsurf, gemini-cli.
21480
+ one of: ${wrapHelpList(clientChoices("install"))}.
20978
21481
  install --list Show every MCP client config location on this
20979
21482
  machine and whether yaw-mcp is wired into each.
20980
21483
  The STATUS column is about YAW-MCP, not about the
20981
- client: \`installed\` means yaw-mcp is configured
20982
- in that file, \`other-entries\` that the file
20983
- exists with other servers in it, \`not installed\`
20984
- that the file is absent (read-only; no writes).
20985
- install --all Configure every installed MCP client in one go.
21484
+ client, and about the one server list that row
21485
+ reads in its file (Claude Code's user and local
21486
+ rows read the same .claude.json, each its own
21487
+ list): \`installed\` means yaw-mcp is in that list,
21488
+ \`other-entries\` that the list holds other
21489
+ servers, \`no-entries\` that the file exists but
21490
+ has no server in that list, \`not installed\` that
21491
+ the file is absent, \`legacy: <key>\` that the only
21492
+ yaw-mcp wiring there is a pre-rename entry,
21493
+ \`malformed\` that the file does not parse,
21494
+ \`not loading (comments or trailing commas)\`
21495
+ that the file parses for yaw-mcp but its client
21496
+ reads it as invalid JSON and so loads no server
21497
+ from it, whatever the list holds,
21498
+ \`unreadable: <reason>\` that its bytes could not
21499
+ be read, and \`not supported yet\` that yaw-mcp
21500
+ cannot configure that client on this OS. An
21501
+ \`installed\` or \`legacy\` row can add \`(other
21502
+ drive case)\`, for a Claude Code local-scope entry
21503
+ an older version left under the other
21504
+ drive-letter spelling of this directory
21505
+ (read-only; no writes).
21506
+ install --all Install into every client yaw-mcp supports on this
21507
+ OS. It plans from that list, not from a probe of
21508
+ what you have installed (--list is the detecting
21509
+ one), so it may create a config for a client that
21510
+ is not on this machine.
20986
21511
  uninstall <client> Unwire a client: removes the yaw-mcp entry (and,
20987
- for Claude Code, its permissions.allow grant).
21512
+ for Claude Code and typed, the permissions.allow
21513
+ grant they share -- kept, and named, while the
21514
+ other still has its entry).
20988
21515
  Your servers in bundles.json are untouched.
20989
21516
 
20990
21517
  Local servers (no account):
@@ -21046,8 +21573,6 @@ if (subcommand === "compliance") {
21046
21573
  poll it. \`--json\` is the machine-readable form.
21047
21574
  doctor Diagnose setup: config, token, clients, learning,
21048
21575
  upgrade, flaky-namespace reliability rollup.
21049
- servers [<filter>] DEPRECATED -- account mode is gone; this always
21050
- fails. Use \`list\` instead.
21051
21576
  bundles [list|match] Browse curated multi-server bundles. \`list\` shows
21052
21577
  all; \`match\` partitions against your enabled
21053
21578
  local servers (ready vs. partially installed).
@@ -21263,8 +21788,68 @@ if (subcommand === "compliance") {
21263
21788
  \`install\`, \`try\` and \`doctor\` whenever they
21264
21789
  locate Claude Code's config, so a non-default
21265
21790
  location is read and written instead of
21266
- ~/.claude. It is Claude Code's knob, not
21791
+ ~/.claude. It also decides which settings.json
21792
+ \`install typed\` adds the permissions.allow
21793
+ grant to, since typed reads that same file;
21794
+ typed's own ~/.config/typed/mcp.json does not
21795
+ follow it, so that grant is scoped to the
21796
+ directory, and install and uninstall say so --
21797
+ except in a Yaw Mode pane, where YAW_MODE
21798
+ (below) decides. It is Claude Code's knob, not
21267
21799
  yaw-mcp's; the server itself never reads it.
21800
+ APPDATA Windows' roaming app-data directory, honored
21801
+ by \`install\`, \`try\`, \`doctor\` and
21802
+ \`install --list\` when they locate a config
21803
+ under it (Claude Desktop, VS Code, Zed, and
21804
+ Cline's per-editor copies). Read once, so all
21805
+ four agree even where it is redirected away
21806
+ from %USERPROFILE%\\AppData\\Roaming.
21807
+ XDG_CONFIG_HOME Honored by the same four commands when they
21808
+ locate Zed's settings.json on Linux, and only
21809
+ when it is ABSOLUTE -- the rule Zed inherits
21810
+ from the dirs crate it resolves paths with. The
21811
+ Flatpak build reads
21812
+ $FLATPAK_XDG_CONFIG_HOME instead, which
21813
+ yaw-mcp does not follow.
21814
+ CLINE_MCP_SETTINGS_PATH Cline's own three knobs, in this precedence,
21815
+ CLINE_DATA_DIR honored by the same four commands when they
21816
+ CLINE_DIR locate Cline's shared cline_mcp_settings.json:
21817
+ the first names the FILE, the second its data
21818
+ directory, the third the directory above that.
21819
+ Cline's per-editor copies are found by probing
21820
+ and are not affected.
21821
+ CONTINUE_GLOBAL_DIR Continue's global directory, honored by the
21822
+ same four commands when they locate
21823
+ <dir>/mcpServers/yaw-mcp.json. A relative value
21824
+ is resolved against the current directory, as
21825
+ Continue's own IDE core does -- note that
21826
+ resolves against ITS working directory, not
21827
+ this one, so an absolute value is safer.
21828
+ CODEX_HOME Codex's own state directory, honored by the
21829
+ same four commands when they locate
21830
+ <dir>/config.toml (it defaults to ~/.codex).
21831
+ Codex requires the directory to EXIST and be a
21832
+ directory; an empty value counts as unset. It
21833
+ does not move a project's .codex/config.toml.
21834
+ TYPED_CLI_BUNDLE The typed CLI bundle typed's launcher runs
21835
+ (default ~/.config/typed/typed-cli/cli.mjs).
21836
+ \`install typed\` reads that file and warns once
21837
+ when it predates ~/.config/typed/mcp.json; it
21838
+ says nothing when no bundle is there. It does
21839
+ not move typed's mcp.json.
21840
+ YAW_MODE Set by Yaw Terminal in a Yaw Mode pane
21841
+ (\`augment\` or \`fresh\`), whose
21842
+ CLAUDE_CONFIG_DIR is a per-pane overlay that
21843
+ does not keep its settings.json. With both set,
21844
+ and CLAUDE_CONFIG_DIR a directory named
21845
+ yaw-mode-* as Yaw names its overlays, \`install\`
21846
+ and \`uninstall\` of Claude Code or typed at user
21847
+ scope also add or remove the permissions.allow
21848
+ grant in ~/.claude/settings.json (augment). In
21849
+ a fresh pane only \`install\` says anything: a
21850
+ note that what it wrote there goes with the
21851
+ pane. A config dir of any other name is
21852
+ handled as outside Yaw.
21268
21853
  LOG_LEVEL Verbosity of yaw-mcp's own JSON log lines on
21269
21854
  stderr: \`debug\` | \`info\` | \`warn\` | \`error\`
21270
21855
  (default info). \`debug\` is what to set when
@@ -21292,7 +21877,7 @@ if (subcommand === "compliance") {
21292
21877
  `);
21293
21878
  process.exitCode = 0;
21294
21879
  } else if (subcommand === "--version" || subcommand === "-V") {
21295
- process.stdout.write(`yaw-mcp ${true ? "1.0.0" : "dev"}
21880
+ process.stdout.write(`yaw-mcp ${true ? "1.0.2" : "dev"}
21296
21881
  `);
21297
21882
  process.exitCode = 0;
21298
21883
  } else if (subcommand !== void 0 && !subcommand.startsWith("-")) {