xclaude-cli 0.1.4 → 0.2.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.
Files changed (3) hide show
  1. package/README.md +9 -4
  2. package/dist/xclaude.js +1082 -479
  3. package/package.json +1 -1
package/dist/xclaude.js CHANGED
@@ -98,6 +98,7 @@ function resolvePaths(env) {
98
98
  cache: path.join(xhome, "cache"),
99
99
  shell: path.join(xhome, "shell"),
100
100
  locks: path.join(xhome, "locks"),
101
+ inherit: path.join(xhome, "inherit"),
101
102
  accounts: path.join(xhome, "accounts")
102
103
  };
103
104
  }
@@ -309,7 +310,8 @@ var SWITCHES = {
309
310
  spawnFallback: false,
310
311
  linkIde: false,
311
312
  normalizePaths: false,
312
- keepSameEmailLogin: false
313
+ keepSameEmailLogin: false,
314
+ memoryInStore: true
313
315
  };
314
316
  function loadSwitches(env) {
315
317
  const switches = { ...SWITCHES };
@@ -338,7 +340,7 @@ function processCtx(io) {
338
340
  }
339
341
 
340
342
  // src/commands/add.ts
341
- import fs15 from "node:fs";
343
+ import fs18 from "node:fs";
342
344
 
343
345
  // src/claude/auth.ts
344
346
  import { execFile } from "node:child_process";
@@ -361,16 +363,29 @@ async function authStatus(claude, env) {
361
363
  email: str(json.email),
362
364
  orgId: str(json.orgId),
363
365
  orgName: str(json.orgName),
366
+ method: str(json.authMethod),
364
367
  error: null
365
368
  };
366
369
  } catch {
367
370
  const why = (res.stderr || res.stdout).trim().split("\n")[0] || `exit code ${res.code}`;
368
- return { loggedIn: false, email: null, orgId: null, orgName: null, error: why };
371
+ return { loggedIn: false, email: null, orgId: null, orgName: null, method: null, error: why };
369
372
  }
370
373
  }
374
+ var NOT_A_LOGIN = {
375
+ oauth_token: "a token",
376
+ api_key: "an API key",
377
+ api_key_helper: "apiKeyHelper",
378
+ third_party: "a cloud provider"
379
+ };
380
+ function otherCredential(s) {
381
+ if (s.error || !s.loggedIn || s.method === null) return null;
382
+ return NOT_A_LOGIN[s.method] ?? null;
383
+ }
371
384
  function describeLogin(s) {
372
385
  if (s.error) return `unknown (${s.error})`;
373
386
  if (!s.loggedIn) return "not logged in";
387
+ const other = otherCredential(s);
388
+ if (other) return s.email ? `${other} (${s.email})` : other;
374
389
  const who = s.email ?? "logged in";
375
390
  return s.orgName ? `${who} (${s.orgName})` : who;
376
391
  }
@@ -447,6 +462,15 @@ function writeFileAtomic(path_, data, opts = {}) {
447
462
  throw e;
448
463
  }
449
464
  }
465
+ function stampOf(st) {
466
+ return st ? { mtimeMs: st.mtimeMs, size: st.size, ino: st.ino } : null;
467
+ }
468
+ function writeIfUnchanged(file, text, seen) {
469
+ const st = lstatOrNull(file);
470
+ const unchanged = seen ? st !== null && st.mtimeMs === seen.mtimeMs && st.size === seen.size && st.ino === seen.ino : st === null;
471
+ if (unchanged) writeFileAtomic(file, text);
472
+ return unchanged;
473
+ }
450
474
  function removeTree(p) {
451
475
  const st = lstatOrNull(p);
452
476
  if (!st) return;
@@ -553,6 +577,7 @@ var isStringArray = (v) => Array.isArray(v) && v.every((x) => typeof x === "stri
553
577
  var isEffortOrNull = (v) => v === null || typeof v === "string" && isEffort(v);
554
578
  function parseDefaults(raw, where) {
555
579
  if (!isObject(raw)) throw new ConfigProblem(`${where.replace(/\.$/, "")} must be an object`);
580
+ field(raw, "inherit", where, true, isBool, "true or false");
556
581
  return {
557
582
  ...raw,
558
583
  model: field(raw, "model", where, null, isStringOrNull, "a model name or null"),
@@ -637,6 +662,9 @@ function identities(config) {
637
662
  if (config.main.enabled) names.push(MAIN);
638
663
  return names;
639
664
  }
665
+ function inherits(config, name) {
666
+ return name !== MAIN && Object.hasOwn(config.accounts, name) && config.accounts[name].inherit === true;
667
+ }
640
668
  function defaultsOf(config, name) {
641
669
  if (name === MAIN) return config.main.enabled ? config.main : null;
642
670
  return Object.hasOwn(config.accounts, name) ? config.accounts[name] : null;
@@ -685,20 +713,147 @@ function stringOption(p, name) {
685
713
  }
686
714
 
687
715
  // src/launch/env.ts
716
+ function sharedMemoryDir(paths, table, switches) {
717
+ if (!switches.memoryInStore) return null;
718
+ return table.dirs.includes("projects") && table.dirs.includes("agent-memory") ? paths.store : null;
719
+ }
720
+ var LOGIN_VARS = [
721
+ "CLAUDE_CODE_OAUTH_TOKEN",
722
+ "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR",
723
+ "CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
724
+ "CLAUDE_CODE_OAUTH_SCOPES"
725
+ ];
726
+ var CREDENTIAL_VARS = [
727
+ "ANTHROPIC_API_KEY",
728
+ "ANTHROPIC_AUTH_TOKEN",
729
+ "CLAUDE_CODE_USE_BEDROCK",
730
+ "CLAUDE_CODE_USE_VERTEX",
731
+ "CLAUDE_CODE_USE_FOUNDRY",
732
+ "ANTHROPIC_PROFILE"
733
+ ];
734
+ function setIn(env, names) {
735
+ return names.filter((name) => {
736
+ const value = env[name];
737
+ return value !== void 0 && value !== "" && !/^(0|false|no|off)$/i.test(value);
738
+ });
739
+ }
688
740
  function buildEnv(base, identity) {
689
741
  const env = {};
690
742
  for (const [k, v] of Object.entries(base)) if (v !== void 0) env[k] = v;
691
- if (identity.configDir) env.CLAUDE_CONFIG_DIR = identity.configDir;
692
- else delete env.CLAUDE_CONFIG_DIR;
743
+ if (identity.configDir) {
744
+ env.CLAUDE_CONFIG_DIR = identity.configDir;
745
+ for (const name of LOGIN_VARS) delete env[name];
746
+ if (identity.memoryDir && !env.CLAUDE_CODE_REMOTE_MEMORY_DIR) env.CLAUDE_CODE_REMOTE_MEMORY_DIR = identity.memoryDir;
747
+ } else {
748
+ delete env.CLAUDE_CONFIG_DIR;
749
+ if (identity.memoryDir && env.CLAUDE_CODE_REMOTE_MEMORY_DIR === identity.memoryDir) delete env.CLAUDE_CODE_REMOTE_MEMORY_DIR;
750
+ }
693
751
  delete env.CLAUDE_SECURESTORAGE_CONFIG_DIR;
694
752
  env.XCLAUDE_ACCOUNT = identity.name;
695
753
  return env;
696
754
  }
697
755
  function identityEnv(ctx, name) {
698
- return buildEnv(ctx.env, { name, configDir: name === MAIN ? null : accountDir(ctx.paths, name) });
756
+ return buildEnv(ctx.env, { name, configDir: name === MAIN ? null : accountDir(ctx.paths, name), memoryDir: null });
757
+ }
758
+ function joined(names) {
759
+ return names.length > 1 ? `${names.slice(0, -1).join(", ")} and ${names.at(-1)}` : names.join("");
760
+ }
761
+ function takeCredentialNotes(state, account, env) {
762
+ const told = new Set(state.credentialNoted[account] ?? []);
763
+ const dropped = setIn(env, LOGIN_VARS).filter((name) => !told.has(name));
764
+ const others = setIn(env, CREDENTIAL_VARS).filter((name) => !told.has(name));
765
+ const lines = [];
766
+ if (dropped.length) {
767
+ const [is, it] = dropped.length === 1 ? ["is", "it"] : ["are", "them"];
768
+ lines.push(`xclaude: ${account} signs in with its own login, so ${joined(dropped)} from your shell ${is} left out (plain claude still gets ${it})`);
769
+ }
770
+ if (others.length) {
771
+ const [is, it] = others.length === 1 ? ["is", "it"] : ["are", "them"];
772
+ lines.push(`xclaude: ${joined(others)} ${is} set in your shell, so Claude Code may use ${it} instead of ${account}'s own login (/status shows which)`);
773
+ }
774
+ if (lines.length) state.credentialNoted[account] = [...told, ...dropped, ...others].sort();
775
+ return lines;
699
776
  }
700
777
 
701
- // src/link/plugins.ts
778
+ // src/core/state.ts
779
+ var MAX_DIRS = 500;
780
+ function emptyState() {
781
+ return {
782
+ installedVersion: null,
783
+ lastAccountByDir: {},
784
+ lastUsedAccount: null,
785
+ seenUnknownEntries: {},
786
+ listedPlugins: {},
787
+ turnedOnPlugins: {},
788
+ inheritNoted: [],
789
+ credentialNoted: {}
790
+ };
791
+ }
792
+ function isRecord(v) {
793
+ return typeof v === "object" && v !== null && !Array.isArray(v);
794
+ }
795
+ function loadState(paths) {
796
+ let raw;
797
+ try {
798
+ raw = JSON.parse(readFileOrNull(paths.state) ?? "{}");
799
+ } catch {
800
+ return emptyState();
801
+ }
802
+ const state = emptyState();
803
+ if (!isRecord(raw)) return state;
804
+ if (typeof raw.installedVersion === "string") state.installedVersion = raw.installedVersion;
805
+ if (typeof raw.lastUsedAccount === "string") state.lastUsedAccount = raw.lastUsedAccount;
806
+ if (isRecord(raw.lastAccountByDir)) {
807
+ for (const [dir, name] of Object.entries(raw.lastAccountByDir)) {
808
+ if (typeof name === "string") state.lastAccountByDir[dir] = name;
809
+ }
810
+ }
811
+ if (isRecord(raw.seenUnknownEntries)) {
812
+ for (const [name, entries] of Object.entries(raw.seenUnknownEntries)) {
813
+ if (Array.isArray(entries)) state.seenUnknownEntries[name] = entries.filter((e) => typeof e === "string");
814
+ }
815
+ }
816
+ for (const key of ["listedPlugins", "turnedOnPlugins", "credentialNoted"]) {
817
+ const lists = raw[key];
818
+ if (!isRecord(lists)) continue;
819
+ for (const [name, ids] of Object.entries(lists)) {
820
+ if (Array.isArray(ids)) state[key][name] = ids.filter((id) => typeof id === "string");
821
+ }
822
+ }
823
+ if (Array.isArray(raw.inheritNoted)) state.inheritNoted = raw.inheritNoted.filter((name) => typeof name === "string");
824
+ return state;
825
+ }
826
+ function saveState(paths, state) {
827
+ ensureXHome(paths);
828
+ writeFileAtomic(paths.state, `${JSON.stringify(state, null, 2)}
829
+ `, { mode: 384 });
830
+ }
831
+ function updateState(paths, change) {
832
+ const state = loadState(paths);
833
+ change(state);
834
+ saveState(paths, state);
835
+ return state;
836
+ }
837
+ function recordUse(state, dir, account) {
838
+ delete state.lastAccountByDir[dir];
839
+ state.lastAccountByDir[dir] = account;
840
+ const dirs = Object.keys(state.lastAccountByDir);
841
+ for (const old of dirs.slice(0, Math.max(0, dirs.length - MAX_DIRS))) delete state.lastAccountByDir[old];
842
+ state.lastUsedAccount = account;
843
+ }
844
+ function forgetAccount(state, account) {
845
+ for (const [dir, name] of Object.entries(state.lastAccountByDir)) {
846
+ if (name === account) delete state.lastAccountByDir[dir];
847
+ }
848
+ if (state.lastUsedAccount === account) state.lastUsedAccount = null;
849
+ delete state.seenUnknownEntries[account];
850
+ delete state.listedPlugins[account];
851
+ delete state.turnedOnPlugins[account];
852
+ state.inheritNoted = state.inheritNoted.filter((name) => name !== account);
853
+ delete state.credentialNoted[account];
854
+ }
855
+
856
+ // src/link/inherit.ts
702
857
  import fs10 from "node:fs";
703
858
  import path6 from "node:path";
704
859
 
@@ -785,79 +940,270 @@ function takeOverStale(lockPath) {
785
940
  }
786
941
  }
787
942
 
788
- // src/core/state.ts
789
- var MAX_DIRS = 500;
790
- function emptyState() {
791
- return { installedVersion: null, lastAccountByDir: {}, lastUsedAccount: null, seenUnknownEntries: {}, listedPlugins: {} };
792
- }
793
- function isRecord(v) {
943
+ // src/link/inherit.ts
944
+ var PER_ACCOUNT_KEYS = [
945
+ "env",
946
+ "enabledPlugins",
947
+ "apiKeyHelper",
948
+ "awsAuthRefresh",
949
+ "awsCredentialExport",
950
+ "gcpAuthRefresh",
951
+ "otelHeadersHelper",
952
+ "forceLoginMethod",
953
+ "forceLoginOrgUUID"
954
+ ];
955
+ function isObject2(v) {
794
956
  return typeof v === "object" && v !== null && !Array.isArray(v);
795
957
  }
796
- function loadState(paths) {
797
- let raw;
958
+ function canon(v) {
959
+ if (v === void 0) return "~";
960
+ if (Array.isArray(v)) return `[${v.map(canon).join(",")}]`;
961
+ if (isObject2(v)) {
962
+ return `{${Object.keys(v).sort().map((k) => `${JSON.stringify(k)}:${canon(v[k])}`).join(",")}}`;
963
+ }
964
+ return JSON.stringify(v);
965
+ }
966
+ function same(a, b) {
967
+ return canon(a) === canon(b);
968
+ }
969
+ function each(values, test) {
970
+ return values.every((v) => v === void 0 || test(v));
971
+ }
972
+ function merge3(base, main2, account, at, kept) {
973
+ if (same(main2, base)) return account;
974
+ if (same(account, base)) return main2;
975
+ if (same(account, main2)) return account;
976
+ const values = [base, main2, account];
977
+ if (each(values, Array.isArray)) {
978
+ const was = new Set((base ?? []).map(canon));
979
+ const now = new Set((main2 ?? []).map(canon));
980
+ const out = (account ?? []).filter((x) => now.has(canon(x)) || !was.has(canon(x)));
981
+ const have = new Set(out.map(canon));
982
+ for (const x of main2 ?? []) if (!was.has(canon(x)) && !have.has(canon(x))) out.push(x);
983
+ return out.length || main2 !== void 0 && account !== void 0 ? out : void 0;
984
+ }
985
+ if (each(values, isObject2)) {
986
+ const b = base ?? {};
987
+ const m = main2 ?? {};
988
+ const a = account ?? {};
989
+ const out = {};
990
+ for (const k of /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(m), ...Object.keys(b)])) {
991
+ const v = merge3(b[k], m[k], a[k], at ? `${at}.${k}` : k, kept);
992
+ if (v !== void 0) out[k] = v;
993
+ }
994
+ return Object.keys(out).length || main2 !== void 0 && account !== void 0 ? out : void 0;
995
+ }
996
+ kept.push(at);
997
+ return account;
998
+ }
999
+ function inheritable(settings) {
1000
+ return Object.fromEntries(Object.entries(settings).filter(([k]) => !PER_ACCOUNT_KEYS.includes(k)));
1001
+ }
1002
+ function mergeSettings(base, main2, account) {
1003
+ const picked = inheritable(main2);
1004
+ const kept = [];
1005
+ const next = { ...account };
1006
+ for (const k of /* @__PURE__ */ new Set([...Object.keys(picked), ...Object.keys(base ?? {})])) {
1007
+ if (PER_ACCOUNT_KEYS.includes(k)) continue;
1008
+ const v = merge3(base?.[k], picked[k], account[k], k, kept);
1009
+ if (v === void 0) delete next[k];
1010
+ else next[k] = v;
1011
+ }
1012
+ return { next, base: picked, kept };
1013
+ }
1014
+ function basePath(paths, account) {
1015
+ return path6.join(paths.inherit, `${account}.json`);
1016
+ }
1017
+ function readBase(paths, account) {
798
1018
  try {
799
- raw = JSON.parse(readFileOrNull(paths.state) ?? "{}");
1019
+ const v = JSON.parse(readFileOrNull(basePath(paths, account)) ?? "null");
1020
+ return isObject2(v) ? v : void 0;
800
1021
  } catch {
801
- return emptyState();
1022
+ return void 0;
802
1023
  }
803
- const state = emptyState();
804
- if (!isRecord(raw)) return state;
805
- if (typeof raw.installedVersion === "string") state.installedVersion = raw.installedVersion;
806
- if (typeof raw.lastUsedAccount === "string") state.lastUsedAccount = raw.lastUsedAccount;
807
- if (isRecord(raw.lastAccountByDir)) {
808
- for (const [dir, name] of Object.entries(raw.lastAccountByDir)) {
809
- if (typeof name === "string") state.lastAccountByDir[dir] = name;
1024
+ }
1025
+ function mainSettings(paths) {
1026
+ let text;
1027
+ try {
1028
+ text = readFileOrNull(path6.join(paths.store, "settings.json"));
1029
+ } catch (e) {
1030
+ return { problem: `~/.claude/settings.json can't be read (${e.message})` };
1031
+ }
1032
+ if (text === null) return { settings: {} };
1033
+ let v;
1034
+ try {
1035
+ v = JSON.parse(text);
1036
+ } catch {
1037
+ return { problem: "~/.claude/settings.json isn't valid JSON" };
1038
+ }
1039
+ return isObject2(v) ? { settings: v } : { problem: "~/.claude/settings.json isn't a JSON object" };
1040
+ }
1041
+ function planInherit(paths, account, main2) {
1042
+ const dir = accountDir(paths, account);
1043
+ if (!lstatOrNull(dir)?.isDirectory()) return null;
1044
+ let theirs = main2;
1045
+ if (!theirs) {
1046
+ const read = mainSettings(paths);
1047
+ if ("problem" in read) return read;
1048
+ theirs = read.settings;
1049
+ }
1050
+ const file = path6.join(dir, "settings.json");
1051
+ const st = lstatOrNull(file);
1052
+ if (st && !st.isFile()) return null;
1053
+ const original = st ? fs10.readFileSync(file, "utf8") : null;
1054
+ let ours = {};
1055
+ if (original !== null) {
1056
+ try {
1057
+ ours = JSON.parse(original);
1058
+ } catch {
1059
+ return null;
810
1060
  }
811
1061
  }
812
- if (isRecord(raw.seenUnknownEntries)) {
813
- for (const [name, entries] of Object.entries(raw.seenUnknownEntries)) {
814
- if (Array.isArray(entries)) state.seenUnknownEntries[name] = entries.filter((e) => typeof e === "string");
1062
+ if (!isObject2(ours)) return null;
1063
+ const current = ours;
1064
+ const stored = original === null ? void 0 : readBase(paths, account);
1065
+ const { next, base, kept } = mergeSettings(stored, theirs, current);
1066
+ const changed = [.../* @__PURE__ */ new Set([...Object.keys(current), ...Object.keys(next)])].filter((k) => !same(current[k], next[k]));
1067
+ const ending = original === null || original.endsWith("\n") ? "\n" : "";
1068
+ return {
1069
+ file,
1070
+ next,
1071
+ text: changed.length ? `${JSON.stringify(next, null, 2)}${ending}` : null,
1072
+ changed,
1073
+ kept,
1074
+ base,
1075
+ baseChanged: !same(stored ?? {}, base),
1076
+ first: stored === void 0,
1077
+ seen: stampOf(st)
1078
+ };
1079
+ }
1080
+ function saveBase(paths, account, base) {
1081
+ mkdirPrivate(paths.inherit);
1082
+ writeFileAtomic(basePath(paths, account), `${JSON.stringify(base, null, 2)}
1083
+ `, { mode: 384 });
1084
+ }
1085
+ function forgetInherit(paths, account) {
1086
+ removeTree(basePath(paths, account));
1087
+ }
1088
+ function listed(names) {
1089
+ return names.length > 6 ? `${names.slice(0, 6).join(", ")} and ${names.length - 6} more` : names.join(", ");
1090
+ }
1091
+ function logMerge(account, plan, log) {
1092
+ if (plan.changed.length) {
1093
+ if (plan.first) {
1094
+ log(`xclaude: ${account} takes ~/.claude/settings.json now (${listed(plan.changed)}); its own changes stay. Turn that off with: xclaude set ${account} --inherit off`);
1095
+ } else log(`xclaude: ${account} took ~/.claude/settings.json's changes to ${listed(plan.changed)}`);
1096
+ }
1097
+ if (plan.kept.length) log(`xclaude: ${account} keeps its own ${listed(plan.kept)}, which ~/.claude/settings.json sets differently`);
1098
+ }
1099
+ function inheritSettings(paths, account, opts) {
1100
+ const result = { changed: [], kept: [], deferred: false };
1101
+ try {
1102
+ const first = planInherit(paths, account);
1103
+ if (first && "problem" in first) {
1104
+ opts.log(`xclaude: ${first.problem}, so ${account} keeps its settings as they are`);
1105
+ return result;
1106
+ }
1107
+ if (!first || first.text === null && !first.baseChanged) return result;
1108
+ const lock = DirLock.acquire(path6.join(paths.locks, "store"), STORE_LOCK, { waitMs: opts.lockWaitMs });
1109
+ if (!lock) return { ...result, deferred: true };
1110
+ try {
1111
+ const plan = planInherit(paths, account);
1112
+ if (!plan || "problem" in plan) return result;
1113
+ if (plan.text !== null && !writeIfUnchanged(plan.file, plan.text, plan.seen)) return { ...result, deferred: true };
1114
+ if (plan.text !== null || plan.baseChanged) saveBase(paths, account, plan.base);
1115
+ logMerge(account, plan, opts.log);
1116
+ return { changed: plan.changed, kept: plan.kept, deferred: false };
1117
+ } finally {
1118
+ lock.release();
815
1119
  }
1120
+ } catch (e) {
1121
+ opts.log(`xclaude: couldn't merge ~/.claude/settings.json into ${account} (${e.message})`);
1122
+ return result;
816
1123
  }
817
- if (isRecord(raw.listedPlugins)) {
818
- for (const [name, ids] of Object.entries(raw.listedPlugins)) {
819
- if (Array.isArray(ids)) state.listedPlugins[name] = ids.filter((id) => typeof id === "string");
1124
+ }
1125
+ function stopInheriting(paths, account, opts) {
1126
+ const lock = DirLock.acquire(path6.join(paths.locks, "store"), STORE_LOCK, { waitMs: opts.lockWaitMs });
1127
+ if (!lock) return false;
1128
+ try {
1129
+ const plan = planInherit(paths, account, {});
1130
+ if (plan && !("problem" in plan) && plan.text !== null) {
1131
+ if (!writeIfUnchanged(plan.file, plan.text, plan.seen)) return false;
1132
+ opts.log(`xclaude: took back what ${account} had from ~/.claude/settings.json: ${listed(plan.changed)}`);
820
1133
  }
1134
+ forgetInherit(paths, account);
1135
+ return true;
1136
+ } finally {
1137
+ lock.release();
821
1138
  }
822
- return state;
823
1139
  }
824
- function saveState(paths, state) {
825
- ensureXHome(paths);
826
- writeFileAtomic(paths.state, `${JSON.stringify(state, null, 2)}
827
- `, { mode: 384 });
1140
+ function resetInherit(paths, account, opts) {
1141
+ forgetInherit(paths, account);
1142
+ return inheritSettings(paths, account, opts);
828
1143
  }
829
- function updateState(paths, change) {
830
- const state = loadState(paths);
831
- change(state);
832
- saveState(paths, state);
833
- return state;
1144
+ function inheritStatus(paths, account, main2) {
1145
+ const plan = planInherit(paths, account, main2);
1146
+ if (!plan || "problem" in plan) return null;
1147
+ const picked = inheritable(main2);
1148
+ return { pending: plan.changed, own: Object.keys(picked).filter((k) => !same(plan.next[k], picked[k])) };
834
1149
  }
835
- function recordUse(state, dir, account) {
836
- delete state.lastAccountByDir[dir];
837
- state.lastAccountByDir[dir] = account;
838
- const dirs = Object.keys(state.lastAccountByDir);
839
- for (const old of dirs.slice(0, Math.max(0, dirs.length - MAX_DIRS))) delete state.lastAccountByDir[old];
840
- state.lastUsedAccount = account;
1150
+
1151
+ // src/link/mcp.ts
1152
+ import fs11 from "node:fs";
1153
+ import path7 from "node:path";
1154
+ function isRecord2(v) {
1155
+ return typeof v === "object" && v !== null && !Array.isArray(v);
841
1156
  }
842
- function forgetAccount(state, account) {
843
- for (const [dir, name] of Object.entries(state.lastAccountByDir)) {
844
- if (name === account) delete state.lastAccountByDir[dir];
1157
+ function serversIn(file) {
1158
+ try {
1159
+ const json = JSON.parse(readFileOrNull(file) ?? "{}");
1160
+ if (!isRecord2(json)) return null;
1161
+ return isRecord2(json.mcpServers) ? json.mcpServers : {};
1162
+ } catch {
1163
+ return null;
845
1164
  }
846
- if (state.lastUsedAccount === account) state.lastUsedAccount = null;
847
- delete state.seenUnknownEntries[account];
848
- delete state.listedPlugins[account];
1165
+ }
1166
+ function mcpFile(paths, account) {
1167
+ return path7.join(paths.inherit, `${account}.mcp.json`);
1168
+ }
1169
+ function mcpServersFor(paths, account) {
1170
+ const main2 = serversIn(path7.join(paths.home, ".claude.json"));
1171
+ const own = serversIn(path7.join(accountDir(paths, account), ".claude.json"));
1172
+ if (!main2 || !own) return null;
1173
+ return Object.fromEntries(Object.entries(main2).filter(([name]) => !Object.hasOwn(own, name)));
1174
+ }
1175
+ function prepareMcp(paths, account) {
1176
+ const file = mcpFile(paths, account);
1177
+ const servers = mcpServersFor(paths, account);
1178
+ if (!servers) return fs11.existsSync(file) ? file : null;
1179
+ if (!Object.keys(servers).length) {
1180
+ removeTree(file);
1181
+ return null;
1182
+ }
1183
+ const text = `${JSON.stringify({ mcpServers: servers }, null, 2)}
1184
+ `;
1185
+ if (readFileOrNull(file) !== text) {
1186
+ mkdirPrivate(paths.inherit);
1187
+ writeFileAtomic(file, text, { mode: 384 });
1188
+ }
1189
+ return file;
1190
+ }
1191
+ function forgetMcp(paths, account) {
1192
+ removeTree(mcpFile(paths, account));
849
1193
  }
850
1194
 
851
1195
  // src/link/plugins.ts
852
- function isRecord2(v) {
1196
+ import fs12 from "node:fs";
1197
+ import path8 from "node:path";
1198
+ function isRecord3(v) {
853
1199
  return typeof v === "object" && v !== null && !Array.isArray(v);
854
1200
  }
855
1201
  function userPlugins(paths) {
856
- const dir = realpathOrNull(path6.join(paths.store, "plugins"));
1202
+ const dir = realpathOrNull(path8.join(paths.store, "plugins"));
857
1203
  if (!dir) return null;
858
1204
  let text;
859
1205
  try {
860
- text = readFileOrNull(path6.join(dir, "installed_plugins.json"));
1206
+ text = readFileOrNull(path8.join(dir, "installed_plugins.json"));
861
1207
  } catch {
862
1208
  return null;
863
1209
  }
@@ -868,20 +1214,29 @@ function userPlugins(paths) {
868
1214
  } catch {
869
1215
  return null;
870
1216
  }
871
- if (!isRecord2(json) || !isRecord2(json.plugins)) return null;
872
- return Object.entries(json.plugins).filter(([, records]) => Array.isArray(records) && records.some((r) => isRecord2(r) && r.scope === "user")).map(([id]) => id).sort();
1217
+ if (!isRecord3(json) || !isRecord3(json.plugins)) return null;
1218
+ return Object.entries(json.plugins).filter(([, records]) => Array.isArray(records) && records.some((r) => isRecord3(r) && r.scope === "user")).map(([id]) => id).sort();
873
1219
  }
874
- function planPlugins(paths, account, tracked) {
1220
+ function mainPlugins(paths) {
1221
+ const read = mainSettings(paths);
1222
+ if ("problem" in read) return null;
1223
+ const enabled = read.settings.enabledPlugins;
1224
+ if (!isRecord3(enabled)) return /* @__PURE__ */ new Set();
1225
+ return new Set(
1226
+ Object.entries(enabled).filter(([, on]) => on === true).map(([id]) => id.toLowerCase())
1227
+ );
1228
+ }
1229
+ function planPlugins(paths, account, tracked, follow = null) {
875
1230
  const dir = accountDir(paths, account);
876
1231
  if (!lstatOrNull(dir)?.isDirectory()) return null;
877
- const store = realpathOrNull(path6.join(paths.store, "plugins"));
878
- if (!store || realpathOrNull(path6.join(dir, "plugins")) !== store) return null;
1232
+ const store = realpathOrNull(path8.join(paths.store, "plugins"));
1233
+ if (!store || realpathOrNull(path8.join(dir, "plugins")) !== store) return null;
879
1234
  const installed = userPlugins(paths);
880
1235
  if (!installed) return null;
881
- const file = path6.join(dir, "settings.json");
1236
+ const file = path8.join(dir, "settings.json");
882
1237
  const st = lstatOrNull(file);
883
1238
  if (st && !st.isFile()) return null;
884
- const original = st ? fs10.readFileSync(file, "utf8") : null;
1239
+ const original = st ? fs12.readFileSync(file, "utf8") : null;
885
1240
  let settings = {};
886
1241
  if (original !== null) {
887
1242
  try {
@@ -890,88 +1245,336 @@ function planPlugins(paths, account, tracked) {
890
1245
  return null;
891
1246
  }
892
1247
  }
893
- if (!isRecord2(settings)) return null;
1248
+ if (!isRecord3(settings)) return null;
894
1249
  const current = settings.enabledPlugins ?? {};
895
- if (!isRecord2(current)) return null;
1250
+ if (!isRecord3(current)) return null;
1251
+ const wanted = (id) => follow?.has(id.toLowerCase()) === true;
896
1252
  const named = new Set(Object.keys(current).map((id) => id.toLowerCase()));
897
1253
  const add = installed.filter((id) => !named.has(id.toLowerCase()));
898
- const keep = [];
1254
+ const next = { ...current };
1255
+ const off = [];
1256
+ const on = [];
1257
+ const turnOn = [];
1258
+ const turnOff = [];
899
1259
  const drop = [];
900
- for (const id of tracked) {
901
- if (current[id] !== false) continue;
902
- if (installed.includes(id)) keep.push(id);
903
- else drop.push(id);
1260
+ for (const [ids, value] of [
1261
+ [tracked.off, false],
1262
+ [tracked.on, true]
1263
+ ]) {
1264
+ for (const id of ids) {
1265
+ if (current[id] !== value) continue;
1266
+ if (!installed.includes(id)) {
1267
+ drop.push(id);
1268
+ delete next[id];
1269
+ } else if (follow && wanted(id) !== value) {
1270
+ next[id] = !value;
1271
+ (value ? turnOff : turnOn).push(id);
1272
+ (value ? off : on).push(id);
1273
+ } else (value ? on : off).push(id);
1274
+ }
1275
+ }
1276
+ for (const id of add) {
1277
+ next[id] = wanted(id);
1278
+ if (wanted(id)) {
1279
+ on.push(id);
1280
+ turnOn.push(id);
1281
+ } else off.push(id);
904
1282
  }
905
1283
  let text = null;
906
- if (add.length || drop.length) {
907
- const next = { ...current };
908
- for (const id of drop) delete next[id];
909
- for (const id of add) next[id] = false;
1284
+ if (add.length || drop.length || turnOn.length || turnOff.length) {
910
1285
  const ending = original === null || original.endsWith("\n") ? "\n" : "";
911
1286
  text = `${JSON.stringify({ ...settings, enabledPlugins: next }, null, 2)}${ending}`;
912
1287
  }
913
- return {
914
- file,
915
- add,
916
- drop,
917
- tracked: [...keep, ...add].sort(),
918
- text,
919
- seen: st ? { mtimeMs: st.mtimeMs, size: st.size, ino: st.ino } : null
920
- };
1288
+ return {
1289
+ file,
1290
+ add,
1291
+ turnOn,
1292
+ turnOff,
1293
+ drop,
1294
+ tracked: { off: off.sort(), on: on.sort() },
1295
+ text,
1296
+ seen: stampOf(st)
1297
+ };
1298
+ }
1299
+ function writePlan(plan) {
1300
+ return plan.text === null || writeIfUnchanged(plan.file, plan.text, plan.seen);
1301
+ }
1302
+ function changesNothing(plan, tracked) {
1303
+ const same2 = (a, b) => a.join("\n") === [...b].sort().join("\n");
1304
+ return plan.text === null && same2(plan.tracked.off, tracked.off) && same2(plan.tracked.on, tracked.on);
1305
+ }
1306
+ function trackedOf(paths, account) {
1307
+ const state = loadState(paths);
1308
+ return { off: state.listedPlugins[account] ?? [], on: state.turnedOnPlugins[account] ?? [] };
1309
+ }
1310
+ function listPlugins(paths, account, opts) {
1311
+ const result = { added: [], dropped: [], deferred: false };
1312
+ try {
1313
+ const follow = opts.turnOffOwn ? /* @__PURE__ */ new Set() : opts.follow ? mainPlugins(paths) : null;
1314
+ const before = trackedOf(paths, account);
1315
+ const first = planPlugins(paths, account, before, follow);
1316
+ if (!first || changesNothing(first, before)) return result;
1317
+ const lock = DirLock.acquire(path8.join(paths.locks, "store"), STORE_LOCK, { waitMs: opts.lockWaitMs });
1318
+ if (!lock) return { ...result, deferred: true };
1319
+ try {
1320
+ const tracked = trackedOf(paths, account);
1321
+ const plan = planPlugins(paths, account, tracked, follow);
1322
+ if (!plan || changesNothing(plan, tracked)) return result;
1323
+ if (!writePlan(plan)) return { ...result, deferred: true };
1324
+ updateState(paths, (state) => {
1325
+ for (const [key, ids] of [
1326
+ ["listedPlugins", plan.tracked.off],
1327
+ ["turnedOnPlugins", plan.tracked.on]
1328
+ ]) {
1329
+ if (ids.length) state[key][account] = ids;
1330
+ else delete state[key][account];
1331
+ }
1332
+ });
1333
+ const off = plan.add.filter((id) => !plan.turnOn.includes(id));
1334
+ if (off.length === 1) {
1335
+ opts.log(`xclaude: ${off[0]} is installed under another login; ${account}'s /plugin lists it now, turned off`);
1336
+ } else if (off.length) {
1337
+ opts.log(`xclaude: ${off.length} plugins installed under other logins are in ${account}'s /plugin now, turned off: ${off.join(", ")}`);
1338
+ }
1339
+ if (plan.turnOn.length) opts.log(`xclaude: ${account} turned on what ~/.claude has on: ${plan.turnOn.join(", ")}`);
1340
+ if (plan.turnOff.length) opts.log(`xclaude: ${account} turned off ${plan.turnOff.join(", ")}, which ${opts.turnOffOwn ? "it had from ~/.claude" : "~/.claude has off now"}`);
1341
+ return { added: plan.add, dropped: plan.drop, deferred: false };
1342
+ } finally {
1343
+ lock.release();
1344
+ }
1345
+ } catch (e) {
1346
+ opts.log(`xclaude: couldn't list other logins' plugins for ${account} (${e.message})`);
1347
+ return result;
1348
+ }
1349
+ }
1350
+
1351
+ // src/launch/picker.ts
1352
+ import fs13 from "node:fs";
1353
+ import tty2 from "node:tty";
1354
+ function parseKeys(chunk) {
1355
+ const keys = [];
1356
+ let i = 0;
1357
+ while (i < chunk.length) {
1358
+ const rest = chunk.slice(i);
1359
+ if (rest.startsWith("\x1B[A") || rest.startsWith("\x1BOA")) {
1360
+ keys.push("up");
1361
+ i += 3;
1362
+ } else if (rest.startsWith("\x1B[B") || rest.startsWith("\x1BOB")) {
1363
+ keys.push("down");
1364
+ i += 3;
1365
+ } else if (rest.startsWith("\x1B[")) {
1366
+ let j = 2;
1367
+ while (j < rest.length && !/[@-~]/.test(rest[j])) j++;
1368
+ keys.push(null);
1369
+ i += j + 1;
1370
+ } else {
1371
+ const c = rest[0];
1372
+ if (c === "\x1B") keys.push(rest.length === 1 ? "cancel" : null);
1373
+ else if (c === "") keys.push("cancel");
1374
+ else if (c === "\r" || c === "\n") keys.push("enter");
1375
+ else if (c === "k") keys.push("up");
1376
+ else if (c === "j") keys.push("down");
1377
+ else if (c >= "1" && c <= "9") keys.push({ jump: Number(c) - 1 });
1378
+ else keys.push(null);
1379
+ i++;
1380
+ }
1381
+ }
1382
+ return keys;
1383
+ }
1384
+ function step(index, count, key) {
1385
+ if (key === "up") return { index: (index - 1 + count) % count };
1386
+ if (key === "down") return { index: (index + 1) % count };
1387
+ if (key === "enter") return { index, done: "chosen" };
1388
+ if (key === "cancel") return { index, done: "cancelled" };
1389
+ if (key && typeof key === "object" && key.jump < count) return { index: key.jump };
1390
+ return { index };
1391
+ }
1392
+ var dim = (s) => `\x1B[2m${s}\x1B[22m`;
1393
+ var bold = (s) => `\x1B[1m${s}\x1B[22m`;
1394
+ function fit(text, width) {
1395
+ return width > 0 && text.length > width ? `${text.slice(0, Math.max(0, width - 1))}\u2026` : text;
1396
+ }
1397
+ function render(title, items, index, width = 0) {
1398
+ const labelWidth = Math.max(...items.map((it) => it.label.length));
1399
+ const lines = [bold(fit(title, width))];
1400
+ items.forEach((it, i) => {
1401
+ const marker = i === index ? "\u276F" : " ";
1402
+ const num = i < 9 ? String(i + 1) : " ";
1403
+ const label = it.label.padEnd(labelWidth);
1404
+ const text = fit(`${marker} ${num} ${label}${it.detail ? ` ${it.detail}` : ""}`, width);
1405
+ const head = text.slice(0, 5 + labelWidth);
1406
+ const tail = text.slice(5 + labelWidth);
1407
+ lines.push(i === index ? `${bold(head)}${dim(tail)}` : `${head}${dim(tail)}`);
1408
+ });
1409
+ lines.push(dim(fit("\u2191/\u2193 or j/k to move \xB7 1\u20139 to jump \xB7 Enter to choose \xB7 Esc to cancel", width)));
1410
+ return lines;
1411
+ }
1412
+ function preselect(names, state, cwd) {
1413
+ for (const candidate of [state.lastAccountByDir[cwd], state.lastUsedAccount]) {
1414
+ if (candidate && names.includes(candidate)) return names.indexOf(candidate);
1415
+ }
1416
+ return 0;
1417
+ }
1418
+ function openKeyboard() {
1419
+ let fd;
1420
+ try {
1421
+ fd = fs13.openSync("/dev/tty", "r");
1422
+ } catch {
1423
+ throw new UsageError("account required: there's no terminal to show the picker on (xclaude <account> [claude args\u2026])");
1424
+ }
1425
+ const input = new tty2.ReadStream(fd);
1426
+ let columns = 0;
1427
+ try {
1428
+ const size = [];
1429
+ const handle = input._handle;
1430
+ if (handle?.getWindowSize?.(size) === 0) columns = size[0] ?? 0;
1431
+ } catch {
1432
+ }
1433
+ return {
1434
+ input,
1435
+ columns,
1436
+ close: () => {
1437
+ input.pause();
1438
+ input.unref();
1439
+ }
1440
+ };
1441
+ }
1442
+ function pick(title, items, initial) {
1443
+ const keyboard = openKeyboard();
1444
+ const { input } = keyboard;
1445
+ const write = (s) => fs13.writeSync(2, s);
1446
+ let index = Math.min(Math.max(initial, 0), items.length - 1);
1447
+ let drawn = 0;
1448
+ const draw = () => {
1449
+ const lines = render(title, items, index, keyboard.columns);
1450
+ write(`${drawn ? `\r\x1B[${drawn}A` : ""}\x1B[J${lines.join("\n")}
1451
+ `);
1452
+ drawn = lines.length;
1453
+ };
1454
+ return new Promise((resolve, reject) => {
1455
+ const finish = (result) => {
1456
+ input.off("data", onData);
1457
+ try {
1458
+ input.setRawMode(false);
1459
+ } finally {
1460
+ keyboard.close();
1461
+ write(`\r\x1B[${drawn}A\x1B[J\x1B[?25h`);
1462
+ }
1463
+ if (result === "chosen") resolve(index);
1464
+ else reject(new Cancelled());
1465
+ };
1466
+ const onData = (chunk) => {
1467
+ for (const key of parseKeys(chunk)) {
1468
+ const next = step(index, items.length, key);
1469
+ index = next.index;
1470
+ if (next.done) {
1471
+ finish(next.done);
1472
+ return;
1473
+ }
1474
+ }
1475
+ draw();
1476
+ };
1477
+ input.setRawMode(true);
1478
+ input.setEncoding("utf8");
1479
+ input.on("data", onData);
1480
+ input.resume();
1481
+ write("\x1B[?25l");
1482
+ draw();
1483
+ });
1484
+ }
1485
+
1486
+ // src/launch/inherit-question.ts
1487
+ function setupPreview(paths, account) {
1488
+ try {
1489
+ return previewLines(paths, account);
1490
+ } catch {
1491
+ return [];
1492
+ }
1493
+ }
1494
+ function previewLines(paths, account) {
1495
+ const lines = [];
1496
+ const main2 = mainSettings(paths);
1497
+ if ("settings" in main2) {
1498
+ const keys = inheritStatus(paths, account, main2.settings)?.pending ?? Object.keys(inheritable(main2.settings));
1499
+ if (keys.length) lines.push(` settings ${listed(keys)}`);
1500
+ }
1501
+ const on = mainPlugins(paths);
1502
+ if (on?.size) {
1503
+ const plan = planPlugins(paths, account, trackedOf(paths, account), on);
1504
+ const ids = plan ? plan.turnOn : (userPlugins(paths) ?? []).filter((id) => on.has(id.toLowerCase()));
1505
+ if (ids.length) lines.push(` plugins turns on ${listed(ids)}`);
1506
+ }
1507
+ const servers = Object.keys(mcpServersFor(paths, account) ?? {});
1508
+ if (servers.length) lines.push(` MCP ${listed(servers)}`);
1509
+ return lines;
921
1510
  }
922
- function writePlan(plan) {
923
- if (plan.text === null) return true;
924
- const st = lstatOrNull(plan.file);
925
- const unchanged = plan.seen ? st !== null && st.mtimeMs === plan.seen.mtimeMs && st.size === plan.seen.size && st.ino === plan.seen.ino : st === null;
926
- if (unchanged) writeFileAtomic(plan.file, plan.text);
927
- return unchanged;
1511
+ function noteOnce(ctx, account) {
1512
+ try {
1513
+ if (loadState(ctx.paths).inheritNoted.includes(account)) return;
1514
+ updateState(ctx.paths, (state) => {
1515
+ state.inheritNoted.push(account);
1516
+ });
1517
+ } catch {
1518
+ }
1519
+ ctx.io.err(
1520
+ `xclaude: ${account} doesn't take ~/.claude's settings, plugins and MCP servers until you choose: launch it in a terminal, or run xclaude set ${account} --inherit on (or off)
1521
+ `
1522
+ );
928
1523
  }
929
- function changesNothing(plan, tracked) {
930
- return plan.text === null && plan.tracked.join("\n") === [...tracked].sort().join("\n");
1524
+ async function askInherit(ctx, account) {
1525
+ const preview = setupPreview(ctx.paths, account);
1526
+ if (!preview.length) return void 0;
1527
+ if (!ctx.tty.stdin || !ctx.tty.stderr) {
1528
+ noteOnce(ctx, account);
1529
+ return void 0;
1530
+ }
1531
+ ctx.io.err(`xclaude: ${account} can take what you set up for plain claude in ~/.claude:
1532
+ ${preview.join("\n")}
1533
+ `);
1534
+ const choice = await pick(
1535
+ `Take it into ${account}?`,
1536
+ [
1537
+ { label: "Yes", detail: `now and at every launch; what ${account} changes itself stays` },
1538
+ { label: "No", detail: `leave ${account} as it is (later: xclaude set ${account} --inherit on)` }
1539
+ ],
1540
+ 0
1541
+ );
1542
+ if (choice === 0) return true;
1543
+ ctx.io.err(`xclaude: ${account} stays as it is; take ~/.claude's setup later with: xclaude set ${account} --inherit on
1544
+ `);
1545
+ return false;
931
1546
  }
932
- function listPlugins(paths, account, opts) {
933
- const result = { added: [], dropped: [], deferred: false };
1547
+ async function settleInherit(ctx, config, account) {
1548
+ if (config.accounts[account]?.inherit !== void 0) return config;
1549
+ const take = await askInherit(ctx, account);
1550
+ if (take === void 0) return config;
934
1551
  try {
935
- const before = loadState(paths).listedPlugins[account] ?? [];
936
- const first = planPlugins(paths, account, before);
937
- if (!first || changesNothing(first, before)) return result;
938
- const lock = DirLock.acquire(path6.join(paths.locks, "store"), STORE_LOCK, { waitMs: opts.lockWaitMs });
939
- if (!lock) return { ...result, deferred: true };
940
- try {
941
- const tracked = loadState(paths).listedPlugins[account] ?? [];
942
- const plan = planPlugins(paths, account, tracked);
943
- if (!plan || changesNothing(plan, tracked)) return result;
944
- if (!writePlan(plan)) return { ...result, deferred: true };
945
- updateState(paths, (state) => {
946
- if (plan.tracked.length) state.listedPlugins[account] = plan.tracked;
947
- else delete state.listedPlugins[account];
948
- });
949
- if (plan.add.length === 1) {
950
- opts.log(`xclaude: ${plan.add[0]} is installed under another login; ${account}'s /plugin lists it now, turned off`);
951
- } else if (plan.add.length) {
952
- opts.log(`xclaude: ${plan.add.length} plugins installed under other logins are in ${account}'s /plugin now, turned off: ${plan.add.join(", ")}`);
953
- }
954
- return { added: plan.add, dropped: plan.drop, deferred: false };
955
- } finally {
956
- lock.release();
957
- }
1552
+ const fresh = loadConfig(ctx.paths, { create: false }).config;
1553
+ const defaults = fresh.accounts[account];
1554
+ if (!defaults) return config;
1555
+ defaults.inherit = take;
1556
+ saveConfig(ctx.paths, fresh);
1557
+ return fresh;
958
1558
  } catch (e) {
959
- opts.log(`xclaude: couldn't list other logins' plugins for ${account} (${e.message})`);
960
- return result;
1559
+ ctx.io.err(`xclaude: couldn't save ${account}'s answer (${e.message}); the next launch asks again
1560
+ `);
1561
+ const once = structuredClone(config);
1562
+ once.accounts[account].inherit = take;
1563
+ return once;
961
1564
  }
962
1565
  }
963
1566
 
964
1567
  // src/link/repair.ts
965
- import fs14 from "node:fs";
966
- import path10 from "node:path";
1568
+ import fs17 from "node:fs";
1569
+ import path12 from "node:path";
967
1570
 
968
1571
  // src/link/history.ts
969
- import fs12 from "node:fs";
970
- import path8 from "node:path";
1572
+ import fs15 from "node:fs";
1573
+ import path10 from "node:path";
971
1574
 
972
1575
  // src/link/merge.ts
973
- import fs11 from "node:fs";
974
- import path7 from "node:path";
1576
+ import fs14 from "node:fs";
1577
+ import path9 from "node:path";
975
1578
  var counter2 = 0;
976
1579
  function asideName(entry) {
977
1580
  return `.xclaude-merge-${entry}-${stamp()}-${process.pid}-${counter2++}`;
@@ -996,23 +1599,23 @@ function remember(rec, c) {
996
1599
  rec.byPath.set(c.path, c);
997
1600
  }
998
1601
  function requireRealDir(dir) {
999
- const st = fs11.lstatSync(dir);
1602
+ const st = fs14.lstatSync(dir);
1000
1603
  if (!st.isDirectory()) throw new Error(`${dir} isn't a real directory; it won't be read through`);
1001
1604
  return st;
1002
1605
  }
1003
1606
  function linkText(src, root) {
1004
- const text = fs11.readlinkSync(src);
1005
- if (path7.isAbsolute(text)) return text;
1006
- const resolved = path7.resolve(path7.dirname(src), text);
1007
- return resolved === root || resolved.startsWith(`${root}${path7.sep}`) ? text : resolved;
1607
+ const text = fs14.readlinkSync(src);
1608
+ if (path9.isAbsolute(text)) return text;
1609
+ const resolved = path9.resolve(path9.dirname(src), text);
1610
+ return resolved === root || resolved.startsWith(`${root}${path9.sep}`) ? text : resolved;
1008
1611
  }
1009
1612
  function identicalEntry(src, srcStat, dst, root) {
1010
1613
  const dstStat = lstatOrNull(dst);
1011
1614
  if (!dstStat) return false;
1012
1615
  if (srcStat.isSymbolicLink()) {
1013
1616
  if (!dstStat.isSymbolicLink()) return false;
1014
- const there = fs11.readlinkSync(dst);
1015
- return there === linkText(src, root) || there === fs11.readlinkSync(src);
1617
+ const there = fs14.readlinkSync(dst);
1618
+ return there === linkText(src, root) || there === fs14.readlinkSync(src);
1016
1619
  }
1017
1620
  return srcStat.isFile() && dstStat.isFile() && sameContent(src, dst);
1018
1621
  }
@@ -1027,18 +1630,18 @@ function conflictName(dir, name, ctx) {
1027
1630
  const base = `${name}.xclaude-conflict-${ctx.account}-${ctx.stamp}`;
1028
1631
  for (let n = 1; ; n++) {
1029
1632
  const candidate = n === 1 ? base : `${base}-${n}`;
1030
- if (!lstatOrNull(path7.join(dir, candidate))) return candidate;
1633
+ if (!lstatOrNull(path9.join(dir, candidate))) return candidate;
1031
1634
  }
1032
1635
  }
1033
1636
  var join = (rel, name) => rel ? `${rel}/${name}` : name;
1034
1637
  function linkTree(src, dst, ctx, stats, rec, root = src, rel = "") {
1035
1638
  let fresh = 0;
1036
- for (const d of fs11.readdirSync(src, { withFileTypes: true })) {
1639
+ for (const d of fs14.readdirSync(src, { withFileTypes: true })) {
1037
1640
  ctx.refresh();
1038
- const s = path7.join(src, d.name);
1039
- const t = path7.join(dst, d.name);
1641
+ const s = path9.join(src, d.name);
1642
+ const t = path9.join(dst, d.name);
1040
1643
  const relName = join(rel, d.name);
1041
- const st = fs11.lstatSync(s);
1644
+ const st = fs14.lstatSync(s);
1042
1645
  const prior = rec.placed.get(relName);
1043
1646
  if (st.isDirectory()) {
1044
1647
  let target = t;
@@ -1046,14 +1649,14 @@ function linkTree(src, dst, ctx, stats, rec, root = src, rel = "") {
1046
1649
  target = prior.target;
1047
1650
  } else {
1048
1651
  try {
1049
- fs11.mkdirSync(t, { mode: st.mode & 4095 | 448 });
1652
+ fs14.mkdirSync(t, { mode: st.mode & 4095 | 448 });
1050
1653
  remember(rec, { path: t, kind: "dir" });
1051
1654
  } catch (e) {
1052
1655
  if (errCode(e) !== "EEXIST") throw e;
1053
- if (!fs11.lstatSync(t).isDirectory()) {
1656
+ if (!fs14.lstatSync(t).isDirectory()) {
1054
1657
  const name2 = conflictName(dst, d.name, ctx);
1055
- target = path7.join(dst, name2);
1056
- fs11.mkdirSync(target, { mode: st.mode & 4095 | 448 });
1658
+ target = path9.join(dst, name2);
1659
+ fs14.mkdirSync(target, { mode: st.mode & 4095 | 448 });
1057
1660
  remember(rec, { path: target, kind: "dir" });
1058
1661
  stats.conflicts.push(join(rel, name2));
1059
1662
  }
@@ -1068,7 +1671,7 @@ function linkTree(src, dst, ctx, stats, rec, root = src, rel = "") {
1068
1671
  const place = (to) => {
1069
1672
  if (st.isSymbolicLink()) {
1070
1673
  const link = linkText(s, root);
1071
- fs11.symlinkSync(link, to);
1674
+ fs14.symlinkSync(link, to);
1072
1675
  remember(rec, { path: to, kind: "symlink", link });
1073
1676
  } else {
1074
1677
  fsops.link(s, to);
@@ -1094,8 +1697,8 @@ function linkTree(src, dst, ctx, stats, rec, root = src, rel = "") {
1094
1697
  continue;
1095
1698
  }
1096
1699
  const name = conflictName(dst, d.name, ctx);
1097
- place(path7.join(dst, name));
1098
- rec.placed.set(relName, { target: path7.join(dst, name) });
1700
+ place(path9.join(dst, name));
1701
+ rec.placed.set(relName, { target: path9.join(dst, name) });
1099
1702
  stats.moved++;
1100
1703
  stats.conflicts.push(join(rel, name));
1101
1704
  }
@@ -1106,29 +1709,29 @@ function undoLinks(rec) {
1106
1709
  const st = lstatOrNull(c.path);
1107
1710
  if (!st) continue;
1108
1711
  try {
1109
- if (c.kind === "dir" && st.isDirectory()) fs11.rmdirSync(c.path);
1110
- else if (c.kind === "symlink" && st.isSymbolicLink() && fs11.readlinkSync(c.path) === c.link) fs11.unlinkSync(c.path);
1111
- else if (c.kind === "file" && st.ino === c.ino && st.dev === c.dev) fs11.unlinkSync(c.path);
1712
+ if (c.kind === "dir" && st.isDirectory()) fs14.rmdirSync(c.path);
1713
+ else if (c.kind === "symlink" && st.isSymbolicLink() && fs14.readlinkSync(c.path) === c.link) fs14.unlinkSync(c.path);
1714
+ else if (c.kind === "file" && st.ino === c.ino && st.dev === c.dev) fs14.unlinkSync(c.path);
1112
1715
  } catch {
1113
1716
  }
1114
1717
  }
1115
1718
  }
1116
1719
  function openForEmptying(dir) {
1117
1720
  const st = requireRealDir(dir);
1118
- if ((st.mode & 448) !== 448) fs11.chmodSync(dir, st.mode & 4095 | 448);
1119
- return fs11.readdirSync(dir, { withFileTypes: true });
1721
+ if ((st.mode & 448) !== 448) fs14.chmodSync(dir, st.mode & 4095 | 448);
1722
+ return fs14.readdirSync(dir, { withFileTypes: true });
1120
1723
  }
1121
1724
  function takeOver(src, placed, rec, dst, ctx, stats, rel) {
1122
1725
  const ours = rec.byPath.get(placed.target);
1123
1726
  const there = lstatOrNull(placed.target);
1124
1727
  if (!ours || ours.kind !== "file" || !there || there.ino !== ours.ino || there.dev !== ours.dev) return false;
1125
- const base = path7.basename(placed.target);
1728
+ const base = path9.basename(placed.target);
1126
1729
  const old = conflictName(dst, base, ctx);
1127
- fsops.link(placed.target, path7.join(dst, old));
1128
- const tmp = path7.join(dst, `.xclaude-tmp-${base}-${process.pid}-${counter2++}`);
1730
+ fsops.link(placed.target, path9.join(dst, old));
1731
+ const tmp = path9.join(dst, `.xclaude-tmp-${base}-${process.pid}-${counter2++}`);
1129
1732
  fsops.link(src, tmp);
1130
- fs11.renameSync(tmp, placed.target);
1131
- fs11.unlinkSync(src);
1733
+ fs14.renameSync(tmp, placed.target);
1734
+ fs14.unlinkSync(src);
1132
1735
  stats.conflicts.push(join(rel, old));
1133
1736
  return true;
1134
1737
  }
@@ -1138,34 +1741,34 @@ function moveTree(src, dst, ctx, stats, rec = null, root = src, rel = "") {
1138
1741
  entries.sort((a, b) => Number(isPlaced(a.name)) - Number(isPlaced(b.name)));
1139
1742
  for (const d of entries) {
1140
1743
  ctx.refresh();
1141
- const s = path7.join(src, d.name);
1142
- const st = fs11.lstatSync(s);
1744
+ const s = path9.join(src, d.name);
1745
+ const st = fs14.lstatSync(s);
1143
1746
  const relName = join(rel, d.name);
1144
1747
  const placed = rec?.placed.get(relName);
1145
1748
  if (st.isDirectory()) {
1146
- let target = path7.join(dst, d.name);
1749
+ let target = path9.join(dst, d.name);
1147
1750
  if (placed && lstatOrNull(placed.target)?.isDirectory()) {
1148
1751
  target = placed.target;
1149
1752
  } else {
1150
1753
  try {
1151
- fs11.mkdirSync(target, { mode: st.mode & 4095 | 448 });
1754
+ fs14.mkdirSync(target, { mode: st.mode & 4095 | 448 });
1152
1755
  } catch (e) {
1153
1756
  if (errCode(e) !== "EEXIST") throw e;
1154
- if (!fs11.lstatSync(target).isDirectory()) {
1757
+ if (!fs14.lstatSync(target).isDirectory()) {
1155
1758
  const name2 = conflictName(dst, d.name, ctx);
1156
- target = path7.join(dst, name2);
1157
- fs11.mkdirSync(target, { mode: st.mode & 4095 | 448 });
1759
+ target = path9.join(dst, name2);
1760
+ fs14.mkdirSync(target, { mode: st.mode & 4095 | 448 });
1158
1761
  stats.conflicts.push(join(rel, name2));
1159
1762
  }
1160
1763
  }
1161
1764
  }
1162
1765
  moveTree(s, target, ctx, stats, rec, root, relName);
1163
- fs11.rmdirSync(s);
1766
+ fs14.rmdirSync(s);
1164
1767
  continue;
1165
1768
  }
1166
1769
  if (placed) {
1167
1770
  if (stillPlaced(placed, s, st, root)) {
1168
- fs11.unlinkSync(s);
1771
+ fs14.unlinkSync(s);
1169
1772
  continue;
1170
1773
  }
1171
1774
  if (st.isFile() && !placed.identical && rec && takeOver(s, placed, rec, dst, ctx, stats, rel)) {
@@ -1175,29 +1778,29 @@ function moveTree(src, dst, ctx, stats, rec = null, root = src, rel = "") {
1175
1778
  }
1176
1779
  if (st.isSymbolicLink()) {
1177
1780
  const link = linkText(s, root);
1178
- const to = path7.join(dst, d.name);
1781
+ const to = path9.join(dst, d.name);
1179
1782
  try {
1180
- fs11.symlinkSync(link, to);
1181
- fs11.unlinkSync(s);
1783
+ fs14.symlinkSync(link, to);
1784
+ fs14.unlinkSync(s);
1182
1785
  stats.moved++;
1183
1786
  continue;
1184
1787
  } catch (e) {
1185
1788
  if (errCode(e) !== "EEXIST") throw e;
1186
1789
  }
1187
- } else if (moveNoClobber(s, path7.join(dst, d.name), st) === "moved") {
1790
+ } else if (moveNoClobber(s, path9.join(dst, d.name), st) === "moved") {
1188
1791
  stats.moved++;
1189
1792
  continue;
1190
1793
  }
1191
- if (identicalEntry(s, st, path7.join(dst, d.name), root)) {
1192
- fs11.unlinkSync(s);
1794
+ if (identicalEntry(s, st, path9.join(dst, d.name), root)) {
1795
+ fs14.unlinkSync(s);
1193
1796
  stats.dropped++;
1194
1797
  continue;
1195
1798
  }
1196
1799
  const name = conflictName(dst, d.name, ctx);
1197
1800
  if (st.isSymbolicLink()) {
1198
- fs11.symlinkSync(linkText(s, root), path7.join(dst, name));
1199
- fs11.unlinkSync(s);
1200
- } else if (moveNoClobber(s, path7.join(dst, name), st) !== "moved") {
1801
+ fs14.symlinkSync(linkText(s, root), path9.join(dst, name));
1802
+ fs14.unlinkSync(s);
1803
+ } else if (moveNoClobber(s, path9.join(dst, name), st) !== "moved") {
1201
1804
  throw new Error(`can't place ${relName}: ${name} is taken`);
1202
1805
  }
1203
1806
  stats.moved++;
@@ -1328,6 +1931,7 @@ var APPENDIX_A = [
1328
1931
  "local-settings",
1329
1932
  "project-settings",
1330
1933
  "remote",
1934
+ "remote-control",
1331
1935
  "scratch",
1332
1936
  "seed-admin",
1333
1937
  "storage-v2",
@@ -1402,7 +2006,7 @@ function readLines(file) {
1402
2006
  return (readFileOrNull(file) ?? "").split("\n");
1403
2007
  }
1404
2008
  function storeLockPath(S) {
1405
- return `${realpathOrNull(path8.join(S, HISTORY)) ?? path8.join(S, HISTORY)}.lock`;
2009
+ return `${realpathOrNull(path10.join(S, HISTORY)) ?? path10.join(S, HISTORY)}.lock`;
1406
2010
  }
1407
2011
  function mergeAsideIntoStore(ctx, aside, alsoHeld) {
1408
2012
  const refreshAll = () => {
@@ -1413,7 +2017,7 @@ function mergeAsideIntoStore(ctx, aside, alsoHeld) {
1413
2017
  const storeLock = DirLock.acquire(storeLockPath(ctx.S), HISTORY_LOCK, { waitMs, onWait: refreshAll });
1414
2018
  if (!storeLock) return { ok: false, reason: "the shared history.jsonl is busy" };
1415
2019
  try {
1416
- const storeFile = realpathOrNull(path8.join(ctx.S, HISTORY));
2020
+ const storeFile = realpathOrNull(path10.join(ctx.S, HISTORY));
1417
2021
  if (!storeFile) return { ok: false, reason: "~/.claude/history.jsonl doesn't resolve" };
1418
2022
  const storeLines = readLines(storeFile);
1419
2023
  const merged = mergeHistoryLines(storeLines, readLines(aside));
@@ -1421,7 +2025,7 @@ function mergeAsideIntoStore(ctx, aside, alsoHeld) {
1421
2025
  if (!storeLock.refresh() || alsoHeld && !alsoHeld.refresh()) return { ok: false, reason: "a history lock was taken over" };
1422
2026
  writeFileAtomic(storeFile, merged.length ? `${merged.join("\n")}
1423
2027
  ` : "", { mode: 384, fsync: true });
1424
- fs12.unlinkSync(aside);
2028
+ fs15.unlinkSync(aside);
1425
2029
  const before = new Set(storeLines);
1426
2030
  return { ok: true, added: merged.filter((line) => !before.has(line)).length };
1427
2031
  } finally {
@@ -1429,37 +2033,37 @@ function mergeAsideIntoStore(ctx, aside, alsoHeld) {
1429
2033
  }
1430
2034
  }
1431
2035
  function mergeHistory(ctx) {
1432
- const file = path8.join(ctx.A, HISTORY);
2036
+ const file = path10.join(ctx.A, HISTORY);
1433
2037
  const accountLock = DirLock.acquire(`${file}.lock`, HISTORY_LOCK, { waitMs: ctx.lockWaitMs, onWait: ctx.refreshStoreLock });
1434
2038
  if (!accountLock) return { ok: false, reason: `this account's history.jsonl is busy` };
1435
2039
  try {
1436
2040
  const st = lstatOrNull(file);
1437
2041
  if (!st?.isFile()) return { ok: true, added: 0 };
1438
- const storeFile = realpathOrNull(path8.join(ctx.S, HISTORY));
2042
+ const storeFile = realpathOrNull(path10.join(ctx.S, HISTORY));
1439
2043
  if (!storeFile) return { ok: false, reason: "~/.claude/history.jsonl doesn't resolve" };
1440
- const aside = path8.join(ctx.A, asideName(HISTORY));
1441
- fs12.linkSync(file, aside);
2044
+ const aside = path10.join(ctx.A, asideName(HISTORY));
2045
+ fs15.linkSync(file, aside);
1442
2046
  const tmp = siblingName(file, "link");
1443
- fs12.symlinkSync(storeFile, tmp);
1444
- fs12.renameSync(tmp, file);
2047
+ fs15.symlinkSync(storeFile, tmp);
2048
+ fs15.renameSync(tmp, file);
1445
2049
  return mergeAsideIntoStore(ctx, aside, accountLock);
1446
2050
  } finally {
1447
2051
  accountLock.release();
1448
2052
  }
1449
2053
  }
1450
2054
  function resumeHistoryAside(ctx, aside, shared) {
1451
- const file = path8.join(ctx.A, HISTORY);
2055
+ const file = path10.join(ctx.A, HISTORY);
1452
2056
  const st = lstatOrNull(file);
1453
- const asideStat = fs12.lstatSync(aside);
2057
+ const asideStat = fs15.lstatSync(aside);
1454
2058
  if (st?.isFile() && st.ino === asideStat.ino && st.dev === asideStat.dev) {
1455
- fs12.unlinkSync(aside);
2059
+ fs15.unlinkSync(aside);
1456
2060
  return { ok: true, added: 0 };
1457
2061
  }
1458
2062
  if (!shared) return mergeAsideIntoAccount(ctx, aside);
1459
2063
  return mergeAsideIntoStore(ctx, aside, null);
1460
2064
  }
1461
2065
  function mergeAsideIntoAccount(ctx, aside) {
1462
- const file = path8.join(ctx.A, HISTORY);
2066
+ const file = path10.join(ctx.A, HISTORY);
1463
2067
  const lock = DirLock.acquire(`${file}.lock`, HISTORY_LOCK, { waitMs: ctx.lockWaitMs, onWait: ctx.refreshStoreLock });
1464
2068
  if (!lock) return { ok: false, reason: "this account's history.jsonl is busy" };
1465
2069
  try {
@@ -1470,7 +2074,7 @@ function mergeAsideIntoAccount(ctx, aside) {
1470
2074
  if (!lock.refresh()) return { ok: false, reason: "a history lock was taken over" };
1471
2075
  writeFileAtomic(file, merged.length ? `${merged.join("\n")}
1472
2076
  ` : "", { mode: 384, fsync: true });
1473
- fs12.unlinkSync(aside);
2077
+ fs15.unlinkSync(aside);
1474
2078
  const before = new Set(own);
1475
2079
  return { ok: true, added: merged.filter((line) => !before.has(line)).length };
1476
2080
  } finally {
@@ -1479,23 +2083,23 @@ function mergeAsideIntoAccount(ctx, aside) {
1479
2083
  }
1480
2084
 
1481
2085
  // src/link/stub.ts
1482
- import fs13 from "node:fs";
1483
- import path9 from "node:path";
2086
+ import fs16 from "node:fs";
2087
+ import path11 from "node:path";
1484
2088
  var STUB_TEXT = "Shared instructions live in ~/.claude/CLAUDE.md, so edit that file.\n@~/.claude/CLAUDE.md\n";
1485
2089
  function stubState(A, S, enabled, detail) {
1486
- const storeHas = enabled && Boolean(statOrNull(path9.join(S, STUB))?.isFile());
1487
- const a = lstatOrNull(path9.join(A, STUB));
2090
+ const storeHas = enabled && Boolean(statOrNull(path11.join(S, STUB))?.isFile());
2091
+ const a = lstatOrNull(path11.join(A, STUB));
1488
2092
  if (!a) return storeHas ? "create" : "none";
1489
2093
  if (storeHas && !detail) return "ok";
1490
- const isStub = a.isFile() && readFileOrNull(path9.join(A, STUB)) === STUB_TEXT;
2094
+ const isStub = a.isFile() && readFileOrNull(path11.join(A, STUB)) === STUB_TEXT;
1491
2095
  if (storeHas) return isStub ? "ok" : "differs";
1492
2096
  return isStub ? "remove" : "differs";
1493
2097
  }
1494
2098
  function applyStub(A, state) {
1495
- const file = path9.join(A, STUB);
2099
+ const file = path11.join(A, STUB);
1496
2100
  if (state === "create") {
1497
2101
  try {
1498
- fs13.writeFileSync(file, STUB_TEXT, { flag: "wx", mode: 384 });
2102
+ fs16.writeFileSync(file, STUB_TEXT, { flag: "wx", mode: 384 });
1499
2103
  return "created";
1500
2104
  } catch (e) {
1501
2105
  if (errCode(e) === "EEXIST") return null;
@@ -1503,7 +2107,7 @@ function applyStub(A, state) {
1503
2107
  }
1504
2108
  }
1505
2109
  if (state === "remove" && readFileOrNull(file) === STUB_TEXT) {
1506
- fs13.unlinkSync(file);
2110
+ fs16.unlinkSync(file);
1507
2111
  return "removed";
1508
2112
  }
1509
2113
  return null;
@@ -1521,8 +2125,8 @@ function storeKind(p) {
1521
2125
  return st.isDirectory() ? "dir" : st.isFile() ? "file" : "other";
1522
2126
  }
1523
2127
  function classifyEntry(A, S, name, kind) {
1524
- const a = path10.join(A, name);
1525
- const s = path10.join(S, name);
2128
+ const a = path12.join(A, name);
2129
+ const s = path12.join(S, name);
1526
2130
  const lst = lstatOrNull(a);
1527
2131
  const optional = OPTIONAL_DIRS.has(name);
1528
2132
  const sk = storeKind(s);
@@ -1553,7 +2157,7 @@ function inspectAccount(paths, account, table, detail = false) {
1553
2157
  const S = paths.store;
1554
2158
  let dirents;
1555
2159
  try {
1556
- dirents = fs14.readdirSync(A, { withFileTypes: true });
2160
+ dirents = fs17.readdirSync(A, { withFileTypes: true });
1557
2161
  } catch (e) {
1558
2162
  if (errCode(e) !== "ENOENT") throw e;
1559
2163
  return { dir: A, exists: false, entries: [], leftovers: [], stub: "none", names: [] };
@@ -1564,8 +2168,8 @@ function inspectAccount(paths, account, table, detail = false) {
1564
2168
  for (const d of dirents) {
1565
2169
  const name = d.name;
1566
2170
  if (!d.isSymbolicLink() || shared.has(name) || name === STUB || NEVER_SHARED.includes(name) || isIgnored(name)) continue;
1567
- const target = readlinkOrNull(path10.join(A, name));
1568
- const s = path10.join(S, name);
2171
+ const target = readlinkOrNull(path12.join(A, name));
2172
+ const s = path12.join(S, name);
1569
2173
  if (target === null || target !== s && target !== realpathOrNull(s)) continue;
1570
2174
  const kind = name === HISTORY || storeKind(s) === "file" ? "file" : "dir";
1571
2175
  entries.push({ name, kind, state: "unshare", target });
@@ -1630,11 +2234,11 @@ function describeProblems(insp, paths) {
1630
2234
  return problems;
1631
2235
  }
1632
2236
  function ensureStoreEntry(S, name, kind) {
1633
- fs14.mkdirSync(S, { recursive: true, mode: 448 });
1634
- const p = path10.join(S, name);
2237
+ fs17.mkdirSync(S, { recursive: true, mode: 448 });
2238
+ const p = path12.join(S, name);
1635
2239
  try {
1636
- if (kind === "dir") fs14.mkdirSync(p, { mode: 448 });
1637
- else fs14.closeSync(fs14.openSync(p, "wx", 384));
2240
+ if (kind === "dir") fs17.mkdirSync(p, { mode: 448 });
2241
+ else fs17.closeSync(fs17.openSync(p, "wx", 384));
1638
2242
  } catch (e) {
1639
2243
  if (errCode(e) !== "EEXIST") throw e;
1640
2244
  }
@@ -1712,10 +2316,10 @@ var Repairer = class {
1712
2316
  /** realpath(S/E), created first if missing. Never a path inside an account dir. */
1713
2317
  linkTarget(info) {
1714
2318
  ensureStoreEntry(this.S, info.name, info.kind);
1715
- const target = realpathOrNull(path10.join(this.S, info.name));
2319
+ const target = realpathOrNull(path12.join(this.S, info.name));
1716
2320
  if (!target) throw new Error(`${this.storePath(info.name)} doesn't resolve`);
1717
2321
  const accounts = realpathOrNull(this.opts.paths.accounts) ?? this.opts.paths.accounts;
1718
- if (target === accounts || target.startsWith(`${accounts}${path10.sep}`)) {
2322
+ if (target === accounts || target.startsWith(`${accounts}${path12.sep}`)) {
1719
2323
  throw new Error(`${this.storePath(info.name)} resolves into ${tildify(target, this.opts.paths.home)}, inside an account dir; make it a real ${info.kind === "dir" ? "directory" : "file"} again`);
1720
2324
  }
1721
2325
  return target;
@@ -1723,7 +2327,7 @@ var Repairer = class {
1723
2327
  createLink(info, depth) {
1724
2328
  const target = this.linkTarget(info);
1725
2329
  try {
1726
- fs14.symlinkSync(target, path10.join(this.A, info.name));
2330
+ fs17.symlinkSync(target, path12.join(this.A, info.name));
1727
2331
  } catch (e) {
1728
2332
  if (errCode(e) !== "EEXIST" || depth > 0) throw e;
1729
2333
  this.act(classifyEntry(this.A, this.S, info.name, info.kind), depth + 1);
@@ -1731,22 +2335,22 @@ var Repairer = class {
1731
2335
  }
1732
2336
  replaceLink(info) {
1733
2337
  const target = this.linkTarget(info);
1734
- const a = path10.join(this.A, info.name);
2338
+ const a = path12.join(this.A, info.name);
1735
2339
  const tmp = siblingName(a, "link");
1736
- fs14.symlinkSync(target, tmp);
1737
- fs14.renameSync(tmp, a);
2340
+ fs17.symlinkSync(target, tmp);
2341
+ fs17.renameSync(tmp, a);
1738
2342
  this.opts.log(`xclaude: ${this.label}/${info.name} pointed to ${info.target}; relinked to ${this.storePath(info.name)}`);
1739
2343
  }
1740
2344
  unshare(info) {
1741
- const a = path10.join(this.A, info.name);
2345
+ const a = path12.join(this.A, info.name);
1742
2346
  if (info.kind === "file") {
1743
2347
  const tmp = siblingName(a, "unshare");
1744
- fs14.closeSync(fs14.openSync(tmp, "wx", 384));
1745
- fs14.renameSync(tmp, a);
2348
+ fs17.closeSync(fs17.openSync(tmp, "wx", 384));
2349
+ fs17.renameSync(tmp, a);
1746
2350
  } else {
1747
- fs14.unlinkSync(a);
2351
+ fs17.unlinkSync(a);
1748
2352
  try {
1749
- fs14.mkdirSync(a, { mode: 448 });
2353
+ fs17.mkdirSync(a, { mode: 448 });
1750
2354
  } catch (e) {
1751
2355
  if (errCode(e) !== "EEXIST") throw e;
1752
2356
  }
@@ -1772,7 +2376,7 @@ var Repairer = class {
1772
2376
  * was lost: then another process may already rely on those links.
1773
2377
  */
1774
2378
  mergeDir(info) {
1775
- const a = path10.join(this.A, info.name);
2379
+ const a = path12.join(this.A, info.name);
1776
2380
  const target = this.linkTarget(info);
1777
2381
  const ctx = this.moveContext();
1778
2382
  const stats = emptyStats();
@@ -1797,15 +2401,15 @@ var Repairer = class {
1797
2401
  }
1798
2402
  const asides = [];
1799
2403
  for (let attempt = 0; ; attempt++) {
1800
- const aside = path10.join(this.A, asideName(info.name));
1801
- fs14.renameSync(a, aside);
2404
+ const aside = path12.join(this.A, asideName(info.name));
2405
+ fs17.renameSync(a, aside);
1802
2406
  asides.push(aside);
1803
2407
  try {
1804
- fs14.symlinkSync(target, a);
2408
+ fs17.symlinkSync(target, a);
1805
2409
  break;
1806
2410
  } catch (e) {
1807
2411
  if (errCode(e) !== "EEXIST") {
1808
- fs14.renameSync(asides[0], a);
2412
+ fs17.renameSync(asides[0], a);
1809
2413
  if (asides.length === 1) undoLinks(rec);
1810
2414
  throw e;
1811
2415
  }
@@ -1816,7 +2420,7 @@ var Repairer = class {
1816
2420
  }
1817
2421
  asides.forEach((aside, i) => {
1818
2422
  moveTree(aside, target, ctx, stats, i === 0 ? rec : null);
1819
- fs14.rmdirSync(aside);
2423
+ fs17.rmdirSync(aside);
1820
2424
  });
1821
2425
  const line = summarize(this.label, info.name, this.storePath(info.name), stats);
1822
2426
  if (line) this.opts.log(line);
@@ -1852,11 +2456,11 @@ var Repairer = class {
1852
2456
  }
1853
2457
  }
1854
2458
  resumeLeftover(name) {
1855
- const p = path10.join(this.A, name);
2459
+ const p = path12.join(this.A, name);
1856
2460
  if (name.startsWith(".xclaude-link-") || name.startsWith(".xclaude-unshare-") || name.startsWith(".xclaude-tmp-")) {
1857
2461
  const st2 = lstatOrNull(p);
1858
- if (st2?.isDirectory()) fs14.rmdirSync(p);
1859
- else if (st2) fs14.unlinkSync(p);
2462
+ if (st2?.isDirectory()) fs17.rmdirSync(p);
2463
+ else if (st2) fs17.unlinkSync(p);
1860
2464
  return;
1861
2465
  }
1862
2466
  const entry = parseAside(name);
@@ -1867,7 +2471,7 @@ var Repairer = class {
1867
2471
  const st = lstatOrNull(p);
1868
2472
  if (!st) return;
1869
2473
  if (st.isSymbolicLink()) {
1870
- fs14.unlinkSync(p);
2474
+ fs17.unlinkSync(p);
1871
2475
  return;
1872
2476
  }
1873
2477
  if (entry === HISTORY ? !st.isFile() : !st.isDirectory()) {
@@ -1881,22 +2485,22 @@ var Repairer = class {
1881
2485
  return;
1882
2486
  }
1883
2487
  if (!this.opts.table.dirs.includes(entry)) {
1884
- const own = path10.join(this.A, entry);
1885
- if (!lstatOrNull(own)) fs14.mkdirSync(own, { mode: 448 });
1886
- const st2 = fs14.lstatSync(own);
2488
+ const own = path12.join(this.A, entry);
2489
+ if (!lstatOrNull(own)) fs17.mkdirSync(own, { mode: 448 });
2490
+ const st2 = fs17.lstatSync(own);
1887
2491
  if (!st2.isDirectory() || st2.isSymbolicLink()) {
1888
2492
  this.problem(name, `left by an interrupted merge of ${entry}; ${entry} isn't a directory, so move the contents back by hand`);
1889
2493
  return;
1890
2494
  }
1891
2495
  moveTree(p, own, this.moveContext(), emptyStats());
1892
- fs14.rmdirSync(p);
2496
+ fs17.rmdirSync(p);
1893
2497
  return;
1894
2498
  }
1895
2499
  const target = this.linkTarget({ name: entry, kind: "dir", state: "ok" });
1896
2500
  const stats = emptyStats();
1897
2501
  try {
1898
2502
  moveTree(p, target, this.moveContext(), stats);
1899
- fs14.rmdirSync(p);
2503
+ fs17.rmdirSync(p);
1900
2504
  } catch (e) {
1901
2505
  this.cannotMerge(entry, e);
1902
2506
  return;
@@ -1909,7 +2513,7 @@ function unmanageable(A, store) {
1909
2513
  if (lstatOrNull(A)?.isSymbolicLink()) return "is a symlink; xclaude only manages real folders there, so it leaves this one alone";
1910
2514
  const realA = realpathOrNull(A);
1911
2515
  const realS = realpathOrNull(store);
1912
- if (realA && realS && (realA === realS || realS.startsWith(`${realA}${path10.sep}`))) {
2516
+ if (realA && realS && (realA === realS || realS.startsWith(`${realA}${path12.sep}`))) {
1913
2517
  return "is the shared store or holds it; xclaude leaves it alone";
1914
2518
  }
1915
2519
  return null;
@@ -1923,7 +2527,7 @@ function repairAccount(opts) {
1923
2527
  const problems = describeProblems(insp, opts.paths);
1924
2528
  return { clean: problems.length === 0, busy: false, problems, names: insp.names };
1925
2529
  }
1926
- const lock = DirLock.acquire(path10.join(opts.paths.locks, "store"), STORE_LOCK, { waitMs: opts.lockWaitMs });
2530
+ const lock = DirLock.acquire(path12.join(opts.paths.locks, "store"), STORE_LOCK, { waitMs: opts.lockWaitMs });
1927
2531
  if (!lock) {
1928
2532
  const problems = describeProblems(insp, opts.paths);
1929
2533
  return { clean: false, busy: true, problems, names: insp.names };
@@ -2036,19 +2640,21 @@ function applyDefaultOptions(p, home, into) {
2036
2640
  const args = stringOption(p, "args");
2037
2641
  if (args !== void 0) into.args = splitShellWords(args, home);
2038
2642
  }
2039
- function formatDefaults(d) {
2643
+ function formatDefaults(d, account = false) {
2644
+ const inherit = d.inherit === void 0 ? "not chosen yet" : d.inherit ? "on" : "off";
2040
2645
  return [
2041
2646
  ` model ${d.model ?? DASH}`,
2042
2647
  ` effort ${d.effort ?? DASH}`,
2043
- ` args ${d.args.length ? quoteShellWords(d.args) : DASH}`
2648
+ ` args ${d.args.length ? quoteShellWords(d.args) : DASH}`,
2649
+ ...account ? [` inherit ${inherit}`] : []
2044
2650
  ].map((l) => `${l}
2045
2651
  `).join("");
2046
2652
  }
2047
2653
 
2048
2654
  // src/commands/add.ts
2049
- var USAGE = 'usage: xclaude add <name> [--model M] [--effort E] [--args "\u2026"]';
2655
+ var USAGE = 'usage: xclaude add <name> [--model M] [--effort E] [--args "\u2026"] [--inherit on|off]';
2050
2656
  async function addCommand(ctx, config, args) {
2051
- const p = parseOptions(args, DEFAULT_OPTIONS, "add");
2657
+ const p = parseOptions(args, { ...DEFAULT_OPTIONS, inherit: { value: true } }, "add");
2052
2658
  const [name, ...extra] = p.positionals;
2053
2659
  if (!name || extra.length) throw new UsageError(USAGE);
2054
2660
  const problem2 = accountNameProblem(name);
@@ -2056,13 +2662,17 @@ async function addCommand(ctx, config, args) {
2056
2662
  if (Object.hasOwn(config.accounts, name)) throw new XError(`account "${name}" already exists; change its defaults with: xclaude set ${name}`);
2057
2663
  const defaults = { model: null, effort: null, args: [] };
2058
2664
  applyDefaultOptions(p, ctx.paths.home, defaults);
2665
+ const inherit = stringOption(p, "inherit");
2666
+ if (inherit !== void 0 && inherit !== "on" && inherit !== "off") throw new UsageError(`--inherit takes on or off, not "${inherit}"`);
2059
2667
  const claude = findClaude(ctx.env, config, ctx.paths.home, ctx.selfPath);
2060
2668
  const log = (line) => ctx.io.err(`${line}
2061
2669
  `);
2062
2670
  const dir = accountDir(ctx.paths, name);
2063
2671
  const refusal = unmanageable(dir, ctx.paths.store);
2064
2672
  if (refusal) throw new XError(`not adding ${name}: ${tildify(dir, ctx.paths.home)} ${refusal}. Replace it with a real folder, or remove it, then add ${name} again.`);
2065
- if (fs15.existsSync(dir)) log(`xclaude: ${tildify(dir, ctx.paths.home)} already exists; reusing it`);
2673
+ const take = inherit !== void 0 ? inherit === "on" : await askInherit(ctx, name);
2674
+ if (take !== void 0) defaults.inherit = take;
2675
+ if (fs18.existsSync(dir)) log(`xclaude: ${tildify(dir, ctx.paths.home)} already exists; reusing it`);
2066
2676
  mkdirPrivate(dir);
2067
2677
  const table = shareTable(config, ctx.switches);
2068
2678
  const res = repairAccount({
@@ -2074,7 +2684,8 @@ async function addCommand(ctx, config, args) {
2074
2684
  log
2075
2685
  });
2076
2686
  for (const pr of res.problems) log(`xclaude: ${problemLine(name, pr)}`);
2077
- if (table.dirs.includes("plugins")) listPlugins(ctx.paths, name, { lockWaitMs: Infinity, log });
2687
+ if (take) inheritSettings(ctx.paths, name, { lockWaitMs: Infinity, log });
2688
+ if (table.dirs.includes("plugins")) listPlugins(ctx.paths, name, { lockWaitMs: Infinity, log, follow: take === true });
2078
2689
  config = loadConfig(ctx.paths, { create: false }).config;
2079
2690
  config.accounts[name] = defaults;
2080
2691
  saveConfig(ctx.paths, config);
@@ -2086,12 +2697,14 @@ async function addCommand(ctx, config, args) {
2086
2697
  log(`xclaude: ${name} isn't logged in yet. Log in later with \`xclaude ${name} auth login\`, or /login inside \`xclaude ${name}\`.`);
2087
2698
  return EXIT_OK;
2088
2699
  }
2089
- log(`xclaude: ${name} is logged in as ${describeLogin(status)}. Launch it with: xclaude ${name}`);
2700
+ const credential = otherCredential(status);
2701
+ if (credential) log(`xclaude: ${name} signs in with ${credential}, not a claude.ai login. Launch it with: xclaude ${name}`);
2702
+ else log(`xclaude: ${name} is logged in as ${describeLogin(status)}. Launch it with: xclaude ${name}`);
2090
2703
  const others = identities(config).filter((n) => n !== name);
2091
2704
  const theirs = await Promise.all(others.map((n) => authStatus(claude, identityEnv(ctx, n))));
2092
2705
  others.forEach((other, i) => {
2093
2706
  const s = theirs[i];
2094
- if (s.loggedIn && s.email === status.email && s.orgId === status.orgId) {
2707
+ if (status.email && s.loggedIn && s.email === status.email && s.orgId === status.orgId) {
2095
2708
  log(`xclaude: warning: ${name} and ${other} use the same login (${describeLogin(status)})`);
2096
2709
  }
2097
2710
  });
@@ -2100,12 +2713,12 @@ async function addCommand(ctx, config, args) {
2100
2713
 
2101
2714
  // src/commands/doctor.ts
2102
2715
  import { spawnSync as spawnSync2 } from "node:child_process";
2103
- import fs20 from "node:fs";
2104
- import path15 from "node:path";
2716
+ import fs23 from "node:fs";
2717
+ import path17 from "node:path";
2105
2718
 
2106
2719
  // src/link/normalize.ts
2107
- import fs16 from "node:fs";
2108
- import path11 from "node:path";
2720
+ import fs19 from "node:fs";
2721
+ import path13 from "node:path";
2109
2722
  var REGISTRY_FILES = ["plugins/installed_plugins.json", "plugins/known_marketplaces.json"];
2110
2723
  function escapeRe(s) {
2111
2724
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -2125,17 +2738,17 @@ function rewrite(value, re, to, onChange) {
2125
2738
  return value;
2126
2739
  }
2127
2740
  function planNormalization(paths, account) {
2128
- const accountsDir = path11.join(paths.xhome, "accounts");
2129
- const to = path11.join(paths.home, ".claude");
2741
+ const accountsDir = path13.join(paths.xhome, "accounts");
2742
+ const to = path13.join(paths.home, ".claude");
2130
2743
  const name = account ? escapeRe(account) : "[a-z][a-z0-9-]{0,31}";
2131
2744
  const re = new RegExp(`^${escapeRe(accountsDir)}/(${name})(/|$)`);
2132
2745
  const plans = [];
2133
2746
  for (const rel of REGISTRY_FILES) {
2134
- const file = realpathOrNull(path11.join(paths.store, rel));
2747
+ const file = realpathOrNull(path13.join(paths.store, rel));
2135
2748
  if (!file) continue;
2136
2749
  const st = lstatOrNull(file);
2137
2750
  if (!st?.isFile()) continue;
2138
- const original = fs16.readFileSync(file, "utf8");
2751
+ const original = fs19.readFileSync(file, "utf8");
2139
2752
  if (!original.includes(accountsDir)) continue;
2140
2753
  let parsed;
2141
2754
  try {
@@ -2168,7 +2781,7 @@ function applyNormalization(plans) {
2168
2781
  function normalizePaths(paths, opts) {
2169
2782
  const plans = planNormalization(paths, opts.account);
2170
2783
  if (!plans.length) return { changed: [], skipped: [], busy: false };
2171
- const lock = DirLock.acquire(path11.join(paths.locks, "store"), STORE_LOCK, { waitMs: opts.lockWaitMs });
2784
+ const lock = DirLock.acquire(path13.join(paths.locks, "store"), STORE_LOCK, { waitMs: opts.lockWaitMs });
2172
2785
  if (!lock) return { changed: [], skipped: plans.map((p) => p.file), busy: true };
2173
2786
  try {
2174
2787
  const result = applyNormalization(plans);
@@ -2182,12 +2795,12 @@ function normalizePaths(paths, opts) {
2182
2795
  }
2183
2796
 
2184
2797
  // src/link/leftover.ts
2185
- import fs17 from "node:fs";
2186
- import path12 from "node:path";
2798
+ import fs20 from "node:fs";
2799
+ import path14 from "node:path";
2187
2800
  function strayFolders(paths, config) {
2188
2801
  let names;
2189
2802
  try {
2190
- names = fs17.readdirSync(paths.accounts);
2803
+ names = fs20.readdirSync(paths.accounts);
2191
2804
  } catch {
2192
2805
  return [];
2193
2806
  }
@@ -2195,14 +2808,14 @@ function strayFolders(paths, config) {
2195
2808
  const out = [];
2196
2809
  for (const name of names.sort()) {
2197
2810
  if (name.endsWith(".lock") || name === ".DS_Store" || Object.hasOwn(config.accounts, name)) continue;
2198
- const dir = path12.join(paths.accounts, name);
2811
+ const dir = path14.join(paths.accounts, name);
2199
2812
  const st = lstatOrNull(dir);
2200
2813
  if (!st) continue;
2201
2814
  if (st.isSymbolicLink()) out.push({ name, dir, kind: "link", entries: [] });
2202
2815
  else if (!st.isDirectory() || accounts.some((a) => a.dev === st.dev && a.ino === st.ino)) continue;
2203
2816
  else if (accountNameProblem(name)) out.push({ name, dir, kind: "stray", entries: [] });
2204
2817
  else {
2205
- const entries = fs17.readdirSync(dir).filter((e) => e !== ".DS_Store" && !lstatOrNull(path12.join(dir, e))?.isSymbolicLink());
2818
+ const entries = fs20.readdirSync(dir).filter((e) => e !== ".DS_Store" && !lstatOrNull(path14.join(dir, e))?.isSymbolicLink());
2206
2819
  out.push({ name, dir, kind: entries.length ? "content" : "leftover", entries });
2207
2820
  }
2208
2821
  }
@@ -2217,27 +2830,31 @@ function linkNames(table) {
2217
2830
  function hasContent(p) {
2218
2831
  const st = lstatOrNull(p);
2219
2832
  if (!st) return false;
2220
- if (st.isDirectory()) return fs17.readdirSync(p).some((e) => e !== ".DS_Store");
2833
+ if (st.isDirectory()) return fs20.readdirSync(p).some((e) => e !== ".DS_Store");
2221
2834
  return st.size > 0;
2222
2835
  }
2836
+ function madeByUser(p, name, table) {
2837
+ if (name === STUB) return !(lstatOrNull(p)?.isFile() && readFileOrNull(p) === STUB_TEXT);
2838
+ return !isKnown(name, table) && !isIgnored(name);
2839
+ }
2223
2840
  function keepOnlyLinks(dir, table) {
2224
2841
  if (lstatOrNull(dir)?.isSymbolicLink()) throw new Error(`${dir} is a symlink`);
2225
2842
  const shared = linkNames(table);
2226
2843
  const content = [];
2227
2844
  let links = 0;
2228
- for (const name of fs17.readdirSync(dir)) {
2229
- const p = path12.join(dir, name);
2845
+ for (const name of fs20.readdirSync(dir).sort()) {
2846
+ const p = path14.join(dir, name);
2230
2847
  if (shared.has(name) && lstatOrNull(p)?.isSymbolicLink()) links++;
2231
- else if (shared.has(name) && hasContent(p)) content.push(name);
2848
+ else if ((shared.has(name) || madeByUser(p, name, table)) && hasContent(p)) content.push(name);
2232
2849
  else removeTree(p);
2233
2850
  }
2234
2851
  if (links || content.length) return { kept: true, content };
2235
- fs17.rmdirSync(dir);
2852
+ fs20.rmdirSync(dir);
2236
2853
  return { kept: false, content };
2237
2854
  }
2238
2855
 
2239
2856
  // src/link/unknown.ts
2240
- import fs18 from "node:fs";
2857
+ import fs21 from "node:fs";
2241
2858
  function unknownEntries(names, table) {
2242
2859
  return names.filter((n) => !isIgnored(n) && !isKnown(n, table)).sort();
2243
2860
  }
@@ -2253,7 +2870,7 @@ function unknownNotice(account, entry, configLabel) {
2253
2870
  function storeUnknownEntries(store, table) {
2254
2871
  let names;
2255
2872
  try {
2256
- names = fs18.readdirSync(store);
2873
+ names = fs21.readdirSync(store);
2257
2874
  } catch (e) {
2258
2875
  if (errCode(e) === "ENOENT") return [];
2259
2876
  throw e;
@@ -2262,8 +2879,8 @@ function storeUnknownEntries(store, table) {
2262
2879
  }
2263
2880
 
2264
2881
  // src/shell/rc.ts
2265
- import fs19 from "node:fs";
2266
- import path13 from "node:path";
2882
+ import fs22 from "node:fs";
2883
+ import path15 from "node:path";
2267
2884
  var START = "# >>> xclaude >>>";
2268
2885
  var END = "# <<< xclaude <<<";
2269
2886
  function dquote(s) {
@@ -2312,14 +2929,14 @@ function sourcesBashrc(text) {
2312
2929
  return text.split("\n").some((l) => !/^\s*#/.test(l) && /\.bashrc\b/.test(l) && /(^|[\s;&|({])(\.|source)\s/.test(l));
2313
2930
  }
2314
2931
  function rcTargets(env, home, platform, want) {
2315
- const zshrc = path13.join(env.ZDOTDIR || home, ".zshrc");
2316
- const bashrc = path13.join(home, ".bashrc");
2932
+ const zshrc = path15.join(env.ZDOTDIR || home, ".zshrc");
2933
+ const bashrc = path15.join(home, ".bashrc");
2317
2934
  const explicit = want.bash || want.zsh;
2318
2935
  const targets = [];
2319
- if (explicit ? want.zsh : fs19.existsSync(zshrc)) targets.push({ shell: "zsh", file: zshrc });
2320
- if (explicit ? want.bash : fs19.existsSync(bashrc)) {
2936
+ if (explicit ? want.zsh : fs22.existsSync(zshrc)) targets.push({ shell: "zsh", file: zshrc });
2937
+ if (explicit ? want.bash : fs22.existsSync(bashrc)) {
2321
2938
  targets.push({ shell: "bash", file: bashrc });
2322
- const profile = path13.join(home, ".bash_profile");
2939
+ const profile = path15.join(home, ".bash_profile");
2323
2940
  const text = platform === "darwin" ? readFileOrNull(profile) : null;
2324
2941
  if (text !== null && !sourcesBashrc(text)) targets.push({ shell: "bash", file: profile });
2325
2942
  }
@@ -2328,11 +2945,11 @@ function rcTargets(env, home, platform, want) {
2328
2945
  function writeRc(file, text, previous) {
2329
2946
  if (text === previous) return { file, status: "unchanged" };
2330
2947
  const real = realpathOrNull(file);
2331
- if (real === null && fs19.lstatSync(file, { throwIfNoEntry: false })?.isSymbolicLink()) return { file, status: "manual", text };
2948
+ if (real === null && fs22.lstatSync(file, { throwIfNoEntry: false })?.isSymbolicLink()) return { file, status: "manual", text };
2332
2949
  try {
2333
2950
  const target = real ?? file;
2334
- fs19.accessSync(path13.dirname(target), fs19.constants.W_OK);
2335
- if (previous !== null) fs19.accessSync(target, fs19.constants.W_OK);
2951
+ fs22.accessSync(path15.dirname(target), fs22.constants.W_OK);
2952
+ if (previous !== null) fs22.accessSync(target, fs22.constants.W_OK);
2336
2953
  writeFileAtomic(target, text, { mode: 420 });
2337
2954
  return { file, status: "written" };
2338
2955
  } catch (e) {
@@ -2342,9 +2959,9 @@ function writeRc(file, text, previous) {
2342
2959
  }
2343
2960
  function knownRcFiles(env, home) {
2344
2961
  return [
2345
- { shell: "zsh", file: path13.join(env.ZDOTDIR || home, ".zshrc") },
2346
- { shell: "bash", file: path13.join(home, ".bashrc") },
2347
- { shell: "bash", file: path13.join(home, ".bash_profile") }
2962
+ { shell: "zsh", file: path15.join(env.ZDOTDIR || home, ".zshrc") },
2963
+ { shell: "bash", file: path15.join(home, ".bashrc") },
2964
+ { shell: "bash", file: path15.join(home, ".bash_profile") }
2348
2965
  ];
2349
2966
  }
2350
2967
  function installedIn(env, home) {
@@ -2353,12 +2970,13 @@ function installedIn(env, home) {
2353
2970
 
2354
2971
  // src/tmux/client.ts
2355
2972
  import { spawnSync } from "node:child_process";
2356
- import path14 from "node:path";
2973
+ import path16 from "node:path";
2357
2974
  var STRIPPED_ENV = [
2358
2975
  "CLAUDE_CONFIG_DIR",
2359
2976
  "XCLAUDE_ACCOUNT",
2360
2977
  "CLAUDE_CODE_CHILD_SESSION",
2361
2978
  "CLAUDE_SECURESTORAGE_CONFIG_DIR",
2979
+ "CLAUDE_CODE_REMOTE_MEMORY_DIR",
2362
2980
  "CLAUDECODE",
2363
2981
  "CLAUDE_CODE_SESSION_ID",
2364
2982
  "CLAUDE_CODE_SESSION_ATTENDED",
@@ -2383,9 +3001,9 @@ function escapeArg(arg) {
2383
3001
  }
2384
3002
  var TMUX_INSTALL_HINT = process.platform === "darwin" ? "install it with: brew install tmux" : "install it with your package manager, e.g. sudo apt install tmux";
2385
3003
  function findTmux(env) {
2386
- for (const dir of (env.PATH ?? "").split(path14.delimiter)) {
2387
- if (!dir || !path14.isAbsolute(dir)) continue;
2388
- const candidate = path14.join(dir, "tmux");
3004
+ for (const dir of (env.PATH ?? "").split(path16.delimiter)) {
3005
+ if (!dir || !path16.isAbsolute(dir)) continue;
3006
+ const candidate = path16.join(dir, "tmux");
2389
3007
  if (isExecutableFile(candidate)) return candidate;
2390
3008
  }
2391
3009
  return null;
@@ -2458,10 +3076,10 @@ function readForcedOrgs(ctx) {
2458
3076
  }
2459
3077
  const files = [];
2460
3078
  for (const dir of dirs) {
2461
- files.push(path15.join(dir, "managed-settings.json"));
3079
+ files.push(path17.join(dir, "managed-settings.json"));
2462
3080
  try {
2463
- for (const name of fs20.readdirSync(path15.join(dir, "managed-settings.d")).sort()) {
2464
- if (name.endsWith(".json")) files.push(path15.join(dir, "managed-settings.d", name));
3081
+ for (const name of fs23.readdirSync(path17.join(dir, "managed-settings.d")).sort()) {
3082
+ if (name.endsWith(".json")) files.push(path17.join(dir, "managed-settings.d", name));
2465
3083
  }
2466
3084
  } catch {
2467
3085
  }
@@ -2498,7 +3116,7 @@ function readForcedOrgs(ctx) {
2498
3116
  }
2499
3117
  function remoteCleanupDays(dir) {
2500
3118
  try {
2501
- const json = JSON.parse(readFileOrNull(path15.join(dir, "remote-settings.json")) ?? "null");
3119
+ const json = JSON.parse(readFileOrNull(path17.join(dir, "remote-settings.json")) ?? "null");
2502
3120
  const value = json?.cleanupPeriodDays ?? json?.settings?.cleanupPeriodDays;
2503
3121
  return typeof value === "number" ? value : null;
2504
3122
  } catch {
@@ -2531,8 +3149,11 @@ async function doctorCommand(ctx, args) {
2531
3149
  repairAccount({ paths: ctx.paths, account: name, table, lockWaitMs: Infinity, replaceWrongLinks: true, log });
2532
3150
  }
2533
3151
  if (ctx.switches.normalizePaths && table.dirs.includes("plugins")) normalizePaths(ctx.paths, { lockWaitMs: Infinity, log });
3152
+ for (const name of Object.keys(config.accounts)) {
3153
+ if (inherits(config, name)) inheritSettings(ctx.paths, name, { lockWaitMs: Infinity, log });
3154
+ }
2534
3155
  if (table.dirs.includes("plugins")) {
2535
- for (const name of Object.keys(config.accounts)) listPlugins(ctx.paths, name, { lockWaitMs: Infinity, log });
3156
+ for (const name of Object.keys(config.accounts)) listPlugins(ctx.paths, name, { lockWaitMs: Infinity, log, follow: inherits(config, name) });
2536
3157
  }
2537
3158
  }
2538
3159
  report.section("Tools");
@@ -2554,7 +3175,7 @@ async function doctorCommand(ctx, args) {
2554
3175
  report.add("ok", `Node ${process.versions.node}`);
2555
3176
  report.section("Config");
2556
3177
  if (configProblem) report.add("error", configProblem);
2557
- else report.add("ok", `${t(ctx.paths.config)}${fs20.existsSync(ctx.paths.config) ? "" : " (not created yet)"}`);
3178
+ else report.add("ok", `${t(ctx.paths.config)}${fs23.existsSync(ctx.paths.config) ? "" : " (not created yet)"}`);
2558
3179
  for (const name of table.refused) report.add("warn", `share.add "${name}" is ignored: never-shared entries and file names can't be shared`);
2559
3180
  const names = identities(config);
2560
3181
  const logins = /* @__PURE__ */ new Map();
@@ -2567,7 +3188,10 @@ async function doctorCommand(ctx, args) {
2567
3188
  if (configProblem) report.add("info", "not checked: fix the config first (account dirs are left alone)");
2568
3189
  else if (!names.length) report.add("info", "no accounts yet; add one with: xclaude add <name>");
2569
3190
  const storeDev = statOrNull(ctx.paths.store)?.dev;
2570
- const listed = loadState(ctx.paths).listedPlugins;
3191
+ const pluginState = loadState(ctx.paths);
3192
+ const mainOn = mainPlugins(ctx.paths);
3193
+ const fromMain = mainSettings(ctx.paths);
3194
+ const shared = "settings" in fromMain && Object.keys(inheritable(fromMain.settings)).length ? fromMain.settings : null;
2571
3195
  for (const name of names) {
2572
3196
  const login = logins.get(name);
2573
3197
  report.lines.push(` ${name}${login ? ` ${describeLogin(login)}` : ""}`);
@@ -2592,9 +3216,36 @@ async function doctorCommand(ctx, args) {
2592
3216
  }
2593
3217
  const unknown = unknownEntries(insp.names, table);
2594
3218
  if (unknown.length) report.add("info", `per-account entries xclaude doesn't know: ${unknown.join(", ")}`, 2);
2595
- const plugins = table.dirs.includes("plugins") ? planPlugins(ctx.paths, name, listed[name] ?? [])?.add : void 0;
2596
- if (plugins?.length) {
2597
- report.add("info", `not in its /plugin yet, installed under another login: ${plugins.join(", ")} (the next launch, or --fix, lists ${plugins.length === 1 ? "it" : "them"} there, turned off)`, 2);
3219
+ const choice = config.accounts[name]?.inherit;
3220
+ if (choice === void 0) {
3221
+ if (setupPreview(ctx.paths, name).length) {
3222
+ report.add("info", `hasn't chosen whether to take ~/.claude's settings, plugins and MCP servers; its next launch in a terminal asks (or: xclaude set ${name} --inherit on, or off)`, 2);
3223
+ }
3224
+ } else if (shared && !choice) {
3225
+ report.add("info", `doesn't take ~/.claude/settings.json (turn that on with: xclaude set ${name} --inherit on)`, 2);
3226
+ } else if (shared) {
3227
+ const status = inheritStatus(ctx.paths, name, shared);
3228
+ if (!status) report.add("warn", "its settings.json is a link or isn't a valid JSON object, so ~/.claude/settings.json isn't merged into it", 2);
3229
+ else if (status.pending.length) {
3230
+ report.add("info", `~/.claude/settings.json changes not taken yet: ${status.pending.join(", ")} (the next launch, or --fix, takes them)`, 2);
3231
+ } else {
3232
+ report.add("ok", `takes ~/.claude/settings.json${status.own.length ? `, keeping its own ${status.own.join(", ")}` : ""}`, 2);
3233
+ }
3234
+ }
3235
+ const servers = inherits(config, name) ? Object.keys(mcpServersFor(ctx.paths, name) ?? {}) : [];
3236
+ if (servers.length) report.add("ok", `gets ~/.claude.json's MCP servers at launch: ${servers.join(", ")}`, 2);
3237
+ const tracked = { off: pluginState.listedPlugins[name] ?? [], on: pluginState.turnedOnPlugins[name] ?? [] };
3238
+ const plan = table.dirs.includes("plugins") ? planPlugins(ctx.paths, name, tracked, inherits(config, name) ? mainOn : null) : null;
3239
+ const them = (ids) => ids.length === 1 ? "it" : "them";
3240
+ const plugins = plan ? plan.add.filter((id) => !plan.turnOn.includes(id)) : [];
3241
+ if (plugins.length) {
3242
+ report.add("info", `not in its /plugin yet, installed under another login: ${plugins.join(", ")} (the next launch, or --fix, lists ${them(plugins)} there, turned off)`, 2);
3243
+ }
3244
+ if (plan?.turnOn.length) {
3245
+ report.add("info", `on in ~/.claude but not here yet: ${plan.turnOn.join(", ")} (the next launch, or --fix, turns ${them(plan.turnOn)} on)`, 2);
3246
+ }
3247
+ if (plan?.turnOff.length) {
3248
+ report.add("info", `off in ~/.claude but still on here: ${plan.turnOff.join(", ")} (the next launch, or --fix, turns ${them(plan.turnOff)} off)`, 2);
2598
3249
  }
2599
3250
  const dev = statOrNull(dir)?.dev;
2600
3251
  if (storeDev !== void 0 && dev !== void 0 && dev !== storeDev) {
@@ -2624,8 +3275,8 @@ async function doctorCommand(ctx, args) {
2624
3275
  ${s.orgId}`, [...byLogin.get(`${s.email}
2625
3276
  ${s.orgId}`) ?? [], n]);
2626
3277
  }
2627
- for (const [key, same] of byLogin) {
2628
- if (same.length > 1) report.add("warn", `${same.join(" and ")} use the same login (${key.split("\n")[0]})`);
3278
+ for (const [key, same2] of byLogin) {
3279
+ if (same2.length > 1) report.add("warn", `${same2.join(" and ")} use the same login (${key.split("\n")[0]})`);
2629
3280
  }
2630
3281
  for (const f of configProblem ? [] : strayFolders(ctx.paths, config)) {
2631
3282
  const where = t(f.dir);
@@ -2641,18 +3292,19 @@ ${s.orgId}`) ?? [], n]);
2641
3292
  }
2642
3293
  report.section("Store");
2643
3294
  const storeUnknown = storeUnknownEntries(ctx.paths.store, table);
2644
- if (!fs20.existsSync(ctx.paths.store)) report.add("info", `${t(ctx.paths.store)} doesn't exist yet`);
3295
+ if (!fs23.existsSync(ctx.paths.store)) report.add("info", `${t(ctx.paths.store)} doesn't exist yet`);
2645
3296
  else if (storeUnknown.length) report.add("info", `entries in ${t(ctx.paths.store)} that no account links to: ${storeUnknown.join(", ")}`);
2646
3297
  else report.add("ok", t(ctx.paths.store));
3298
+ if ("problem" in fromMain) report.add("warn", `${fromMain.problem}, so the accounts can't take it`);
2647
3299
  const mainDays = remoteCleanupDays(ctx.paths.store);
2648
3300
  if (mainDays !== null && mainDays < 30) {
2649
3301
  report.add("warn", `the ~/.claude login's organization sets cleanupPeriodDays to ${mainDays}: plain claude deletes everyone's shared transcripts older than ${mainDays} days`);
2650
3302
  }
2651
3303
  for (const entry of SHARED_DIRS) {
2652
- const p2 = path15.join(ctx.paths.store, entry);
2653
- if (!fs20.existsSync(p2)) continue;
3304
+ const p2 = path17.join(ctx.paths.store, entry);
3305
+ if (!fs23.existsSync(p2)) continue;
2654
3306
  try {
2655
- fs20.accessSync(p2, fs20.constants.W_OK);
3307
+ fs23.accessSync(p2, fs23.constants.W_OK);
2656
3308
  } catch {
2657
3309
  report.add("warn", `${t(p2)} isn't writable, so sessions can't save ${entry} there`);
2658
3310
  }
@@ -2672,6 +3324,19 @@ ${s.orgId}`) ?? [], n]);
2672
3324
  report.add("warn", `CLAUDE_CODE_EFFORT_LEVEL is set (${ctx.env.CLAUDE_CODE_EFFORT_LEVEL}); it overrides the effort level saved in every account's settings`);
2673
3325
  envFindings++;
2674
3326
  }
3327
+ const dropped = setIn(ctx.env, LOGIN_VARS);
3328
+ if (dropped.length) {
3329
+ const [is, it] = dropped.length === 1 ? ["is", "it"] : ["are", "them"];
3330
+ report.add("info", `${dropped.join(", ")} ${is} set: accounts don't get ${it}, so each signs in with its own login (plain claude still uses ${it})`);
3331
+ }
3332
+ const memory = ctx.env.CLAUDE_CODE_REMOTE_MEMORY_DIR;
3333
+ if (memory && memory !== ctx.paths.store) {
3334
+ report.add("info", `CLAUDE_CODE_REMOTE_MEMORY_DIR is set (${memory}): accounts keep it, so their memory goes there, as plain claude's does`);
3335
+ }
3336
+ for (const name of setIn(ctx.env, CREDENTIAL_VARS)) {
3337
+ report.add("warn", `${name} is set, so Claude Code may use it instead of each account's own login; unset it in your shell profile to stop that`);
3338
+ envFindings++;
3339
+ }
2675
3340
  if (!envFindings) report.add("ok", "nothing that overrides accounts");
2676
3341
  report.lines.push("");
2677
3342
  const summary = report.errors || report.warnings ? `${report.errors} problem${report.errors === 1 ? "" : "s"}, ${report.warnings} warning${report.warnings === 1 ? "" : "s"}${report.errors && !p.values.fix ? ". Run `xclaude doctor --fix` to repair what can be repaired." : "."}` : "All good.";
@@ -2682,8 +3347,8 @@ ${s.orgId}`) ?? [], n]);
2682
3347
  }
2683
3348
 
2684
3349
  // src/shell/init.ts
2685
- import fs21 from "node:fs";
2686
- import path16 from "node:path";
3350
+ import fs24 from "node:fs";
3351
+ import path18 from "node:path";
2687
3352
  function header(shell, version) {
2688
3353
  return `# xclaude ${version}: ${shell} integration. Written by \`xclaude shell install\`, \`xclaude guard on|off\`
2689
3354
  # and after xclaude updates; don't edit, changes are overwritten.
@@ -2788,7 +3453,7 @@ ${guard ? `
2788
3453
  ${GUARD}` : ""}`;
2789
3454
  }
2790
3455
  function initFile(paths, shell) {
2791
- return path16.join(paths.shell, `init.${shell}`);
3456
+ return path18.join(paths.shell, `init.${shell}`);
2792
3457
  }
2793
3458
  function writeInitFiles(paths, config, version) {
2794
3459
  mkdirPrivate(paths.shell);
@@ -2796,11 +3461,11 @@ function writeInitFiles(paths, config, version) {
2796
3461
  writeFileAtomic(initFile(paths, "zsh"), initZsh(version, config.guard), { mode: 420 });
2797
3462
  }
2798
3463
  function refreshInitFiles(paths, config, version) {
2799
- if (fs21.existsSync(paths.shell)) writeInitFiles(paths, config, version);
3464
+ if (fs24.existsSync(paths.shell)) writeInitFiles(paths, config, version);
2800
3465
  }
2801
3466
 
2802
3467
  // package.json
2803
- var package_default = { version: "0.1.4" };
3468
+ var package_default = { version: "0.2.2" };
2804
3469
 
2805
3470
  // src/version.ts
2806
3471
  var VERSION = package_default.version;
@@ -2856,19 +3521,34 @@ Commands:
2856
3521
  Conversations, prompt history, memory and personal content (skills, agents,
2857
3522
  commands, plugins\u2026) are shared by every account, so \`xclaude other -c\`
2858
3523
  continues the last conversation in this folder, whichever account it ran on.
2859
- Plugins are turned on per account: one installed under another login shows
2860
- in /plugin, turned off.
3524
+ An account can also take what ~/.claude/settings.json sets (rules, hooks, auto
3525
+ mode\u2026) at every launch, keeping its own changes, with the plugins ~/.claude
3526
+ has on and the MCP servers in ~/.claude.json. Its first launch in a terminal
3527
+ asks; set <name> --inherit on|off changes the answer. A plugin installed under
3528
+ another login shows in /plugin: on when the account takes ~/.claude's setup
3529
+ and ~/.claude has it on, otherwise off.
3530
+
3531
+ Each account signs in with its own login: a CLAUDE_CODE_OAUTH_TOKEN in your
3532
+ shell is left out of accounts, and a launch says once when ANTHROPIC_API_KEY or
3533
+ another credential there may stand in for the account's login.
2861
3534
  `;
2862
3535
  var COMMAND_HELP = {
2863
3536
  add: `Usage: xclaude add <name> [--model M] [--effort E] [--args "\u2026"]
3537
+ [--inherit on|off]
2864
3538
 
2865
3539
  Creates the account, links it to the shared ~/.claude, then starts Claude Code
2866
3540
  in it so you can go through the first-run screens and log in with /login.
3541
+ First, when ~/.claude has something to give, it asks whether the account takes
3542
+ ~/.claude's setup: what ~/.claude/settings.json sets, the plugins ~/.claude has
3543
+ on and the MCP servers in ~/.claude.json.
2867
3544
 
2868
3545
  --model M default model, e.g. opus or sonnet
2869
3546
  --effort E default effort: low, medium, high, xhigh, max or ultracode
2870
3547
  --args "\u2026" extra Claude Code arguments for every launch, split like a
2871
3548
  shell line
3549
+ --inherit on|off
3550
+ answer that question up front: on takes ~/.claude's setup now
3551
+ and at every launch, off leaves the account as it is
2872
3552
 
2873
3553
  Names use lowercase letters, digits and dashes, and start with a letter.
2874
3554
  `,
@@ -2878,9 +3558,11 @@ Names use lowercase letters, digits and dashes, and start with a letter.
2878
3558
  Removes an account: stops its background sessions, logs it out, and deletes its
2879
3559
  login, settings and caches. Shared conversations and content stay in ~/.claude.
2880
3560
 
2881
- Its folder keeps only its links into ~/.claude, so its old conversations can
2882
- still open their saved long outputs. Run rm on the name again to delete that
2883
- leftover folder, or --leftovers to delete every one, after a confirmation.
3561
+ Its folder keeps its links into ~/.claude, so its old conversations can still
3562
+ open their saved long outputs, and files of its own, such as a CLAUDE.md you
3563
+ edited with /memory. Once it holds only links, run rm on the name again to
3564
+ delete that leftover folder, or --leftovers to delete every one, after a
3565
+ confirmation.
2884
3566
 
2885
3567
  --keep-login don't log the account out
2886
3568
  --leftovers delete the leftover folders of all removed accounts
@@ -2890,10 +3572,12 @@ leftover folder, or --leftovers to delete every one, after a confirmation.
2890
3572
 
2891
3573
  Lists the accounts with their email, organization and login status, their
2892
3574
  defaults, and each one's config dir (the CLAUDE_CONFIG_DIR to use elsewhere,
2893
- e.g. in an editor's environment settings).
3575
+ e.g. in an editor's environment settings). When Claude Code signs an account
3576
+ in with something else, such as an ANTHROPIC_API_KEY in your shell, LOGIN
3577
+ names it.
2894
3578
  `,
2895
3579
  set: `Usage: xclaude set <name> [--model M] [--effort E] [--args "\u2026"]
2896
- [--unset model|effort|args]
3580
+ [--unset model|effort|args] [--inherit on|off|reset]
2897
3581
  xclaude set main --enable|--disable
2898
3582
 
2899
3583
  Changes an account's launch defaults; with no options, prints them.
@@ -2903,6 +3587,14 @@ Arguments typed at launch always win over these defaults.
2903
3587
  --effort E default effort: low, medium, high, xhigh, max or ultracode
2904
3588
  --args "\u2026" extra Claude Code arguments, split like a shell line
2905
3589
  --unset KEY clear model, effort or args
3590
+ --inherit on|off|reset
3591
+ on: take what ~/.claude/settings.json sets at every launch,
3592
+ except login-bound settings such as env, with the plugins
3593
+ ~/.claude has on and the MCP servers in ~/.claude.json; the
3594
+ account's own changes stay. off: stop, and take back what it
3595
+ took and hasn't changed since. reset: take everything again.
3596
+ Until one is set, the account's first launch in a terminal
3597
+ asks.
2906
3598
  --enable (main only) use the login in ~/.claude as the account "main"
2907
3599
  --disable (main only) turn it off again
2908
3600
  `,
@@ -2948,7 +3640,8 @@ machine-managed settings and the environment. Exits non-zero if something is
2948
3640
  wrong.
2949
3641
 
2950
3642
  --fix repair links, merge left-behind directories, fix CLAUDE.md stubs,
2951
- list plugins installed under other logins (turned off)
3643
+ merge ~/.claude/settings.json into the accounts that take it,
3644
+ list plugins installed under other logins
2952
3645
  `,
2953
3646
  help: `Usage: xclaude help [command]
2954
3647
  `
@@ -2964,13 +3657,13 @@ function wantsHelp(args) {
2964
3657
  }
2965
3658
 
2966
3659
  // src/shell/complete.ts
2967
- import fs23 from "node:fs";
2968
- import path18 from "node:path";
3660
+ import fs26 from "node:fs";
3661
+ import path20 from "node:path";
2969
3662
 
2970
3663
  // src/claude/help.ts
2971
3664
  import { spawnSync as spawnSync3 } from "node:child_process";
2972
- import fs22 from "node:fs";
2973
- import path17 from "node:path";
3665
+ import fs25 from "node:fs";
3666
+ import path19 from "node:path";
2974
3667
  var FALLBACK_SUBCOMMANDS = ["auth", "mcp", "plugin", "agents", "daemon", "doctor", "update", "install", "setup-token"];
2975
3668
  var opt = (names, value, placeholder, choices) => ({
2976
3669
  names,
@@ -3092,12 +3785,12 @@ function loadHelp(claude, cacheDir, env) {
3092
3785
  const real = realpathOrNull(claude) ?? claude;
3093
3786
  let st;
3094
3787
  try {
3095
- st = fs22.statSync(real);
3788
+ st = fs25.statSync(real);
3096
3789
  } catch {
3097
3790
  return FALLBACK_HELP;
3098
3791
  }
3099
3792
  const key = { path: real, mtimeMs: st.mtimeMs, size: st.size };
3100
- const file = path17.join(cacheDir, "claude-help.json");
3793
+ const file = path19.join(cacheDir, "claude-help.json");
3101
3794
  try {
3102
3795
  const cached = JSON.parse(readFileOrNull(file) ?? "null");
3103
3796
  if (cached && cached.key.path === key.path && cached.key.mtimeMs === key.mtimeMs && cached.key.size === key.size) {
@@ -3190,14 +3883,14 @@ function logicalWords(shell, words2, cword) {
3190
3883
  return { prior, cur };
3191
3884
  }
3192
3885
  function suggestLabel(cwd) {
3193
- const label = path18.basename(cwd).replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^[^A-Za-z0-9]+/, "").slice(0, 64);
3886
+ const label = path20.basename(cwd).replace(/[^A-Za-z0-9_-]+/g, "-").replace(/^[^A-Za-z0-9]+/, "").slice(0, 64);
3194
3887
  return label || null;
3195
3888
  }
3196
3889
  function resumeCandidates(store, cwd) {
3197
- const dir = path18.join(store, "projects", cwd.replace(/[^a-zA-Z0-9]/g, "-"));
3890
+ const dir = path20.join(store, "projects", cwd.replace(/[^a-zA-Z0-9]/g, "-"));
3198
3891
  let files;
3199
3892
  try {
3200
- files = fs23.readdirSync(dir).filter((n) => n.endsWith(".jsonl")).map((n) => ({ id: n.slice(0, -".jsonl".length), file: path18.join(dir, n), mtime: fs23.statSync(path18.join(dir, n)).mtimeMs }));
3893
+ files = fs26.readdirSync(dir).filter((n) => n.endsWith(".jsonl")).map((n) => ({ id: n.slice(0, -".jsonl".length), file: path20.join(dir, n), mtime: fs26.statSync(path20.join(dir, n)).mtimeMs }));
3201
3894
  } catch {
3202
3895
  return [];
3203
3896
  }
@@ -3209,12 +3902,12 @@ function resumeCandidates(store, cwd) {
3209
3902
  function sessionTitle(file) {
3210
3903
  let head;
3211
3904
  try {
3212
- const fd = fs23.openSync(file, "r");
3905
+ const fd = fs26.openSync(file, "r");
3213
3906
  try {
3214
3907
  const buf = Buffer.alloc(16384);
3215
- head = buf.subarray(0, fs23.readSync(fd, buf, 0, buf.length, 0)).toString("utf8");
3908
+ head = buf.subarray(0, fs26.readSync(fd, buf, 0, buf.length, 0)).toString("utf8");
3216
3909
  } finally {
3217
- fs23.closeSync(fd);
3910
+ fs26.closeSync(fd);
3218
3911
  }
3219
3912
  } catch {
3220
3913
  return null;
@@ -3256,7 +3949,7 @@ var Completer = class {
3256
3949
  claudeHelp() {
3257
3950
  if (this.help) return this.help;
3258
3951
  this.help = FALLBACK_HELP;
3259
- if (fs23.existsSync(this.ctx.paths.xhome)) {
3952
+ if (fs26.existsSync(this.ctx.paths.xhome)) {
3260
3953
  try {
3261
3954
  const claude = findClaude(this.ctx.env, this.config, this.ctx.paths.home, this.ctx.selfPath);
3262
3955
  this.help = loadHelp(claude, this.ctx.paths.cache, this.ctx.env);
@@ -3287,7 +3980,7 @@ var Completer = class {
3287
3980
  if (first.startsWith("-")) return this.claudeArgs(args, cur);
3288
3981
  switch (first) {
3289
3982
  case "add":
3290
- return this.own(rest, cur, { "--model": "model", "--effort": "effort", "--args": "text" }, 1, () => []);
3983
+ return this.own(rest, cur, { "--model": "model", "--effort": "effort", "--args": "text", "--inherit": "inherit-add" }, 1, () => []);
3291
3984
  case "rm":
3292
3985
  if (rest.includes("--leftovers")) return this.own(rest, cur, { "-y": null }, 0, () => []);
3293
3986
  return this.own(
@@ -3302,7 +3995,7 @@ var Completer = class {
3302
3995
  return this.own(
3303
3996
  rest,
3304
3997
  cur,
3305
- { "--model": "model", "--effort": "effort", "--args": "text", "--unset": "unset", "--enable": null, "--disable": null },
3998
+ { "--model": "model", "--effort": "effort", "--args": "text", "--unset": "unset", "--inherit": "inherit", "--enable": null, "--disable": null },
3306
3999
  1,
3307
4000
  () => [...Object.keys(this.config.accounts), MAIN]
3308
4001
  );
@@ -3340,7 +4033,7 @@ var Completer = class {
3340
4033
  return words(positional(), describe);
3341
4034
  }
3342
4035
  ownValues(kind, prefix) {
3343
- const values = kind === "model" ? MODEL_ALIASES : kind === "effort" ? EFFORTS : kind === "unset" ? ["model", "effort", "args"] : [];
4036
+ const values = kind === "model" ? MODEL_ALIASES : kind === "effort" ? EFFORTS : kind === "unset" ? ["model", "effort", "args"] : kind === "inherit" ? ["on", "off", "reset"] : kind === "inherit-add" ? ["on", "off"] : [];
3344
4037
  return words(values.map((v) => `${prefix}${v}`));
3345
4038
  }
3346
4039
  claudeFlags() {
@@ -3443,14 +4136,14 @@ function formatCompletion(c, shell, cur) {
3443
4136
 
3444
4137
  // src/update.ts
3445
4138
  import { spawnSync as spawnSync4 } from "node:child_process";
3446
- import path19 from "node:path";
4139
+ import path21 from "node:path";
3447
4140
  var PACKAGE = "xclaude-cli";
3448
4141
  var REGISTRY_URL = `https://registry.npmjs.org/${PACKAGE}/latest`;
3449
4142
  var CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
3450
4143
  var FETCH_TIMEOUT_MS = 1e4;
3451
4144
  var SEMVER = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
3452
4145
  function checkFile(paths) {
3453
- return path19.join(paths.cache, "update-check.json");
4146
+ return path21.join(paths.cache, "update-check.json");
3454
4147
  }
3455
4148
  function readUpdateCheck(paths) {
3456
4149
  try {
@@ -3572,24 +4265,24 @@ async function lsCommand(ctx, config, args) {
3572
4265
  }
3573
4266
 
3574
4267
  // src/core/prompt.ts
3575
- import fs24 from "node:fs";
4268
+ import fs27 from "node:fs";
3576
4269
  function confirm(question) {
3577
- fs24.writeSync(2, `${question} [y/N] `);
4270
+ fs27.writeSync(2, `${question} [y/N] `);
3578
4271
  let fd;
3579
4272
  try {
3580
- fd = fs24.openSync("/dev/tty", "r");
4273
+ fd = fs27.openSync("/dev/tty", "r");
3581
4274
  } catch {
3582
4275
  return false;
3583
4276
  }
3584
4277
  try {
3585
4278
  const buf = Buffer.alloc(256);
3586
- const n = fs24.readSync(fd, buf, 0, buf.length, null);
4279
+ const n = fs27.readSync(fd, buf, 0, buf.length, null);
3587
4280
  const answer = buf.subarray(0, n).toString("utf8").trim().toLowerCase();
3588
4281
  return answer === "y" || answer === "yes";
3589
4282
  } catch {
3590
4283
  return false;
3591
4284
  } finally {
3592
- fs24.closeSync(fd);
4285
+ fs27.closeSync(fd);
3593
4286
  }
3594
4287
  }
3595
4288
 
@@ -3647,7 +4340,7 @@ async function rmCommand(ctx, config, args, listSessions2 = () => []) {
3647
4340
  }
3648
4341
  if (!yes) {
3649
4342
  if (!ctx.tty.stdin) throw new UsageError(`removing ${name} needs a confirmation: run it in a terminal, or pass -y`);
3650
- const ok = confirm(`Remove account ${name}? Its login and settings go; shared conversations and content stay in ~/.claude.`);
4343
+ const ok = confirm(`Remove account ${name}? Its login, settings.json, keybindings.json and caches go; files of its own stay in its folder, shared conversations and content in ~/.claude.`);
3651
4344
  if (!ok) {
3652
4345
  log("xclaude: nothing removed");
3653
4346
  throw new Cancelled();
@@ -3700,6 +4393,8 @@ function forget(ctx, name) {
3700
4393
  delete fresh.accounts[name];
3701
4394
  saveConfig(ctx.paths, fresh);
3702
4395
  updateState(ctx.paths, (s) => forgetAccount(s, name));
4396
+ forgetInherit(ctx.paths, name);
4397
+ forgetMcp(ctx.paths, name);
3703
4398
  }
3704
4399
  function whyNot(f, where) {
3705
4400
  switch (f.kind) {
@@ -3773,9 +4468,9 @@ async function logout(ctx, config, claude, name, keep, log) {
3773
4468
  log(`xclaude: not logging ${name} out: couldn't read the login of ${unknown.map((o) => o.label).join(", ")}, which may use the same email`);
3774
4469
  return;
3775
4470
  }
3776
- const same = others.filter((_, i) => theirs[i].loggedIn && theirs[i].email === mine.email);
3777
- if (same.length) {
3778
- log(`xclaude: not logging ${name} out: ${same.map((o) => o.label).join(", ")} ${same.length > 1 ? "are" : "is"} logged in with the same email (${mine.email}), and a logout could affect ${same.length > 1 ? "them" : "it"}`);
4471
+ const same2 = others.filter((_, i) => theirs[i].loggedIn && theirs[i].email === mine.email);
4472
+ if (same2.length) {
4473
+ log(`xclaude: not logging ${name} out: ${same2.map((o) => o.label).join(", ")} ${same2.length > 1 ? "are" : "is"} logged in with the same email (${mine.email}), and a logout could affect ${same2.length > 1 ? "them" : "it"}`);
3779
4474
  return;
3780
4475
  }
3781
4476
  }
@@ -3784,10 +4479,11 @@ async function logout(ctx, config, claude, name, keep, log) {
3784
4479
  }
3785
4480
 
3786
4481
  // src/commands/set.ts
3787
- var USAGE3 = 'usage: xclaude set <name> [--model M] [--effort E] [--args "\u2026"] [--unset model|effort|args], or xclaude set main --enable|--disable';
4482
+ var USAGE3 = 'usage: xclaude set <name> [--model M] [--effort E] [--args "\u2026"] [--unset model|effort|args] [--inherit on|off|reset], or xclaude set main --enable|--disable';
3788
4483
  var KEYS = ["model", "effort", "args"];
4484
+ var INHERIT = ["on", "off", "reset"];
3789
4485
  function setCommand(ctx, config, args) {
3790
- const p = parseOptions(args, { ...DEFAULT_OPTIONS, unset: { value: true, repeat: true }, enable: {}, disable: {} }, "set");
4486
+ const p = parseOptions(args, { ...DEFAULT_OPTIONS, unset: { value: true, repeat: true }, inherit: { value: true }, enable: {}, disable: {} }, "set");
3791
4487
  const [name, ...extra] = p.positionals;
3792
4488
  if (!name || extra.length) throw new UsageError(USAGE3);
3793
4489
  const isMain = name === MAIN;
@@ -3802,6 +4498,11 @@ function setCommand(ctx, config, args) {
3802
4498
  if (!KEYS.includes(key)) throw new UsageError(`--unset takes model, effort or args, not "${key}"`);
3803
4499
  if (p.values[key] !== void 0) throw new UsageError(`--${key} and --unset ${key} contradict each other`);
3804
4500
  }
4501
+ const inherit = stringOption(p, "inherit");
4502
+ if (inherit !== void 0) {
4503
+ if (isMain) throw new UsageError("--inherit is for accounts; the main identity is ~/.claude itself");
4504
+ if (!INHERIT.includes(inherit)) throw new UsageError(`--inherit takes on, off or reset, not "${inherit}"`);
4505
+ }
3805
4506
  if (Object.keys(p.values).length) {
3806
4507
  applyDefaultOptions(p, ctx.paths.home, target);
3807
4508
  for (const key of unset) {
@@ -3809,16 +4510,34 @@ function setCommand(ctx, config, args) {
3809
4510
  else if (key === "model") target.model = null;
3810
4511
  else target.effort = null;
3811
4512
  }
4513
+ if (inherit !== void 0) target.inherit = inherit !== "off";
3812
4514
  if (p.values.enable) config.main.enabled = true;
3813
4515
  if (p.values.disable) config.main.enabled = false;
3814
4516
  saveConfig(ctx.paths, config);
3815
4517
  }
4518
+ if (inherit !== void 0) applyInherit(ctx, name, inherit);
3816
4519
  let head = name;
3817
4520
  if (isMain) head += config.main.enabled ? " (enabled: the login in ~/.claude)" : " (disabled; enable with: xclaude set main --enable)";
3818
4521
  ctx.io.out(`${head}
3819
- ${formatDefaults(target)}`);
4522
+ ${formatDefaults(target, !isMain)}`);
3820
4523
  return EXIT_OK;
3821
4524
  }
4525
+ function applyInherit(ctx, name, inherit) {
4526
+ const log = (line) => ctx.io.err(`${line}
4527
+ `);
4528
+ const opts = { lockWaitMs: Infinity, log };
4529
+ if (inherit === "off") {
4530
+ if (!stopInheriting(ctx.paths, name, opts)) {
4531
+ log(`xclaude: Claude Code wrote ${name}'s settings.json meanwhile, so what it took from ~/.claude/settings.json is still there; run this again`);
4532
+ }
4533
+ listPlugins(ctx.paths, name, { ...opts, turnOffOwn: true });
4534
+ forgetMcp(ctx.paths, name);
4535
+ return;
4536
+ }
4537
+ if (inherit === "reset") resetInherit(ctx.paths, name, opts);
4538
+ else inheritSettings(ctx.paths, name, opts);
4539
+ listPlugins(ctx.paths, name, { ...opts, follow: true });
4540
+ }
3822
4541
 
3823
4542
  // src/commands/shell.ts
3824
4543
  function install(ctx, config, args) {
@@ -3886,8 +4605,8 @@ function shellCommand(ctx, config, args) {
3886
4605
  }
3887
4606
 
3888
4607
  // src/commands/tmux.ts
3889
- import fs27 from "node:fs";
3890
- import path20 from "node:path";
4608
+ import fs29 from "node:fs";
4609
+ import path22 from "node:path";
3891
4610
 
3892
4611
  // src/launch/args.ts
3893
4612
  function hasFlag(args, flag) {
@@ -3961,141 +4680,6 @@ function needsHelp(defaults, userArgs) {
3961
4680
  return defaults.args.length > 0 || first !== void 0 && !first.startsWith("-");
3962
4681
  }
3963
4682
 
3964
- // src/launch/picker.ts
3965
- import fs25 from "node:fs";
3966
- import tty2 from "node:tty";
3967
- function parseKeys(chunk) {
3968
- const keys = [];
3969
- let i = 0;
3970
- while (i < chunk.length) {
3971
- const rest = chunk.slice(i);
3972
- if (rest.startsWith("\x1B[A") || rest.startsWith("\x1BOA")) {
3973
- keys.push("up");
3974
- i += 3;
3975
- } else if (rest.startsWith("\x1B[B") || rest.startsWith("\x1BOB")) {
3976
- keys.push("down");
3977
- i += 3;
3978
- } else if (rest.startsWith("\x1B[")) {
3979
- let j = 2;
3980
- while (j < rest.length && !/[@-~]/.test(rest[j])) j++;
3981
- keys.push(null);
3982
- i += j + 1;
3983
- } else {
3984
- const c = rest[0];
3985
- if (c === "\x1B") keys.push(rest.length === 1 ? "cancel" : null);
3986
- else if (c === "") keys.push("cancel");
3987
- else if (c === "\r" || c === "\n") keys.push("enter");
3988
- else if (c === "k") keys.push("up");
3989
- else if (c === "j") keys.push("down");
3990
- else if (c >= "1" && c <= "9") keys.push({ jump: Number(c) - 1 });
3991
- else keys.push(null);
3992
- i++;
3993
- }
3994
- }
3995
- return keys;
3996
- }
3997
- function step(index, count, key) {
3998
- if (key === "up") return { index: (index - 1 + count) % count };
3999
- if (key === "down") return { index: (index + 1) % count };
4000
- if (key === "enter") return { index, done: "chosen" };
4001
- if (key === "cancel") return { index, done: "cancelled" };
4002
- if (key && typeof key === "object" && key.jump < count) return { index: key.jump };
4003
- return { index };
4004
- }
4005
- var dim = (s) => `\x1B[2m${s}\x1B[22m`;
4006
- var bold = (s) => `\x1B[1m${s}\x1B[22m`;
4007
- function fit(text, width) {
4008
- return width > 0 && text.length > width ? `${text.slice(0, Math.max(0, width - 1))}\u2026` : text;
4009
- }
4010
- function render(title, items, index, width = 0) {
4011
- const labelWidth = Math.max(...items.map((it) => it.label.length));
4012
- const lines = [bold(fit(title, width))];
4013
- items.forEach((it, i) => {
4014
- const marker = i === index ? "\u276F" : " ";
4015
- const num = i < 9 ? String(i + 1) : " ";
4016
- const label = it.label.padEnd(labelWidth);
4017
- const text = fit(`${marker} ${num} ${label}${it.detail ? ` ${it.detail}` : ""}`, width);
4018
- const head = text.slice(0, 5 + labelWidth);
4019
- const tail = text.slice(5 + labelWidth);
4020
- lines.push(i === index ? `${bold(head)}${dim(tail)}` : `${head}${dim(tail)}`);
4021
- });
4022
- lines.push(dim(fit("\u2191/\u2193 or j/k to move \xB7 1\u20139 to jump \xB7 Enter to choose \xB7 Esc to cancel", width)));
4023
- return lines;
4024
- }
4025
- function preselect(names, state, cwd) {
4026
- for (const candidate of [state.lastAccountByDir[cwd], state.lastUsedAccount]) {
4027
- if (candidate && names.includes(candidate)) return names.indexOf(candidate);
4028
- }
4029
- return 0;
4030
- }
4031
- function openKeyboard() {
4032
- let fd;
4033
- try {
4034
- fd = fs25.openSync("/dev/tty", "r");
4035
- } catch {
4036
- throw new UsageError("account required: there's no terminal to show the picker on (xclaude <account> [claude args\u2026])");
4037
- }
4038
- const input = new tty2.ReadStream(fd);
4039
- let columns = 0;
4040
- try {
4041
- const size = [];
4042
- const handle = input._handle;
4043
- if (handle?.getWindowSize?.(size) === 0) columns = size[0] ?? 0;
4044
- } catch {
4045
- }
4046
- return {
4047
- input,
4048
- columns,
4049
- close: () => {
4050
- input.pause();
4051
- input.unref();
4052
- }
4053
- };
4054
- }
4055
- function pick(title, items, initial) {
4056
- const keyboard = openKeyboard();
4057
- const { input } = keyboard;
4058
- const write = (s) => fs25.writeSync(2, s);
4059
- let index = Math.min(Math.max(initial, 0), items.length - 1);
4060
- let drawn = 0;
4061
- const draw = () => {
4062
- const lines = render(title, items, index, keyboard.columns);
4063
- write(`${drawn ? `\r\x1B[${drawn}A` : ""}\x1B[J${lines.join("\n")}
4064
- `);
4065
- drawn = lines.length;
4066
- };
4067
- return new Promise((resolve, reject) => {
4068
- const finish = (result) => {
4069
- input.off("data", onData);
4070
- try {
4071
- input.setRawMode(false);
4072
- } finally {
4073
- keyboard.close();
4074
- write(`\r\x1B[${drawn}A\x1B[J\x1B[?25h`);
4075
- }
4076
- if (result === "chosen") resolve(index);
4077
- else reject(new Cancelled());
4078
- };
4079
- const onData = (chunk) => {
4080
- for (const key of parseKeys(chunk)) {
4081
- const next = step(index, items.length, key);
4082
- index = next.index;
4083
- if (next.done) {
4084
- finish(next.done);
4085
- return;
4086
- }
4087
- }
4088
- draw();
4089
- };
4090
- input.setRawMode(true);
4091
- input.setEncoding("utf8");
4092
- input.on("data", onData);
4093
- input.resume();
4094
- write("\x1B[?25l");
4095
- draw();
4096
- });
4097
- }
4098
-
4099
4683
  // src/launch/launch.ts
4100
4684
  function identityItems(config) {
4101
4685
  return identities(config).map((name) => {
@@ -4136,23 +4720,42 @@ function repairForLaunch(ctx, config, account, log) {
4136
4720
  if (ctx.switches.normalizePaths && table.dirs.includes("plugins")) {
4137
4721
  normalizePaths(ctx.paths, { lockWaitMs: LAUNCH_LOCK_WAIT_MS, log });
4138
4722
  }
4139
- if (table.dirs.includes("plugins") && !res.busy) listPlugins(ctx.paths, account, { lockWaitMs: LAUNCH_LOCK_WAIT_MS, log });
4723
+ if (inherits(config, account) && !res.busy) inheritSettings(ctx.paths, account, { lockWaitMs: LAUNCH_LOCK_WAIT_MS, log });
4724
+ if (table.dirs.includes("plugins") && !res.busy) {
4725
+ listPlugins(ctx.paths, account, { lockWaitMs: LAUNCH_LOCK_WAIT_MS, log, follow: inherits(config, account) });
4726
+ }
4140
4727
  return unknownEntries(res.names, table);
4141
4728
  }
4729
+ function mcpForLaunch(ctx, config, account, defaults, userArgs, help) {
4730
+ if (!inherits(config, account) || isSubcommand(userArgs[0], help)) return null;
4731
+ if (hasFlag(userArgs, "--strict-mcp-config") || hasFlag(defaults.args, "--strict-mcp-config")) return null;
4732
+ try {
4733
+ return prepareMcp(ctx.paths, account);
4734
+ } catch (e) {
4735
+ ctx.io.err(`xclaude: couldn't pass ~/.claude.json's MCP servers to ${account} (${e.message}); launching without them
4736
+ `);
4737
+ return null;
4738
+ }
4739
+ }
4142
4740
  async function launch(ctx, config, account, userArgs) {
4143
4741
  const defaults = defaultsOf(config, account);
4144
4742
  if (!defaults) throw unknownAccount(account, config);
4145
4743
  const isMain = account === MAIN;
4146
- const unknown = isMain ? [] : prepareAccount(ctx, config, account);
4744
+ const settled = isMain ? config : await settleInherit(ctx, config, account);
4745
+ const unknown = isMain ? [] : prepareAccount(ctx, settled, account);
4147
4746
  const claude = findClaude(ctx.env, config, ctx.paths.home, ctx.selfPath);
4148
4747
  const help = needsHelp(defaults, userArgs) ? loadHelp(claude, ctx.paths.cache, ctx.env) : null;
4149
- const args = buildArgs(defaults, userArgs, help);
4150
- const env = buildEnv(ctx.env, { name: account, configDir: isMain ? null : accountDir(ctx.paths, account) });
4748
+ const mcp = isMain ? null : mcpForLaunch(ctx, settled, account, defaults, userArgs, help);
4749
+ const args = [...mcp ? [`--mcp-config=${mcp}`] : [], ...buildArgs(defaults, userArgs, help)];
4750
+ const memoryDir = sharedMemoryDir(ctx.paths, shareTable(settled, ctx.switches), ctx.switches);
4751
+ const env = buildEnv(ctx.env, { name: account, configDir: isMain ? null : accountDir(ctx.paths, account), memoryDir });
4151
4752
  try {
4152
4753
  updateState(ctx.paths, (state) => {
4153
4754
  recordUse(state, ctx.cwd, account);
4154
4755
  const configLabel = tildify(ctx.paths.config, ctx.paths.home);
4155
4756
  for (const entry of takeNewUnknown(state, account, unknown)) ctx.io.err(`${unknownNotice(account, entry, configLabel)}
4757
+ `);
4758
+ if (!isMain) for (const line of takeCredentialNotes(state, account, ctx.env)) ctx.io.err(`${line}
4156
4759
  `);
4157
4760
  });
4158
4761
  } catch {
@@ -4162,7 +4765,7 @@ async function launch(ctx, config, account, userArgs) {
4162
4765
 
4163
4766
  // src/tmux/claude-state.ts
4164
4767
  import { spawnSync as spawnSync5 } from "node:child_process";
4165
- import fs26 from "node:fs";
4768
+ import fs28 from "node:fs";
4166
4769
  function describeAgent(e) {
4167
4770
  if (e.status === "waiting") return { text: e.waitingFor ? `needs input (${e.waitingFor})` : "needs input", rank: 3 };
4168
4771
  if (e.status === "busy") return { text: "working", rank: 2 };
@@ -4170,10 +4773,10 @@ function describeAgent(e) {
4170
4773
  return null;
4171
4774
  }
4172
4775
  function parentLookup() {
4173
- if (process.platform === "linux" && fs26.existsSync("/proc/self/stat")) {
4776
+ if (process.platform === "linux" && fs28.existsSync("/proc/self/stat")) {
4174
4777
  return (pid) => {
4175
4778
  try {
4176
- const stat = fs26.readFileSync(`/proc/${pid}/stat`, "utf8");
4779
+ const stat = fs28.readFileSync(`/proc/${pid}/stat`, "utf8");
4177
4780
  const ppid = Number(stat.slice(stat.lastIndexOf(")") + 2).split(" ")[1]);
4178
4781
  return Number.isFinite(ppid) ? ppid : null;
4179
4782
  } catch {
@@ -4299,8 +4902,8 @@ async function tmuxNew(ctx, config, args) {
4299
4902
  account ??= await chooseAccount(ctx, config, `Run Claude Code in tmux session "${req.label}" as`);
4300
4903
  if (!defaultsOf(config, account)) throw unknownAccount(account, config);
4301
4904
  }
4302
- const dir = path20.resolve(ctx.cwd, req.dir ?? ".");
4303
- if (!fs27.statSync(dir, { throwIfNoEntry: false })?.isDirectory()) throw new XError(`--dir ${req.dir}: not a directory`);
4905
+ const dir = path22.resolve(ctx.cwd, req.dir ?? ".");
4906
+ if (!fs29.statSync(dir, { throwIfNoEntry: false })?.isDirectory()) throw new XError(`--dir ${req.dir}: not a directory`);
4304
4907
  const existing = findByLabel(listSessions(tmux), req.label);
4305
4908
  if (existing) {
4306
4909
  throw new XError(`"${req.label}" is running (${describeSession(existing, ctx.paths.home)}): xclaude tmux attach ${req.label}, or kill it first`);