context-mode 2.1.0 → 2.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/pi/index.js CHANGED
@@ -657,10 +657,10 @@ function assignProp(target, prop, value) {
657
657
  configurable: true
658
658
  });
659
659
  }
660
- function getElementAtPath(obj, path7) {
661
- if (!path7)
660
+ function getElementAtPath(obj, path8) {
661
+ if (!path8)
662
662
  return obj;
663
- return path7.reduce((acc, key) => acc?.[key], obj);
663
+ return path8.reduce((acc, key) => acc?.[key], obj);
664
664
  }
665
665
  function promiseAllObject(promisesObj) {
666
666
  const keys = Object.keys(promisesObj);
@@ -980,11 +980,11 @@ function aborted(x, startIndex = 0) {
980
980
  }
981
981
  return false;
982
982
  }
983
- function prefixIssues(path7, issues) {
983
+ function prefixIssues(path8, issues) {
984
984
  return issues.map((iss) => {
985
985
  var _a5;
986
986
  (_a5 = iss).path ?? (_a5.path = []);
987
- iss.path.unshift(path7);
987
+ iss.path.unshift(path8);
988
988
  return iss;
989
989
  });
990
990
  }
@@ -1121,7 +1121,7 @@ function treeifyError(error42, _mapper) {
1121
1121
  return issue4.message;
1122
1122
  };
1123
1123
  const result = { errors: [] };
1124
- const processError = (error43, path7 = []) => {
1124
+ const processError = (error43, path8 = []) => {
1125
1125
  var _a5, _b;
1126
1126
  for (const issue4 of error43.issues) {
1127
1127
  if (issue4.code === "invalid_union" && issue4.errors.length) {
@@ -1131,7 +1131,7 @@ function treeifyError(error42, _mapper) {
1131
1131
  } else if (issue4.code === "invalid_element") {
1132
1132
  processError({ issues: issue4.issues }, issue4.path);
1133
1133
  } else {
1134
- const fullpath = [...path7, ...issue4.path];
1134
+ const fullpath = [...path8, ...issue4.path];
1135
1135
  if (fullpath.length === 0) {
1136
1136
  result.errors.push(mapper(issue4));
1137
1137
  continue;
@@ -1161,9 +1161,9 @@ function treeifyError(error42, _mapper) {
1161
1161
  processError(error42);
1162
1162
  return result;
1163
1163
  }
1164
- function toDotPath(path7) {
1164
+ function toDotPath(path8) {
1165
1165
  const segs = [];
1166
- for (const seg of path7) {
1166
+ for (const seg of path8) {
1167
1167
  if (typeof seg === "number")
1168
1168
  segs.push(`[${seg}]`);
1169
1169
  else if (typeof seg === "symbol")
@@ -11571,7 +11571,7 @@ var DECISION_OPTION_KEY = "option";
11571
11571
  var DECISION_LABEL_JOIN = " | ";
11572
11572
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
11573
11573
  var RELEASE_BRANCH = "release";
11574
- var BUNDLE_SHA = true ? "d232ce4ddfb581a63a4c0d6ef894b64a0f8464f6" : void 0;
11574
+ var BUNDLE_SHA = true ? "1ce32b37e98bfffd69edcd071b13e1e2d43a0ae9" : void 0;
11575
11575
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
11576
11576
  var DOCTOR_LABEL = Object.freeze({
11577
11577
  D1: "version",
@@ -11893,6 +11893,11 @@ var V1_CACHE_HEAL_NAME = "context-mode-cache-heal";
11893
11893
  var V1_CACHE_HEAL_EXTS = Object.freeze([".mjs", ".sh"]);
11894
11894
  var V1_STATUSLINE_COMMAND = "context-mode statusline";
11895
11895
  var V1_PI_PACKAGE = "npm:context-mode";
11896
+ var PI_NPM_DIR = "npm";
11897
+ var PI_NODE_MODULES_DIR = "node_modules";
11898
+ var PI_PACKAGE_JSON_FILE = "package.json";
11899
+ var PI_LIST_COMMAND = "pi list";
11900
+ var PI_CURRENT_MAJOR = 2;
11896
11901
  var V1_OPENCODE_PLUGIN_SPEC = "context-mode";
11897
11902
  var V1_TMP_PREFIX = "context-mode-";
11898
11903
  var V1_TOML_SECTION_ROOT = "mcp_servers";
@@ -12109,7 +12114,7 @@ var PI_EVENTS = {
12109
12114
  tool_call: { event: "PreToolUse" },
12110
12115
  tool_result: { event: "PostToolUse" }
12111
12116
  };
12112
- var NATIVE_TO_CANONICAL = { bash: "Bash", read: "Read" };
12117
+ var NATIVE_TO_CANONICAL = { bash: "Bash", read: "Read", edit: "Edit", write: "Write" };
12113
12118
  function record2(v) {
12114
12119
  return typeof v === "object" && v !== null && !Array.isArray(v) ? v : {};
12115
12120
  }
@@ -12273,7 +12278,7 @@ function outputOf(resp) {
12273
12278
  function textSlot(r) {
12274
12279
  const file2 = r.file;
12275
12280
  if (r.type === "text" && typeof file2 === "object" && file2 !== null && typeof file2.content === "string") {
12276
- return { text: file2.content, put: (o, output) => ({ ...o, file: { ...o.file, content: output } }) };
12281
+ return { text: file2.content, put: (o, output) => ({ ...o, file: readFile(o.file, output) }) };
12277
12282
  }
12278
12283
  if (isGrepContent(r)) return { text: r.content, put: (o, output) => ({ ...o, content: output }) };
12279
12284
  if (Array.isArray(r.filenames) && r.filenames.every((f) => typeof f === "string")) {
@@ -12282,13 +12287,35 @@ function textSlot(r) {
12282
12287
  if (typeof r.result === "string") return { text: r.result, put: (o, output) => ({ ...o, result: output }) };
12283
12288
  return null;
12284
12289
  }
12290
+ function readFile(file2, output) {
12291
+ const start = typeof file2.startLine === "number" ? file2.startLine : 1;
12292
+ const lines = String(file2.content).split("\n");
12293
+ const read3 = typeof file2.numLines === "number" ? file2.numLines : lines.length;
12294
+ const out = output.split("\n");
12295
+ const run = firstRun(lines, out);
12296
+ if (run === null) return { ...file2, content: output, startLine: start + read3, numLines: out.length };
12297
+ const kept = out.slice(0, run.length);
12298
+ if (run.length < out.length) kept.push(out[out.length - 1]);
12299
+ return { ...file2, content: kept.join("\n"), startLine: start + run.at, numLines: kept.length };
12300
+ }
12301
+ function firstRun(lines, out) {
12302
+ let best = null;
12303
+ for (let i = 0; i < lines.length; i++) {
12304
+ if (lines[i] !== out[0]) continue;
12305
+ let n = 1;
12306
+ while (n < out.length && i + n < lines.length && lines[i + n] === out[n]) n++;
12307
+ if (best === null || n > best.length) best = { at: i, length: n };
12308
+ if (n === out.length) break;
12309
+ }
12310
+ return best;
12311
+ }
12285
12312
  function isShellShape(resp) {
12286
12313
  const r = resp;
12287
12314
  return typeof r.stdout === "string" || typeof r.stderr === "string";
12288
12315
  }
12289
12316
  function isGrepContent(resp) {
12290
12317
  const r = resp;
12291
- return r.mode === "content" && typeof r.content === "string";
12318
+ return (r.mode === "content" || r.mode === "count") && typeof r.content === "string";
12292
12319
  }
12293
12320
  function blocksOf(resp) {
12294
12321
  const parts = [];
@@ -12304,6 +12331,7 @@ function readResult2(resp) {
12304
12331
  const text = outputOf(resp);
12305
12332
  const isError = typeof resp === "object" && resp !== null && resp.is_error === true;
12306
12333
  const info = { isError, bytes: Buffer.byteLength(text), text };
12334
+ if (typeof resp === "object" && resp !== null && !Array.isArray(resp) && isShellShape(resp)) info.shape = resp;
12307
12335
  if (typeof resp === "object" && resp !== null && !Array.isArray(resp) && !isShellShape(resp)) {
12308
12336
  if (textSlot(resp) !== null) info.shape = resp;
12309
12337
  else info.keep = true;
@@ -12343,8 +12371,11 @@ function decodeClaudeShape(raw, agent, ownPrefix, sources) {
12343
12371
  return ev;
12344
12372
  }
12345
12373
  function replaceShape(ev, output) {
12346
- if (ev.tool?.canonicalName === "Bash") return { stdout: output, stderr: "", interrupted: false };
12347
12374
  const shape = ev.result?.shape;
12375
+ if (ev.tool?.canonicalName === "Bash") {
12376
+ const { persistedOutputPath: _p, persistedOutputSize: _s, ...host } = shape ?? {};
12377
+ return { interrupted: false, ...host, stdout: output, stderr: "" };
12378
+ }
12348
12379
  const slot = shape === void 0 ? null : textSlot(shape);
12349
12380
  if (shape !== void 0 && slot !== null) return slot.put(shape, output);
12350
12381
  if (ev.result?.blocks === true) return [{ type: "text", text: output }];
@@ -12906,8 +12937,8 @@ var ADAPTERS = Object.freeze([
12906
12937
  hookTimeoutMs: HOOK_TIMEOUT_MS,
12907
12938
  denyChannel: "deny-reason",
12908
12939
  hookChannel: { kind: "package", path: "hooks/claude-code.json" },
12909
- skillChannel: { kind: "package", path: "claude-code/skills" },
12910
- // ADR-0020, D-HQ-SKILLS-2
12940
+ skillChannel: { kind: "package", path: "skills" },
12941
+ // ADR-0020, D-R33-CC-SKILLS-1: Claude Code always loads <plugin>/skills, shared with gemini and qwen
12911
12942
  decode: decode2,
12912
12943
  encode: encode2
12913
12944
  },
@@ -13051,8 +13082,9 @@ var ADAPTERS = Object.freeze([
13051
13082
  installMode: "in-process",
13052
13083
  projectSource: "pi:ctx.cwd",
13053
13084
  toolNamePrefix: TOOL_NAME_PREFIX,
13054
- nativeTools: { shell: ["bash"], read: ["read"] },
13085
+ nativeTools: { shell: ["bash", "powershell"], read: ["read"] },
13055
13086
  execReadOnlyHint: false,
13087
+ // D-R38-PI-PWSH-1: Pi on Windows names its shell tool "powershell"
13056
13088
  eventMap: { SessionStart: "session_start", UserPromptSubmit: "input", PreToolUse: "tool_call", PostToolUse: "tool_result" },
13057
13089
  compactDelivery: "pi-flag",
13058
13090
  compactSummary: "none",
@@ -14451,21 +14483,21 @@ function kiroDirOf(env, home, platform = process.platform) {
14451
14483
  if (dir === void 0 || dir === "" || !p.isAbsolute(dir)) return fallback;
14452
14484
  if (platform === "win32" && p.parse(dir).root.length < 2) return fallback;
14453
14485
  const abs = p.resolve(dir);
14454
- const real2 = platform === process.platform ? realOrSelf : (x) => x;
14455
- const target = real2(abs);
14486
+ const real3 = platform === process.platform ? realOrSelf : (x) => x;
14487
+ const target = real3(abs);
14456
14488
  if (p.parse(target).root === target) return fallback;
14457
- const up = p.relative(target, real2(p.resolve(home)));
14489
+ const up = p.relative(target, real3(p.resolve(home)));
14458
14490
  if (!p.isAbsolute(up) && up.split(p.sep)[0] !== "..") return fallback;
14459
14491
  return abs;
14460
14492
  }
14461
- function realOrSelf(path7) {
14493
+ function realOrSelf(path8) {
14462
14494
  const tail = [];
14463
- for (let at2 = path7; ; ) {
14495
+ for (let at2 = path8; ; ) {
14464
14496
  try {
14465
14497
  return join(realpathSync.native(at2), ...tail.reverse());
14466
14498
  } catch {
14467
14499
  const up = dirname(at2);
14468
- if (up === at2) return path7;
14500
+ if (up === at2) return path8;
14469
14501
  tail.push(basename(at2));
14470
14502
  at2 = up;
14471
14503
  }
@@ -14590,10 +14622,10 @@ function readPluginAgent(claudeDir, type) {
14590
14622
  }
14591
14623
  return null;
14592
14624
  }
14593
- function readAgentFile(path7) {
14625
+ function readAgentFile(path8) {
14594
14626
  let text;
14595
14627
  try {
14596
- text = readFileSync(path7, "utf8");
14628
+ text = readFileSync(path8, "utf8");
14597
14629
  } catch {
14598
14630
  return null;
14599
14631
  }
@@ -14856,12 +14888,12 @@ function readUserDeny(projectDir, agent) {
14856
14888
  }
14857
14889
  return out;
14858
14890
  }
14859
- function tokenize(glob, path7) {
14891
+ function tokenize(glob, path8) {
14860
14892
  const toks = [];
14861
14893
  let i = 0;
14862
14894
  while (i < glob.length) {
14863
14895
  const c = glob[i];
14864
- if (c === "*" && path7 && glob[i + 1] === "*") {
14896
+ if (c === "*" && path8 && glob[i + 1] === "*") {
14865
14897
  const dir = glob[i + "**".length] === "/";
14866
14898
  toks.push({ t: dir ? "globstarDir" : "globstar" });
14867
14899
  i += dir ? "**/".length : "**".length;
@@ -14875,8 +14907,8 @@ function tokenize(glob, path7) {
14875
14907
  }
14876
14908
  return toks;
14877
14909
  }
14878
- function globMatch(glob, text, path7) {
14879
- const toks = tokenize(glob, path7);
14910
+ function globMatch(glob, text, path8) {
14911
+ const toks = tokenize(glob, path8);
14880
14912
  const n = text.length;
14881
14913
  let next = new Uint8Array(n + 1);
14882
14914
  next[n] = 1;
@@ -14892,10 +14924,10 @@ function globMatch(glob, text, path7) {
14892
14924
  cur[j] = has3 && ch === tok.c ? next[j + 1] : 0;
14893
14925
  break;
14894
14926
  case "any1":
14895
- cur[j] = has3 && !(path7 && ch === "/") ? next[j + 1] : 0;
14927
+ cur[j] = has3 && !(path8 && ch === "/") ? next[j + 1] : 0;
14896
14928
  break;
14897
14929
  case "star":
14898
- cur[j] = next[j] || (has3 && !(path7 && ch === "/") ? cur[j + 1] : 0);
14930
+ cur[j] = next[j] || (has3 && !(path8 && ch === "/") ? cur[j + 1] : 0);
14899
14931
  break;
14900
14932
  case "globstar":
14901
14933
  cur[j] = next[j] || (has3 ? cur[j + 1] : 0);
@@ -14975,8 +15007,8 @@ var READ_DENY_TEMPLATE = 'context-mode: {size}-byte file, over the one-read limi
14975
15007
  // src/core/policy/read-deny.ts
14976
15008
  var SIZE = "{size}";
14977
15009
  var PATH = "{path}";
14978
- function READ_DENY_MESSAGE(path7, size, prefix = "") {
14979
- return prefixToolNames(READ_DENY_TEMPLATE, prefix).split(SIZE).join(String(size)).split(PATH).join(path7);
15010
+ function READ_DENY_MESSAGE(path8, size, prefix = "") {
15011
+ return prefixToolNames(READ_DENY_TEMPLATE, prefix).split(SIZE).join(String(size)).split(PATH).join(path8);
14980
15012
  }
14981
15013
 
14982
15014
  // src/core/policy/decide.ts
@@ -15684,9 +15716,9 @@ function readUserVersion(raw) {
15684
15716
  const row5 = raw.prepare("PRAGMA user_version").get();
15685
15717
  return row5.user_version;
15686
15718
  }
15687
- function createAtomically(sqlite, path7) {
15719
+ function createAtomically(sqlite, path8) {
15688
15720
  const { randomUUID: randomUUID2 } = process.getBuiltinModule("node:crypto");
15689
- const tmp = path7 + "." + randomUUID2() + DB_TMP_SUFFIX;
15721
+ const tmp = path8 + "." + randomUUID2() + DB_TMP_SUFFIX;
15690
15722
  try {
15691
15723
  const raw = new sqlite.DatabaseSync(tmp, { timeout: DB_TIMEOUT_MS });
15692
15724
  try {
@@ -15695,7 +15727,7 @@ function createAtomically(sqlite, path7) {
15695
15727
  raw.close();
15696
15728
  }
15697
15729
  try {
15698
- linkSync(tmp, path7);
15730
+ linkSync(tmp, path8);
15699
15731
  } catch (err) {
15700
15732
  if (err.code !== "EEXIST") throw err;
15701
15733
  }
@@ -15703,11 +15735,11 @@ function createAtomically(sqlite, path7) {
15703
15735
  for (const suffix of ["", DB_WAL_SUFFIX, DB_SHM_SUFFIX]) rmSync(tmp + suffix, { force: true });
15704
15736
  }
15705
15737
  }
15706
- function openWritable(sqlite, path7) {
15738
+ function openWritable(sqlite, path8) {
15707
15739
  let raw = null;
15708
15740
  try {
15709
- if (!existsSync2(path7)) createAtomically(sqlite, path7);
15710
- raw = new sqlite.DatabaseSync(path7, { timeout: DB_TIMEOUT_MS });
15741
+ if (!existsSync2(path8)) createAtomically(sqlite, path8);
15742
+ raw = new sqlite.DatabaseSync(path8, { timeout: DB_TIMEOUT_MS });
15711
15743
  applyMigrations(raw, readUserVersion(raw));
15712
15744
  return raw;
15713
15745
  } catch (err) {
@@ -15715,8 +15747,8 @@ function openWritable(sqlite, path7) {
15715
15747
  throw err;
15716
15748
  }
15717
15749
  }
15718
- function openReadOnly(sqlite, path7) {
15719
- const raw = new sqlite.DatabaseSync(path7, { timeout: DB_TIMEOUT_MS, readOnly: true });
15750
+ function openReadOnly(sqlite, path8) {
15751
+ const raw = new sqlite.DatabaseSync(path8, { timeout: DB_TIMEOUT_MS, readOnly: true });
15720
15752
  try {
15721
15753
  const found = readUserVersion(raw);
15722
15754
  if (found !== SCHEMA_VERSION) throw new CtxError("SCHEMA_STALE", { found, want: SCHEMA_VERSION });
@@ -15730,20 +15762,20 @@ async function openDb(project, opts) {
15730
15762
  if (isBelow(process.version, NODE_MIN)) throw new CtxError("NODE_TOO_OLD", { v: process.version });
15731
15763
  const sqlite = await loadSqlite();
15732
15764
  mkdirSync2(project.projectDir, { recursive: true });
15733
- const path7 = project.dbPath;
15734
- const sibling = existsSync2(path7 + DB_WAL_SUFFIX) || existsSync2(path7 + DB_SHM_SUFFIX);
15735
- if (sibling && !existsSync2(path7)) {
15765
+ const path8 = project.dbPath;
15766
+ const sibling = existsSync2(path8 + DB_WAL_SUFFIX) || existsSync2(path8 + DB_SHM_SUFFIX);
15767
+ if (sibling && !existsSync2(path8)) {
15736
15768
  throw new CtxError("DB_GONE");
15737
15769
  }
15738
15770
  try {
15739
15771
  let raw;
15740
15772
  if (opts?.readOnly === true) {
15741
- if (!existsSync2(path7)) openWritable(sqlite, path7).close();
15742
- raw = openReadOnly(sqlite, path7);
15773
+ if (!existsSync2(path8)) openWritable(sqlite, path8).close();
15774
+ raw = openReadOnly(sqlite, path8);
15743
15775
  } else {
15744
- raw = openWritable(sqlite, path7);
15776
+ raw = openWritable(sqlite, path8);
15745
15777
  }
15746
- return { raw, projectKey: project.projectKey, path: path7, ...opts?.readOnly === true ? { readOnly: true } : {} };
15778
+ return { raw, projectKey: project.projectKey, path: path8, ...opts?.readOnly === true ? { readOnly: true } : {} };
15747
15779
  } catch (err) {
15748
15780
  if (isCorrupt(err)) throw new CtxError("DB_CORRUPT");
15749
15781
  throw err;
@@ -18538,8 +18570,8 @@ function buildCandidates(rows, sessionId) {
18538
18570
  edits.set(r.path, { row: r, count: (edits.get(r.path)?.count ?? 0) + 1 });
18539
18571
  }
18540
18572
  const changedFiles = [];
18541
- for (const [path7, e] of edits) {
18542
- const c = make("changed_files", e.row, "edited " + path7 + " x" + e.count, e.count, path7);
18573
+ for (const [path8, e] of edits) {
18574
+ const c = make("changed_files", e.row, "edited " + path8 + " x" + e.count, e.count, path8);
18543
18575
  changedFiles.push({ ...c, editCount: e.count });
18544
18576
  }
18545
18577
  changedFiles.sort((a, b) => a.seq - b.seq);
@@ -19873,9 +19905,13 @@ async function preToolUse(ev, row5, project, env) {
19873
19905
  const userDeny = readUserDeny(project.worktree, ev.agent);
19874
19906
  const decision0 = decide(ev, row5, userDeny);
19875
19907
  let decision = decision0;
19876
- if (decision0.kind === "deny" && isSubagentCall(ev)) {
19877
- const subCase = pickSubagentCase(ev, toolSetForAgentType(ev, { projectDir: project.worktree, env }));
19878
- if (subCase === "B") decision = caseB(ev, row5, decision0, userDeny);
19908
+ if (decision0.kind === "deny" && isSubagentCall(ev) && !isUserPolicyDeny(decision0.reason, row5)) {
19909
+ const set3 = toolSetForAgentType(ev, { projectDir: project.worktree, env });
19910
+ const subCase = pickSubagentCase(ev, set3);
19911
+ const tool = ev.tool;
19912
+ const runs = set3 !== null || (ev.agentType ?? "") !== "" && hasReplace(row5);
19913
+ if (subCase === "B" && tool !== void 0 && isShell(tool, row5)) decision = caseB(ev, row5, decision0, userDeny);
19914
+ else if (subCase !== "A" && runs) decision = ALLOW2;
19879
19915
  }
19880
19916
  return decision;
19881
19917
  }
@@ -20322,19 +20358,19 @@ function steeringFiles(worktree) {
20322
20358
  function readAutoMemory(project) {
20323
20359
  const rows = [];
20324
20360
  for (const segs of [...MEMORY_FILES, ...steeringFiles(project.worktree)]) {
20325
- const path7 = join7(project.worktree, ...segs);
20326
- if (!isInside(project.worktree, path7)) continue;
20361
+ const path8 = join7(project.worktree, ...segs);
20362
+ if (!isInside(project.worktree, path8)) continue;
20327
20363
  try {
20328
- const st = statSync4(path7);
20364
+ const st = statSync4(path8);
20329
20365
  if (!st.isFile()) continue;
20330
20366
  rows.push({
20331
20367
  origin: "memory",
20332
20368
  ts: Math.trunc(st.mtimeMs),
20333
20369
  seq: null,
20334
20370
  sourceId: null,
20335
- path: path7,
20371
+ path: path8,
20336
20372
  label: segs.join("/"),
20337
- text: readFileSync5(path7, "utf8")
20373
+ text: readFileSync5(path8, "utf8")
20338
20374
  });
20339
20375
  } catch {
20340
20376
  }
@@ -20904,7 +20940,7 @@ var ctxBatch = Object.freeze({
20904
20940
  });
20905
20941
 
20906
20942
  // src/core/tools/doctor.ts
20907
- import { readdirSync as readdirSync6, readFileSync as readFileSync13, existsSync as existsSync14 } from "node:fs";
20943
+ import { readdirSync as readdirSync6, readFileSync as readFileSync14, existsSync as existsSync15 } from "node:fs";
20908
20944
  import { basename as basename5, join as join17 } from "node:path";
20909
20945
 
20910
20946
  // src/core/ops/bundle-dir.ts
@@ -20930,7 +20966,7 @@ function ownBundleDir() {
20930
20966
  }
20931
20967
 
20932
20968
  // src/core/ops/doctor-config.ts
20933
- import { existsSync as existsSync7, readdirSync as readdirSync4 } from "node:fs";
20969
+ import { existsSync as existsSync8, readdirSync as readdirSync4 } from "node:fs";
20934
20970
  import { join as join12 } from "node:path";
20935
20971
 
20936
20972
  // src/core/ops/detect-v1.ts
@@ -23049,15 +23085,15 @@ function atomicWriteFile(file2, text, opts = {}) {
23049
23085
  }
23050
23086
 
23051
23087
  // src/core/ops/host-config.ts
23052
- function formatOf(path7) {
23053
- if (path7.endsWith(JSONC_EXT)) return "jsonc";
23054
- if (path7.endsWith(TOML_EXT)) return "toml";
23088
+ function formatOf(path8) {
23089
+ if (path8.endsWith(JSONC_EXT)) return "jsonc";
23090
+ if (path8.endsWith(TOML_EXT)) return "toml";
23055
23091
  return "json";
23056
23092
  }
23057
- function readHostConfig(agent, path7) {
23058
- let file2 = path7;
23093
+ function readHostConfig(agent, path8) {
23094
+ let file2 = path8;
23059
23095
  if (agent === "opencode") {
23060
- const jsonc = join9(dirname6(path7), OPENCODE_CONFIG_FILES[0]);
23096
+ const jsonc = join9(dirname6(path8), OPENCODE_CONFIG_FILES[0]);
23061
23097
  if (existsSync4(jsonc)) file2 = jsonc;
23062
23098
  }
23063
23099
  const raw = existsSync4(file2) ? readFileSync6(file2, "utf8") : "";
@@ -23221,14 +23257,14 @@ function scanToml(text) {
23221
23257
  continue;
23222
23258
  }
23223
23259
  if (!node3.resolvedKey.every((seg) => typeof seg === "string")) continue;
23224
- const path7 = node3.resolvedKey;
23225
- for (const kv of node3.body) addKey(path7, kv);
23260
+ const path8 = node3.resolvedKey;
23261
+ for (const kv of node3.body) addKey(path8, kv);
23226
23262
  if (node3.kind !== "standard") continue;
23227
23263
  const start = lineStartOf(text, node3.range[0]);
23228
23264
  const headEnd = lineEndOf(text, node3.key.range[1]);
23229
23265
  const last2 = node3.body[node3.body.length - 1];
23230
23266
  tables.push({
23231
- path: path7,
23267
+ path: path8,
23232
23268
  header: text.slice(start, text[headEnd - 1] === "\n" ? headEnd - 1 : headEnd),
23233
23269
  start,
23234
23270
  end: last2 === void 0 ? headEnd : lineEndOf(text, last2.range[1])
@@ -23239,16 +23275,16 @@ function scanToml(text) {
23239
23275
  function tomlTableSpans(text) {
23240
23276
  return scanToml(text).tables;
23241
23277
  }
23242
- function parseHostConfig(agent, path7, text, format) {
23278
+ function parseHostConfig(agent, path8, text, format) {
23243
23279
  try {
23244
23280
  return format === "toml" ? scanToml(text).value : scanJson(text, format).value;
23245
23281
  } catch {
23246
- throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path7, format });
23282
+ throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path8, format });
23247
23283
  }
23248
23284
  }
23249
- function hostConfigValueAt(value, path7) {
23285
+ function hostConfigValueAt(value, path8) {
23250
23286
  let cur = value;
23251
- for (const seg of path7) {
23287
+ for (const seg of path8) {
23252
23288
  if (!isPlainObject3(cur)) return void 0;
23253
23289
  cur = cur[seg];
23254
23290
  }
@@ -23281,32 +23317,32 @@ function indentUnit(root, clean) {
23281
23317
  function render(value, unit, base) {
23282
23318
  return JSON.stringify(value, null, unit).split("\n").join("\n" + base);
23283
23319
  }
23284
- function nest(path7, value) {
23320
+ function nest(path8, value) {
23285
23321
  let out = value;
23286
- for (let k = path7.length - 1; k >= 0; k -= 1) out = { [path7[k]]: out };
23322
+ for (let k = path8.length - 1; k >= 0; k -= 1) out = { [path8[k]]: out };
23287
23323
  return out;
23288
23324
  }
23289
- function setJsonText(text, format, path7, value) {
23325
+ function setJsonText(text, format, path8, value) {
23290
23326
  const doc = scanJson(text, format);
23291
23327
  const unit = indentUnit(doc.root, doc.clean);
23292
- if (doc.root === null) return render(nest(path7, value), unit, "") + "\n";
23328
+ if (doc.root === null) return render(nest(path8, value), unit, "") + "\n";
23293
23329
  let node3 = doc.root;
23294
23330
  let depth = 0;
23295
- while (depth < path7.length && node3.kind === "object") {
23296
- const hit = node3.members.find((m) => m.key === path7[depth]);
23331
+ while (depth < path8.length && node3.kind === "object") {
23332
+ const hit = node3.members.find((m) => m.key === path8[depth]);
23297
23333
  if (hit === void 0) break;
23298
23334
  node3 = hit.node;
23299
23335
  depth += 1;
23300
23336
  }
23301
- if (depth === path7.length) {
23337
+ if (depth === path8.length) {
23302
23338
  return text.slice(0, node3.start) + render(value, unit, lineIndent(doc.clean, node3.start)) + text.slice(node3.end);
23303
23339
  }
23304
- if (node3.kind !== "object") throw new SyntaxError("not an object at " + path7.slice(0, depth).join("."));
23305
- const rest = nest(path7.slice(depth + 1), value);
23340
+ if (node3.kind !== "object") throw new SyntaxError("not an object at " + path8.slice(0, depth).join("."));
23341
+ const rest = nest(path8.slice(depth + 1), value);
23306
23342
  const last2 = node3.members[node3.members.length - 1];
23307
23343
  if (last2 === void 0) {
23308
23344
  const base2 = lineIndent(doc.clean, node3.start);
23309
- const member2 = "\n" + base2 + unit + JSON.stringify(path7[depth]) + ": " + render(rest, unit, base2 + unit) + "\n" + base2;
23345
+ const member2 = "\n" + base2 + unit + JSON.stringify(path8[depth]) + ": " + render(rest, unit, base2 + unit) + "\n" + base2;
23310
23346
  return text.slice(0, node3.start + 1) + member2 + text.slice(node3.end - 1);
23311
23347
  }
23312
23348
  const base = lineIndent(doc.clean, last2.keyStart);
@@ -23314,7 +23350,7 @@ function setJsonText(text, format, path7, value) {
23314
23350
  while (" \r\n".includes(doc.clean[at2])) at2 += 1;
23315
23351
  const trailing = doc.clean[at2] === ",";
23316
23352
  const insertAt = trailing ? at2 + 1 : last2.node.end;
23317
- const member = (trailing ? "" : ",") + "\n" + base + JSON.stringify(path7[depth]) + ": " + render(rest, unit, base);
23353
+ const member = (trailing ? "" : ",") + "\n" + base + JSON.stringify(path8[depth]) + ": " + render(rest, unit, base);
23318
23354
  return text.slice(0, insertAt) + member + text.slice(insertAt);
23319
23355
  }
23320
23356
  function tomlScalar(v) {
@@ -23332,17 +23368,17 @@ function tomlHeaderKey(seg) {
23332
23368
  }
23333
23369
  return seg;
23334
23370
  }
23335
- function tomlBlock(path7, value) {
23336
- let out = "[" + path7.map(tomlHeaderKey).join(".") + "]\n";
23371
+ function tomlBlock(path8, value) {
23372
+ let out = "[" + path8.map(tomlHeaderKey).join(".") + "]\n";
23337
23373
  const subs = [];
23338
23374
  for (const [k, v] of Object.entries(value)) {
23339
- if (isPlainObject3(v)) subs.push(tomlBlock([...path7, k], v));
23375
+ if (isPlainObject3(v)) subs.push(tomlBlock([...path8, k], v));
23340
23376
  else out += tomlHeaderKey(k) + " = " + tomlScalar(v) + "\n";
23341
23377
  }
23342
23378
  return [out, ...subs].join("\n");
23343
23379
  }
23344
- function under(path7, prefix) {
23345
- return path7.length >= prefix.length && prefix.every((seg, k) => path7[k] === seg);
23380
+ function under(path8, prefix) {
23381
+ return path8.length >= prefix.length && prefix.every((seg, k) => path8[k] === seg);
23346
23382
  }
23347
23383
  function keyLineRange(text, k) {
23348
23384
  const ls = lineStartOf(text, k.start);
@@ -23359,10 +23395,10 @@ function withValueAt(root, rel, value) {
23359
23395
  else base[rel[0]] = next;
23360
23396
  return base;
23361
23397
  }
23362
- function replaceToml(text, doc, path7, value) {
23363
- const block = value === void 0 ? "" : tomlBlock(path7, value);
23364
- const owned = doc.tables.filter((t) => under(t.path, path7));
23365
- const cuts = doc.keys.filter((k) => under(k.full, path7) && !under(k.base, path7)).map((k) => [...keyLineRange(text, k), ""]);
23398
+ function replaceToml(text, doc, path8, value) {
23399
+ const block = value === void 0 ? "" : tomlBlock(path8, value);
23400
+ const owned = doc.tables.filter((t) => under(t.path, path8));
23401
+ const cuts = doc.keys.filter((k) => under(k.full, path8) && !under(k.base, path8)).map((k) => [...keyLineRange(text, k), ""]);
23366
23402
  owned.forEach((t, n) => cuts.push([t.start, t.end, n === 0 ? block : ""]));
23367
23403
  cuts.sort((a, b) => b[0] - a[0]);
23368
23404
  let out = text;
@@ -23372,27 +23408,27 @@ function replaceToml(text, doc, path7, value) {
23372
23408
  return out + sep4 + block;
23373
23409
  }
23374
23410
  var tableLike = (v) => v === void 0 || isPlainObject3(v);
23375
- function setTomlText(text, path7, value) {
23411
+ function setTomlText(text, path8, value) {
23376
23412
  if (value !== void 0 && !isPlainObject3(value)) throw new SyntaxError("TOML edits replace a whole table");
23377
23413
  const doc = scanToml(text);
23378
- const cur = hostConfigValueAt(doc.value, path7);
23414
+ const cur = hostConfigValueAt(doc.value, path8);
23379
23415
  if (sameValue(cur, value)) return text;
23380
- const inline = doc.keys.find((k) => k.inline && k.full.length < path7.length && under(path7, k.full));
23416
+ const inline = doc.keys.find((k) => k.inline && k.full.length < path8.length && under(path8, k.full));
23381
23417
  if (inline !== void 0) {
23382
- const whole2 = withValueAt(hostConfigValueAt(doc.value, inline.full), path7.slice(inline.full.length), value);
23418
+ const whole2 = withValueAt(hostConfigValueAt(doc.value, inline.full), path8.slice(inline.full.length), value);
23383
23419
  return replaceToml(text, doc, inline.full, whole2);
23384
23420
  }
23385
23421
  if (isPlainObject3(cur) && isPlainObject3(value)) {
23386
23422
  const names = [.../* @__PURE__ */ new Set([...Object.keys(cur), ...Object.keys(value)])].filter((k) => !sameValue(cur[k], value[k]));
23387
23423
  if (names.every((k) => tableLike(cur[k]) && tableLike(value[k]))) {
23388
23424
  let out = text;
23389
- for (const k of names) out = setTomlText(out, [...path7, k], value[k]);
23425
+ for (const k of names) out = setTomlText(out, [...path8, k], value[k]);
23390
23426
  return out;
23391
23427
  }
23392
23428
  }
23393
- return replaceToml(text, doc, path7, value);
23429
+ return replaceToml(text, doc, path8, value);
23394
23430
  }
23395
- function setText(agent, path7, text, format, key, value) {
23431
+ function setText(agent, path8, text, format, key, value) {
23396
23432
  try {
23397
23433
  if (format !== "toml") return setJsonText(text, format, key, value);
23398
23434
  const out = setTomlText(text, key, value);
@@ -23401,7 +23437,7 @@ function setText(agent, path7, text, format, key, value) {
23401
23437
  if (!sameValue(landed, value) && !(emptyTable && landed === void 0)) throw new SyntaxError("edit did not land");
23402
23438
  return out;
23403
23439
  } catch {
23404
- throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path7, format });
23440
+ throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path8, format });
23405
23441
  }
23406
23442
  }
23407
23443
  function serverScript() {
@@ -23448,14 +23484,14 @@ function ownTargets(agent, accept) {
23448
23484
  if (agent === "pi") return [listTarget(PI_PACKAGES_KEY, PI_GIT_PACKAGE, V1_PI_PACKAGE)];
23449
23485
  return [];
23450
23486
  }
23451
- function applyEdits(agent, path7, text, format, wanted) {
23452
- const parsed = parseHostConfig(agent, path7, text, format);
23487
+ function applyEdits(agent, path8, text, format, wanted) {
23488
+ const parsed = parseHostConfig(agent, path8, text, format);
23453
23489
  let out = text;
23454
23490
  const edits = [];
23455
23491
  for (const [key, after] of wanted) {
23456
23492
  const before = hostConfigValueAt(parsed, key);
23457
23493
  if (sameValue(before, after)) continue;
23458
- out = setText(agent, path7, out, format, key, after);
23494
+ out = setText(agent, path8, out, format, key, after);
23459
23495
  edits.push({ path: key.join("."), before, after });
23460
23496
  }
23461
23497
  return { text: out, format, edits };
@@ -23476,7 +23512,7 @@ function writeHostConfigEdit(_requested, current, patch) {
23476
23512
  // src/core/ops/detect-v1.ts
23477
23513
  var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
23478
23514
  var keyPath = (...parts) => parts.join(".");
23479
- var finding = (file2, path7, reason) => ({ file: file2, path: path7, reason });
23515
+ var finding = (file2, path8, reason) => ({ file: file2, path: path8, reason });
23480
23516
  function stripJsonc(text) {
23481
23517
  let out = "";
23482
23518
  let inStr = false;
@@ -23681,12 +23717,17 @@ function scanKiro(agentHome, project, out) {
23681
23717
  }
23682
23718
  dataDir(join10(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
23683
23719
  }
23720
+ function piNpmIsCurrent(piAgentDir) {
23721
+ const doc = readJson(join10(piAgentDir, PI_NPM_DIR, PI_NODE_MODULES_DIR, SERVER_KEY, PI_PACKAGE_JSON_FILE));
23722
+ const version4 = isObj(doc) && typeof doc.version === "string" ? doc.version : "";
23723
+ return Number.parseInt(version4, 10) >= PI_CURRENT_MAJOR;
23724
+ }
23684
23725
  function scanPi(piAgentDir, agentHome, out) {
23685
23726
  const file2 = join10(piAgentDir, SETTINGS_FILE);
23686
23727
  const doc = readJson(file2);
23687
23728
  listOf(isObj(doc) ? doc[PI_PACKAGES_KEY] : void 0).forEach((pkg, i) => {
23688
23729
  const spec = isObj(pkg) ? pkg[PI_PACKAGE_SOURCE_KEY] : pkg;
23689
- if (spec === V1_PI_PACKAGE) out.push(finding(file2, keyPath(PI_PACKAGES_KEY, i), V1_REASON.piNpm));
23730
+ if (spec === V1_PI_PACKAGE && !piNpmIsCurrent(piAgentDir)) out.push(finding(file2, keyPath(PI_PACKAGES_KEY, i), V1_REASON.piNpm));
23690
23731
  });
23691
23732
  dataDir(join10(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
23692
23733
  }
@@ -23783,8 +23824,8 @@ function detectV1(agent, home, scope = {}) {
23783
23824
  import { existsSync as existsSync6, readdirSync as readdirSync3, readFileSync as readFileSync8, realpathSync as realpathSync4 } from "node:fs";
23784
23825
  import { dirname as dirname7, isAbsolute as isAbsolute2, join as join11, sep as sep3 } from "node:path";
23785
23826
  import { fileURLToPath as fileURLToPath2 } from "node:url";
23786
- function missing(agent, path7) {
23787
- return new CtxError("PLUGIN_ROOT_MISSING", { agent, path: path7 });
23827
+ function missing(agent, path8) {
23828
+ return new CtxError("PLUGIN_ROOT_MISSING", { agent, path: path8 });
23788
23829
  }
23789
23830
  var parseOrNull = (text) => {
23790
23831
  try {
@@ -23813,9 +23854,9 @@ function recordedInstalls(text) {
23813
23854
  }
23814
23855
  return out;
23815
23856
  }
23816
- var realOrNull = (path7) => {
23857
+ var realOrNull = (path8) => {
23817
23858
  try {
23818
- return realpathSync4.native(path7);
23859
+ return realpathSync4.native(path8);
23819
23860
  } catch {
23820
23861
  return null;
23821
23862
  }
@@ -23913,14 +23954,83 @@ function candidate(adapter, env, worktree) {
23913
23954
  }
23914
23955
  }
23915
23956
  function resolvePluginRoot(adapter, env, worktree) {
23916
- const path7 = candidate(adapter, env, worktree);
23957
+ const path8 = candidate(adapter, env, worktree);
23917
23958
  try {
23918
- return realpathSync4.native(path7);
23959
+ return realpathSync4.native(path8);
23919
23960
  } catch {
23920
- throw missing(adapter.id, path7);
23961
+ throw missing(adapter.id, path8);
23921
23962
  }
23922
23963
  }
23923
23964
 
23965
+ // src/setup/pi-gate.ts
23966
+ import { existsSync as existsSync7, readFileSync as readFileSync9, realpathSync as realpathSync5 } from "node:fs";
23967
+ import path4 from "node:path";
23968
+ var EXTENSIONS_KEY = "extensions";
23969
+ var PROJECT_DIR = ".pi";
23970
+ var TRUST_FILE = "trust.json";
23971
+ var ALWAYS = "always";
23972
+ var SOURCE_PREFIXES = ["npm:", "git:"];
23973
+ function load(file2) {
23974
+ if (!existsSync7(file2)) return void 0;
23975
+ try {
23976
+ return { file: file2, doc: parseHostConfig("pi", file2, hostText(readFileSync9(file2, "utf8")), "json") };
23977
+ } catch {
23978
+ return void 0;
23979
+ }
23980
+ }
23981
+ var real2 = (p) => {
23982
+ try {
23983
+ return realpathSync5(p);
23984
+ } catch {
23985
+ return path4.resolve(p);
23986
+ }
23987
+ };
23988
+ function sourceName(source) {
23989
+ let s = source;
23990
+ for (const p of SOURCE_PREFIXES) if (s.startsWith(p)) s = s.slice(p.length);
23991
+ const last2 = s.split("/").pop() ?? "";
23992
+ const at2 = last2.indexOf("@", 1);
23993
+ const name = at2 > 0 ? last2.slice(0, at2) : last2;
23994
+ return name.endsWith(".git") ? name.slice(0, -4) : name;
23995
+ }
23996
+ function isOwn(source, pkgDir) {
23997
+ if (typeof source !== "string") return false;
23998
+ return real2(source) === real2(pkgDir) || sourceName(source) === SERVER_KEY;
23999
+ }
24000
+ function ownEntries(src, pkgDir) {
24001
+ const list4 = hostConfigValueAt(src.doc, [PI_PACKAGES_KEY]);
24002
+ if (!Array.isArray(list4)) return [];
24003
+ const out = [];
24004
+ for (const e of list4) {
24005
+ const obj = typeof e === "object" && e !== null && !Array.isArray(e) ? e : void 0;
24006
+ if (!isOwn(obj ? obj[PI_PACKAGE_SOURCE_KEY] : e, pkgDir)) continue;
24007
+ const ext = obj?.[EXTENSIONS_KEY];
24008
+ out.push({ source: src, patterns: Array.isArray(ext) ? ext.filter((x) => typeof x === "string") : void 0 });
24009
+ }
24010
+ return out;
24011
+ }
24012
+ function projectTrusted(agentDir, userDoc, cwd) {
24013
+ const trust = load(path4.join(agentDir, TRUST_FILE));
24014
+ const entries = /* @__PURE__ */ new Map();
24015
+ if (trust && typeof trust.doc === "object" && trust.doc !== null) for (const [k, v] of Object.entries(trust.doc)) entries.set(real2(k), v);
24016
+ let dir = real2(cwd);
24017
+ for (; ; ) {
24018
+ const v = entries.get(dir);
24019
+ if (v === true || v === false) return v;
24020
+ const up = path4.dirname(dir);
24021
+ if (up === dir) break;
24022
+ dir = up;
24023
+ }
24024
+ return hostConfigValueAt(userDoc, ["defaultProjectTrust"]) === ALWAYS;
24025
+ }
24026
+ function piInstalledIn(env, home, pkgDir, cwd) {
24027
+ const agentDir = piAgentDirOf(env, home);
24028
+ const user = load(path4.join(agentDir, SETTINGS_FILE));
24029
+ const project = load(path4.join(cwd, PROJECT_DIR, SETTINGS_FILE));
24030
+ if (project && projectTrusted(agentDir, user?.doc, cwd) && ownEntries(project, pkgDir).length > 0) return project.file;
24031
+ return user && ownEntries(user, pkgDir).length > 0 ? user.file : void 0;
24032
+ }
24033
+
23924
24034
  // src/core/ops/doctor-config.ts
23925
24035
  var [PART_MCP, PART_HOOKS, PART_TIMEOUT] = D3_PARTS;
23926
24036
  var isObject4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
@@ -24021,14 +24131,14 @@ function codexNativeDir(env, home) {
24021
24131
  }
24022
24132
  if (enabled !== true) return null;
24023
24133
  const cache = join12(codexDir, "plugins", PLUGIN_CACHE_DIR_NAME);
24024
- if (!existsSync7(cache)) return null;
24134
+ if (!existsSync8(cache)) return null;
24025
24135
  const found = [];
24026
24136
  for (const market of readdirSync4(cache)) {
24027
24137
  const plugin = join12(cache, market, SERVER_KEY);
24028
- if (!existsSync7(plugin)) continue;
24138
+ if (!existsSync8(plugin)) continue;
24029
24139
  for (const version4 of readdirSync4(plugin).sort()) {
24030
24140
  const dir = join12(plugin, version4, CODEX_PLUGIN_SUBDIR);
24031
- if (existsSync7(join12(dir, CODEX_PLUGIN_MCP_FILE))) found.push(dir);
24141
+ if (existsSync8(join12(dir, CODEX_PLUGIN_MCP_FILE))) found.push(dir);
24032
24142
  }
24033
24143
  }
24034
24144
  return found.length === 0 ? null : found[found.length - 1];
@@ -24119,12 +24229,17 @@ function checkHostConfig(row5, env, worktree) {
24119
24229
  const choice = marketplaceChoice(env, worktree);
24120
24230
  if ("installs" in choice) return fail2("D3", D3_ROOT_DETAIL(choice.installs.map((r) => r.installPath)), D3_ROOT_FIX(choice.installs));
24121
24231
  }
24232
+ if (row5.id === "pi") return checkPiInstall(env, home, worktree);
24122
24233
  const parts = [...mcpWrong(row5, home, env, worktree) ? [PART_MCP] : [], ...hookParts(row5, home, env, worktree)];
24123
- const read3 = row5.id === "pi" ? mcpFile(row5, home, env) : null;
24124
- if (parts.length === 0) return read3 === null ? pass("D3") : { ...pass("D3"), detail: read3 };
24234
+ if (parts.length === 0) return pass("D3");
24125
24235
  const detail = D3_DETAIL(parts);
24126
24236
  const fix = parts.includes(PART_MCP) ? D3_NO_SETUP_FIX(row5.id) : DOCTOR_FIX_UPGRADE;
24127
- return fail2("D3", read3 === null ? detail : detail + D4_REASON_JOIN + read3, fix);
24237
+ return fail2("D3", detail, fix);
24238
+ }
24239
+ function checkPiInstall(env, home, worktree) {
24240
+ const found = piInstalledIn(env, home, ownBundleDir(), worktree);
24241
+ if (found !== void 0) return { ...pass("D3"), detail: found };
24242
+ return fail2("D3", D3_DETAIL([PART_MCP]) + D4_REASON_JOIN + join12(piAgentDirOf(env, home), SETTINGS_FILE), NATIVE_INSTALL.pi[0]);
24128
24243
  }
24129
24244
  function checkV1Leftovers(agent, home, scope = {}) {
24130
24245
  const findings = detectV1(agent, home, scope);
@@ -24177,7 +24292,7 @@ function configPaths(row5, env, worktree) {
24177
24292
  }
24178
24293
 
24179
24294
  // src/core/ops/doctor-db.ts
24180
- import { existsSync as existsSync8, statSync as statSync5 } from "node:fs";
24295
+ import { existsSync as existsSync9, statSync as statSync5 } from "node:fs";
24181
24296
  var unknown2 = (id, detail) => ({ id, label: DOCTOR_LABEL[id], status: "UNKNOWN", detail });
24182
24297
  var pass2 = (id, detail) => ({ id, label: DOCTOR_LABEL[id], status: "PASS", detail });
24183
24298
  var fail3 = (detail, fixCommand) => ({ id: "D8", label: DOCTOR_LABEL.D8, status: "FAIL", detail, fixCommand });
@@ -24196,8 +24311,8 @@ async function loadSqlite2() {
24196
24311
  return null;
24197
24312
  }
24198
24313
  }
24199
- function openRead(sqlite, path7) {
24200
- return new sqlite.DatabaseSync(path7, { timeout: DB_TIMEOUT_MS, readOnly: true });
24314
+ function openRead(sqlite, path8) {
24315
+ return new sqlite.DatabaseSync(path8, { timeout: DB_TIMEOUT_MS, readOnly: true });
24201
24316
  }
24202
24317
  var cell = (row5) => Object.values(row5)[0];
24203
24318
  function readSchema(raw) {
@@ -24218,16 +24333,16 @@ function failsOnCorrupt(step) {
24218
24333
  function orphanFiles(dbPath) {
24219
24334
  const files = [];
24220
24335
  for (const suffix of [DB_WAL_SUFFIX, DB_SHM_SUFFIX]) {
24221
- const path7 = dbPath + suffix;
24222
- if (existsSync8(path7)) files.push({ path: path7, bytes: statSync5(path7).size });
24336
+ const path8 = dbPath + suffix;
24337
+ if (existsSync9(path8)) files.push({ path: path8, bytes: statSync5(path8).size });
24223
24338
  }
24224
- return files.length > 0 && !existsSync8(dbPath) ? files : [];
24339
+ return files.length > 0 && !existsSync9(dbPath) ? files : [];
24225
24340
  }
24226
24341
  async function checkDb(project) {
24227
24342
  const clean = { schemaStale: false, integrityFailed: false, orphan: [] };
24228
24343
  const orphan = orphanFiles(project.dbPath);
24229
24344
  if (orphan.length > 0) return { row: fail3(D8_ORPHAN_DETAIL(orphan), D8_ORPHAN_FIX), schemaStale: false, integrityFailed: false, orphan };
24230
- if (!existsSync8(project.dbPath)) return { row: pass2("D8", DOCTOR_PASS_DETAIL), ...clean };
24345
+ if (!existsSync9(project.dbPath)) return { row: pass2("D8", DOCTOR_PASS_DETAIL), ...clean };
24231
24346
  const sqlite = await loadSqlite2();
24232
24347
  if (sqlite === null) return { row: unknown2("D8", D2_SQLITE_DETAIL), ...clean };
24233
24348
  let raw = null;
@@ -24253,7 +24368,7 @@ async function checkDb(project) {
24253
24368
  }
24254
24369
  }
24255
24370
  async function checkIndex(project) {
24256
- if (!existsSync8(project.dbPath)) return pass2("D9", D9_INDEX_DETAIL(0, 0));
24371
+ if (!existsSync9(project.dbPath)) return pass2("D9", D9_INDEX_DETAIL(0, 0));
24257
24372
  const sqlite = await loadSqlite2();
24258
24373
  if (sqlite === null) return unknown2("D9", D2_SQLITE_DETAIL);
24259
24374
  let raw = null;
@@ -24270,7 +24385,7 @@ async function checkIndex(project) {
24270
24385
  }
24271
24386
 
24272
24387
  // src/core/ops/doctor-env.ts
24273
- import { existsSync as existsSync9, readFileSync as readFileSync9, realpathSync as realpathSync5 } from "node:fs";
24388
+ import { existsSync as existsSync10, readFileSync as readFileSync10, realpathSync as realpathSync6 } from "node:fs";
24274
24389
  import { isAbsolute as isAbsolute3, join as join13, relative as relative2 } from "node:path";
24275
24390
  function pass3(id, detail = DOCTOR_PASS_DETAIL) {
24276
24391
  return { id, label: DOCTOR_LABEL[id], status: "PASS", detail };
@@ -24283,7 +24398,7 @@ function fail4(id, detail, fixCommand) {
24283
24398
  }
24284
24399
  function bundleVersion(bundleDir2) {
24285
24400
  try {
24286
- const v = JSON.parse(readFileSync9(join13(bundleDir2, D1_PACKAGE_FILE), "utf8")).version;
24401
+ const v = JSON.parse(readFileSync10(join13(bundleDir2, D1_PACKAGE_FILE), "utf8")).version;
24287
24402
  return typeof v === "string" && v !== "" ? v : void 0;
24288
24403
  } catch {
24289
24404
  return void 0;
@@ -24433,8 +24548,8 @@ function checkMcp(ctx) {
24433
24548
  return named2 || versioned ? pass3("D6") : unknown3("D6", D6_UNKNOWN_DETAIL);
24434
24549
  }
24435
24550
  function piCwdInside(worktree, piCwd) {
24436
- if (piCwd === void 0 || !existsSync9(piCwd)) return false;
24437
- const rel = relative2(worktree, realpathSync5.native(piCwd));
24551
+ if (piCwd === void 0 || !existsSync10(piCwd)) return false;
24552
+ const rel = relative2(worktree, realpathSync6.native(piCwd));
24438
24553
  return rel === "" || !rel.startsWith("..") && !isAbsolute3(rel);
24439
24554
  }
24440
24555
  function checkProject(i) {
@@ -24454,20 +24569,20 @@ function checkShell(env) {
24454
24569
  }
24455
24570
 
24456
24571
  // src/core/ops/doctor-hook.ts
24457
- import { existsSync as existsSync11, mkdtempSync, readFileSync as readFileSync10, realpathSync as realpathSync7, rmSync as rmSync2 } from "node:fs";
24572
+ import { existsSync as existsSync12, mkdtempSync, readFileSync as readFileSync11, realpathSync as realpathSync8, rmSync as rmSync2 } from "node:fs";
24458
24573
  import { tmpdir as tmpdir2 } from "node:os";
24459
- import path6 from "node:path";
24574
+ import path7 from "node:path";
24460
24575
 
24461
24576
  // src/setup/codex-trust.ts
24462
24577
  import { createHash } from "node:crypto";
24463
- import { existsSync as existsSync10, realpathSync as realpathSync6 } from "node:fs";
24464
- import path5 from "node:path";
24578
+ import { existsSync as existsSync11, realpathSync as realpathSync7 } from "node:fs";
24579
+ import path6 from "node:path";
24465
24580
  import { spawn as spawn2, spawnSync as spawnSync2 } from "node:child_process";
24466
24581
 
24467
24582
  // src/setup/spawn-bin.ts
24468
24583
  import { spawnSync } from "node:child_process";
24469
24584
  import { accessSync as accessSync2, constants as fsc, statSync as statSync6 } from "node:fs";
24470
- import path4 from "node:path";
24585
+ import path5 from "node:path";
24471
24586
  var WIN_EXT = ".COM;.EXE;.BAT;.CMD";
24472
24587
  var WIN_SHIM_EXTS = Object.freeze([".cmd", ".bat"]);
24473
24588
  var DEFAULT_COMSPEC = "cmd.exe";
@@ -24478,10 +24593,10 @@ function whichBin(bin, env, platform = process.platform) {
24478
24593
  const get = (k) => envGet(env, k);
24479
24594
  const win = platform === "win32";
24480
24595
  const exts = win ? (get("PATHEXT") || WIN_EXT).split(";").filter(Boolean) : [""];
24481
- const names = win && path4.extname(bin) ? [bin] : exts.map((e) => bin + e.toLowerCase());
24596
+ const names = win && path5.extname(bin) ? [bin] : exts.map((e) => bin + e.toLowerCase());
24482
24597
  for (const dir of pathEntries(get("PATH") ?? "", platform)) {
24483
24598
  for (const n of names) {
24484
- const f = path4.join(dir, n);
24599
+ const f = path5.join(dir, n);
24485
24600
  try {
24486
24601
  accessSync2(f, fsc.X_OK);
24487
24602
  if (statSync6(f).isFile()) return f;
@@ -24522,7 +24637,7 @@ function winCmdLine(file2, args, env = {}) {
24522
24637
  return `"${[file2, ...args].map(q).join(" ")}"`;
24523
24638
  }
24524
24639
  function spawnForm(file2, args, env, platform = process.platform) {
24525
- if (platform === "win32" && WIN_SHIM_EXTS.includes(path4.extname(file2).toLowerCase())) {
24640
+ if (platform === "win32" && WIN_SHIM_EXTS.includes(path5.extname(file2).toLowerCase())) {
24526
24641
  return { command: envGet(env, "COMSPEC") || DEFAULT_COMSPEC, args: ["/d", "/v:off", "/s", "/c", winCmdLine(file2, args, env)], windowsVerbatimArguments: true };
24527
24642
  }
24528
24643
  return { command: file2, args, windowsVerbatimArguments: false };
@@ -24546,10 +24661,10 @@ function codexHomeFromReply(out) {
24546
24661
  return void 0;
24547
24662
  }
24548
24663
  function sameDir(a, b, platform = process.platform) {
24549
- if (platform !== "win32") return path5.posix.normalize(a) === path5.posix.normalize(b);
24664
+ if (platform !== "win32") return path6.posix.normalize(a) === path6.posix.normalize(b);
24550
24665
  const norm2 = (p) => {
24551
24666
  const bare2 = p.startsWith(WIN_VERBATIM_PREFIX) ? p.slice(WIN_VERBATIM_PREFIX.length) : p;
24552
- const n = path5.win32.normalize(bare2).toLowerCase();
24667
+ const n = path6.win32.normalize(bare2).toLowerCase();
24553
24668
  return n.length > 3 && n.endsWith("\\") ? n.slice(0, -1) : n;
24554
24669
  };
24555
24670
  return norm2(a) === norm2(b);
@@ -24682,11 +24797,11 @@ function isObject5(v) {
24682
24797
  return typeof v === "object" && v !== null && !Array.isArray(v);
24683
24798
  }
24684
24799
  function loadFixture(bundleDir2, agent) {
24685
- const file2 = path6.join(bundleDir2, HOOK_FIXTURE_DIR, HOOK_FIXTURE_FILE);
24686
- if (!existsSync11(file2)) return { cause: D5_FIXTURE_FILE_ABSENT(file2) };
24800
+ const file2 = path7.join(bundleDir2, HOOK_FIXTURE_DIR, HOOK_FIXTURE_FILE);
24801
+ if (!existsSync12(file2)) return { cause: D5_FIXTURE_FILE_ABSENT(file2) };
24687
24802
  let all;
24688
24803
  try {
24689
- all = JSON.parse(hostText(readFileSync10(file2, "utf8")));
24804
+ all = JSON.parse(hostText(readFileSync11(file2, "utf8")));
24690
24805
  } catch (err) {
24691
24806
  return { cause: D5_FIXTURE_PARSE(file2, err instanceof Error ? err.message : String(err)) };
24692
24807
  }
@@ -24748,7 +24863,7 @@ function isNativeShape(agent, stdout, exitCode, killed, event) {
24748
24863
  var READ_PROBE_LINES = 4 * Math.ceil(REPLACE_TRIGGER_BYTES / 40);
24749
24864
  function readProbePayload(cwd) {
24750
24865
  const content = Array.from({ length: READ_PROBE_LINES }, (_, n) => "d5 read probe line " + n + " ".padEnd(20, "x")).join("\n");
24751
- const filePath = path6.join(cwd, "d5-read-probe.txt");
24866
+ const filePath = path7.join(cwd, "d5-read-probe.txt");
24752
24867
  return {
24753
24868
  session_id: "d5-read-probe",
24754
24869
  transcript_path: "",
@@ -24775,9 +24890,9 @@ function isReadShape(stdout) {
24775
24890
  return typeof f.filePath === "string" && typeof f.content === "string" && ["numLines", "startLine", "totalLines"].every((k) => typeof f[k] === "number");
24776
24891
  }
24777
24892
  async function readProbeOk(i, timeoutMs) {
24778
- const home = mkdtempSync(path6.join(tmpdir2(), "cm-d5-read-"));
24893
+ const home = mkdtempSync(path7.join(tmpdir2(), "cm-d5-read-"));
24779
24894
  try {
24780
- const r = await runProcess([process.execPath, path6.join(i.bundleDir, HOOK_ENTRY_FILE), AGENT_ARG, i.agent], {
24895
+ const r = await runProcess([process.execPath, path7.join(i.bundleDir, HOOK_ENTRY_FILE), AGENT_ARG, i.agent], {
24781
24896
  cwd: i.bundleDir,
24782
24897
  env: { ...i.env, HOME: home, USERPROFILE: home },
24783
24898
  signal: i.signal,
@@ -24795,7 +24910,7 @@ function codexHookJournaled(db) {
24795
24910
  }
24796
24911
  function realDir(p) {
24797
24912
  try {
24798
- return realpathSync7(p);
24913
+ return realpathSync8(p);
24799
24914
  } catch {
24800
24915
  return p;
24801
24916
  }
@@ -24822,7 +24937,7 @@ async function checkHookRoundTrip(i) {
24822
24937
  const trust = await codexPluginTrust(i);
24823
24938
  if (trust !== null) return trust;
24824
24939
  }
24825
- if (i.agent === "codex" && existsSync11(path6.join(i.codexConfigDir, HOOKS_JSON_FILE)) && !codexHookJournaled(i.db)) {
24940
+ if (i.agent === "codex" && existsSync12(path7.join(i.codexConfigDir, HOOKS_JSON_FILE)) && !codexHookJournaled(i.db)) {
24826
24941
  return row("UNKNOWN", D5_CODEX_UNTRUSTED_DETAIL);
24827
24942
  }
24828
24943
  const fixture = loadFixture(i.bundleDir, i.agent);
@@ -24842,7 +24957,7 @@ async function checkHookRoundTrip(i) {
24842
24957
  let ms = 0;
24843
24958
  for (let n = 1; n <= maxPairs; n++) {
24844
24959
  const start = now();
24845
- const r = await runProcess([process.execPath, path6.join(i.bundleDir, HOOK_ENTRY_FILE), AGENT_ARG, i.agent], {
24960
+ const r = await runProcess([process.execPath, path7.join(i.bundleDir, HOOK_ENTRY_FILE), AGENT_ARG, i.agent], {
24846
24961
  cwd: i.bundleDir,
24847
24962
  env: i.env,
24848
24963
  signal: i.signal,
@@ -24861,11 +24976,11 @@ async function checkHookRoundTrip(i) {
24861
24976
  }
24862
24977
 
24863
24978
  // src/core/ops/db-heal.ts
24864
- import { existsSync as existsSync12, mkdirSync as mkdirSync5, rmSync as rmSync4 } from "node:fs";
24979
+ import { existsSync as existsSync13, mkdirSync as mkdirSync5, rmSync as rmSync4 } from "node:fs";
24865
24980
  import { basename as basename4, dirname as dirname8, join as join15 } from "node:path";
24866
24981
 
24867
24982
  // src/core/store/owners.ts
24868
- import { mkdirSync as mkdirSync4, readdirSync as readdirSync5, readFileSync as readFileSync11, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "node:fs";
24983
+ import { mkdirSync as mkdirSync4, readdirSync as readdirSync5, readFileSync as readFileSync12, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "node:fs";
24869
24984
  import { basename as basename3, join as join14 } from "node:path";
24870
24985
  function ownersDir(configDir, projectKey) {
24871
24986
  return join14(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
@@ -24909,7 +25024,7 @@ function listLiveOwners(configDir, projectKey) {
24909
25024
  const file2 = join14(dir, name);
24910
25025
  let text;
24911
25026
  try {
24912
- text = readFileSync11(file2, "utf8");
25027
+ text = readFileSync12(file2, "utf8");
24913
25028
  } catch (err) {
24914
25029
  if (errCode2(err) === "ENOENT") continue;
24915
25030
  throw err;
@@ -24955,7 +25070,7 @@ function renameAside(dbPath) {
24955
25070
  const ts = String(Date.now());
24956
25071
  for (const suffix of DB_SIBLING_SUFFIXES) {
24957
25072
  const file2 = dbPath + suffix;
24958
- if (existsSync12(file2)) renameWithRetry(file2, file2 + HEAL_TS_SEP + ts + HEAL_BACKUP_SUFFIX);
25073
+ if (existsSync13(file2)) renameWithRetry(file2, file2 + HEAL_TS_SEP + ts + HEAL_BACKUP_SUFFIX);
24959
25074
  }
24960
25075
  return ts;
24961
25076
  }
@@ -25062,7 +25177,7 @@ function buildReportHead(input) {
25062
25177
 
25063
25178
  // src/core/ops/doctor-issue.ts
25064
25179
  import { spawnSync as spawnSync3 } from "node:child_process";
25065
- import { closeSync, existsSync as existsSync13, fstatSync, mkdirSync as mkdirSync6, openSync, readFileSync as readFileSync12, readSync, realpathSync as realpathSync8, writeFileSync as writeFileSync3 } from "node:fs";
25180
+ import { closeSync, existsSync as existsSync14, fstatSync, mkdirSync as mkdirSync6, openSync, readFileSync as readFileSync13, readSync, realpathSync as realpathSync9, writeFileSync as writeFileSync3 } from "node:fs";
25066
25181
  import { delimiter, join as join16 } from "node:path";
25067
25182
  var TOKEN_PREFIXES = ["ghp_", "gho_", "github_pat_", "sk-", "xoxb-", "AKIA"];
25068
25183
  function tildeOf(env) {
@@ -25070,8 +25185,8 @@ function tildeOf(env) {
25070
25185
  if (home === null || home === "") return (t) => t;
25071
25186
  const homes = [home];
25072
25187
  try {
25073
- const real2 = realpathSync8.native(home);
25074
- if (real2 !== home) homes.push(real2);
25188
+ const real3 = realpathSync9.native(home);
25189
+ if (real3 !== home) homes.push(real3);
25075
25190
  } catch {
25076
25191
  }
25077
25192
  homes.sort((a, b) => b.length - a.length);
@@ -25104,7 +25219,7 @@ function onPath(env, tool) {
25104
25219
  const out = [];
25105
25220
  for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter)) {
25106
25221
  if (dir === "") continue;
25107
- for (const n of names) if (existsSync13(join16(dir, n))) {
25222
+ for (const n of names) if (existsSync14(join16(dir, n))) {
25108
25223
  out.push(join16(dir, n));
25109
25224
  break;
25110
25225
  }
@@ -25113,7 +25228,7 @@ function onPath(env, tool) {
25113
25228
  }
25114
25229
  function hookLogTail(env) {
25115
25230
  const file2 = hookLogPath(env);
25116
- if (file2 === "" || !existsSync13(file2)) return [`(${file2 || "hook-errors.log"} holds zero lines)`];
25231
+ if (file2 === "" || !existsSync14(file2)) return [`(${file2 || "hook-errors.log"} holds zero lines)`];
25117
25232
  try {
25118
25233
  const fd = openSync(file2, "r");
25119
25234
  try {
@@ -25133,7 +25248,7 @@ function hookLogTail(env) {
25133
25248
  }
25134
25249
  async function journalRows(ctx) {
25135
25250
  const head = ["| kind | tool | bytes | ok | exit_code | created_at |", "|---|---|---|---|---|---|"];
25136
- if (!existsSync13(ctx.project.dbPath)) return [`(context.db is absent at ${ctx.project.dbPath})`];
25251
+ if (!existsSync14(ctx.project.dbPath)) return [`(context.db is absent at ${ctx.project.dbPath})`];
25137
25252
  try {
25138
25253
  const db = await openDb(ctx.project, { readOnly: true });
25139
25254
  try {
@@ -25159,13 +25274,13 @@ function agentConfig(adapter, env, worktree) {
25159
25274
  for (const f of files) {
25160
25275
  if (seen.has(f.path)) continue;
25161
25276
  seen.add(f.path);
25162
- if (!existsSync13(f.path)) {
25277
+ if (!existsSync14(f.path)) {
25163
25278
  out.push(`${f.label}: ${f.path} (absent)`);
25164
25279
  continue;
25165
25280
  }
25166
25281
  let text = "";
25167
25282
  try {
25168
- text = readFileSync12(f.path, "utf8");
25283
+ text = readFileSync13(f.path, "utf8");
25169
25284
  } catch (err) {
25170
25285
  out.push(`${f.label}: ${f.path} (read: ${err instanceof Error ? err.message : String(err)})`);
25171
25286
  continue;
@@ -25264,7 +25379,7 @@ async function guard(id, run) {
25264
25379
  }
25265
25380
  }
25266
25381
  async function codexDb(ctx, adapter) {
25267
- if (adapter.id !== "codex" || !existsSync14(ctx.project.dbPath)) return null;
25382
+ if (adapter.id !== "codex" || !existsSync15(ctx.project.dbPath)) return null;
25268
25383
  try {
25269
25384
  return await openDb(ctx.project, { readOnly: true });
25270
25385
  } catch {
@@ -25295,10 +25410,10 @@ async function hookRow(ctx, adapter, host) {
25295
25410
  }
25296
25411
  function ownServerId(configDir, projectKey) {
25297
25412
  const dir = join17(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
25298
- if (!existsSync14(dir)) return "";
25413
+ if (!existsSync15(dir)) return "";
25299
25414
  for (const name of readdirSync6(dir)) {
25300
25415
  if (!name.endsWith(OWNER_PID_EXT)) continue;
25301
- if (readFileSync13(join17(dir, name), "utf8").trim() === String(process.pid)) return basename5(name, OWNER_PID_EXT);
25416
+ if (readFileSync14(join17(dir, name), "utf8").trim() === String(process.pid)) return basename5(name, OWNER_PID_EXT);
25302
25417
  }
25303
25418
  return "";
25304
25419
  }
@@ -25354,7 +25469,7 @@ async function doctorReply(ctx, host) {
25354
25469
  const adapter = getAdapter(ctx.project.agent);
25355
25470
  const rows = await runDoctorChecks(ctx, adapter, host);
25356
25471
  const failed2 = rows.some((r) => r.status === "FAIL");
25357
- const command = `context-mode ${failed2 ? "setup" : "doctor"} --agents ${adapter.id}`;
25472
+ const command = adapter.id === "pi" ? failed2 ? NATIVE_INSTALL.pi[0] : PI_LIST_COMMAND : `context-mode ${failed2 ? "setup" : "doctor"} --agents ${adapter.id}`;
25358
25473
  const input = { agent: adapter.id, rows, env: reportEnv(host.env), command };
25359
25474
  const envLine2 = environmentLine(ctx, adapter, host.env, bundleVersion(host.bundleDir));
25360
25475
  const table3 = buildReport(input);
@@ -25381,7 +25496,7 @@ async function doctorReply(ctx, host) {
25381
25496
  return { text, isError: false, sandboxBytes: bytes5 };
25382
25497
  }
25383
25498
  async function handler2(_input, ctx) {
25384
- return doctorReply(ctx, { env: process.env, bundleDir: ownBundleDir(), piCwd: void 0 });
25499
+ return doctorReply(ctx, { env: process.env, bundleDir: ownBundleDir(), piCwd: ctx.piCwd });
25385
25500
  }
25386
25501
  var ctxDoctor = Object.freeze({
25387
25502
  name: "ctx_doctor",
@@ -25393,7 +25508,7 @@ var ctxDoctor = Object.freeze({
25393
25508
  });
25394
25509
 
25395
25510
  // src/core/tools/execute.ts
25396
- import { existsSync as existsSync15, mkdtempSync as mkdtempSync2, rmSync as rmSync5, writeFileSync as writeFileSync4 } from "node:fs";
25511
+ import { existsSync as existsSync16, mkdtempSync as mkdtempSync2, rmSync as rmSync5, writeFileSync as writeFileSync4 } from "node:fs";
25397
25512
  import { tmpdir as tmpdir3 } from "node:os";
25398
25513
  import { dirname as dirname10, join as join18, parse as parse3, resolve as resolve6 } from "node:path";
25399
25514
 
@@ -25479,7 +25594,7 @@ function schemaLine(issue4) {
25479
25594
  }
25480
25595
  function fileError(given, abs, root) {
25481
25596
  let dir = abs;
25482
- while (!existsSync15(dir) && dirname10(dir) !== dir) dir = dirname10(dir);
25597
+ while (!existsSync16(dir) && dirname10(dir) !== dir) dir = dirname10(dir);
25483
25598
  if (isInside(root, dir)) return null;
25484
25599
  return new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine();
25485
25600
  }
@@ -25596,19 +25711,19 @@ var ctxExecute = {
25596
25711
  };
25597
25712
 
25598
25713
  // src/core/tools/index.ts
25599
- import { existsSync as existsSync16, readFileSync as readFileSync15, statSync as statSync8 } from "node:fs";
25714
+ import { existsSync as existsSync17, readFileSync as readFileSync16, statSync as statSync8 } from "node:fs";
25600
25715
  import { dirname as dirname11, extname, join as join20, relative as relative3, resolve as resolve7 } from "node:path";
25601
25716
 
25602
25717
  // src/core/index/walk.ts
25603
- import { readdirSync as readdirSync7, readFileSync as readFileSync14, realpathSync as realpathSync9, statSync as statSync7 } from "node:fs";
25718
+ import { readdirSync as readdirSync7, readFileSync as readFileSync15, realpathSync as realpathSync10, statSync as statSync7 } from "node:fs";
25604
25719
  import { join as join19 } from "node:path";
25605
25720
  var GITIGNORE = ".gitignore";
25606
25721
  var GIT_DIR = ".git";
25607
25722
  function walkDir(root, containmentRoot) {
25608
- const real2 = realpathSync9(root);
25609
- if (!isInside(containmentRoot, real2)) throw new CtxError("OUTSIDE_ROOT", { p: root, root: containmentRoot });
25723
+ const real3 = realpathSync10(root);
25724
+ if (!isInside(containmentRoot, real3)) throw new CtxError("OUTSIDE_ROOT", { p: root, root: containmentRoot });
25610
25725
  const found = [];
25611
- visit(real2, [], [], containmentRoot, /* @__PURE__ */ new Set([real2]), found);
25726
+ visit(real3, [], [], containmentRoot, /* @__PURE__ */ new Set([real3]), found);
25612
25727
  found.sort(compareFound);
25613
25728
  return found.map((f) => ({ absPath: f.absPath, relPath: join19(...f.dir, f.name) }));
25614
25729
  }
@@ -25622,14 +25737,14 @@ function visit(abs, rel, parent, contain, seen, found) {
25622
25737
  const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join19(abs, GITIGNORE), rel)) : parent;
25623
25738
  for (const e of entries) {
25624
25739
  if (e.name === GIT_DIR) continue;
25625
- const path7 = join19(abs, e.name);
25740
+ const path8 = join19(abs, e.name);
25626
25741
  let isDir = e.isDirectory();
25627
25742
  let isFile = e.isFile();
25628
- let target = path7;
25743
+ let target = path8;
25629
25744
  if (e.isSymbolicLink()) {
25630
25745
  let resolved;
25631
25746
  try {
25632
- resolved = realpathSync9(path7);
25747
+ resolved = realpathSync10(path8);
25633
25748
  } catch {
25634
25749
  continue;
25635
25750
  }
@@ -25642,12 +25757,12 @@ function visit(abs, rel, parent, contain, seen, found) {
25642
25757
  const segs = rel.concat(e.name);
25643
25758
  if (ignored(rules, segs, isDir)) continue;
25644
25759
  if (isFile) {
25645
- found.push({ dir: rel, name: e.name, absPath: path7 });
25760
+ found.push({ dir: rel, name: e.name, absPath: path8 });
25646
25761
  } else if (isDir) {
25647
- const key = e.isSymbolicLink() ? target : realpathSync9(path7);
25762
+ const key = e.isSymbolicLink() ? target : realpathSync10(path8);
25648
25763
  if (seen.has(key)) continue;
25649
25764
  seen.add(key);
25650
- visit(path7, segs, rules, contain, seen, found);
25765
+ visit(path8, segs, rules, contain, seen, found);
25651
25766
  }
25652
25767
  }
25653
25768
  }
@@ -25662,7 +25777,7 @@ function compareFound(a, b) {
25662
25777
  function readRules(file2, base) {
25663
25778
  let body;
25664
25779
  try {
25665
- body = readFileSync14(file2, "utf8");
25780
+ body = readFileSync15(file2, "utf8");
25666
25781
  } catch {
25667
25782
  return [];
25668
25783
  }
@@ -25838,12 +25953,12 @@ function tlsName(host) {
25838
25953
  function request(u, conn, proxy, signal) {
25839
25954
  const host = bare(u.hostname);
25840
25955
  const port = u.port === "" ? defaultPort(u.protocol) : Number(u.port);
25841
- const path7 = u.pathname + u.search;
25956
+ const path8 = u.pathname + u.search;
25842
25957
  return new Promise((resolve8, reject) => {
25843
25958
  const onErr = (err) => reject(fail6(causeCode(err)));
25844
25959
  if (proxy === void 0) {
25845
25960
  const mod = u.protocol === "https:" ? https : http;
25846
- const req = mod.request({ host: conn.address, port, path: path7, signal, servername: tlsName(host), headers: { host: u.host } });
25961
+ const req = mod.request({ host: conn.address, port, path: path8, signal, servername: tlsName(host), headers: { host: u.host } });
25847
25962
  req.on("response", resolve8).on("error", onErr).end();
25848
25963
  return;
25849
25964
  }
@@ -25865,7 +25980,7 @@ function request(u, conn, proxy, signal) {
25865
25980
  const req = https.request({
25866
25981
  host,
25867
25982
  port,
25868
- path: path7,
25983
+ path: path8,
25869
25984
  signal,
25870
25985
  headers: { host: u.host },
25871
25986
  createConnection: () => tlsConnect({ socket, host, servername: tlsName(host) })
@@ -29745,14 +29860,14 @@ function kindOfType(contentType) {
29745
29860
  }
29746
29861
  function readUtf8(absPath) {
29747
29862
  try {
29748
- return utf8.decode(readFileSync15(absPath));
29863
+ return utf8.decode(readFileSync16(absPath));
29749
29864
  } catch {
29750
29865
  return void 0;
29751
29866
  }
29752
29867
  }
29753
29868
  function missingOrOutside(given, abs, root) {
29754
29869
  let dir = abs;
29755
- while (!existsSync16(dir) && dirname11(dir) !== dir) dir = dirname11(dir);
29870
+ while (!existsSync17(dir) && dirname11(dir) !== dir) dir = dirname11(dir);
29756
29871
  if (dir !== abs && isInside(root, dir)) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
29757
29872
  return new CtxError("OUTSIDE_ROOT", { p: given, root });
29758
29873
  }
@@ -30303,11 +30418,11 @@ var ctxStats = Object.freeze({
30303
30418
  });
30304
30419
 
30305
30420
  // src/core/tools/upgrade.ts
30306
- import { existsSync as existsSync22, realpathSync as realpathSync10, rmSync as rmSync10 } from "node:fs";
30421
+ import { existsSync as existsSync23, realpathSync as realpathSync11, rmSync as rmSync10 } from "node:fs";
30307
30422
  import { basename as basename7, dirname as dirname13, join as join26 } from "node:path";
30308
30423
 
30309
30424
  // src/core/ops/host-write.ts
30310
- import { copyFileSync, existsSync as existsSync17, mkdirSync as mkdirSync7, writeFileSync as writeFileSync5 } from "node:fs";
30425
+ import { copyFileSync, existsSync as existsSync18, mkdirSync as mkdirSync7, writeFileSync as writeFileSync5 } from "node:fs";
30311
30426
  import { dirname as dirname12, join as join21 } from "node:path";
30312
30427
  function defaultWrite(file2, text) {
30313
30428
  writeFileSync5(file2, text, "utf8");
@@ -30336,7 +30451,7 @@ function toRow(file2, edit) {
30336
30451
  function writeWithRollback(file2, text, write2, atomic) {
30337
30452
  const trash = file2 + UPGRADE_TRASH_SUFFIX;
30338
30453
  const tmp = `${file2}${HOST_CONFIG_TMP_SUFFIX}.${process.pid}`;
30339
- const had = existsSync17(file2);
30454
+ const had = existsSync18(file2);
30340
30455
  mkdirSync7(dirname12(file2), { recursive: true });
30341
30456
  if (had) copyFileSync(file2, trash);
30342
30457
  try {
@@ -30366,7 +30481,7 @@ function regenerateHostConfig(row5, home, opts = {}) {
30366
30481
  if (requested === null) return [];
30367
30482
  const current = readHostConfig(row5.id, requested);
30368
30483
  const result = mergeOwnEntries(row5.id, current.text, current.format, row5);
30369
- const exists = existsSync17(current.path);
30484
+ const exists = existsSync18(current.path);
30370
30485
  if (exists && result.text === current.text) return [];
30371
30486
  const text = result.text === "" && current.format !== "toml" ? JSON.stringify({}) : result.text;
30372
30487
  writeWithRollback(current.path, current.layout === void 0 ? text : withLayout(text, current.layout), opts.write ?? defaultWrite, opts.atomic ?? {});
@@ -30374,15 +30489,15 @@ function regenerateHostConfig(row5, home, opts = {}) {
30374
30489
  }
30375
30490
 
30376
30491
  // src/core/ops/plugin-swap.ts
30377
- import { existsSync as existsSync18, lstatSync, readdirSync as readdirSync8, readlinkSync, rmSync as rmSync6, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
30492
+ import { existsSync as existsSync19, lstatSync, readdirSync as readdirSync8, readlinkSync, rmSync as rmSync6, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
30378
30493
  import { basename as basename6, join as join22, win32 as win322 } from "node:path";
30379
- function linkTarget(path7, win) {
30380
- if (!isLink(path7)) return null;
30381
- const target = readlinkSync(path7);
30494
+ function linkTarget(path8, win) {
30495
+ if (!isLink(path8)) return null;
30496
+ const target = readlinkSync(path8);
30382
30497
  return win ? win322.basename(target) : target;
30383
30498
  }
30384
- function isLink(path7) {
30385
- return lstatSync(path7, { throwIfNoEntry: false })?.isSymbolicLink() === true;
30499
+ function isLink(path8) {
30500
+ return lstatSync(path8, { throwIfNoEntry: false })?.isSymbolicLink() === true;
30386
30501
  }
30387
30502
  function generations(agentDir) {
30388
30503
  return readdirSync8(agentDir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name).filter((name) => !name.startsWith(UPGRADE_FETCH_DIR_PREFIX) && !name.endsWith(UPGRADE_TRASH_SUFFIX)).sort();
@@ -30395,7 +30510,7 @@ function settleLinks(link, tmp, old, opts) {
30395
30510
  }
30396
30511
  function swapPluginCurrent(agentDir, sha, opts = {}) {
30397
30512
  const next = join22(agentDir, sha);
30398
- if (!existsSync18(next) || !lstatSync(next).isDirectory()) {
30513
+ if (!existsSync19(next) || !lstatSync(next).isDirectory()) {
30399
30514
  throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename6(agentDir), path: next });
30400
30515
  }
30401
30516
  const link = join22(agentDir, PLUGIN_CURRENT_LINK);
@@ -30415,12 +30530,12 @@ function swapPluginCurrent(agentDir, sha, opts = {}) {
30415
30530
  if (before !== null) keep.add(before);
30416
30531
  const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join22(agentDir, name));
30417
30532
  for (const dir of removed) rmSync6(dir, { recursive: true, force: true });
30418
- const previous = before !== null && existsSync18(join22(agentDir, before)) ? join22(agentDir, before) : null;
30533
+ const previous = before !== null && existsSync19(join22(agentDir, before)) ? join22(agentDir, before) : null;
30419
30534
  return { current: next, previous, removed };
30420
30535
  }
30421
30536
 
30422
30537
  // src/core/ops/release-fetch.ts
30423
- import { existsSync as existsSync19, mkdirSync as mkdirSync8, rmSync as rmSync7 } from "node:fs";
30538
+ import { existsSync as existsSync20, mkdirSync as mkdirSync8, rmSync as rmSync7 } from "node:fs";
30424
30539
  import { join as join23 } from "node:path";
30425
30540
  function failed(r) {
30426
30541
  if (r.exitCode === null && r.killed === null) return new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
@@ -30444,7 +30559,7 @@ async function fetchRelease(agent, url4, env, signal, opts = {}) {
30444
30559
  await git2(gitBin, [...GIT_CLONE_ARGS, RELEASE_BRANCH, url4, fetchDir], agentDir, childEnv, signal);
30445
30560
  const sha = await git2(gitBin, GIT_HEAD_SHA_ARGS, fetchDir, childEnv, signal);
30446
30561
  const dir = join23(agentDir, sha);
30447
- if (existsSync19(dir)) rmSync7(fetchDir, { recursive: true, force: true });
30562
+ if (existsSync20(dir)) rmSync7(fetchDir, { recursive: true, force: true });
30448
30563
  else renameWithRetry(fetchDir, dir, opts);
30449
30564
  return { sha, dir };
30450
30565
  } catch (e) {
@@ -30454,7 +30569,7 @@ async function fetchRelease(agent, url4, env, signal, opts = {}) {
30454
30569
  }
30455
30570
 
30456
30571
  // src/core/ops/uninstall.ts
30457
- import { existsSync as existsSync20, readdirSync as readdirSync9, rmSync as rmSync8, writeFileSync as writeFileSync6 } from "node:fs";
30572
+ import { existsSync as existsSync21, readdirSync as readdirSync9, rmSync as rmSync8, writeFileSync as writeFileSync6 } from "node:fs";
30458
30573
  import { join as join24 } from "node:path";
30459
30574
  function row2(area, before, after) {
30460
30575
  return { area, before, after };
@@ -30488,7 +30603,7 @@ function removeCache(adapter, env, configDir) {
30488
30603
  }
30489
30604
  case "plugin": {
30490
30605
  const agentDir = join24(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
30491
- if (!existsSync20(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
30606
+ if (!existsSync21(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
30492
30607
  rmSync8(agentDir, { recursive: true, force: true });
30493
30608
  return row2(UPGRADE_CACHE_AREA, agentDir, UPGRADE_REMOVED);
30494
30609
  }
@@ -30507,7 +30622,7 @@ function isObj3(v) {
30507
30622
  function piSource(entry) {
30508
30623
  return isObj3(entry) ? entry[PI_PACKAGE_SOURCE_KEY] : entry;
30509
30624
  }
30510
- function ownEntries(agent, env) {
30625
+ function ownEntries2(agent, env) {
30511
30626
  const home = requireHomeDir(env);
30512
30627
  const mcp = OWN_MCP_ENTRY[agent];
30513
30628
  if (mcp !== void 0) {
@@ -30515,10 +30630,10 @@ function ownEntries(agent, env) {
30515
30630
  const inner = mcp.key.slice(1, -1);
30516
30631
  const own4 = mcp.key[mcp.key.length - 1];
30517
30632
  const holder = (v) => inner.reduce((cur, k) => isObj3(cur) ? cur[k] : void 0, v);
30518
- const without = (v, path7) => {
30633
+ const without = (v, path8) => {
30519
30634
  const o = v;
30520
- if (path7.length === 0) return Object.fromEntries(Object.entries(o).filter(([k]) => k !== own4));
30521
- return { ...o, [path7[0]]: without(o[path7[0]], path7.slice(1)) };
30635
+ if (path8.length === 0) return Object.fromEntries(Object.entries(o).filter(([k]) => k !== own4));
30636
+ return { ...o, [path8[0]]: without(o[path8[0]], path8.slice(1)) };
30522
30637
  };
30523
30638
  return [{
30524
30639
  file: ownMcpFileOf(agent, mcp.file, env, home),
@@ -30555,7 +30670,7 @@ function ownEntries(agent, env) {
30555
30670
  }
30556
30671
  function removeOwnEntries(agent, env) {
30557
30672
  const rows = [];
30558
- for (const entry of ownEntries(agent, env)) {
30673
+ for (const entry of ownEntries2(agent, env)) {
30559
30674
  const current = readHostConfig(agent, entry.file);
30560
30675
  if (current.text === "") continue;
30561
30676
  const value = hostConfigValueAt(parseHostConfig(agent, current.path, current.text, current.format), [entry.key]);
@@ -30568,7 +30683,7 @@ function removeOwnEntries(agent, env) {
30568
30683
  function removeProjectData(configDir, projectKey) {
30569
30684
  const projects = join24(configDir, PROJECTS_DIR_NAME);
30570
30685
  const dir = join24(projects, projectKey);
30571
- if (!existsSync20(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
30686
+ if (!existsSync21(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
30572
30687
  if (dir === projects || !isInside(projects, dir)) throw new CtxError("OUTSIDE_ROOT", { p: dir, root: projects });
30573
30688
  for (const name of readdirSync9(dir)) {
30574
30689
  if (name !== OWNERS_DIR_NAME) rmSync8(join24(dir, name), { recursive: true, force: true });
@@ -30584,7 +30699,7 @@ function runUninstall(input) {
30584
30699
  }
30585
30700
 
30586
30701
  // src/core/ops/v1-remove.ts
30587
- import { copyFileSync as copyFileSync2, existsSync as existsSync21, readFileSync as readFileSync16, rmSync as rmSync9 } from "node:fs";
30702
+ import { copyFileSync as copyFileSync2, existsSync as existsSync22, readFileSync as readFileSync17, rmSync as rmSync9 } from "node:fs";
30588
30703
  var isObj4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
30589
30704
  var areaOf = (f) => f.path === "" ? f.file : f.file + UPGRADE_AREA_KEY_SEP + f.path;
30590
30705
  var row3 = (f, after) => ({ area: areaOf(f), before: f.reason, after });
@@ -30614,8 +30729,8 @@ function cutTomlTable(text, header) {
30614
30729
  function writeAtomic(file2, text) {
30615
30730
  atomicWriteFile(file2, text);
30616
30731
  }
30617
- function locate(doc, path7) {
30618
- const segs = path7.split(V1_KEY_PATH_SEP);
30732
+ function locate(doc, path8) {
30733
+ const segs = path8.split(V1_KEY_PATH_SEP);
30619
30734
  let cur = doc;
30620
30735
  for (const seg of segs.slice(0, -1)) {
30621
30736
  if (Array.isArray(cur)) cur = cur[Number(seg)];
@@ -30628,8 +30743,8 @@ function locate(doc, path7) {
30628
30743
  return null;
30629
30744
  }
30630
30745
  function stripJsonEntries(agent, file2, findings, kept, undo) {
30631
- const layout = hostLayout(readFileSync16(file2, "utf8"));
30632
- const text = hostText(readFileSync16(file2, "utf8"));
30746
+ const layout = hostLayout(readFileSync17(file2, "utf8"));
30747
+ const text = hostText(readFileSync17(file2, "utf8"));
30633
30748
  const doc = parseHostConfig(agent, file2, text, "jsonc");
30634
30749
  const hit = /* @__PURE__ */ new Set();
30635
30750
  const byContainer = /* @__PURE__ */ new Map();
@@ -30665,19 +30780,19 @@ function removeV1(agent, findings) {
30665
30780
  for (const f of findings) {
30666
30781
  if (UPGRADE_REPORT_ONLY_REASONS.includes(f.reason)) done.set(f, UPGRADE_REPORT_ONLY);
30667
30782
  else if (f.path === "") {
30668
- if (existsSync21(f.file)) {
30783
+ if (existsSync22(f.file)) {
30669
30784
  moveAside(f.file, undo);
30670
30785
  done.set(f, UPGRADE_REMOVED);
30671
30786
  } else done.set(f, UPGRADE_NOT_FOUND);
30672
30787
  } else entries.set(f.file, [...entries.get(f.file) ?? [], f]);
30673
30788
  }
30674
30789
  for (const [file2, list4] of entries) {
30675
- if (!existsSync21(file2)) {
30790
+ if (!existsSync22(file2)) {
30676
30791
  for (const f of list4) done.set(f, UPGRADE_NOT_FOUND);
30677
30792
  continue;
30678
30793
  }
30679
30794
  if (file2.endsWith(TOML_EXT)) {
30680
- const rawToml = readFileSync16(file2, "utf8");
30795
+ const rawToml = readFileSync17(file2, "utf8");
30681
30796
  const tomlLayout = hostLayout(rawToml);
30682
30797
  let text = hostText(rawToml);
30683
30798
  for (const f of list4) {
@@ -30705,7 +30820,7 @@ function removeV1(agent, findings) {
30705
30820
  },
30706
30821
  rollback() {
30707
30822
  for (const u of undo.splice(0).reverse()) {
30708
- if (!existsSync21(u.trash)) continue;
30823
+ if (!existsSync22(u.trash)) continue;
30709
30824
  rmSync9(u.target, { recursive: true, force: true });
30710
30825
  renameWithRetry(u.trash, u.target);
30711
30826
  }
@@ -30715,7 +30830,7 @@ function removeV1(agent, findings) {
30715
30830
 
30716
30831
  // src/core/ops/verify-sums.ts
30717
30832
  import { createHash as createHash2 } from "node:crypto";
30718
- import { lstatSync as lstatSync2, readdirSync as readdirSync10, readFileSync as readFileSync17 } from "node:fs";
30833
+ import { lstatSync as lstatSync2, readdirSync as readdirSync10, readFileSync as readFileSync18 } from "node:fs";
30719
30834
  import { join as join25 } from "node:path";
30720
30835
  function mismatch() {
30721
30836
  return new CtxError("BUNDLE_HASH_MISMATCH");
@@ -30747,14 +30862,14 @@ function verifySums(dir) {
30747
30862
  const sumsPath = join25(dir, RELEASE_SUMS_FILE);
30748
30863
  const sumsStat = lstatSync2(sumsPath, { throwIfNoEntry: false });
30749
30864
  if (sumsStat === void 0 || !sumsStat.isFile()) throw mismatch();
30750
- const sums = parseSums(readFileSync17(sumsPath, "utf8"));
30865
+ const sums = parseSums(readFileSync18(sumsPath, "utf8"));
30751
30866
  const files = /* @__PURE__ */ new Map();
30752
30867
  walk3(dir, "", files);
30753
30868
  if (files.size !== sums.size) throw mismatch();
30754
30869
  for (const [rel, abs] of files) {
30755
30870
  const want = sums.get(rel);
30756
30871
  if (want === void 0) throw mismatch();
30757
- const got = createHash2(SUMS_HASH_ALGORITHM).update(readFileSync17(abs)).digest(HASH_ENCODING);
30872
+ const got = createHash2(SUMS_HASH_ALGORITHM).update(readFileSync18(abs)).digest(HASH_ENCODING);
30758
30873
  if (got !== want) throw mismatch();
30759
30874
  }
30760
30875
  }
@@ -30783,7 +30898,7 @@ function pluginRootRow(adapter, env) {
30783
30898
  }
30784
30899
  function isCurrent(agentDir, dir) {
30785
30900
  const link = join26(agentDir, PLUGIN_CURRENT_LINK);
30786
- return existsSync22(link) && realpathSync10.native(link) === realpathSync10.native(dir);
30901
+ return existsSync23(link) && realpathSync11.native(link) === realpathSync11.native(dir);
30787
30902
  }
30788
30903
  async function checkout(adapter, deps) {
30789
30904
  const fetched = await fetchRelease(adapter.id, deps.releaseUrl, deps.env, deps.signal);
@@ -30903,7 +31018,7 @@ function checkCall(tool, input) {
30903
31018
 
30904
31019
  // src/entries/server.ts
30905
31020
  import { randomUUID } from "node:crypto";
30906
- import { existsSync as existsSync24, realpathSync as realpathSync12, rmSync as rmSync12 } from "node:fs";
31021
+ import { existsSync as existsSync25, realpathSync as realpathSync13, rmSync as rmSync12 } from "node:fs";
30907
31022
  import { dirname as dirname14, join as join28 } from "node:path";
30908
31023
  import { fileURLToPath as fileURLToPath3 } from "node:url";
30909
31024
 
@@ -31201,10 +31316,10 @@ function mergeDefs(...defs) {
31201
31316
  function cloneDef(schema) {
31202
31317
  return mergeDefs(schema._zod.def);
31203
31318
  }
31204
- function getElementAtPath2(obj, path7) {
31205
- if (!path7)
31319
+ function getElementAtPath2(obj, path8) {
31320
+ if (!path8)
31206
31321
  return obj;
31207
- return path7.reduce((acc, key) => acc?.[key], obj);
31322
+ return path8.reduce((acc, key) => acc?.[key], obj);
31208
31323
  }
31209
31324
  function promiseAllObject2(promisesObj) {
31210
31325
  const keys = Object.keys(promisesObj);
@@ -31544,11 +31659,11 @@ function explicitlyAborted(x, startIndex = 0) {
31544
31659
  }
31545
31660
  return false;
31546
31661
  }
31547
- function prefixIssues2(path7, issues) {
31662
+ function prefixIssues2(path8, issues) {
31548
31663
  return issues.map((iss) => {
31549
31664
  var _a5;
31550
31665
  (_a5 = iss).path ?? (_a5.path = []);
31551
- iss.path.unshift(path7);
31666
+ iss.path.unshift(path8);
31552
31667
  return iss;
31553
31668
  });
31554
31669
  }
@@ -32009,16 +32124,16 @@ function flattenError2(error42, mapper = (issue4) => issue4.message) {
32009
32124
  }
32010
32125
  function formatError3(error42, mapper = (issue4) => issue4.message) {
32011
32126
  const fieldErrors = { _errors: [] };
32012
- const processError = (error43, path7 = []) => {
32127
+ const processError = (error43, path8 = []) => {
32013
32128
  for (const issue4 of error43.issues) {
32014
32129
  if (issue4.code === "invalid_union" && issue4.errors.length) {
32015
- issue4.errors.map((issues) => processError({ issues }, [...path7, ...issue4.path]));
32130
+ issue4.errors.map((issues) => processError({ issues }, [...path8, ...issue4.path]));
32016
32131
  } else if (issue4.code === "invalid_key") {
32017
- processError({ issues: issue4.issues }, [...path7, ...issue4.path]);
32132
+ processError({ issues: issue4.issues }, [...path8, ...issue4.path]);
32018
32133
  } else if (issue4.code === "invalid_element") {
32019
- processError({ issues: issue4.issues }, [...path7, ...issue4.path]);
32134
+ processError({ issues: issue4.issues }, [...path8, ...issue4.path]);
32020
32135
  } else {
32021
- const fullpath = [...path7, ...issue4.path];
32136
+ const fullpath = [...path8, ...issue4.path];
32022
32137
  if (fullpath.length === 0) {
32023
32138
  fieldErrors._errors.push(mapper(issue4));
32024
32139
  } else {
@@ -38782,10 +38897,10 @@ function mergeDefs2(...defs) {
38782
38897
  function cloneDef2(schema) {
38783
38898
  return mergeDefs2(schema._zod.def);
38784
38899
  }
38785
- function getElementAtPath3(obj, path7) {
38786
- if (!path7)
38900
+ function getElementAtPath3(obj, path8) {
38901
+ if (!path8)
38787
38902
  return obj;
38788
- return path7.reduce((acc, key) => acc?.[key], obj);
38903
+ return path8.reduce((acc, key) => acc?.[key], obj);
38789
38904
  }
38790
38905
  function promiseAllObject3(promisesObj) {
38791
38906
  const keys = Object.keys(promisesObj);
@@ -39125,11 +39240,11 @@ function explicitlyAborted2(x, startIndex = 0) {
39125
39240
  }
39126
39241
  return false;
39127
39242
  }
39128
- function prefixIssues3(path7, issues) {
39243
+ function prefixIssues3(path8, issues) {
39129
39244
  return issues.map((iss) => {
39130
39245
  var _a5;
39131
39246
  (_a5 = iss).path ?? (_a5.path = []);
39132
- iss.path.unshift(path7);
39247
+ iss.path.unshift(path8);
39133
39248
  return iss;
39134
39249
  });
39135
39250
  }
@@ -39587,16 +39702,16 @@ function flattenError3(error42, mapper = (issue4) => issue4.message) {
39587
39702
  }
39588
39703
  function formatError4(error42, mapper = (issue4) => issue4.message) {
39589
39704
  const fieldErrors = { _errors: [] };
39590
- const processError = (error43, path7 = []) => {
39705
+ const processError = (error43, path8 = []) => {
39591
39706
  for (const issue4 of error43.issues) {
39592
39707
  if (issue4.code === "invalid_union" && issue4.errors.length) {
39593
- issue4.errors.map((issues) => processError({ issues }, [...path7, ...issue4.path]));
39708
+ issue4.errors.map((issues) => processError({ issues }, [...path8, ...issue4.path]));
39594
39709
  } else if (issue4.code === "invalid_key") {
39595
- processError({ issues: issue4.issues }, [...path7, ...issue4.path]);
39710
+ processError({ issues: issue4.issues }, [...path8, ...issue4.path]);
39596
39711
  } else if (issue4.code === "invalid_element") {
39597
- processError({ issues: issue4.issues }, [...path7, ...issue4.path]);
39712
+ processError({ issues: issue4.issues }, [...path8, ...issue4.path]);
39598
39713
  } else {
39599
- const fullpath = [...path7, ...issue4.path];
39714
+ const fullpath = [...path8, ...issue4.path];
39600
39715
  if (fullpath.length === 0) {
39601
39716
  fieldErrors._errors.push(mapper(issue4));
39602
39717
  } else {
@@ -47812,9 +47927,9 @@ var rev2026Codec = {
47812
47927
  });
47813
47928
  const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta3);
47814
47929
  if (!parsed.success) for (const issue4 of parsed.error.issues) {
47815
- const path7 = issue4.path.map(String);
47816
- const key = path7.length > 0 ? path7.join(".") : "_meta";
47817
- if (path7.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue;
47930
+ const path8 = issue4.path.map(String);
47931
+ const key = path8.length > 0 ? path8.join(".") : "_meta";
47932
+ if (path8.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue;
47818
47933
  issues.push({
47819
47934
  key,
47820
47935
  problem: issue4.message
@@ -48141,29 +48256,29 @@ var PERMITTED_X_MCP_HEADER_TYPES = /* @__PURE__ */ new Set([
48141
48256
  function scanXMcpHeaderDeclarations(inputSchema) {
48142
48257
  const declarations = [];
48143
48258
  const seenLower = /* @__PURE__ */ new Map();
48144
- const visit2 = (node3, path7, reachable) => {
48259
+ const visit2 = (node3, path8, reachable) => {
48145
48260
  if (node3 === null || typeof node3 !== "object") return void 0;
48146
48261
  const schema = node3;
48147
48262
  if (X_MCP_HEADER_KEY in schema) {
48148
- if (!reachable || path7.length === 0) return `${pathName(path7)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;
48263
+ if (!reachable || path8.length === 0) return `${pathName(path8)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`;
48149
48264
  const raw = schema[X_MCP_HEADER_KEY];
48150
- if (typeof raw !== "string" || raw.length === 0) return `${pathName(path7)}: x-mcp-header MUST be a non-empty string`;
48151
- if (!RFC9110_TOKEN.test(raw)) return `${pathName(path7)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;
48265
+ if (typeof raw !== "string" || raw.length === 0) return `${pathName(path8)}: x-mcp-header MUST be a non-empty string`;
48266
+ if (!RFC9110_TOKEN.test(raw)) return `${pathName(path8)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;
48152
48267
  const type = typeof schema.type === "string" ? schema.type : void 0;
48153
- if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path7)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? "<none>"}`;
48268
+ if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path8)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? "<none>"}`;
48154
48269
  const lower = raw.toLowerCase();
48155
48270
  const prior = seenLower.get(lower);
48156
48271
  if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`;
48157
48272
  seenLower.set(lower, raw);
48158
48273
  declarations.push({
48159
- path: path7,
48274
+ path: path8,
48160
48275
  headerName: raw,
48161
48276
  type
48162
48277
  });
48163
48278
  }
48164
48279
  const properties = schema.properties;
48165
48280
  if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) {
48166
- const fault$1 = visit2(child, [...path7, key], reachable);
48281
+ const fault$1 = visit2(child, [...path8, key], reachable);
48167
48282
  if (fault$1 !== void 0) return fault$1;
48168
48283
  }
48169
48284
  for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) {
@@ -48171,7 +48286,7 @@ function scanXMcpHeaderDeclarations(inputSchema) {
48171
48286
  if (sub === void 0) continue;
48172
48287
  const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub];
48173
48288
  for (const branch of branches) {
48174
- const fault$1 = visit2(branch, [...path7, `<${k}>`], false);
48289
+ const fault$1 = visit2(branch, [...path8, `<${k}>`], false);
48175
48290
  if (fault$1 !== void 0) return fault$1;
48176
48291
  }
48177
48292
  }
@@ -48211,8 +48326,8 @@ var OBJECT_VALUED_SUBSCHEMA_KEYWORDS = /* @__PURE__ */ new Set([
48211
48326
  "$defs",
48212
48327
  "definitions"
48213
48328
  ]);
48214
- function pathName(path7) {
48215
- return path7.length === 0 ? "<root>" : path7.join(".");
48329
+ function pathName(path8) {
48330
+ return path8.length === 0 ? "<root>" : path8.join(".");
48216
48331
  }
48217
48332
  var HEADER_MISMATCH_ERROR_CODE = -32020;
48218
48333
  var INBOUND_VALIDATION_LADDER = [
@@ -48501,7 +48616,7 @@ var PROPERTY_KEYS_BY_TYPE = {
48501
48616
  array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema])
48502
48617
  };
48503
48618
  var SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options);
48504
- function walkProperty(node3, path7, vendor, unsupported) {
48619
+ function walkProperty(node3, path8, vendor, unsupported) {
48505
48620
  if (!isJsonObject(node3)) return node3;
48506
48621
  const allowedKeys = typeof node3.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node3.type) ? PROPERTY_KEYS_BY_TYPE[node3.type] : void 0;
48507
48622
  if (allowedKeys === void 0) return node3;
@@ -48509,8 +48624,8 @@ function walkProperty(node3, path7, vendor, unsupported) {
48509
48624
  for (const [key, value] of Object.entries(node3)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value;
48510
48625
  else if (key === "pattern" && node3.type === "string" && typeof node3.format === "string") {
48511
48626
  if (!SUPPORTED_STRING_FORMATS.has(node3.format)) pruned[key] = value;
48512
- else if (typeof value !== "string" || !isLibraryFormatPattern(node3.format, value, vendor)) unsupported.push(`${path7}.${key}`);
48513
- } else unsupported.push(`${path7}.${key}`);
48627
+ else if (typeof value !== "string" || !isLibraryFormatPattern(node3.format, value, vendor)) unsupported.push(`${path8}.${key}`);
48628
+ } else unsupported.push(`${path8}.${key}`);
48514
48629
  return pruned;
48515
48630
  }
48516
48631
  function walkRequestedSchema(converted, vendor) {
@@ -48527,11 +48642,11 @@ function describeUnsupportedProperties(pruned, fallback) {
48527
48642
  const offenders = Object.entries(pruned.properties).filter(([, node3]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node3).success).map(([name]) => `properties.${name}`);
48528
48643
  return offenders.length > 0 ? offenders.join(", ") : fallback;
48529
48644
  }
48530
- function findDroppedConstraintPaths(original, parsed, path7 = "") {
48531
- if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path7}[${index}]`));
48645
+ function findDroppedConstraintPaths(original, parsed, path8 = "") {
48646
+ if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path8}[${index}]`));
48532
48647
  if (!isJsonObject(original) || !isJsonObject(parsed)) return [];
48533
48648
  return Object.entries(original).flatMap(([key, value]) => {
48534
- const childPath = path7 ? `${path7}.${key}` : key;
48649
+ const childPath = path8 ? `${path8}.${key}` : key;
48535
48650
  if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath];
48536
48651
  return findDroppedConstraintPaths(value, parsed[key], childPath);
48537
48652
  });
@@ -52619,8 +52734,8 @@ var require_utils = /* @__PURE__ */ __commonJSMin((exports, module) => {
52619
52734
  for (let i = 0; i < str4.length; i++) if (str4[i] === token) ind++;
52620
52735
  return ind;
52621
52736
  }
52622
- function removeDotSegments(path7) {
52623
- let input = path7;
52737
+ function removeDotSegments(path8) {
52738
+ let input = path8;
52624
52739
  const output = [];
52625
52740
  let nextSlash = -1;
52626
52741
  let len = 0;
@@ -52773,8 +52888,8 @@ var require_schemes = /* @__PURE__ */ __commonJSMin((exports, module) => {
52773
52888
  wsComponent.secure = void 0;
52774
52889
  }
52775
52890
  if (wsComponent.resourceName) {
52776
- const [path7, query] = wsComponent.resourceName.split("?");
52777
- wsComponent.path = path7 && path7 !== "/" ? path7 : void 0;
52891
+ const [path8, query] = wsComponent.resourceName.split("?");
52892
+ wsComponent.path = path8 && path8 !== "/" ? path8 : void 0;
52778
52893
  wsComponent.query = query;
52779
52894
  wsComponent.resourceName = void 0;
52780
52895
  }
@@ -58969,7 +59084,7 @@ function installExitGuard(opts) {
58969
59084
  }
58970
59085
 
58971
59086
  // src/core/store/cleanup.ts
58972
- import { existsSync as existsSync23, readdirSync as readdirSync11, rmSync as rmSync11 } from "node:fs";
59087
+ import { existsSync as existsSync24, readdirSync as readdirSync11, rmSync as rmSync11 } from "node:fs";
58973
59088
  import { join as join27 } from "node:path";
58974
59089
  function deleteSource(raw, id) {
58975
59090
  raw.prepare("DELETE FROM sources WHERE id = ?").run(id);
@@ -59005,7 +59120,7 @@ function userVersion(raw) {
59005
59120
  return raw.prepare("PRAGMA user_version").get().user_version;
59006
59121
  }
59007
59122
  function openForSweep(dbPath, projectKey) {
59008
- if (!existsSync23(dbPath) && (existsSync23(dbPath + DB_WAL_SUFFIX) || existsSync23(dbPath + DB_SHM_SUFFIX))) {
59123
+ if (!existsSync24(dbPath) && (existsSync24(dbPath + DB_WAL_SUFFIX) || existsSync24(dbPath + DB_SHM_SUFFIX))) {
59009
59124
  throw new CtxError("DB_GONE");
59010
59125
  }
59011
59126
  const sqlite = process.getBuiltinModule("node:sqlite");
@@ -59059,12 +59174,12 @@ function sweepDeadProjects(configDir) {
59059
59174
  }
59060
59175
 
59061
59176
  // src/entries/is-entry.ts
59062
- import { realpathSync as realpathSync11 } from "node:fs";
59177
+ import { realpathSync as realpathSync12 } from "node:fs";
59063
59178
  function isEntry(main, argv1, self) {
59064
59179
  if (main !== void 0) return main;
59065
59180
  if (argv1 === void 0 || argv1 === "") return false;
59066
59181
  try {
59067
- return realpathSync11(argv1) === realpathSync11(self);
59182
+ return realpathSync12(argv1) === realpathSync12(self);
59068
59183
  } catch {
59069
59184
  return false;
59070
59185
  }
@@ -59140,7 +59255,7 @@ function workspaceFromMeta(meta3) {
59140
59255
  }
59141
59256
  function realOrSame(p) {
59142
59257
  try {
59143
- return realpathSync12.native(p);
59258
+ return realpathSync13.native(p);
59144
59259
  } catch {
59145
59260
  return p;
59146
59261
  }
@@ -59188,7 +59303,7 @@ async function startServer(argv, env) {
59188
59303
  opening.catch(() => pending.delete(project.dbPath));
59189
59304
  }
59190
59305
  const db = await opening;
59191
- if (!existsSync24(db.path)) throw new CtxError("DB_GONE");
59306
+ if (!existsSync25(db.path)) throw new CtxError("DB_GONE");
59192
59307
  return db;
59193
59308
  }
59194
59309
  function stopMarker(configDir, projectKey) {
@@ -59196,7 +59311,7 @@ async function startServer(argv, env) {
59196
59311
  }
59197
59312
  function stopRequested() {
59198
59313
  const configDir = resolveConfigDir(process.env);
59199
- return held.some((db) => existsSync24(stopMarker(configDir, db.projectKey)));
59314
+ return held.some((db) => existsSync25(stopMarker(configDir, db.projectKey)));
59200
59315
  }
59201
59316
  async function journal(project, ctx, name, reply4) {
59202
59317
  const db = await ownDb(project);
@@ -59358,7 +59473,9 @@ function piExtension(pi) {
59358
59473
  turn,
59359
59474
  // #1182: Pi's abort signal reaches the handler, which kills the process tree and replies "Cancelled.".
59360
59475
  signal: signal ?? new AbortController().signal,
59361
- protocolVersion: ""
59476
+ protocolVersion: "",
59477
+ piCwd: cwd === "" ? void 0 : cwd
59478
+ // D-R38-PI-D7-1 (#1312): ctx_doctor D7 compares against Pi's live ctx.cwd
59362
59479
  };
59363
59480
  let reply4;
59364
59481
  try {