context-mode 2.0.0-next.23 → 2.0.0-next.25

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, path5) {
661
- if (!path5)
660
+ function getElementAtPath(obj, path7) {
661
+ if (!path7)
662
662
  return obj;
663
- return path5.reduce((acc, key) => acc?.[key], obj);
663
+ return path7.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(path5, issues) {
983
+ function prefixIssues(path7, issues) {
984
984
  return issues.map((iss) => {
985
985
  var _a5;
986
986
  (_a5 = iss).path ?? (_a5.path = []);
987
- iss.path.unshift(path5);
987
+ iss.path.unshift(path7);
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, path5 = []) => {
1124
+ const processError = (error43, path7 = []) => {
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 = [...path5, ...issue4.path];
1134
+ const fullpath = [...path7, ...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(path5) {
1164
+ function toDotPath(path7) {
1165
1165
  const segs = [];
1166
- for (const seg of path5) {
1166
+ for (const seg of path7) {
1167
1167
  if (typeof seg === "number")
1168
1168
  segs.push(`[${seg}]`);
1169
1169
  else if (typeof seg === "symbol")
@@ -11154,6 +11154,7 @@ function prefixToolNames(text, prefix) {
11154
11154
  return out;
11155
11155
  }
11156
11156
  var OUTPUT_CAP = 16384;
11157
+ var EXEC_PREVIEW_BYTES = 4096;
11157
11158
  var STATE_BUDGET = 2048;
11158
11159
  var RESUME_CAP = 2048;
11159
11160
  var REPORT_CAP = 4096;
@@ -11331,7 +11332,7 @@ var TOOLS_TTL_MS = 36e5;
11331
11332
  var IN_PROCESS_TIMEOUT_MS = 0;
11332
11333
  var MS_PER_DAY = 864e5;
11333
11334
  var PROJECT_KEY_HEX_LEN = 16;
11334
- var SCHEMA_VERSION = 5;
11335
+ var SCHEMA_VERSION = 6;
11335
11336
  var RETENTION_IDLE_DAYS = 30;
11336
11337
  var RETENTION_SIZE_CAP_BYTES = 524288e3;
11337
11338
  var PROJECT_DEAD_IDLE_DAYS = 14;
@@ -11365,6 +11366,13 @@ var HOST_PLUGINS_DIR_NAME = "plugins";
11365
11366
  var INSTALLED_PLUGINS_FILE = "installed_plugins.json";
11366
11367
  var PLUGIN_AGENT_SEPARATOR = ":";
11367
11368
  var PLUGIN_KEY_SEPARATOR = "@";
11369
+ var CLAUDE_PLUGIN_ROOT_ENV = "CLAUDE_PLUGIN_ROOT";
11370
+ var CLAUDE_PROJECT_DIR_ENV = "CLAUDE_PROJECT_DIR";
11371
+ var ENABLED_PLUGINS_KEY = "enabledPlugins";
11372
+ var SETTINGS_LOCAL_FILE = "settings.local.json";
11373
+ var DEFAULT_PLUGIN_SCOPE = "user";
11374
+ var PROJECT_PLUGIN_SCOPES = Object.freeze(["local", "project"]);
11375
+ var PLUGIN_SCOPE_RANK = Object.freeze({ local: 0, project: 1, user: 2, managed: 2 });
11368
11376
  var FRONTMATTER_FENCE = "---";
11369
11377
  var FRONTMATTER_TOOLS_KEY = "tools";
11370
11378
  var FRONTMATTER_DISALLOWED_KEY = "disallowedTools";
@@ -11508,7 +11516,7 @@ var DECISION_OPTION_KEY = "option";
11508
11516
  var DECISION_LABEL_JOIN = " | ";
11509
11517
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
11510
11518
  var RELEASE_BRANCH = "release";
11511
- var BUNDLE_SHA = true ? "68e0af5aafeaa4c61af68ee8d8e347cddb887f81" : void 0;
11519
+ var BUNDLE_SHA = true ? "58d6b744f8c640e9f43f03516d8bc50dc1292ae0" : void 0;
11512
11520
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
11513
11521
  var DOCTOR_LABEL = Object.freeze({
11514
11522
  D1: "version",
@@ -11665,6 +11673,13 @@ var D3_PART_JOIN = ", ";
11665
11673
  function D3_DETAIL(parts) {
11666
11674
  return `wrong: ${parts.join(D3_PART_JOIN)}`;
11667
11675
  }
11676
+ function D3_ROOT_DETAIL(paths) {
11677
+ return `pick one install for this project: ${paths.join(D3_PART_JOIN)}`;
11678
+ }
11679
+ var D3_ROOT_FIX_JOIN = " or ";
11680
+ function D3_ROOT_FIX(installs) {
11681
+ return `remove the extra install: ${installs.map((i) => `claude plugin uninstall ${i.key} --scope ${i.scope}`).join(D3_ROOT_FIX_JOIN)}`;
11682
+ }
11668
11683
  var HOOK_HOST_FILE = Object.freeze({
11669
11684
  "claude-code": { root: "plugin", file: ["hooks", "claude-code.json"], key: ["hooks"], shape: "nested", timeoutKey: "timeout", matcher: true },
11670
11685
  codex: { root: "home", file: [".codex", "hooks.json"], key: ["hooks"], shape: "nested", timeoutKey: "timeout", matcher: true },
@@ -11993,7 +12008,7 @@ var CtxError = class extends Error {
11993
12008
  };
11994
12009
 
11995
12010
  // src/core/hooks/dispatch.ts
11996
- import { dirname as dirname3, join as join6 } from "node:path";
12011
+ import { dirname as dirname4, join as join6 } from "node:path";
11997
12012
 
11998
12013
  // src/core/contracts/agents.ts
11999
12014
  var AGENT_IDS = ["claude-code", "codex", "gemini", "qwen", "copilot-cli", "vscode", "kiro", "zcode", "pi", "opencode"];
@@ -12835,7 +12850,7 @@ function getAdapter(id) {
12835
12850
  }
12836
12851
 
12837
12852
  // src/core/policy/decide.ts
12838
- import { resolve as resolve2 } from "node:path";
12853
+ import { resolve as resolve3 } from "node:path";
12839
12854
 
12840
12855
  // src/core/policy/lexer.ts
12841
12856
  var OPS = ["&&", "||", ";;", "|&", ";", "|", "&", "(", ")"];
@@ -14140,7 +14155,7 @@ function withLayout(text, layout) {
14140
14155
  }
14141
14156
 
14142
14157
  // src/core/project/config-dir.ts
14143
- import { join, posix, win32 } from "node:path";
14158
+ import { basename, dirname, join, posix, resolve as resolve2, win32 } from "node:path";
14144
14159
  var { mkdirSync, realpathSync } = process.getBuiltinModule("node:fs");
14145
14160
  function homeDirOf(env, platform = process.platform) {
14146
14161
  const set3 = (v) => v !== void 0 && v !== "";
@@ -14156,6 +14171,20 @@ function codexDirOf(env, home) {
14156
14171
  const dir = env[CODEX_HOME_ENV];
14157
14172
  return dir !== void 0 && dir !== "" ? dir : join(home, ...AGENT_HOME_DIR.codex);
14158
14173
  }
14174
+ function codexPluginHomeOf(bundleDir2) {
14175
+ let dir = resolve2(bundleDir2);
14176
+ while (dirname(dir) !== dir) {
14177
+ const up = dirname(dir);
14178
+ if (basename(dir) === PLUGIN_CACHE_DIR_NAME && basename(up) === HOST_PLUGINS_DIR_NAME) return dirname(up);
14179
+ dir = up;
14180
+ }
14181
+ return null;
14182
+ }
14183
+ function codexRunDirOf(env, home, bundleDir2) {
14184
+ const dir = env[CODEX_HOME_ENV];
14185
+ if (dir !== void 0 && dir !== "") return dir;
14186
+ return codexPluginHomeOf(bundleDir2) ?? codexDirOf(env, home);
14187
+ }
14159
14188
  function copilotDirOf(env, home) {
14160
14189
  const dir = env[COPILOT_HOME_ENV];
14161
14190
  return dir !== void 0 && dir !== "" ? dir : join(home, ...AGENT_HOME_DIR["copilot-cli"]);
@@ -14291,10 +14320,10 @@ function readPluginAgent(claudeDir, type) {
14291
14320
  }
14292
14321
  return null;
14293
14322
  }
14294
- function readAgentFile(path5) {
14323
+ function readAgentFile(path7) {
14295
14324
  let text;
14296
14325
  try {
14297
- text = readFileSync(path5, "utf8");
14326
+ text = readFileSync(path7, "utf8");
14298
14327
  } catch {
14299
14328
  return null;
14300
14329
  }
@@ -14557,12 +14586,12 @@ function readUserDeny(projectDir, agent) {
14557
14586
  }
14558
14587
  return out;
14559
14588
  }
14560
- function tokenize(glob, path5) {
14589
+ function tokenize(glob, path7) {
14561
14590
  const toks = [];
14562
14591
  let i = 0;
14563
14592
  while (i < glob.length) {
14564
14593
  const c = glob[i];
14565
- if (c === "*" && path5 && glob[i + 1] === "*") {
14594
+ if (c === "*" && path7 && glob[i + 1] === "*") {
14566
14595
  const dir = glob[i + "**".length] === "/";
14567
14596
  toks.push({ t: dir ? "globstarDir" : "globstar" });
14568
14597
  i += dir ? "**/".length : "**".length;
@@ -14576,8 +14605,8 @@ function tokenize(glob, path5) {
14576
14605
  }
14577
14606
  return toks;
14578
14607
  }
14579
- function globMatch(glob, text, path5) {
14580
- const toks = tokenize(glob, path5);
14608
+ function globMatch(glob, text, path7) {
14609
+ const toks = tokenize(glob, path7);
14581
14610
  const n = text.length;
14582
14611
  let next = new Uint8Array(n + 1);
14583
14612
  next[n] = 1;
@@ -14593,10 +14622,10 @@ function globMatch(glob, text, path5) {
14593
14622
  cur[j] = has3 && ch === tok.c ? next[j + 1] : 0;
14594
14623
  break;
14595
14624
  case "any1":
14596
- cur[j] = has3 && !(path5 && ch === "/") ? next[j + 1] : 0;
14625
+ cur[j] = has3 && !(path7 && ch === "/") ? next[j + 1] : 0;
14597
14626
  break;
14598
14627
  case "star":
14599
- cur[j] = next[j] || (has3 && !(path5 && ch === "/") ? cur[j + 1] : 0);
14628
+ cur[j] = next[j] || (has3 && !(path7 && ch === "/") ? cur[j + 1] : 0);
14600
14629
  break;
14601
14630
  case "globstar":
14602
14631
  cur[j] = next[j] || (has3 ? cur[j + 1] : 0);
@@ -14676,8 +14705,8 @@ var READ_DENY_TEMPLATE = 'context-mode: {size}-byte file, over the one-read limi
14676
14705
  // src/core/policy/read-deny.ts
14677
14706
  var SIZE = "{size}";
14678
14707
  var PATH = "{path}";
14679
- function READ_DENY_MESSAGE(path5, size, prefix = "") {
14680
- return prefixToolNames(READ_DENY_TEMPLATE, prefix).split(SIZE).join(String(size)).split(PATH).join(path5);
14708
+ function READ_DENY_MESSAGE(path7, size, prefix = "") {
14709
+ return prefixToolNames(READ_DENY_TEMPLATE, prefix).split(SIZE).join(String(size)).split(PATH).join(path7);
14681
14710
  }
14682
14711
 
14683
14712
  // src/core/policy/decide.ts
@@ -14735,7 +14764,7 @@ function readPath(input) {
14735
14764
  }
14736
14765
  function userDenyHit(canonical, input, cwd, rules) {
14737
14766
  if (rules.length === 0) return null;
14738
- const readRule = (p) => matchesAnyDenyPattern(resolve2(cwd, p), rules, { tool: READ, projectDir: cwd });
14767
+ const readRule = (p) => matchesAnyDenyPattern(resolve3(cwd, p), rules, { tool: READ, projectDir: cwd });
14739
14768
  if (canonical === BASH) {
14740
14769
  const cmd = str(input.command);
14741
14770
  return cmd === void 0 ? null : matchesAnyDenyPattern(cmd, rules);
@@ -14846,7 +14875,7 @@ function read(ev, row5, input) {
14846
14875
  if (!present(input.offset) && !present(input.limit)) {
14847
14876
  const p = readPath(input);
14848
14877
  if (p !== void 0) {
14849
- const abs = resolve2(ev.cwd, p);
14878
+ const abs = resolve3(ev.cwd, p);
14850
14879
  const size = fileSize(abs);
14851
14880
  if (size > OUTPUT_CAP) return deny(READ_DENY_MESSAGE(abs, size, row5.toolNamePrefix));
14852
14881
  }
@@ -14859,7 +14888,7 @@ function shellDump(cmds, cwd, row5) {
14859
14888
  let verdict = null;
14860
14889
  for (const c of cmds) {
14861
14890
  const name = c.argv0.toLowerCase();
14862
- if (name === CD_COMMAND && c.args.length === 1 && c.insideConstruct === void 0) dir = resolve2(dir, c.args[0]);
14891
+ if (name === CD_COMMAND && c.args.length === 1 && c.insideConstruct === void 0) dir = resolve3(dir, c.args[0]);
14863
14892
  if (c.redirectsToFile || c.endsInBoundedSink || c.pipesOut === true || c.insideConstruct !== void 0) continue;
14864
14893
  if (!has(SHELL_DUMP_COMMANDS, name)) continue;
14865
14894
  const d = dumpTarget(name, c.args);
@@ -14868,7 +14897,7 @@ function shellDump(cmds, cwd, row5) {
14868
14897
  verdict = ALLOW;
14869
14898
  continue;
14870
14899
  }
14871
- const abs = resolve2(dir, d.file);
14900
+ const abs = resolve3(dir, d.file);
14872
14901
  const size = fileSize(abs);
14873
14902
  if (size > OUTPUT_CAP) return deny(READ_DENY_MESSAGE(abs, size, row5.toolNamePrefix));
14874
14903
  }
@@ -14939,10 +14968,10 @@ function dumpTarget(name, args) {
14939
14968
  }
14940
14969
 
14941
14970
  // src/core/project/resolve.ts
14942
- import { basename, dirname as dirname2, join as join4, resolve as resolve3 } from "node:path";
14971
+ import { basename as basename2, dirname as dirname3, join as join4, resolve as resolve4 } from "node:path";
14943
14972
 
14944
14973
  // src/core/project/contain.ts
14945
- import { dirname, sep as sep2 } from "node:path";
14974
+ import { dirname as dirname2, sep as sep2 } from "node:path";
14946
14975
  var { realpathSync: realpathSync2 } = process.getBuiltinModule("node:fs");
14947
14976
  function real(p) {
14948
14977
  try {
@@ -14979,7 +15008,7 @@ function commonRoot(paths) {
14979
15008
  n = i;
14980
15009
  }
14981
15010
  let q = first;
14982
- while (components(q).length > n && dirname(q) !== q) q = dirname(q);
15011
+ while (components(q).length > n && dirname2(q) !== q) q = dirname2(q);
14983
15012
  return q;
14984
15013
  }
14985
15014
 
@@ -15146,9 +15175,9 @@ function gitDirs(dir) {
15146
15175
  const gitDir = gitDirAt(join4(cur, GIT_DIR_NAME));
15147
15176
  if (gitDir !== null) {
15148
15177
  const common = firstLine(join4(gitDir, GIT_COMMONDIR_FILE));
15149
- return { commonDir: realpathSync3.native(common === null ? gitDir : resolve3(gitDir, common)), worktree: cur, start };
15178
+ return { commonDir: realpathSync3.native(common === null ? gitDir : resolve4(gitDir, common)), worktree: cur, start };
15150
15179
  }
15151
- const up = dirname2(cur);
15180
+ const up = dirname3(cur);
15152
15181
  if (up === cur) return { commonDir: null, start };
15153
15182
  cur = up;
15154
15183
  }
@@ -15161,7 +15190,7 @@ function gitDirAt(dotGit) {
15161
15190
  } else {
15162
15191
  const line = firstLine(dotGit);
15163
15192
  if (line === null || !line.startsWith(GITDIR_FILE_PREFIX)) return null;
15164
- gitDir = resolve3(dirname2(dotGit), line.slice(GITDIR_FILE_PREFIX.length));
15193
+ gitDir = resolve4(dirname3(dotGit), line.slice(GITDIR_FILE_PREFIX.length));
15165
15194
  }
15166
15195
  } catch {
15167
15196
  return null;
@@ -15180,15 +15209,15 @@ function firstLine(file2) {
15180
15209
  return line === "" ? null : line;
15181
15210
  }
15182
15211
  function git(dir, args) {
15183
- const { spawnSync } = process.getBuiltinModule("node:child_process");
15184
- const r = spawnSync("git", args, { cwd: dir, shell: false, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
15212
+ const { spawnSync: spawnSync3 } = process.getBuiltinModule("node:child_process");
15213
+ const r = spawnSync3("git", args, { cwd: dir, shell: false, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
15185
15214
  if (r.error !== void 0 || r.status !== 0) throw new CtxError("NO_GIT_DIR", { path: dir });
15186
15215
  return r.stdout.split("\n").filter((l) => l !== "");
15187
15216
  }
15188
15217
  function containmentRootOf(dir, commonDir) {
15189
- const repoDir = basename(commonDir) === GIT_DIR_NAME ? dirname2(commonDir) : commonDir;
15218
+ const repoDir = basename2(commonDir) === GIT_DIR_NAME ? dirname3(commonDir) : commonDir;
15190
15219
  const worktrees = git(dir, ["worktree", "list", "--porcelain"]).filter((l) => l.startsWith(GIT_WORKTREE_LINE_PREFIX)).map((l) => l.slice(GIT_WORKTREE_LINE_PREFIX.length));
15191
- return commonRoot([dirname2(repoDir), ...worktrees]);
15220
+ return commonRoot([dirname3(repoDir), ...worktrees]);
15192
15221
  }
15193
15222
  function resolveProject(agent, src) {
15194
15223
  const source = sourceOf(agent);
@@ -15322,12 +15351,16 @@ CREATE VIRTUAL TABLE line_units USING fts5(
15322
15351
  ${FTS_TOKENIZE}
15323
15352
  );
15324
15353
  `;
15354
+ var DDL_V6 = `
15355
+ UPDATE sources SET label = replace(label, char(92), '/') WHERE kind = 'path' AND instr(label, char(92)) > 0;
15356
+ `;
15325
15357
  var MIGRATIONS = [
15326
15358
  { version: 1, sql: DDL },
15327
15359
  { version: 2, sql: DDL_V2 },
15328
15360
  { version: 3, sql: DDL_V3 },
15329
15361
  { version: 4, sql: DDL_V4 },
15330
- { version: 5, sql: DDL_V5 }
15362
+ { version: 5, sql: DDL_V5 },
15363
+ { version: 6, sql: DDL_V6 }
15331
15364
  ];
15332
15365
  function applyMigrations(db, fromVersion) {
15333
15366
  if (fromVersion === SCHEMA_VERSION2) return;
@@ -15381,9 +15414,9 @@ function readUserVersion(raw) {
15381
15414
  const row5 = raw.prepare("PRAGMA user_version").get();
15382
15415
  return row5.user_version;
15383
15416
  }
15384
- function createAtomically(sqlite, path5) {
15417
+ function createAtomically(sqlite, path7) {
15385
15418
  const { randomUUID: randomUUID2 } = process.getBuiltinModule("node:crypto");
15386
- const tmp = path5 + "." + randomUUID2() + DB_TMP_SUFFIX;
15419
+ const tmp = path7 + "." + randomUUID2() + DB_TMP_SUFFIX;
15387
15420
  try {
15388
15421
  const raw = new sqlite.DatabaseSync(tmp, { timeout: DB_TIMEOUT_MS });
15389
15422
  try {
@@ -15392,7 +15425,7 @@ function createAtomically(sqlite, path5) {
15392
15425
  raw.close();
15393
15426
  }
15394
15427
  try {
15395
- linkSync(tmp, path5);
15428
+ linkSync(tmp, path7);
15396
15429
  } catch (err) {
15397
15430
  if (err.code !== "EEXIST") throw err;
15398
15431
  }
@@ -15400,11 +15433,11 @@ function createAtomically(sqlite, path5) {
15400
15433
  for (const suffix of ["", DB_WAL_SUFFIX, DB_SHM_SUFFIX]) rmSync(tmp + suffix, { force: true });
15401
15434
  }
15402
15435
  }
15403
- function openWritable(sqlite, path5) {
15436
+ function openWritable(sqlite, path7) {
15404
15437
  let raw = null;
15405
15438
  try {
15406
- if (!existsSync2(path5)) createAtomically(sqlite, path5);
15407
- raw = new sqlite.DatabaseSync(path5, { timeout: DB_TIMEOUT_MS });
15439
+ if (!existsSync2(path7)) createAtomically(sqlite, path7);
15440
+ raw = new sqlite.DatabaseSync(path7, { timeout: DB_TIMEOUT_MS });
15408
15441
  applyMigrations(raw, readUserVersion(raw));
15409
15442
  return raw;
15410
15443
  } catch (err) {
@@ -15412,8 +15445,8 @@ function openWritable(sqlite, path5) {
15412
15445
  throw err;
15413
15446
  }
15414
15447
  }
15415
- function openReadOnly(sqlite, path5) {
15416
- const raw = new sqlite.DatabaseSync(path5, { timeout: DB_TIMEOUT_MS, readOnly: true });
15448
+ function openReadOnly(sqlite, path7) {
15449
+ const raw = new sqlite.DatabaseSync(path7, { timeout: DB_TIMEOUT_MS, readOnly: true });
15417
15450
  try {
15418
15451
  const found = readUserVersion(raw);
15419
15452
  if (found !== SCHEMA_VERSION) throw new CtxError("SCHEMA_STALE", { found, want: SCHEMA_VERSION });
@@ -15427,20 +15460,20 @@ async function openDb(project, opts) {
15427
15460
  if (isBelow(process.version, NODE_MIN)) throw new CtxError("NODE_TOO_OLD", { v: process.version });
15428
15461
  const sqlite = await loadSqlite();
15429
15462
  mkdirSync2(project.projectDir, { recursive: true });
15430
- const path5 = project.dbPath;
15431
- const sibling = existsSync2(path5 + DB_WAL_SUFFIX) || existsSync2(path5 + DB_SHM_SUFFIX);
15432
- if (sibling && !existsSync2(path5)) {
15463
+ const path7 = project.dbPath;
15464
+ const sibling = existsSync2(path7 + DB_WAL_SUFFIX) || existsSync2(path7 + DB_SHM_SUFFIX);
15465
+ if (sibling && !existsSync2(path7)) {
15433
15466
  throw new CtxError("DB_GONE");
15434
15467
  }
15435
15468
  try {
15436
15469
  let raw;
15437
15470
  if (opts?.readOnly === true) {
15438
- if (!existsSync2(path5)) openWritable(sqlite, path5).close();
15439
- raw = openReadOnly(sqlite, path5);
15471
+ if (!existsSync2(path7)) openWritable(sqlite, path7).close();
15472
+ raw = openReadOnly(sqlite, path7);
15440
15473
  } else {
15441
- raw = openWritable(sqlite, path5);
15474
+ raw = openWritable(sqlite, path7);
15442
15475
  }
15443
- return { raw, projectKey: project.projectKey, path: path5, ...opts?.readOnly === true ? { readOnly: true } : {} };
15476
+ return { raw, projectKey: project.projectKey, path: path7, ...opts?.readOnly === true ? { readOnly: true } : {} };
15444
15477
  } catch (err) {
15445
15478
  if (isCorrupt(err)) throw new CtxError("DB_CORRUPT");
15446
15479
  throw err;
@@ -17864,7 +17897,7 @@ function ftsQuery(db, q, scope, ctx, sessionId, limit, offset, source) {
17864
17897
  }
17865
17898
  return page2.map((e) => {
17866
17899
  const r = rows.get(Number(e.r.rid));
17867
- return { sourceId: Number(r.source_id), label: r.label, ord: Number(r.ord), snippet: highlight(r.body, q, SNIPPET_MAX_BYTES), score: e.s };
17900
+ return { sourceId: Number(r.source_id), label: r.label, ord: Number(r.ord), snippet: highlight(r.body, q, SNIPPET_MAX_BYTES), score: e.s, full: e.full === 1 };
17868
17901
  });
17869
17902
  }
17870
17903
  var LIST = `
@@ -18033,17 +18066,29 @@ function parseSourceHandle(s) {
18033
18066
  }
18034
18067
  return n > 0 && sourceHandle(n) === s ? n : null;
18035
18068
  }
18069
+ function pathLabel(p) {
18070
+ return p.includes("\\") ? p.split("\\").join("/") : p;
18071
+ }
18072
+ function labelStored(db, label) {
18073
+ return stmt(db.raw, "SELECT 1 AS x FROM sources WHERE label = ? LIMIT 1").get(label) !== void 0;
18074
+ }
18075
+ function storedLabel(db, source) {
18076
+ if (labelStored(db, source)) return source;
18077
+ const canon = pathLabel(source);
18078
+ return canon !== source && labelStored(db, canon) ? canon : source;
18079
+ }
18036
18080
  function resolveSourceLabel(db, source) {
18037
18081
  const id = parseSourceHandle(source);
18038
18082
  if (id !== null) {
18039
18083
  const row5 = stmt(db.raw, "SELECT label FROM sources WHERE id = ?").get(id);
18040
18084
  if (row5 !== void 0) return row5.label;
18041
18085
  }
18042
- if (stmt(db.raw, "SELECT 1 AS x FROM sources WHERE label = ? LIMIT 1").get(source) !== void 0) return source;
18043
- const prefix = source + LABEL_SUFFIX_SEP;
18086
+ const named = storedLabel(db, source);
18087
+ if (labelStored(db, named)) return named;
18088
+ const prefix = named + LABEL_SUFFIX_SEP;
18044
18089
  const rows = stmt(db.raw, "SELECT label FROM sources WHERE substr(label, 1, ?) = ? ORDER BY id DESC").all(prefix.length, prefix);
18045
18090
  for (const r of rows) {
18046
- if (r.label.lastIndexOf(LABEL_SUFFIX_SEP) === source.length) return r.label;
18091
+ if (r.label.lastIndexOf(LABEL_SUFFIX_SEP) === named.length) return r.label;
18047
18092
  }
18048
18093
  return source;
18049
18094
  }
@@ -18149,8 +18194,8 @@ function buildCandidates(rows, sessionId) {
18149
18194
  edits.set(r.path, { row: r, count: (edits.get(r.path)?.count ?? 0) + 1 });
18150
18195
  }
18151
18196
  const changedFiles = [];
18152
- for (const [path5, e] of edits) {
18153
- const c = make("changed_files", e.row, "edited " + path5 + " x" + e.count, e.count, path5);
18197
+ for (const [path7, e] of edits) {
18198
+ const c = make("changed_files", e.row, "edited " + path7 + " x" + e.count, e.count, path7);
18154
18199
  changedFiles.push({ ...c, editCount: e.count });
18155
18200
  }
18156
18201
  changedFiles.sort((a, b) => a.seq - b.seq);
@@ -19102,7 +19147,7 @@ function shouldHint(db, sessionId, onceKey, everyN) {
19102
19147
  }
19103
19148
 
19104
19149
  // src/core/hooks/fallback.ts
19105
- import { join as join5, resolve as resolve4 } from "node:path";
19150
+ import { join as join5, resolve as resolve5 } from "node:path";
19106
19151
  var fs = process.getBuiltinModule("node:fs");
19107
19152
  function isRec(v) {
19108
19153
  return typeof v === "object" && v !== null && !Array.isArray(v);
@@ -19217,7 +19262,7 @@ function bigRead(input, cwd) {
19217
19262
  const p = firstString(input, READ_PATH_KEYS);
19218
19263
  if (p === "") return false;
19219
19264
  try {
19220
- const st = fs.statSync(resolve4(cwd, p));
19265
+ const st = fs.statSync(resolve5(cwd, p));
19221
19266
  return st.isFile() && st.size > OUTPUT_CAP;
19222
19267
  } catch {
19223
19268
  return false;
@@ -19288,20 +19333,24 @@ async function handleHook(agent, raw, env) {
19288
19333
  return fail7("project", err, "hooks: no project: " + String(err.code ?? "ERROR") + " " + message(err) + "\n");
19289
19334
  }
19290
19335
  let decision;
19336
+ const settle3 = {};
19291
19337
  try {
19292
19338
  fault(env, "policy");
19293
- decision = await dispatch(ev, row5, project, env);
19339
+ decision = await dispatch(ev, row5, project, env, settle3);
19294
19340
  } catch (err) {
19295
19341
  return fail7("store", err);
19296
19342
  }
19297
19343
  try {
19298
19344
  fault(env, "encode");
19299
- return row5.encode(ev, decision);
19345
+ const out = row5.encode(ev, decision);
19346
+ settle3.run?.(true);
19347
+ return out;
19300
19348
  } catch (err) {
19349
+ settle3.run?.(false);
19301
19350
  return fail7("encode", err);
19302
19351
  }
19303
19352
  }
19304
- function dispatch(ev, row5, project, env) {
19353
+ function dispatch(ev, row5, project, env, settle3) {
19305
19354
  switch (ev.event) {
19306
19355
  case "SessionStart":
19307
19356
  return sessionStart(ev, row5, project);
@@ -19310,7 +19359,7 @@ function dispatch(ev, row5, project, env) {
19310
19359
  case "PreToolUse":
19311
19360
  return preToolUse(ev, row5, project, env);
19312
19361
  case "PostToolUse":
19313
- return postToolUse(ev, row5, project, env);
19362
+ return postToolUse(ev, row5, project, env, settle3);
19314
19363
  case "PreCompact":
19315
19364
  return preCompact(ev, row5, project);
19316
19365
  case "Usage":
@@ -19500,7 +19549,7 @@ function caseB(ev, row5, d0, userDeny) {
19500
19549
  if (tool === void 0 || !isShell(tool, row5) || isUserPolicyDeny(d0.reason, row5)) return d0;
19501
19550
  const command = tool.input.command;
19502
19551
  if (typeof command !== "string") return d0;
19503
- const wrapper = '"' + join6(dirname3(process.argv[1] ?? ""), RUN_WRAPPER_FILE) + '"';
19552
+ const wrapper = '"' + join6(dirname4(process.argv[1] ?? ""), RUN_WRAPPER_FILE) + '"';
19504
19553
  const rewritten = [RUN_WRAPPER_NODE, wrapper, b64(command), b64(JSON.stringify(userDeny ?? [])), b64(str2(tool.input.description))].join(" ");
19505
19554
  return { kind: "deny", reason: SUBAGENT_RUN_DENY, rewritten };
19506
19555
  }
@@ -19537,7 +19586,7 @@ function pathOf(input) {
19537
19586
  for (const k of EDIT_PATH_KEYS) if (typeof input[k] === "string") return input[k];
19538
19587
  return null;
19539
19588
  }
19540
- async function postToolUse(ev, row5, project, env) {
19589
+ async function postToolUse(ev, row5, project, env, settle3) {
19541
19590
  const tool = ev.tool;
19542
19591
  if (tool === void 0 || tool.canonicalName.startsWith(OWN_TOOL_PREFIX)) return ALLOW2;
19543
19592
  const result = ev.result ?? { isError: false, bytes: 0 };
@@ -19545,7 +19594,8 @@ async function postToolUse(ev, row5, project, env) {
19545
19594
  if (result.persistedPath !== void 0) result.bytes = Buffer.byteLength(text);
19546
19595
  if (tool.canonicalName === DECISION_TOOL) askDetached(ev, project, tool, text);
19547
19596
  const kind = journalKind(tool, row5, result.isError);
19548
- if (kind !== null) {
19597
+ const journal = (returned) => {
19598
+ if (kind === null) return;
19549
19599
  const key = kind === "cmd" ? canonicalKey(tool.canonicalName, str2(tool.input.command)) : kind === "toolerr" ? tool.canonicalName + ":" + stableJson(tool.input) : null;
19550
19600
  appendDetached(project, ev.sessionId, {
19551
19601
  // step 4; body is the whole text (D-M3-H2-6)
@@ -19562,18 +19612,30 @@ async function postToolUse(ev, row5, project, env) {
19562
19612
  body: text,
19563
19613
  turn: ev.turn ?? 0,
19564
19614
  sandbox_bytes: result.bytes,
19565
- returned_bytes: result.bytes
19615
+ returned_bytes: returned
19566
19616
  });
19617
+ };
19618
+ let decision;
19619
+ try {
19620
+ decision = await postReplace(ev, row5, project, env, tool, result, text);
19621
+ } catch (err) {
19622
+ journal(result.bytes);
19623
+ throw err;
19567
19624
  }
19625
+ const decided = decision;
19626
+ settle3.run = (encoded) => journal(encoded && decided.kind === "replace" ? Buffer.byteLength(decided.output) : result.bytes);
19627
+ return decision;
19628
+ }
19629
+ async function postReplace(ev, row5, project, env, tool, result, text) {
19568
19630
  if (result.bytes <= REPLACE_TRIGGER_BYTES) return ALLOW2;
19569
19631
  if (result.keep === true) return ALLOW2;
19632
+ if (!hasReplace(row5)) return ALLOW2;
19570
19633
  let label;
19571
19634
  if (isSubagentCall(ev)) {
19572
19635
  const subCase = pickSubagentCase(ev, toolSetForAgentType(ev, { projectDir: project.worktree, env }));
19573
19636
  if (subCase === "A") return ALLOW2;
19574
19637
  label = SUBAGENT_SOURCE_PREFIX + tool.canonicalName + ":" + String(ev.turn ?? 0);
19575
19638
  } else {
19576
- if (!hasReplace(row5)) return ALLOW2;
19577
19639
  label = mainLabel(tool, ev);
19578
19640
  }
19579
19641
  const intent = [tool.input.description, tool.input.command, tool.input.file_path, tool.input.pattern, tool.input.url].map(str2).find((v) => v.trim() !== "") ?? "";
@@ -19830,10 +19892,10 @@ function startArgv(argv) {
19830
19892
  return sh === null ? null : [sh, ...argv];
19831
19893
  }
19832
19894
  function runProcess(argv, o) {
19833
- return new Promise((resolve7) => {
19895
+ return new Promise((resolve8) => {
19834
19896
  const isWin2 = process.platform === "win32";
19835
19897
  const start = startArgv(argv);
19836
- if (start === null) return resolve7(NOT_STARTED);
19898
+ if (start === null) return resolve8(NOT_STARTED);
19837
19899
  let child;
19838
19900
  try {
19839
19901
  child = spawn(start[0], start.slice(1), {
@@ -19847,7 +19909,7 @@ function runProcess(argv, o) {
19847
19909
  windowsHide: true
19848
19910
  });
19849
19911
  } catch {
19850
- return resolve7(NOT_STARTED);
19912
+ return resolve8(NOT_STARTED);
19851
19913
  }
19852
19914
  const stdoutChunks = [];
19853
19915
  const stderrChunks = [];
@@ -19872,7 +19934,7 @@ function runProcess(argv, o) {
19872
19934
  settled = true;
19873
19935
  clearTimeout(timer);
19874
19936
  o.signal.removeEventListener("abort", onAbort);
19875
- resolve7({
19937
+ resolve8({
19876
19938
  stdout: Buffer.concat(stdoutChunks),
19877
19939
  stderr: Buffer.concat(stderrChunks),
19878
19940
  exitCode,
@@ -19904,19 +19966,19 @@ function readAutoMemory(project) {
19904
19966
  if (project.agent !== "claude-code") return [];
19905
19967
  const rows = [];
19906
19968
  for (const segs of CLAUDE_CODE_MEMORY_FILES) {
19907
- const path5 = join7(project.worktree, ...segs);
19908
- if (!isInside(project.worktree, path5)) continue;
19969
+ const path7 = join7(project.worktree, ...segs);
19970
+ if (!isInside(project.worktree, path7)) continue;
19909
19971
  try {
19910
- const st = statSync4(path5);
19972
+ const st = statSync4(path7);
19911
19973
  if (!st.isFile()) continue;
19912
19974
  rows.push({
19913
19975
  origin: "memory",
19914
19976
  ts: Math.trunc(st.mtimeMs),
19915
19977
  seq: null,
19916
19978
  sourceId: null,
19917
- path: path5,
19979
+ path: path7,
19918
19980
  label: segs.join("/"),
19919
- text: readFileSync5(path5, "utf8")
19981
+ text: readFileSync5(path7, "utf8")
19920
19982
  });
19921
19983
  } catch {
19922
19984
  }
@@ -20032,12 +20094,20 @@ function sourceBytes(db, ids) {
20032
20094
  }
20033
20095
  return out;
20034
20096
  }
20097
+ var LEAN_HITS = 3;
20098
+ function replyHits(hits, size) {
20099
+ if (hits.length === 0 || hits[0].full !== true) return Math.min(size, hits.length);
20100
+ let n = Math.min(LEAN_HITS, size, hits.length);
20101
+ while (n < size && n < hits.length && hits[n].full === true) n++;
20102
+ return n;
20103
+ }
20035
20104
  function relevance(db, given, scope, ctx) {
20036
20105
  const input = { ...given, queries: decisionQueries(given) };
20037
20106
  const offset = input.offset ?? 0;
20038
20107
  const size = pageSize(input);
20039
20108
  const fetched = input.queries.map((q) => page(db, q, input, scope, ctx, offset, 1));
20040
- const pages = fetched.map((h) => h.slice(0, size));
20109
+ const take = fetched.map((h) => replyHits(h, size));
20110
+ const pages = fetched.map((h, i) => h.slice(0, take[i]));
20041
20111
  if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source);
20042
20112
  const moreLine3 = (q, pos) => "More: " + callText([q], scope, input.source, "offset:" + pos);
20043
20113
  let reserve = 0;
@@ -20052,7 +20122,7 @@ function relevance(db, given, scope, ctx) {
20052
20122
  input.queries.forEach((q, qi) => {
20053
20123
  const hits = pages[qi];
20054
20124
  if (stopped) {
20055
- more.push(moreLine3(q, offset));
20125
+ more.push({ q, pos: offset });
20056
20126
  return;
20057
20127
  }
20058
20128
  const head = "Query " + JSON.stringify(q) + ":";
@@ -20090,10 +20160,14 @@ function relevance(db, given, scope, ctx) {
20090
20160
  lines.push(line);
20091
20161
  used += bytes2(line) + 1;
20092
20162
  }
20093
- if (cut >= 0) more.push(moreLine3(q, cut));
20094
- else if (fetched[qi].length > size) more.push(moreLine3(q, offset + size));
20163
+ if (cut >= 0) more.push({ q, pos: cut });
20164
+ else if (fetched[qi].length > take[qi]) more.push({ q, pos: offset + take[qi] });
20095
20165
  });
20096
- return reply(lines.concat(more).join("\n"), false);
20166
+ const moreLines = [];
20167
+ const byPos = /* @__PURE__ */ new Map();
20168
+ for (const m of more) byPos.set(m.pos, [...byPos.get(m.pos) ?? [], m.q]);
20169
+ for (const [pos, qs] of byPos) moreLines.push("More: " + callText(qs, scope, input.source, "offset:" + pos));
20170
+ return reply(lines.concat(moreLines).join("\n"), false);
20097
20171
  }
20098
20172
  function timelineLine(r) {
20099
20173
  const nl = r.text.indexOf("\n");
@@ -20233,6 +20307,7 @@ function indexCombined(db, ctx, label, ran, deadline, budgetBytes) {
20233
20307
  const chunks = chunkText(ran.map((r) => r.block).join(BLOCK_SEP), "text");
20234
20308
  const display = shown(chunks, ran.map((r) => r.head));
20235
20309
  const bodies = /* @__PURE__ */ new Map();
20310
+ const raw = /* @__PURE__ */ new Map();
20236
20311
  let total = 0;
20237
20312
  for (const c of chunks) total += c.bytes;
20238
20313
  let indexed = 0;
@@ -20253,7 +20328,10 @@ function indexCombined(db, ctx, label, ran, deadline, budgetBytes) {
20253
20328
  chunkCount: group.length,
20254
20329
  createdAt: Date.now()
20255
20330
  }, group);
20256
- for (const c of group) bodies.set(chunkKey(id, c.ord), display[c.ord]);
20331
+ for (const c of group) {
20332
+ bodies.set(chunkKey(id, c.ord), display[c.ord]);
20333
+ raw.set(chunkKey(id, c.ord), c.text);
20334
+ }
20257
20335
  indexed += groupBytes;
20258
20336
  group = [];
20259
20337
  groupBytes = 0;
@@ -20262,15 +20340,15 @@ function indexCombined(db, ctx, label, ran, deadline, budgetBytes) {
20262
20340
  for (const c of chunks) {
20263
20341
  if (queued + c.bytes > budgetBytes) {
20264
20342
  const stop2 = flush() ? "budget" : "deadline";
20265
- return { bodies, indexed, total, stop: stop2 };
20343
+ return { bodies, raw, indexed, total, stop: stop2 };
20266
20344
  }
20267
- if (group.length > 0 && groupBytes + c.bytes > INDEX_WRITE_CHUNK && !flush()) return { bodies, indexed, total, stop: "deadline" };
20345
+ if (group.length > 0 && groupBytes + c.bytes > INDEX_WRITE_CHUNK && !flush()) return { bodies, raw, indexed, total, stop: "deadline" };
20268
20346
  group.push(c);
20269
20347
  groupBytes += c.bytes;
20270
20348
  queued += c.bytes;
20271
20349
  }
20272
20350
  const stop = flush() ? null : "deadline";
20273
- return { bodies, indexed, total, stop };
20351
+ return { bodies, raw, indexed, total, stop };
20274
20352
  }
20275
20353
  function bytes3(s) {
20276
20354
  return Buffer.byteLength(s, "utf8");
@@ -20303,7 +20381,7 @@ function answer(db, ctx, label, queries, share, own4) {
20303
20381
  else if (body.length === 0) body.push("No new section.");
20304
20382
  lines.push(head, ...body);
20305
20383
  }
20306
- return lines;
20384
+ return { lines, seen };
20307
20385
  }
20308
20386
  async function runBatch(input, ctx, boundMs, budgetBytes) {
20309
20387
  const parsed = ctxBatchSchema.safeParse(input);
@@ -20324,9 +20402,10 @@ async function runBatch(input, ctx, boundMs, budgetBytes) {
20324
20402
  const db = await openDb(ctx.project);
20325
20403
  let sections;
20326
20404
  let idx;
20327
- const summary = commands.length + " command(s), " + queries.length + " querie(s), exit " + last2.exitCode;
20405
+ const exitLine = last2.exitCode === null || last2.exitCode === 0 ? null : "exit " + last2.exitCode;
20328
20406
  const footer = "more: ctx_search({queries:[...], source:" + JSON.stringify(label) + "})";
20329
20407
  let notice;
20408
+ let showMore;
20330
20409
  try {
20331
20410
  idx = indexCombined(db, ctx, label, ran, deadline, budgetBytes);
20332
20411
  const stop = last2.error;
@@ -20334,13 +20413,21 @@ async function runBatch(input, ctx, boundMs, budgetBytes) {
20334
20413
  const timeout = formatError2("TIMEOUT", { ms: boundMs });
20335
20414
  const cause = stop ?? (ctx.signal.aborted ? CANCELLED_LINE : idx.stop === "deadline" ? timeout : null);
20336
20415
  notice = cut === null ? stop : cause === null ? cut : cause + " " + cut;
20337
- const fixed = bytes3(summary) + 1 + (notice === null ? 0 : bytes3(notice) + 1) + bytes3(footer);
20416
+ const fixed = (exitLine === null ? 0 : bytes3(exitLine) + 1) + (notice === null ? 0 : bytes3(notice) + 1) + bytes3(footer);
20338
20417
  const share = Math.floor((OUTPUT_CAP - fixed) / queries.length);
20339
- sections = answer(db, ctx, label, queries, share, idx.bodies);
20418
+ const answered = answer(db, ctx, label, queries, share, idx.bodies);
20419
+ sections = answered.lines;
20420
+ const unseen = [...idx.bodies].filter(([k, text]) => text !== "" && !answered.seen.has(k)).map(([k]) => idx.raw.get(k));
20421
+ const unseenBytes = unseen.reduce((n, t) => n + bytes3(t) + 1, 0);
20422
+ if (unseen.length === 0 && cut === null) showMore = false;
20423
+ else if (cut === null && unseenBytes <= bytes3(footer) + 1) {
20424
+ showMore = false;
20425
+ sections = [...sections, ...unseen.map((t) => t.endsWith(LINE_SEP) ? t.slice(0, -1) : t)];
20426
+ } else showMore = true;
20340
20427
  } finally {
20341
20428
  closeDb(db);
20342
20429
  }
20343
- const lines = [summary, ...notice === null ? [] : [notice], ...sections, footer];
20430
+ const lines = [...exitLine === null ? [] : [exitLine], ...notice === null ? [] : [notice], ...sections, ...showMore ? [footer] : []];
20344
20431
  return {
20345
20432
  text: capBytes(lines.join(LINE_SEP), OUTPUT_CAP).text,
20346
20433
  // step 10: final bound (D-M2-6)
@@ -20364,8 +20451,8 @@ var ctxBatch = Object.freeze({
20364
20451
  });
20365
20452
 
20366
20453
  // src/core/tools/doctor.ts
20367
- import { readdirSync as readdirSync5, readFileSync as readFileSync11, existsSync as existsSync11 } from "node:fs";
20368
- import { basename as basename3, dirname as dirname6, join as join13 } from "node:path";
20454
+ import { readdirSync as readdirSync5, readFileSync as readFileSync11, existsSync as existsSync12 } from "node:fs";
20455
+ import { basename as basename4, dirname as dirname7, join as join13 } from "node:path";
20369
20456
 
20370
20457
  // src/core/ops/doctor-config.ts
20371
20458
  import { existsSync as existsSync6, readdirSync as readdirSync3 } from "node:fs";
@@ -20378,7 +20465,7 @@ import { join as join9 } from "node:path";
20378
20465
 
20379
20466
  // src/core/ops/host-config.ts
20380
20467
  import { existsSync as existsSync3, readFileSync as readFileSync6 } from "node:fs";
20381
- import { dirname as dirname4, join as join8 } from "node:path";
20468
+ import { dirname as dirname5, join as join8 } from "node:path";
20382
20469
 
20383
20470
  // node_modules/eslint-visitor-keys/lib/visitor-keys.js
20384
20471
  var KEYS2 = {
@@ -22487,15 +22574,15 @@ function atomicWriteFile(file2, text, opts = {}) {
22487
22574
  }
22488
22575
 
22489
22576
  // src/core/ops/host-config.ts
22490
- function formatOf(path5) {
22491
- if (path5.endsWith(JSONC_EXT)) return "jsonc";
22492
- if (path5.endsWith(TOML_EXT)) return "toml";
22577
+ function formatOf(path7) {
22578
+ if (path7.endsWith(JSONC_EXT)) return "jsonc";
22579
+ if (path7.endsWith(TOML_EXT)) return "toml";
22493
22580
  return "json";
22494
22581
  }
22495
- function readHostConfig(agent, path5) {
22496
- let file2 = path5;
22582
+ function readHostConfig(agent, path7) {
22583
+ let file2 = path7;
22497
22584
  if (agent === "opencode") {
22498
- const jsonc = join8(dirname4(path5), OPENCODE_CONFIG_FILES[0]);
22585
+ const jsonc = join8(dirname5(path7), OPENCODE_CONFIG_FILES[0]);
22499
22586
  if (existsSync3(jsonc)) file2 = jsonc;
22500
22587
  }
22501
22588
  const raw = existsSync3(file2) ? readFileSync6(file2, "utf8") : "";
@@ -22659,14 +22746,14 @@ function scanToml(text) {
22659
22746
  continue;
22660
22747
  }
22661
22748
  if (!node3.resolvedKey.every((seg) => typeof seg === "string")) continue;
22662
- const path5 = node3.resolvedKey;
22663
- for (const kv of node3.body) addKey(path5, kv);
22749
+ const path7 = node3.resolvedKey;
22750
+ for (const kv of node3.body) addKey(path7, kv);
22664
22751
  if (node3.kind !== "standard") continue;
22665
22752
  const start = lineStartOf(text, node3.range[0]);
22666
22753
  const headEnd = lineEndOf(text, node3.key.range[1]);
22667
22754
  const last2 = node3.body[node3.body.length - 1];
22668
22755
  tables.push({
22669
- path: path5,
22756
+ path: path7,
22670
22757
  header: text.slice(start, text[headEnd - 1] === "\n" ? headEnd - 1 : headEnd),
22671
22758
  start,
22672
22759
  end: last2 === void 0 ? headEnd : lineEndOf(text, last2.range[1])
@@ -22677,16 +22764,16 @@ function scanToml(text) {
22677
22764
  function tomlTableSpans(text) {
22678
22765
  return scanToml(text).tables;
22679
22766
  }
22680
- function parseHostConfig(agent, path5, text, format) {
22767
+ function parseHostConfig(agent, path7, text, format) {
22681
22768
  try {
22682
22769
  return format === "toml" ? scanToml(text).value : scanJson(text, format).value;
22683
22770
  } catch {
22684
- throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path5, format });
22771
+ throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path7, format });
22685
22772
  }
22686
22773
  }
22687
- function hostConfigValueAt(value, path5) {
22774
+ function hostConfigValueAt(value, path7) {
22688
22775
  let cur = value;
22689
- for (const seg of path5) {
22776
+ for (const seg of path7) {
22690
22777
  if (!isPlainObject3(cur)) return void 0;
22691
22778
  cur = cur[seg];
22692
22779
  }
@@ -22719,32 +22806,32 @@ function indentUnit(root, clean) {
22719
22806
  function render(value, unit, base) {
22720
22807
  return JSON.stringify(value, null, unit).split("\n").join("\n" + base);
22721
22808
  }
22722
- function nest(path5, value) {
22809
+ function nest(path7, value) {
22723
22810
  let out = value;
22724
- for (let k = path5.length - 1; k >= 0; k -= 1) out = { [path5[k]]: out };
22811
+ for (let k = path7.length - 1; k >= 0; k -= 1) out = { [path7[k]]: out };
22725
22812
  return out;
22726
22813
  }
22727
- function setJsonText(text, format, path5, value) {
22814
+ function setJsonText(text, format, path7, value) {
22728
22815
  const doc = scanJson(text, format);
22729
22816
  const unit = indentUnit(doc.root, doc.clean);
22730
- if (doc.root === null) return render(nest(path5, value), unit, "") + "\n";
22817
+ if (doc.root === null) return render(nest(path7, value), unit, "") + "\n";
22731
22818
  let node3 = doc.root;
22732
22819
  let depth = 0;
22733
- while (depth < path5.length && node3.kind === "object") {
22734
- const hit = node3.members.find((m) => m.key === path5[depth]);
22820
+ while (depth < path7.length && node3.kind === "object") {
22821
+ const hit = node3.members.find((m) => m.key === path7[depth]);
22735
22822
  if (hit === void 0) break;
22736
22823
  node3 = hit.node;
22737
22824
  depth += 1;
22738
22825
  }
22739
- if (depth === path5.length) {
22826
+ if (depth === path7.length) {
22740
22827
  return text.slice(0, node3.start) + render(value, unit, lineIndent(doc.clean, node3.start)) + text.slice(node3.end);
22741
22828
  }
22742
- if (node3.kind !== "object") throw new SyntaxError("not an object at " + path5.slice(0, depth).join("."));
22743
- const rest = nest(path5.slice(depth + 1), value);
22829
+ if (node3.kind !== "object") throw new SyntaxError("not an object at " + path7.slice(0, depth).join("."));
22830
+ const rest = nest(path7.slice(depth + 1), value);
22744
22831
  const last2 = node3.members[node3.members.length - 1];
22745
22832
  if (last2 === void 0) {
22746
22833
  const base2 = lineIndent(doc.clean, node3.start);
22747
- const member2 = "\n" + base2 + unit + JSON.stringify(path5[depth]) + ": " + render(rest, unit, base2 + unit) + "\n" + base2;
22834
+ const member2 = "\n" + base2 + unit + JSON.stringify(path7[depth]) + ": " + render(rest, unit, base2 + unit) + "\n" + base2;
22748
22835
  return text.slice(0, node3.start + 1) + member2 + text.slice(node3.end - 1);
22749
22836
  }
22750
22837
  const base = lineIndent(doc.clean, last2.keyStart);
@@ -22752,7 +22839,7 @@ function setJsonText(text, format, path5, value) {
22752
22839
  while (" \r\n".includes(doc.clean[at2])) at2 += 1;
22753
22840
  const trailing = doc.clean[at2] === ",";
22754
22841
  const insertAt = trailing ? at2 + 1 : last2.node.end;
22755
- const member = (trailing ? "" : ",") + "\n" + base + JSON.stringify(path5[depth]) + ": " + render(rest, unit, base);
22842
+ const member = (trailing ? "" : ",") + "\n" + base + JSON.stringify(path7[depth]) + ": " + render(rest, unit, base);
22756
22843
  return text.slice(0, insertAt) + member + text.slice(insertAt);
22757
22844
  }
22758
22845
  function tomlScalar(v) {
@@ -22770,17 +22857,17 @@ function tomlHeaderKey(seg) {
22770
22857
  }
22771
22858
  return seg;
22772
22859
  }
22773
- function tomlBlock(path5, value) {
22774
- let out = "[" + path5.map(tomlHeaderKey).join(".") + "]\n";
22860
+ function tomlBlock(path7, value) {
22861
+ let out = "[" + path7.map(tomlHeaderKey).join(".") + "]\n";
22775
22862
  const subs = [];
22776
22863
  for (const [k, v] of Object.entries(value)) {
22777
- if (isPlainObject3(v)) subs.push(tomlBlock([...path5, k], v));
22864
+ if (isPlainObject3(v)) subs.push(tomlBlock([...path7, k], v));
22778
22865
  else out += tomlHeaderKey(k) + " = " + tomlScalar(v) + "\n";
22779
22866
  }
22780
22867
  return [out, ...subs].join("\n");
22781
22868
  }
22782
- function under(path5, prefix) {
22783
- return path5.length >= prefix.length && prefix.every((seg, k) => path5[k] === seg);
22869
+ function under(path7, prefix) {
22870
+ return path7.length >= prefix.length && prefix.every((seg, k) => path7[k] === seg);
22784
22871
  }
22785
22872
  function keyLineRange(text, k) {
22786
22873
  const ls = lineStartOf(text, k.start);
@@ -22797,10 +22884,10 @@ function withValueAt(root, rel, value) {
22797
22884
  else base[rel[0]] = next;
22798
22885
  return base;
22799
22886
  }
22800
- function replaceToml(text, doc, path5, value) {
22801
- const block = value === void 0 ? "" : tomlBlock(path5, value);
22802
- const owned = doc.tables.filter((t) => under(t.path, path5));
22803
- const cuts = doc.keys.filter((k) => under(k.full, path5) && !under(k.base, path5)).map((k) => [...keyLineRange(text, k), ""]);
22887
+ function replaceToml(text, doc, path7, value) {
22888
+ const block = value === void 0 ? "" : tomlBlock(path7, value);
22889
+ const owned = doc.tables.filter((t) => under(t.path, path7));
22890
+ const cuts = doc.keys.filter((k) => under(k.full, path7) && !under(k.base, path7)).map((k) => [...keyLineRange(text, k), ""]);
22804
22891
  owned.forEach((t, n) => cuts.push([t.start, t.end, n === 0 ? block : ""]));
22805
22892
  cuts.sort((a, b) => b[0] - a[0]);
22806
22893
  let out = text;
@@ -22810,27 +22897,27 @@ function replaceToml(text, doc, path5, value) {
22810
22897
  return out + sep4 + block;
22811
22898
  }
22812
22899
  var tableLike = (v) => v === void 0 || isPlainObject3(v);
22813
- function setTomlText(text, path5, value) {
22900
+ function setTomlText(text, path7, value) {
22814
22901
  if (value !== void 0 && !isPlainObject3(value)) throw new SyntaxError("TOML edits replace a whole table");
22815
22902
  const doc = scanToml(text);
22816
- const cur = hostConfigValueAt(doc.value, path5);
22903
+ const cur = hostConfigValueAt(doc.value, path7);
22817
22904
  if (sameValue(cur, value)) return text;
22818
- const inline = doc.keys.find((k) => k.inline && k.full.length < path5.length && under(path5, k.full));
22905
+ const inline = doc.keys.find((k) => k.inline && k.full.length < path7.length && under(path7, k.full));
22819
22906
  if (inline !== void 0) {
22820
- const whole = withValueAt(hostConfigValueAt(doc.value, inline.full), path5.slice(inline.full.length), value);
22907
+ const whole = withValueAt(hostConfigValueAt(doc.value, inline.full), path7.slice(inline.full.length), value);
22821
22908
  return replaceToml(text, doc, inline.full, whole);
22822
22909
  }
22823
22910
  if (isPlainObject3(cur) && isPlainObject3(value)) {
22824
22911
  const names = [.../* @__PURE__ */ new Set([...Object.keys(cur), ...Object.keys(value)])].filter((k) => !sameValue(cur[k], value[k]));
22825
22912
  if (names.every((k) => tableLike(cur[k]) && tableLike(value[k]))) {
22826
22913
  let out = text;
22827
- for (const k of names) out = setTomlText(out, [...path5, k], value[k]);
22914
+ for (const k of names) out = setTomlText(out, [...path7, k], value[k]);
22828
22915
  return out;
22829
22916
  }
22830
22917
  }
22831
- return replaceToml(text, doc, path5, value);
22918
+ return replaceToml(text, doc, path7, value);
22832
22919
  }
22833
- function setText(agent, path5, text, format, key, value) {
22920
+ function setText(agent, path7, text, format, key, value) {
22834
22921
  try {
22835
22922
  if (format !== "toml") return setJsonText(text, format, key, value);
22836
22923
  const out = setTomlText(text, key, value);
@@ -22839,11 +22926,11 @@ function setText(agent, path5, text, format, key, value) {
22839
22926
  if (!sameValue(landed, value) && !(emptyTable && landed === void 0)) throw new SyntaxError("edit did not land");
22840
22927
  return out;
22841
22928
  } catch {
22842
- throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path5, format });
22929
+ throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path7, format });
22843
22930
  }
22844
22931
  }
22845
22932
  function serverScript() {
22846
- return join8(dirname4(process.argv[1] ?? ""), SERVER_ENTRY_FILE);
22933
+ return join8(dirname5(process.argv[1] ?? ""), SERVER_ENTRY_FILE);
22847
22934
  }
22848
22935
  function isNodeCommand(command) {
22849
22936
  if (typeof command !== "string") return false;
@@ -22859,7 +22946,7 @@ function ownMcpValue(agent, node3, server) {
22859
22946
  return { ...mcp.fields, [MCP_COMMAND_FIELD]: node3, [MCP_ARGS_FIELD]: [server, AGENT_ARG, agent, ...tail] };
22860
22947
  }
22861
22948
  function opencodePluginFile() {
22862
- return dirname4(process.argv[1] ?? "");
22949
+ return dirname5(process.argv[1] ?? "");
22863
22950
  }
22864
22951
  function listTarget(key, own4, v1, alt = []) {
22865
22952
  return {
@@ -22886,14 +22973,14 @@ function ownTargets(agent, accept) {
22886
22973
  if (agent === "pi") return [listTarget(PI_PACKAGES_KEY, PI_GIT_PACKAGE, V1_PI_PACKAGE)];
22887
22974
  return [];
22888
22975
  }
22889
- function applyEdits(agent, path5, text, format, wanted) {
22890
- const parsed = parseHostConfig(agent, path5, text, format);
22976
+ function applyEdits(agent, path7, text, format, wanted) {
22977
+ const parsed = parseHostConfig(agent, path7, text, format);
22891
22978
  let out = text;
22892
22979
  const edits = [];
22893
22980
  for (const [key, after] of wanted) {
22894
22981
  const before = hostConfigValueAt(parsed, key);
22895
22982
  if (sameValue(before, after)) continue;
22896
- out = setText(agent, path5, out, format, key, after);
22983
+ out = setText(agent, path7, out, format, key, after);
22897
22984
  edits.push({ path: key.join("."), before, after });
22898
22985
  }
22899
22986
  return { text: out, format, edits };
@@ -22914,7 +23001,7 @@ function writeHostConfigEdit(_requested, current, patch) {
22914
23001
  // src/core/ops/detect-v1.ts
22915
23002
  var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
22916
23003
  var keyPath = (...parts) => parts.join(".");
22917
- var finding = (file2, path5, reason) => ({ file: file2, path: path5, reason });
23004
+ var finding = (file2, path7, reason) => ({ file: file2, path: path7, reason });
22918
23005
  function stripJsonc(text) {
22919
23006
  let out = "";
22920
23007
  let inStr = false;
@@ -23219,20 +23306,23 @@ function detectV1(agent, home, scope = {}) {
23219
23306
 
23220
23307
  // src/core/ops/plugin-root.ts
23221
23308
  import { existsSync as existsSync5, readdirSync as readdirSync2, readFileSync as readFileSync8, realpathSync as realpathSync4 } from "node:fs";
23222
- import { dirname as dirname5, isAbsolute as isAbsolute2, join as join10, sep as sep3 } from "node:path";
23309
+ import { dirname as dirname6, isAbsolute as isAbsolute2, join as join10, sep as sep3 } from "node:path";
23223
23310
  import { fileURLToPath } from "node:url";
23224
- function missing(agent, path5) {
23225
- return new CtxError("PLUGIN_ROOT_MISSING", { agent, path: path5 });
23311
+ function missing(agent, path7) {
23312
+ return new CtxError("PLUGIN_ROOT_MISSING", { agent, path: path7 });
23226
23313
  }
23227
- function recordedInstallPaths(text) {
23228
- let parsed;
23314
+ var parseOrNull = (text) => {
23229
23315
  try {
23230
- parsed = JSON.parse(hostText(text));
23316
+ return JSON.parse(hostText(text));
23231
23317
  } catch {
23232
- return [];
23318
+ return null;
23233
23319
  }
23234
- const plugins = parsed?.plugins;
23235
- if (plugins === null || typeof plugins !== "object") return [];
23320
+ };
23321
+ var isRecord3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
23322
+ function recordedInstalls(text) {
23323
+ const parsed = parseOrNull(text);
23324
+ const plugins = isRecord3(parsed) ? parsed.plugins : void 0;
23325
+ if (!isRecord3(plugins)) return [];
23236
23326
  const out = [];
23237
23327
  for (const key of Object.keys(plugins)) {
23238
23328
  const at2 = key.indexOf(PLUGIN_KEY_SEPARATOR);
@@ -23240,39 +23330,77 @@ function recordedInstallPaths(text) {
23240
23330
  const entries = plugins[key];
23241
23331
  if (!Array.isArray(entries)) continue;
23242
23332
  for (const e of entries) {
23243
- const dir = e?.installPath;
23244
- if (typeof dir === "string" && dir !== "" && !out.includes(dir)) out.push(dir);
23333
+ if (!isRecord3(e) || typeof e.installPath !== "string" || e.installPath === "") continue;
23334
+ const scope = typeof e.scope === "string" ? e.scope : DEFAULT_PLUGIN_SCOPE;
23335
+ const projectPath = typeof e.projectPath === "string" ? e.projectPath : void 0;
23336
+ out.push({ key, scope, projectPath, installPath: e.installPath });
23245
23337
  }
23246
23338
  }
23247
23339
  return out;
23248
23340
  }
23249
- var realOrNull = (path5) => {
23341
+ var realOrNull = (path7) => {
23250
23342
  try {
23251
- return realpathSync4.native(path5);
23343
+ return realpathSync4.native(path7);
23252
23344
  } catch {
23253
23345
  return null;
23254
23346
  }
23255
23347
  };
23256
- function marketplaceRoot(adapter, env) {
23257
- const claudeDir = claudeDirOf(env, requireHomeDir(env));
23258
- const plugins = join10(claudeDir, HOST_PLUGINS_DIR_NAME);
23259
- const cache = join10(plugins, PLUGIN_CACHE_DIR_NAME);
23260
- const script = process.argv[1];
23261
- const ownReal = script === void 0 || script === "" ? null : realOrNull(dirname5(script));
23262
- let record6 = null;
23348
+ var readOrNull = (file2) => {
23263
23349
  try {
23264
- record6 = readFileSync8(join10(plugins, INSTALLED_PLUGINS_FILE), "utf8");
23350
+ return readFileSync8(file2, "utf8");
23265
23351
  } catch {
23266
- record6 = null;
23352
+ return null;
23267
23353
  }
23268
- const recorded = record6 === null ? [] : recordedInstallPaths(record6);
23269
- if (recorded.length > 0) {
23270
- const live = recorded.filter((dir) => existsSync5(dir));
23271
- const mine = live.find((dir) => realOrNull(dir) === ownReal);
23272
- if (mine !== void 0) return mine;
23273
- if (live.length === 1) return live[0];
23274
- throw missing(adapter.id, recorded.join(", "));
23354
+ };
23355
+ var samePath = (a, b) => a === b || (realOrNull(a) ?? a) === (realOrNull(b) ?? b);
23356
+ function enabledPlugins(claudeDir, project) {
23357
+ const files = [join10(claudeDir, SETTINGS_FILE)];
23358
+ if (project !== void 0) files.push(join10(project, HOST_CONFIG_DIR_NAME, SETTINGS_FILE), join10(project, HOST_CONFIG_DIR_NAME, SETTINGS_LOCAL_FILE));
23359
+ const out = {};
23360
+ for (const file2 of files) {
23361
+ const text = readOrNull(file2);
23362
+ const doc = text === null ? null : parseOrNull(text);
23363
+ const on = isRecord3(doc) ? doc[ENABLED_PLUGINS_KEY] : void 0;
23364
+ if (isRecord3(on)) Object.assign(out, on);
23275
23365
  }
23366
+ return out;
23367
+ }
23368
+ function marketplaceChoice(env, worktree) {
23369
+ const claudeDir = claudeDirOf(env, requireHomeDir(env));
23370
+ const script = process.argv[1];
23371
+ const ownReal = script === void 0 || script === "" ? null : realOrNull(dirname6(script));
23372
+ const hostRoot = env[CLAUDE_PLUGIN_ROOT_ENV];
23373
+ if (ownReal !== null && hostRoot !== void 0 && hostRoot !== "" && realOrNull(hostRoot) === ownReal) return { root: ownReal };
23374
+ const record6 = readOrNull(join10(claudeDir, HOST_PLUGINS_DIR_NAME, INSTALLED_PLUGINS_FILE));
23375
+ const recorded = record6 === null ? [] : recordedInstalls(record6);
23376
+ if (recorded.length === 0) return { record: false };
23377
+ const live = recorded.filter((r) => existsSync5(r.installPath));
23378
+ const mine = live.find((r) => realOrNull(r.installPath) === ownReal);
23379
+ if (mine !== void 0) return { root: mine.installPath };
23380
+ const dirs = live.filter((r, i) => live.findIndex((o) => samePath(o.installPath, r.installPath)) === i);
23381
+ if (dirs.length === 1) return { root: dirs[0].installPath };
23382
+ const projectEnv = env[CLAUDE_PROJECT_DIR_ENV];
23383
+ const project = worktree ?? (projectEnv === void 0 || projectEnv === "" ? void 0 : projectEnv);
23384
+ const on = enabledPlugins(claudeDir, project);
23385
+ const applies = (r) => !PROJECT_PLUGIN_SCOPES.includes(r.scope) || project !== void 0 && r.projectPath !== void 0 && samePath(r.projectPath, project);
23386
+ const rank = (r) => PLUGIN_SCOPE_RANK[r.scope] ?? PLUGIN_SCOPE_RANK[DEFAULT_PLUGIN_SCOPE];
23387
+ const used = live.filter((r) => on[r.key] === true && applies(r));
23388
+ if (used.length > 0) {
23389
+ const best = Math.min(...used.map(rank));
23390
+ const top = used.filter((r) => rank(r) === best);
23391
+ if (top.every((r) => samePath(r.installPath, top[0].installPath))) return { root: top[0].installPath };
23392
+ }
23393
+ return { installs: live.length === 0 ? recorded : live };
23394
+ }
23395
+ function marketplaceRoot(adapter, env, worktree) {
23396
+ const claudeDir = claudeDirOf(env, requireHomeDir(env));
23397
+ const plugins = join10(claudeDir, HOST_PLUGINS_DIR_NAME);
23398
+ const cache = join10(plugins, PLUGIN_CACHE_DIR_NAME);
23399
+ const script = process.argv[1];
23400
+ const ownReal = script === void 0 || script === "" ? null : realOrNull(dirname6(script));
23401
+ const choice = marketplaceChoice(env, worktree);
23402
+ if ("root" in choice) return choice.root;
23403
+ if ("installs" in choice) throw missing(adapter.id, choice.installs.map((r) => r.installPath).join(", "));
23276
23404
  const cacheReal = realOrNull(cache);
23277
23405
  if (ownReal !== null && cacheReal !== null && ownReal.startsWith(cacheReal + sep3) && existsSync5(join10(ownReal, SERVER_ENTRY_FILE))) return ownReal;
23278
23406
  const pattern = join10(cache, "*", PLUGIN_NAME);
@@ -23291,12 +23419,12 @@ function configEntryRoot(adapter, env) {
23291
23419
  const args = hostConfigValueAt(value, [...spec.key, MCP_ARGS_FIELD]);
23292
23420
  const script = Array.isArray(args) ? args[0] : void 0;
23293
23421
  if (typeof script !== "string" || !isAbsolute2(script)) throw missing(adapter.id, file2);
23294
- return dirname5(script);
23422
+ return dirname6(script);
23295
23423
  }
23296
- function candidate(adapter, env) {
23424
+ function candidate(adapter, env, worktree) {
23297
23425
  switch (adapter.installMode) {
23298
23426
  case "marketplace":
23299
- return marketplaceRoot(adapter, env);
23427
+ return marketplaceRoot(adapter, env, worktree);
23300
23428
  case "config-mcp":
23301
23429
  case "mcp-entry":
23302
23430
  case "hooks+mcp":
@@ -23306,15 +23434,15 @@ function candidate(adapter, env) {
23306
23434
  case "plugin":
23307
23435
  return join10(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, adapter.id, PLUGIN_CURRENT_LINK);
23308
23436
  case "in-process":
23309
- return dirname5(fileURLToPath(import.meta.url));
23437
+ return dirname6(fileURLToPath(import.meta.url));
23310
23438
  }
23311
23439
  }
23312
- function resolvePluginRoot(adapter, env) {
23313
- const path5 = candidate(adapter, env);
23440
+ function resolvePluginRoot(adapter, env, worktree) {
23441
+ const path7 = candidate(adapter, env, worktree);
23314
23442
  try {
23315
- return realpathSync4.native(path5);
23443
+ return realpathSync4.native(path7);
23316
23444
  } catch {
23317
- throw missing(adapter.id, path5);
23445
+ throw missing(adapter.id, path7);
23318
23446
  }
23319
23447
  }
23320
23448
 
@@ -23441,13 +23569,13 @@ function nativeMcpWrong(dir, row5) {
23441
23569
  return true;
23442
23570
  }
23443
23571
  }
23444
- function mcpWrong(row5, home, env) {
23572
+ function mcpWrong(row5, home, env, worktree) {
23445
23573
  const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
23446
23574
  if (native !== null) return nativeMcpWrong(native, row5);
23447
23575
  const file2 = mcpFile(row5, home, env);
23448
23576
  try {
23449
23577
  if (file2 === null) {
23450
- resolvePluginRoot(row5, env);
23578
+ resolvePluginRoot(row5, env, worktree);
23451
23579
  return false;
23452
23580
  }
23453
23581
  const cur = readHostConfig(row5.id, file2);
@@ -23461,7 +23589,7 @@ function hookParts(row5, home, env, worktree) {
23461
23589
  if (spec === null) return [];
23462
23590
  let block;
23463
23591
  try {
23464
- const root = spec.root === "plugin" ? resolvePluginRoot(row5, env) : spec.root === "home" ? home : worktree;
23592
+ const root = spec.root === "plugin" ? resolvePluginRoot(row5, env, worktree) : spec.root === "home" ? home : worktree;
23465
23593
  const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
23466
23594
  const file2 = native !== null ? join11(native, CODEX_PLUGIN_HOOKS_FILE) : row5.id === "codex" ? join11(codexDirOf(env, home), HOOKS_JSON_FILE) : row5.id === "copilot-cli" ? join11(copilotDirOf(env, home), ...spec.file.slice(1)) : row5.id === "kiro" ? join11(kiroDirOf(env, home), ...spec.file.slice(1)) : join11(root, ...spec.file);
23467
23595
  block = hostConfigValueAt(readParsed(row5.id, file2).value, spec.key);
@@ -23496,7 +23624,11 @@ function hookParts(row5, home, env, worktree) {
23496
23624
  function checkHostConfig(row5, env, worktree) {
23497
23625
  const home = homeDirOf(env);
23498
23626
  if (home === null) return fail2("D3", D3_DETAIL(D3_PARTS), DOCTOR_FIX_UPGRADE);
23499
- const parts = [...mcpWrong(row5, home, env) ? [PART_MCP] : [], ...hookParts(row5, home, env, worktree)];
23627
+ if (row5.installMode === "marketplace") {
23628
+ const choice = marketplaceChoice(env, worktree);
23629
+ if ("installs" in choice) return fail2("D3", D3_ROOT_DETAIL(choice.installs.map((r) => r.installPath)), D3_ROOT_FIX(choice.installs));
23630
+ }
23631
+ const parts = [...mcpWrong(row5, home, env, worktree) ? [PART_MCP] : [], ...hookParts(row5, home, env, worktree)];
23500
23632
  const read3 = row5.id === "pi" ? mcpFile(row5, home, env) : null;
23501
23633
  if (parts.length === 0) return read3 === null ? pass("D3") : { ...pass("D3"), detail: read3 };
23502
23634
  const detail = D3_DETAIL(parts);
@@ -23545,8 +23677,8 @@ async function loadSqlite2() {
23545
23677
  return null;
23546
23678
  }
23547
23679
  }
23548
- function openRead(sqlite, path5) {
23549
- return new sqlite.DatabaseSync(path5, { timeout: DB_TIMEOUT_MS, readOnly: true });
23680
+ function openRead(sqlite, path7) {
23681
+ return new sqlite.DatabaseSync(path7, { timeout: DB_TIMEOUT_MS, readOnly: true });
23550
23682
  }
23551
23683
  var cell = (row5) => Object.values(row5)[0];
23552
23684
  function readSchema(raw) {
@@ -23688,17 +23820,229 @@ function checkShell(env) {
23688
23820
  }
23689
23821
 
23690
23822
  // src/core/ops/doctor-hook.ts
23691
- import { existsSync as existsSync9, readFileSync as readFileSync9 } from "node:fs";
23823
+ import { existsSync as existsSync10, readFileSync as readFileSync9, realpathSync as realpathSync7 } from "node:fs";
23824
+ import path6 from "node:path";
23825
+
23826
+ // src/setup/codex-trust.ts
23827
+ import { createHash } from "node:crypto";
23828
+ import { existsSync as existsSync9, realpathSync as realpathSync6 } from "node:fs";
23829
+ import path5 from "node:path";
23830
+ import { spawn as spawn2, spawnSync as spawnSync2 } from "node:child_process";
23831
+
23832
+ // src/setup/spawn-bin.ts
23833
+ import { spawnSync } from "node:child_process";
23834
+ import { accessSync as accessSync2, constants as fsc, statSync as statSync5 } from "node:fs";
23692
23835
  import path4 from "node:path";
23836
+ var WIN_EXT = ".COM;.EXE;.BAT;.CMD";
23837
+ var WIN_SHIM_EXTS = Object.freeze([".cmd", ".bat"]);
23838
+ var DEFAULT_COMSPEC = "cmd.exe";
23839
+ function envGet(env, k) {
23840
+ return env[Object.keys(env).find((x) => x.toUpperCase() === k) ?? k];
23841
+ }
23842
+ function whichBin(bin, env, platform = process.platform) {
23843
+ const get = (k) => envGet(env, k);
23844
+ const win = platform === "win32";
23845
+ const exts = win ? (get("PATHEXT") || WIN_EXT).split(";").filter(Boolean) : [""];
23846
+ const names = win && path4.extname(bin) ? [bin] : exts.map((e) => bin + e.toLowerCase());
23847
+ for (const dir of pathEntries(get("PATH") ?? "", platform)) {
23848
+ for (const n of names) {
23849
+ const f = path4.join(dir, n);
23850
+ try {
23851
+ accessSync2(f, fsc.X_OK);
23852
+ if (statSync5(f).isFile()) return f;
23853
+ } catch {
23854
+ }
23855
+ }
23856
+ }
23857
+ return void 0;
23858
+ }
23859
+ var CMD_QUOTE_CHARS = '"&|<>^()!';
23860
+ var CMD_PERCENT = "%";
23861
+ var CMD_SUBSTRING_MARK = ":";
23862
+ var CMD_DYNAMIC_VARS = Object.freeze(["CD", "DATE", "TIME", "RANDOM", "ERRORLEVEL", "CMDEXTVERSION", "CMDCMDLINE", "HIGHESTNUMANODENUMBER"]);
23863
+ function needsCmdQuotes(a) {
23864
+ if (a === "") return true;
23865
+ for (const c of a) if (c.trim() === "" || CMD_QUOTE_CHARS.includes(c)) return true;
23866
+ return false;
23867
+ }
23868
+ function expandablePercent(text, env) {
23869
+ const names = new Set(CMD_DYNAMIC_VARS);
23870
+ for (const k of Object.keys(env)) names.add(k.toUpperCase());
23871
+ for (let i = text.indexOf(CMD_PERCENT); i >= 0; i = text.indexOf(CMD_PERCENT, i + 1)) {
23872
+ for (let j = text.indexOf(CMD_PERCENT, i + 1); j >= 0; j = text.indexOf(CMD_PERCENT, j + 1)) {
23873
+ const inner = text.slice(i + 1, j);
23874
+ const cut = inner.indexOf(CMD_SUBSTRING_MARK);
23875
+ const name = cut < 0 ? inner : inner.slice(0, cut);
23876
+ if (name !== "" && names.has(name.toUpperCase())) return `${CMD_PERCENT}${inner}${CMD_PERCENT}`;
23877
+ }
23878
+ }
23879
+ return void 0;
23880
+ }
23881
+ function winCmdLine(file2, args, env = {}) {
23882
+ for (const a of [file2, ...args]) {
23883
+ const hit = expandablePercent(a, env);
23884
+ if (hit !== void 0) throw new Error(`cannot run ${file2} through cmd.exe: cmd.exe expands ${hit} inside quotes, so the value ${JSON.stringify(a)} would change. Use a path and arguments without it`);
23885
+ }
23886
+ const q = (a) => needsCmdQuotes(a) ? `"${a.split('"').join('""')}"` : a;
23887
+ return `"${[file2, ...args].map(q).join(" ")}"`;
23888
+ }
23889
+ function spawnForm(file2, args, env, platform = process.platform) {
23890
+ if (platform === "win32" && WIN_SHIM_EXTS.includes(path4.extname(file2).toLowerCase())) {
23891
+ return { command: envGet(env, "COMSPEC") || DEFAULT_COMSPEC, args: ["/d", "/v:off", "/s", "/c", winCmdLine(file2, args, env)], windowsVerbatimArguments: true };
23892
+ }
23893
+ return { command: file2, args, windowsVerbatimArguments: false };
23894
+ }
23895
+
23896
+ // src/setup/codex-trust.ts
23897
+ var isObj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
23898
+ var TRUST_KEY = ["hooks", "state"];
23899
+ var CODEX_TRUST_PATH = TRUST_KEY.join(".") + ".";
23900
+ var WIN_VERBATIM_PREFIX = "\\\\?\\";
23901
+ function codexHomeFromReply(out) {
23902
+ for (const line of out.split("\n")) {
23903
+ let m;
23904
+ try {
23905
+ m = JSON.parse(line);
23906
+ } catch {
23907
+ continue;
23908
+ }
23909
+ if (isObj2(m) && isObj2(m.result) && typeof m.result.codexHome === "string" && m.result.codexHome !== "") return m.result.codexHome;
23910
+ }
23911
+ return void 0;
23912
+ }
23913
+ function sameDir(a, b, platform = process.platform) {
23914
+ if (platform !== "win32") return path5.posix.normalize(a) === path5.posix.normalize(b);
23915
+ const norm2 = (p) => {
23916
+ const bare2 = p.startsWith(WIN_VERBATIM_PREFIX) ? p.slice(WIN_VERBATIM_PREFIX.length) : p;
23917
+ const n = path5.win32.normalize(bare2).toLowerCase();
23918
+ return n.length > 3 && n.endsWith("\\") ? n.slice(0, -1) : n;
23919
+ };
23920
+ return norm2(a) === norm2(b);
23921
+ }
23922
+ var LIST_TIMEOUT_MS = 15e3;
23923
+ var EXIT_GRACE_MS = 5e3;
23924
+ var PLUGIN_SOURCE = "plugin";
23925
+ var TRUSTED = "trusted";
23926
+ function pluginHooksFromReply(m, pluginId) {
23927
+ const out = [];
23928
+ if (!isObj2(m) || !isObj2(m.result) || !Array.isArray(m.result.data)) return out;
23929
+ for (const d of m.result.data) {
23930
+ if (!isObj2(d) || !Array.isArray(d.hooks)) continue;
23931
+ for (const h of d.hooks) {
23932
+ if (!isObj2(h) || h.source !== PLUGIN_SOURCE || h.pluginId !== pluginId) continue;
23933
+ if (typeof h.key !== "string" || typeof h.currentHash !== "string") continue;
23934
+ if (out.some((x) => x.key === h.key)) continue;
23935
+ out.push({ key: h.key, hash: h.currentHash, trusted: h.trustStatus === TRUSTED });
23936
+ }
23937
+ }
23938
+ return out;
23939
+ }
23940
+ function askPluginHooks(env, pluginId, cwd) {
23941
+ const bin = whichBin("codex", env);
23942
+ if (!bin) return Promise.resolve({ kind: "absent" });
23943
+ return new Promise((resolve8) => {
23944
+ let asked;
23945
+ const done_ = (hooks) => hooks === void 0 ? { kind: "silent" } : { kind: "list", hooks, codexHome: asked };
23946
+ let f;
23947
+ try {
23948
+ f = spawnForm(bin, ["app-server"], env);
23949
+ } catch {
23950
+ resolve8({ kind: "silent" });
23951
+ return;
23952
+ }
23953
+ const child = spawn2(f.command, f.args, { env, cwd, stdio: ["pipe", "pipe", "ignore"], windowsVerbatimArguments: f.windowsVerbatimArguments, windowsHide: true });
23954
+ let buf = "";
23955
+ let done = false;
23956
+ let exited = false;
23957
+ let result;
23958
+ const settle3 = () => {
23959
+ clearTimeout(grace);
23960
+ resolve8(done_(result));
23961
+ };
23962
+ let grace;
23963
+ const finish2 = (v) => {
23964
+ if (done) return;
23965
+ done = true;
23966
+ clearTimeout(timer);
23967
+ result = v;
23968
+ child.stdin.destroy();
23969
+ if (exited) {
23970
+ settle3();
23971
+ return;
23972
+ }
23973
+ grace = setTimeout(settle3, EXIT_GRACE_MS);
23974
+ stopTree(child.pid, () => child.kill());
23975
+ };
23976
+ const timer = setTimeout(() => finish2(void 0), LIST_TIMEOUT_MS);
23977
+ const send = (o) => {
23978
+ try {
23979
+ child.stdin.write(JSON.stringify(o) + "\n");
23980
+ } catch {
23981
+ finish2(void 0);
23982
+ }
23983
+ };
23984
+ child.on("error", () => finish2(void 0));
23985
+ child.on("close", () => {
23986
+ exited = true;
23987
+ if (done) settle3();
23988
+ else finish2(void 0);
23989
+ });
23990
+ child.stdin.on("error", () => finish2(void 0));
23991
+ child.stdout.setEncoding("utf8");
23992
+ child.stdout.on("data", (d) => {
23993
+ buf += d;
23994
+ const lines = buf.split("\n");
23995
+ buf = lines.pop() ?? "";
23996
+ for (const line of lines) {
23997
+ let m;
23998
+ try {
23999
+ m = JSON.parse(line);
24000
+ } catch {
24001
+ continue;
24002
+ }
24003
+ if (!isObj2(m)) continue;
24004
+ if (m.id === 1) {
24005
+ asked = codexHomeFromReply(line);
24006
+ send({ method: "initialized" });
24007
+ send({ id: 2, method: "hooks/list", params: { cwds: [cwd] } });
24008
+ } else if (m.id === 2) finish2(pluginHooksFromReply(m, pluginId));
24009
+ }
24010
+ });
24011
+ send({ id: 1, method: "initialize", params: { clientInfo: { name: "context-mode-setup", version: "2.0.0" } } });
24012
+ });
24013
+ }
24014
+ function stopTree(pid, kill) {
24015
+ if (process.platform === "win32" && pid !== void 0) {
24016
+ try {
24017
+ spawnSync2("taskkill", ["/pid", String(pid), "/T", "/F"], { windowsHide: true, stdio: "ignore", timeout: 5e3 });
24018
+ } catch {
24019
+ }
24020
+ }
24021
+ kill();
24022
+ }
24023
+ var CODEX_PLUGIN_ID = `${SERVER_KEY}@${SERVER_KEY}`;
24024
+ var CODEX_UNTRUSTED_FIX = "run: context-mode setup";
24025
+ function untrustedPluginHooksDetail(hooks) {
24026
+ const bad = hooks.filter((h) => !h.trusted);
24027
+ if (!bad.length) return void 0;
24028
+ return `codex lists ${bad.length} of ${hooks.length} context-mode plugin hooks untrusted, so they do not run; ${CODEX_UNTRUSTED_FIX}`;
24029
+ }
24030
+
24031
+ // src/core/ops/doctor-hook.ts
23693
24032
  var D5_MIN_PAIRS = 3;
23694
24033
  var D5_MAX_PAIRS = 9;
24034
+ var D5_CODEX_TRUST_FIX = "context-mode setup --agents codex";
24035
+ var D5_CODEX_ABSENT_DETAIL = (home) => `codex is not on PATH, so the trust of the context-mode plugin hooks in ${home} is not known`;
24036
+ var D5_CODEX_SILENT_DETAIL = (home) => `codex app-server gave no hooks/list answer for ${home} in time, so the context-mode plugin hooks are not known to run`;
24037
+ var D5_CODEX_OTHER_HOME_DETAIL = (asked, home) => `codex answers for ${asked}, but the context-mode plugin runs from ${home}`;
24038
+ var D5_CODEX_NONE_DETAIL = (home) => `codex lists no context-mode plugin hooks in ${home}, so they do not run`;
23695
24039
  var row = (status, detail, fixCommand) => fixCommand === void 0 ? { id: "D5", label: DOCTOR_LABEL.D5, status, detail } : { id: "D5", label: DOCTOR_LABEL.D5, status, detail, fixCommand };
23696
24040
  function isObject5(v) {
23697
24041
  return typeof v === "object" && v !== null && !Array.isArray(v);
23698
24042
  }
23699
24043
  function loadFixture(bundleDir2, agent) {
23700
- const file2 = path4.join(bundleDir2, HOOK_FIXTURE_DIR, HOOK_FIXTURE_FILE);
23701
- if (!existsSync9(file2)) return null;
24044
+ const file2 = path6.join(bundleDir2, HOOK_FIXTURE_DIR, HOOK_FIXTURE_FILE);
24045
+ if (!existsSync10(file2)) return null;
23702
24046
  let all;
23703
24047
  try {
23704
24048
  all = JSON.parse(hostText(readFileSync9(file2, "utf8")));
@@ -23728,8 +24072,36 @@ function codexHookJournaled(db) {
23728
24072
  if (db === null) return false;
23729
24073
  return db.raw.prepare("SELECT 1 FROM events WHERE agent = ? LIMIT 1").get("codex") !== void 0;
23730
24074
  }
24075
+ function realDir(p) {
24076
+ try {
24077
+ return realpathSync7(p);
24078
+ } catch {
24079
+ return p;
24080
+ }
24081
+ }
24082
+ async function codexPluginTrust(i) {
24083
+ const home = i.codexConfigDir;
24084
+ const plugin = codexPluginHomeOf(i.bundleDir) !== null;
24085
+ const reply4 = await askPluginHooks({ ...i.env, CODEX_HOME: home }, CODEX_PLUGIN_ID, i.worktree ?? i.bundleDir);
24086
+ if (reply4.kind === "list") {
24087
+ const detail = untrustedPluginHooksDetail(reply4.hooks);
24088
+ if (detail !== void 0) return row("FAIL", detail, D5_CODEX_TRUST_FIX);
24089
+ }
24090
+ if (!plugin) return null;
24091
+ if (reply4.kind === "absent") return row("UNKNOWN", D5_CODEX_ABSENT_DETAIL(home), D5_CODEX_TRUST_FIX);
24092
+ if (reply4.kind === "silent") return row("FAIL", D5_CODEX_SILENT_DETAIL(home), D5_CODEX_TRUST_FIX);
24093
+ if (reply4.codexHome !== void 0 && !sameDir(realDir(reply4.codexHome), realDir(home))) {
24094
+ return row("FAIL", D5_CODEX_OTHER_HOME_DETAIL(reply4.codexHome, home), D5_CODEX_TRUST_FIX);
24095
+ }
24096
+ if (reply4.hooks.length === 0) return row("FAIL", D5_CODEX_NONE_DETAIL(home), D5_CODEX_TRUST_FIX);
24097
+ return null;
24098
+ }
23731
24099
  async function checkHookRoundTrip(i) {
23732
- if (i.agent === "codex" && existsSync9(path4.join(i.codexConfigDir, HOOKS_JSON_FILE)) && !codexHookJournaled(i.db)) {
24100
+ if (i.agent === "codex") {
24101
+ const trust = await codexPluginTrust(i);
24102
+ if (trust !== null) return trust;
24103
+ }
24104
+ if (i.agent === "codex" && existsSync10(path6.join(i.codexConfigDir, HOOKS_JSON_FILE)) && !codexHookJournaled(i.db)) {
23733
24105
  return row("UNKNOWN", D5_CODEX_UNTRUSTED_DETAIL);
23734
24106
  }
23735
24107
  const fixture = loadFixture(i.bundleDir, i.agent);
@@ -23748,7 +24120,7 @@ async function checkHookRoundTrip(i) {
23748
24120
  let ms = 0;
23749
24121
  for (let n = 1; n <= maxPairs; n++) {
23750
24122
  const start = now();
23751
- const r = await runProcess([process.execPath, path4.join(i.bundleDir, HOOK_ENTRY_FILE), AGENT_ARG, i.agent], {
24123
+ const r = await runProcess([process.execPath, path6.join(i.bundleDir, HOOK_ENTRY_FILE), AGENT_ARG, i.agent], {
23752
24124
  cwd: i.bundleDir,
23753
24125
  env: i.env,
23754
24126
  signal: i.signal,
@@ -23766,11 +24138,11 @@ async function checkHookRoundTrip(i) {
23766
24138
  }
23767
24139
 
23768
24140
  // src/core/ops/db-heal.ts
23769
- import { existsSync as existsSync10, rmSync as rmSync3 } from "node:fs";
24141
+ import { existsSync as existsSync11, rmSync as rmSync3 } from "node:fs";
23770
24142
 
23771
24143
  // src/core/store/owners.ts
23772
24144
  import { mkdirSync as mkdirSync4, readdirSync as readdirSync4, readFileSync as readFileSync10, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
23773
- import { basename as basename2, join as join12 } from "node:path";
24145
+ import { basename as basename3, join as join12 } from "node:path";
23774
24146
  function ownersDir(configDir, projectKey) {
23775
24147
  return join12(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
23776
24148
  }
@@ -23818,7 +24190,7 @@ function listLiveOwners(configDir, projectKey) {
23818
24190
  if (errCode2(err) === "ENOENT") continue;
23819
24191
  throw err;
23820
24192
  }
23821
- const serverId = basename2(name, OWNER_PID_EXT);
24193
+ const serverId = basename3(name, OWNER_PID_EXT);
23822
24194
  if (isLive(Number(text.trim()))) live.push(serverId);
23823
24195
  else rmSync2(file2, { force: true });
23824
24196
  }
@@ -23859,7 +24231,7 @@ function renameAside(dbPath) {
23859
24231
  const ts = String(Date.now());
23860
24232
  for (const suffix of DB_SIBLING_SUFFIXES) {
23861
24233
  const file2 = dbPath + suffix;
23862
- if (existsSync10(file2)) renameWithRetry(file2, file2 + HEAL_TS_SEP + ts + HEAL_BACKUP_SUFFIX);
24234
+ if (existsSync11(file2)) renameWithRetry(file2, file2 + HEAL_TS_SEP + ts + HEAL_BACKUP_SUFFIX);
23863
24235
  }
23864
24236
  return ts;
23865
24237
  }
@@ -23940,7 +24312,7 @@ async function guard(id, run) {
23940
24312
  }
23941
24313
  }
23942
24314
  async function codexDb(ctx, adapter) {
23943
- if (adapter.id !== "codex" || !existsSync11(ctx.project.dbPath)) return null;
24315
+ if (adapter.id !== "codex" || !existsSync12(ctx.project.dbPath)) return null;
23944
24316
  try {
23945
24317
  return await openDb(ctx.project, { readOnly: true });
23946
24318
  } catch {
@@ -23958,7 +24330,7 @@ async function hookRow(ctx, adapter, host) {
23958
24330
  env: buildChildEnv(host.env),
23959
24331
  signal: ctx.signal,
23960
24332
  codexConfigDir: codexDirOf(host.env, requireHomeDir(host.env)),
23961
- // same Codex dir D3 reads (D-N6-CODEX-HOME-2)
24333
+ // = codexRunDirOf: runDoctorChecks sets CODEX_HOME for codex (D-CODEX-HOME-RUN-1)
23962
24334
  db
23963
24335
  });
23964
24336
  const last2 = lastHookError(host.env);
@@ -23971,14 +24343,15 @@ async function hookRow(ctx, adapter, host) {
23971
24343
  }
23972
24344
  function ownServerId(configDir, projectKey) {
23973
24345
  const dir = join13(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
23974
- if (!existsSync11(dir)) return "";
24346
+ if (!existsSync12(dir)) return "";
23975
24347
  for (const name of readdirSync5(dir)) {
23976
24348
  if (!name.endsWith(OWNER_PID_EXT)) continue;
23977
- if (readFileSync11(join13(dir, name), "utf8").trim() === String(process.pid)) return basename3(name, OWNER_PID_EXT);
24349
+ if (readFileSync11(join13(dir, name), "utf8").trim() === String(process.pid)) return basename4(name, OWNER_PID_EXT);
23978
24350
  }
23979
24351
  return "";
23980
24352
  }
23981
- async function runDoctorChecks(ctx, adapter, host) {
24353
+ async function runDoctorChecks(ctx, adapter, host0) {
24354
+ const host = adapter.id === "codex" ? { ...host0, env: { ...host0.env, CODEX_HOME: codexRunDirOf(host0.env, homeDirOf(host0.env) ?? "", host0.bundleDir) } } : host0;
23982
24355
  const env = host.env;
23983
24356
  const project = ctx.project;
23984
24357
  let integrityFailed = false;
@@ -24020,7 +24393,7 @@ function reportEnv(env) {
24020
24393
  }
24021
24394
  async function handler2(_input, ctx) {
24022
24395
  const adapter = getAdapter(ctx.project.agent);
24023
- const host = { env: process.env, bundleDir: dirname6(process.argv[1]), piCwd: void 0 };
24396
+ const host = { env: process.env, bundleDir: dirname7(process.argv[1]), piCwd: void 0 };
24024
24397
  const rows = await runDoctorChecks(ctx, adapter, host);
24025
24398
  const command = `context-mode ${rows.some((r) => r.status === "FAIL") ? "setup" : "doctor"} --agents ${adapter.id}`;
24026
24399
  const input = { agent: adapter.id, rows, env: reportEnv(process.env), command };
@@ -24046,9 +24419,9 @@ var ctxDoctor = Object.freeze({
24046
24419
  });
24047
24420
 
24048
24421
  // src/core/tools/execute.ts
24049
- import { existsSync as existsSync12, mkdtempSync, rmSync as rmSync4, writeFileSync as writeFileSync3 } from "node:fs";
24422
+ import { existsSync as existsSync13, mkdtempSync, rmSync as rmSync4, writeFileSync as writeFileSync3 } from "node:fs";
24050
24423
  import { tmpdir as tmpdir2 } from "node:os";
24051
- import { dirname as dirname7, join as join14, parse as parse3, resolve as resolve5 } from "node:path";
24424
+ import { dirname as dirname8, join as join14, parse as parse3, resolve as resolve6 } from "node:path";
24052
24425
 
24053
24426
  // src/core/sandbox/win-build.ts
24054
24427
  var SEPARATORS2 = ";&|(\n";
@@ -24132,7 +24505,7 @@ function schemaLine(issue4) {
24132
24505
  }
24133
24506
  function fileError(given, abs, root) {
24134
24507
  let dir = abs;
24135
- while (!existsSync12(dir) && dirname7(dir) !== dir) dir = dirname7(dir);
24508
+ while (!existsSync13(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
24136
24509
  if (isInside(root, dir)) return null;
24137
24510
  return new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine();
24138
24511
  }
@@ -24170,12 +24543,14 @@ async function finish(input, ctx, r, exitCode, journal) {
24170
24543
  const fullBytes = Buffer.byteLength(combined, "utf8");
24171
24544
  const head = summaryLine(exitCode, fullBytes);
24172
24545
  const intent = input.intent ?? "";
24173
- const direct = head + "\n" + (input.summary === true ? echoBlock(input.language, input.code) + "\n" : "") + combined;
24174
- if (intent === "" && Buffer.byteLength(direct, "utf8") <= OUTPUT_CAP) {
24546
+ const bare2 = exitCode === 0 && input.summary !== true && combined !== "";
24547
+ const direct = (bare2 ? "" : head + "\n") + (input.summary === true ? echoBlock(input.language, input.code) + "\n" : "") + combined;
24548
+ const fits = Buffer.byteLength(head + "\n" + (input.summary === true ? echoBlock(input.language, input.code) + "\n" : "") + combined, "utf8") <= OUTPUT_CAP;
24549
+ if (intent === "" && fits) {
24175
24550
  return { text: direct, isError, sandboxBytes: fullBytes, journal };
24176
24551
  }
24177
24552
  const label = sourceLabel(input.code);
24178
- const budget = OUTPUT_CAP - Buffer.byteLength(head, "utf8") - 2 - moreReserve(intent, label);
24553
+ const budget = (fits ? OUTPUT_CAP : EXEC_PREVIEW_BYTES) - Buffer.byteLength(head, "utf8") - 2 - moreReserve(intent, label);
24179
24554
  const db = await openDb(ctx.project);
24180
24555
  let picked;
24181
24556
  try {
@@ -24194,7 +24569,7 @@ async function handler3(raw, ctx) {
24194
24569
  const cwd = ctx.project.worktree;
24195
24570
  const extra = { ...PLAIN_OUTPUT_ENV2 };
24196
24571
  if (input.file !== void 0) {
24197
- const abs = resolve5(cwd, input.file);
24572
+ const abs = resolve6(cwd, input.file);
24198
24573
  const bad = fileError(input.file, abs, ctx.project.containmentRoot);
24199
24574
  if (bad !== null) return fail5(bad);
24200
24575
  extra.CTX_FILE = abs;
@@ -24247,16 +24622,16 @@ var ctxExecute = {
24247
24622
  };
24248
24623
 
24249
24624
  // src/core/tools/index.ts
24250
- import { existsSync as existsSync13, readFileSync as readFileSync13, statSync as statSync6 } from "node:fs";
24251
- import { dirname as dirname8, extname, join as join16, relative as relative3, resolve as resolve6 } from "node:path";
24625
+ import { existsSync as existsSync14, readFileSync as readFileSync13, statSync as statSync7 } from "node:fs";
24626
+ import { dirname as dirname9, extname, join as join16, relative as relative3, resolve as resolve7 } from "node:path";
24252
24627
 
24253
24628
  // src/core/index/walk.ts
24254
- import { readdirSync as readdirSync6, readFileSync as readFileSync12, realpathSync as realpathSync6, statSync as statSync5 } from "node:fs";
24629
+ import { readdirSync as readdirSync6, readFileSync as readFileSync12, realpathSync as realpathSync8, statSync as statSync6 } from "node:fs";
24255
24630
  import { join as join15 } from "node:path";
24256
24631
  var GITIGNORE = ".gitignore";
24257
24632
  var GIT_DIR = ".git";
24258
24633
  function walkDir(root, containmentRoot) {
24259
- const real2 = realpathSync6(root);
24634
+ const real2 = realpathSync8(root);
24260
24635
  if (!isInside(containmentRoot, real2)) throw new CtxError("OUTSIDE_ROOT", { p: root, root: containmentRoot });
24261
24636
  const found = [];
24262
24637
  visit(real2, [], [], containmentRoot, /* @__PURE__ */ new Set([real2]), found);
@@ -24273,19 +24648,19 @@ function visit(abs, rel, parent, contain, seen, found) {
24273
24648
  const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join15(abs, GITIGNORE), rel)) : parent;
24274
24649
  for (const e of entries) {
24275
24650
  if (e.name === GIT_DIR) continue;
24276
- const path5 = join15(abs, e.name);
24651
+ const path7 = join15(abs, e.name);
24277
24652
  let isDir = e.isDirectory();
24278
24653
  let isFile = e.isFile();
24279
- let target = path5;
24654
+ let target = path7;
24280
24655
  if (e.isSymbolicLink()) {
24281
24656
  let resolved;
24282
24657
  try {
24283
- resolved = realpathSync6(path5);
24658
+ resolved = realpathSync8(path7);
24284
24659
  } catch {
24285
24660
  continue;
24286
24661
  }
24287
24662
  if (!isInside(contain, resolved)) continue;
24288
- const st = statSync5(resolved);
24663
+ const st = statSync6(resolved);
24289
24664
  isDir = st.isDirectory();
24290
24665
  isFile = st.isFile();
24291
24666
  target = resolved;
@@ -24293,12 +24668,12 @@ function visit(abs, rel, parent, contain, seen, found) {
24293
24668
  const segs = rel.concat(e.name);
24294
24669
  if (ignored(rules, segs, isDir)) continue;
24295
24670
  if (isFile) {
24296
- found.push({ dir: rel, name: e.name, absPath: path5 });
24671
+ found.push({ dir: rel, name: e.name, absPath: path7 });
24297
24672
  } else if (isDir) {
24298
- const key = e.isSymbolicLink() ? target : realpathSync6(path5);
24673
+ const key = e.isSymbolicLink() ? target : realpathSync8(path7);
24299
24674
  if (seen.has(key)) continue;
24300
24675
  seen.add(key);
24301
- visit(path5, segs, rules, contain, seen, found);
24676
+ visit(path7, segs, rules, contain, seen, found);
24302
24677
  }
24303
24678
  }
24304
24679
  }
@@ -24489,19 +24864,19 @@ function tlsName(host) {
24489
24864
  function request(u, conn, proxy, signal) {
24490
24865
  const host = bare(u.hostname);
24491
24866
  const port = u.port === "" ? defaultPort(u.protocol) : Number(u.port);
24492
- const path5 = u.pathname + u.search;
24493
- return new Promise((resolve7, reject) => {
24867
+ const path7 = u.pathname + u.search;
24868
+ return new Promise((resolve8, reject) => {
24494
24869
  const onErr = (err) => reject(fail6(causeCode(err)));
24495
24870
  if (proxy === void 0) {
24496
24871
  const mod = u.protocol === "https:" ? https : http;
24497
- const req = mod.request({ host: conn.address, port, path: path5, signal, servername: tlsName(host), headers: { host: u.host } });
24498
- req.on("response", resolve7).on("error", onErr).end();
24872
+ const req = mod.request({ host: conn.address, port, path: path7, signal, servername: tlsName(host), headers: { host: u.host } });
24873
+ req.on("response", resolve8).on("error", onErr).end();
24499
24874
  return;
24500
24875
  }
24501
24876
  const proxyHeaders = proxy.auth === void 0 ? {} : { "proxy-authorization": proxy.auth };
24502
24877
  if (u.protocol === "http:") {
24503
24878
  const req = http.request({ host: conn.address, port: conn.port, path: u.href, signal, headers: { host: u.host, ...proxyHeaders } });
24504
- req.on("response", resolve7).on("error", onErr).end();
24879
+ req.on("response", resolve8).on("error", onErr).end();
24505
24880
  return;
24506
24881
  }
24507
24882
  const authority = (isIP(host) === 6 ? "[" + host + "]" : host) + ":" + port;
@@ -24516,21 +24891,21 @@ function request(u, conn, proxy, signal) {
24516
24891
  const req = https.request({
24517
24892
  host,
24518
24893
  port,
24519
- path: path5,
24894
+ path: path7,
24520
24895
  signal,
24521
24896
  headers: { host: u.host },
24522
24897
  createConnection: () => tlsConnect({ socket, host, servername: tlsName(host) })
24523
24898
  });
24524
- req.on("response", resolve7).on("error", onErr).end();
24899
+ req.on("response", resolve8).on("error", onErr).end();
24525
24900
  });
24526
24901
  tunnel.end();
24527
24902
  });
24528
24903
  }
24529
24904
  function readBody(res) {
24530
- return new Promise((resolve7, reject) => {
24905
+ return new Promise((resolve8, reject) => {
24531
24906
  const parts = [];
24532
24907
  res.on("data", (b) => parts.push(b));
24533
- res.on("end", () => resolve7(Buffer.concat(parts)));
24908
+ res.on("end", () => resolve8(Buffer.concat(parts)));
24534
24909
  res.on("error", (err) => reject(fail6(causeCode(err))));
24535
24910
  res.on("aborted", () => reject(fail6("ECONNRESET")));
24536
24911
  });
@@ -28403,23 +28778,23 @@ function readUtf8(absPath) {
28403
28778
  }
28404
28779
  function missingOrOutside(given, abs, root) {
28405
28780
  let dir = abs;
28406
- while (!existsSync13(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
28781
+ while (!existsSync14(dir) && dirname9(dir) !== dir) dir = dirname9(dir);
28407
28782
  if (dir !== abs && isInside(root, dir)) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
28408
28783
  return new CtxError("OUTSIDE_ROOT", { p: given, root });
28409
28784
  }
28410
28785
  function pathItems(input, project) {
28411
- const abs = resolve6(project.worktree, input.path);
28786
+ const abs = resolve7(project.worktree, input.path);
28412
28787
  if (!isInside(project.containmentRoot, abs)) throw missingOrOutside(input.path, abs, project.containmentRoot);
28413
28788
  const base = relative3(project.worktree, abs);
28414
- if (statSync6(abs).isDirectory()) {
28789
+ if (statSync7(abs).isDirectory()) {
28415
28790
  return walkDir(abs, project.containmentRoot).map((f) => ({
28416
28791
  sourceKind: "path",
28417
- label: join16(base, f.relPath),
28792
+ label: pathLabel(join16(base, f.relPath)),
28418
28793
  kind: kindOfPath(f.relPath),
28419
28794
  read: () => readUtf8(f.absPath)
28420
28795
  }));
28421
28796
  }
28422
- return [{ sourceKind: "path", label: base === "" ? input.path : base, kind: kindOfPath(abs), read: () => readUtf8(abs) }];
28797
+ return [{ sourceKind: "path", label: pathLabel(base === "" ? input.path : base), kind: kindOfPath(abs), read: () => readUtf8(abs) }];
28423
28798
  }
28424
28799
  async function itemsOf(input, ctx) {
28425
28800
  if (input.content !== void 0) {
@@ -28430,7 +28805,7 @@ async function itemsOf(input, ctx) {
28430
28805
  }
28431
28806
  if (input.path !== void 0) {
28432
28807
  const items = pathItems({ ...input, path: input.path }, ctx.project);
28433
- return { items, from: items.length === 1 ? items[0].label : input.path };
28808
+ return { items, from: items.length === 1 ? items[0].label : pathLabel(input.path) };
28434
28809
  }
28435
28810
  const res = await safeFetch(input.url ?? "", AbortSignal.any([ctx.signal, AbortSignal.timeout(EXEC_TIMEOUT_MS)]));
28436
28811
  const text = res.body.toString("utf8");
@@ -28527,10 +28902,11 @@ function scopesOf(input) {
28527
28902
  function changes(raw, sql, ...args) {
28528
28903
  return Number(raw.prepare(sql).run(...args).changes);
28529
28904
  }
28530
- function purgeScope(raw, scope, input) {
28905
+ function purgeScope(db, scope, input) {
28906
+ const raw = db.raw;
28531
28907
  if (scope === "session") return changes(raw, "DELETE FROM events WHERE session_id = ?", input.session);
28532
28908
  if (scope === "source") {
28533
- const label = input.source;
28909
+ const label = storedLabel(db, input.source);
28534
28910
  return deleteChunkRows(raw, { label }) + changes(raw, "DELETE FROM sources WHERE label = ?", label);
28535
28911
  }
28536
28912
  const chunks = deleteChunkRows(raw, "all");
@@ -28548,7 +28924,7 @@ async function handler5(input, ctx) {
28548
28924
  try {
28549
28925
  const db = await openDb(ctx.project);
28550
28926
  try {
28551
- const rows = withWrite(db, (h) => purgeScope(h.raw, scope, input));
28927
+ const rows = withWrite(db, (h) => purgeScope(h, scope, input));
28552
28928
  return reply2(PURGE_SUMMARY(rows, scope), false);
28553
28929
  } finally {
28554
28930
  closeDb(db);
@@ -28670,12 +29046,12 @@ var ctxStats = Object.freeze({
28670
29046
  });
28671
29047
 
28672
29048
  // src/core/tools/upgrade.ts
28673
- import { existsSync as existsSync19, realpathSync as realpathSync7, rmSync as rmSync9 } from "node:fs";
28674
- import { basename as basename5, dirname as dirname10, join as join22 } from "node:path";
29049
+ import { existsSync as existsSync20, realpathSync as realpathSync9, rmSync as rmSync9 } from "node:fs";
29050
+ import { basename as basename6, dirname as dirname11, join as join22 } from "node:path";
28675
29051
 
28676
29052
  // src/core/ops/host-write.ts
28677
- import { copyFileSync, existsSync as existsSync14, mkdirSync as mkdirSync5, writeFileSync as writeFileSync4 } from "node:fs";
28678
- import { dirname as dirname9, join as join17 } from "node:path";
29053
+ import { copyFileSync, existsSync as existsSync15, mkdirSync as mkdirSync5, writeFileSync as writeFileSync4 } from "node:fs";
29054
+ import { dirname as dirname10, join as join17 } from "node:path";
28679
29055
  function defaultWrite(file2, text) {
28680
29056
  writeFileSync4(file2, text, "utf8");
28681
29057
  }
@@ -28703,8 +29079,8 @@ function toRow(file2, edit) {
28703
29079
  function writeWithRollback(file2, text, write2, atomic) {
28704
29080
  const trash = file2 + UPGRADE_TRASH_SUFFIX;
28705
29081
  const tmp = `${file2}${HOST_CONFIG_TMP_SUFFIX}.${process.pid}`;
28706
- const had = existsSync14(file2);
28707
- mkdirSync5(dirname9(file2), { recursive: true });
29082
+ const had = existsSync15(file2);
29083
+ mkdirSync5(dirname10(file2), { recursive: true });
28708
29084
  if (had) copyFileSync(file2, trash);
28709
29085
  try {
28710
29086
  write2(tmp, text);
@@ -28733,7 +29109,7 @@ function regenerateHostConfig(row5, home, opts = {}) {
28733
29109
  if (requested === null) return [];
28734
29110
  const current = readHostConfig(row5.id, requested);
28735
29111
  const result = mergeOwnEntries(row5.id, current.text, current.format, row5);
28736
- const exists = existsSync14(current.path);
29112
+ const exists = existsSync15(current.path);
28737
29113
  if (exists && result.text === current.text) return [];
28738
29114
  const text = result.text === "" && current.format !== "toml" ? JSON.stringify({}) : result.text;
28739
29115
  writeWithRollback(current.path, current.layout === void 0 ? text : withLayout(text, current.layout), opts.write ?? defaultWrite, opts.atomic ?? {});
@@ -28741,15 +29117,15 @@ function regenerateHostConfig(row5, home, opts = {}) {
28741
29117
  }
28742
29118
 
28743
29119
  // src/core/ops/plugin-swap.ts
28744
- import { existsSync as existsSync15, lstatSync, readdirSync as readdirSync7, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
28745
- import { basename as basename4, join as join18, win32 as win322 } from "node:path";
28746
- function linkTarget(path5, win) {
28747
- if (!isLink(path5)) return null;
28748
- const target = readlinkSync(path5);
29120
+ import { existsSync as existsSync16, lstatSync, readdirSync as readdirSync7, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
29121
+ import { basename as basename5, join as join18, win32 as win322 } from "node:path";
29122
+ function linkTarget(path7, win) {
29123
+ if (!isLink(path7)) return null;
29124
+ const target = readlinkSync(path7);
28749
29125
  return win ? win322.basename(target) : target;
28750
29126
  }
28751
- function isLink(path5) {
28752
- return lstatSync(path5, { throwIfNoEntry: false })?.isSymbolicLink() === true;
29127
+ function isLink(path7) {
29128
+ return lstatSync(path7, { throwIfNoEntry: false })?.isSymbolicLink() === true;
28753
29129
  }
28754
29130
  function generations(agentDir) {
28755
29131
  return readdirSync7(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();
@@ -28762,8 +29138,8 @@ function settleLinks(link, tmp, old, opts) {
28762
29138
  }
28763
29139
  function swapPluginCurrent(agentDir, sha, opts = {}) {
28764
29140
  const next = join18(agentDir, sha);
28765
- if (!existsSync15(next) || !lstatSync(next).isDirectory()) {
28766
- throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename4(agentDir), path: next });
29141
+ if (!existsSync16(next) || !lstatSync(next).isDirectory()) {
29142
+ throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename5(agentDir), path: next });
28767
29143
  }
28768
29144
  const link = join18(agentDir, PLUGIN_CURRENT_LINK);
28769
29145
  const tmp = link + PLUGIN_LINK_TMP_SUFFIX;
@@ -28782,12 +29158,12 @@ function swapPluginCurrent(agentDir, sha, opts = {}) {
28782
29158
  if (before !== null) keep.add(before);
28783
29159
  const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join18(agentDir, name));
28784
29160
  for (const dir of removed) rmSync5(dir, { recursive: true, force: true });
28785
- const previous = before !== null && existsSync15(join18(agentDir, before)) ? join18(agentDir, before) : null;
29161
+ const previous = before !== null && existsSync16(join18(agentDir, before)) ? join18(agentDir, before) : null;
28786
29162
  return { current: next, previous, removed };
28787
29163
  }
28788
29164
 
28789
29165
  // src/core/ops/release-fetch.ts
28790
- import { existsSync as existsSync16, mkdirSync as mkdirSync6, rmSync as rmSync6 } from "node:fs";
29166
+ import { existsSync as existsSync17, mkdirSync as mkdirSync6, rmSync as rmSync6 } from "node:fs";
28791
29167
  import { join as join19 } from "node:path";
28792
29168
  function failed(r) {
28793
29169
  if (r.exitCode === null && r.killed === null) return new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
@@ -28811,7 +29187,7 @@ async function fetchRelease(agent, url4, env, signal, opts = {}) {
28811
29187
  await git2(gitBin, [...GIT_CLONE_ARGS, RELEASE_BRANCH, url4, fetchDir], agentDir, childEnv, signal);
28812
29188
  const sha = await git2(gitBin, GIT_HEAD_SHA_ARGS, fetchDir, childEnv, signal);
28813
29189
  const dir = join19(agentDir, sha);
28814
- if (existsSync16(dir)) rmSync6(fetchDir, { recursive: true, force: true });
29190
+ if (existsSync17(dir)) rmSync6(fetchDir, { recursive: true, force: true });
28815
29191
  else renameWithRetry(fetchDir, dir, opts);
28816
29192
  return { sha, dir };
28817
29193
  } catch (e) {
@@ -28821,7 +29197,7 @@ async function fetchRelease(agent, url4, env, signal, opts = {}) {
28821
29197
  }
28822
29198
 
28823
29199
  // src/core/ops/uninstall.ts
28824
- import { existsSync as existsSync17, readdirSync as readdirSync8, rmSync as rmSync7, writeFileSync as writeFileSync5 } from "node:fs";
29200
+ import { existsSync as existsSync18, readdirSync as readdirSync8, rmSync as rmSync7, writeFileSync as writeFileSync5 } from "node:fs";
28825
29201
  import { join as join20 } from "node:path";
28826
29202
  function row2(area, before, after) {
28827
29203
  return { area, before, after };
@@ -28846,12 +29222,16 @@ function removeCache(adapter, env, configDir) {
28846
29222
  case "extension": {
28847
29223
  const root = rootOrNull(adapter, env);
28848
29224
  if (root === null) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
29225
+ if (adapter.installMode === "marketplace") {
29226
+ const cache = join20(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
29227
+ if (!isInside(cache, root) || isInside(root, cache)) return row2(UPGRADE_CACHE_AREA, root, UPGRADE_CACHE_BY_HAND);
29228
+ }
28849
29229
  rmSync7(root, { recursive: true, force: true });
28850
29230
  return row2(UPGRADE_CACHE_AREA, root, UPGRADE_REMOVED);
28851
29231
  }
28852
29232
  case "plugin": {
28853
29233
  const agentDir = join20(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
28854
- if (!existsSync17(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
29234
+ if (!existsSync18(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
28855
29235
  rmSync7(agentDir, { recursive: true, force: true });
28856
29236
  return row2(UPGRADE_CACHE_AREA, agentDir, UPGRADE_REMOVED);
28857
29237
  }
@@ -28864,11 +29244,11 @@ function removeCache(adapter, env, configDir) {
28864
29244
  }
28865
29245
  }
28866
29246
  }
28867
- function isObj2(v) {
29247
+ function isObj3(v) {
28868
29248
  return typeof v === "object" && v !== null && !Array.isArray(v);
28869
29249
  }
28870
29250
  function piSource(entry) {
28871
- return isObj2(entry) ? entry[PI_PACKAGE_SOURCE_KEY] : entry;
29251
+ return isObj3(entry) ? entry[PI_PACKAGE_SOURCE_KEY] : entry;
28872
29252
  }
28873
29253
  function ownEntries(agent, env) {
28874
29254
  const home = requireHomeDir(env);
@@ -28877,11 +29257,11 @@ function ownEntries(agent, env) {
28877
29257
  const top = mcp.key[0];
28878
29258
  const inner = mcp.key.slice(1, -1);
28879
29259
  const own4 = mcp.key[mcp.key.length - 1];
28880
- const holder = (v) => inner.reduce((cur, k) => isObj2(cur) ? cur[k] : void 0, v);
28881
- const without = (v, path5) => {
29260
+ const holder = (v) => inner.reduce((cur, k) => isObj3(cur) ? cur[k] : void 0, v);
29261
+ const without = (v, path7) => {
28882
29262
  const o = v;
28883
- if (path5.length === 0) return Object.fromEntries(Object.entries(o).filter(([k]) => k !== own4));
28884
- return { ...o, [path5[0]]: without(o[path5[0]], path5.slice(1)) };
29263
+ if (path7.length === 0) return Object.fromEntries(Object.entries(o).filter(([k]) => k !== own4));
29264
+ return { ...o, [path7[0]]: without(o[path7[0]], path7.slice(1)) };
28885
29265
  };
28886
29266
  return [{
28887
29267
  file: ownMcpFileOf(agent, mcp.file, env, home),
@@ -28889,7 +29269,7 @@ function ownEntries(agent, env) {
28889
29269
  shown: mcp.key.join(V1_KEY_PATH_SEP),
28890
29270
  has: (v) => {
28891
29271
  const h = holder(v);
28892
- return isObj2(h) && Object.hasOwn(h, own4);
29272
+ return isObj3(h) && Object.hasOwn(h, own4);
28893
29273
  },
28894
29274
  drop: (v) => without(v, inner)
28895
29275
  }];
@@ -28931,7 +29311,7 @@ function removeOwnEntries(agent, env) {
28931
29311
  function removeProjectData(configDir, projectKey) {
28932
29312
  const projects = join20(configDir, PROJECTS_DIR_NAME);
28933
29313
  const dir = join20(projects, projectKey);
28934
- if (!existsSync17(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
29314
+ if (!existsSync18(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
28935
29315
  if (dir === projects || !isInside(projects, dir)) throw new CtxError("OUTSIDE_ROOT", { p: dir, root: projects });
28936
29316
  for (const name of readdirSync8(dir)) {
28937
29317
  if (name !== OWNERS_DIR_NAME) rmSync7(join20(dir, name), { recursive: true, force: true });
@@ -28947,8 +29327,8 @@ function runUninstall(input) {
28947
29327
  }
28948
29328
 
28949
29329
  // src/core/ops/v1-remove.ts
28950
- import { copyFileSync as copyFileSync2, existsSync as existsSync18, readFileSync as readFileSync14, rmSync as rmSync8 } from "node:fs";
28951
- var isObj3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
29330
+ import { copyFileSync as copyFileSync2, existsSync as existsSync19, readFileSync as readFileSync14, rmSync as rmSync8 } from "node:fs";
29331
+ var isObj4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
28952
29332
  var areaOf = (f) => f.path === "" ? f.file : f.file + UPGRADE_AREA_KEY_SEP + f.path;
28953
29333
  var row3 = (f, after) => ({ area: areaOf(f), before: f.reason, after });
28954
29334
  function moveAside(target, undo) {
@@ -28977,17 +29357,17 @@ function cutTomlTable(text, header) {
28977
29357
  function writeAtomic(file2, text) {
28978
29358
  atomicWriteFile(file2, text);
28979
29359
  }
28980
- function locate(doc, path5) {
28981
- const segs = path5.split(V1_KEY_PATH_SEP);
29360
+ function locate(doc, path7) {
29361
+ const segs = path7.split(V1_KEY_PATH_SEP);
28982
29362
  let cur = doc;
28983
29363
  for (const seg of segs.slice(0, -1)) {
28984
29364
  if (Array.isArray(cur)) cur = cur[Number(seg)];
28985
- else if (isObj3(cur)) cur = cur[seg];
29365
+ else if (isObj4(cur)) cur = cur[seg];
28986
29366
  else return null;
28987
29367
  }
28988
29368
  const last2 = segs[segs.length - 1];
28989
29369
  if (Array.isArray(cur)) return Number(last2) < cur.length ? [cur, last2] : null;
28990
- if (isObj3(cur)) return Object.hasOwn(cur, last2) ? [cur, last2] : null;
29370
+ if (isObj4(cur)) return Object.hasOwn(cur, last2) ? [cur, last2] : null;
28991
29371
  return null;
28992
29372
  }
28993
29373
  function stripJsonEntries(agent, file2, findings, kept, undo) {
@@ -29028,14 +29408,14 @@ function removeV1(agent, findings) {
29028
29408
  for (const f of findings) {
29029
29409
  if (UPGRADE_REPORT_ONLY_REASONS.includes(f.reason)) done.set(f, UPGRADE_REPORT_ONLY);
29030
29410
  else if (f.path === "") {
29031
- if (existsSync18(f.file)) {
29411
+ if (existsSync19(f.file)) {
29032
29412
  moveAside(f.file, undo);
29033
29413
  done.set(f, UPGRADE_REMOVED);
29034
29414
  } else done.set(f, UPGRADE_NOT_FOUND);
29035
29415
  } else entries.set(f.file, [...entries.get(f.file) ?? [], f]);
29036
29416
  }
29037
29417
  for (const [file2, list4] of entries) {
29038
- if (!existsSync18(file2)) {
29418
+ if (!existsSync19(file2)) {
29039
29419
  for (const f of list4) done.set(f, UPGRADE_NOT_FOUND);
29040
29420
  continue;
29041
29421
  }
@@ -29068,7 +29448,7 @@ function removeV1(agent, findings) {
29068
29448
  },
29069
29449
  rollback() {
29070
29450
  for (const u of undo.splice(0).reverse()) {
29071
- if (!existsSync18(u.trash)) continue;
29451
+ if (!existsSync19(u.trash)) continue;
29072
29452
  rmSync8(u.target, { recursive: true, force: true });
29073
29453
  renameWithRetry(u.trash, u.target);
29074
29454
  }
@@ -29077,7 +29457,7 @@ function removeV1(agent, findings) {
29077
29457
  }
29078
29458
 
29079
29459
  // src/core/ops/verify-sums.ts
29080
- import { createHash } from "node:crypto";
29460
+ import { createHash as createHash2 } from "node:crypto";
29081
29461
  import { lstatSync as lstatSync2, readdirSync as readdirSync9, readFileSync as readFileSync15 } from "node:fs";
29082
29462
  import { join as join21 } from "node:path";
29083
29463
  function mismatch() {
@@ -29117,7 +29497,7 @@ function verifySums(dir) {
29117
29497
  for (const [rel, abs] of files) {
29118
29498
  const want = sums.get(rel);
29119
29499
  if (want === void 0) throw mismatch();
29120
- const got = createHash(SUMS_HASH_ALGORITHM).update(readFileSync15(abs)).digest(HASH_ENCODING);
29500
+ const got = createHash2(SUMS_HASH_ALGORITHM).update(readFileSync15(abs)).digest(HASH_ENCODING);
29121
29501
  if (got !== want) throw mismatch();
29122
29502
  }
29123
29503
  }
@@ -29131,7 +29511,7 @@ function row4(area, before, after) {
29131
29511
  return { area, before, after };
29132
29512
  }
29133
29513
  function bundleDir() {
29134
- return dirname10(process.argv[1] ?? "");
29514
+ return dirname11(process.argv[1] ?? "");
29135
29515
  }
29136
29516
  function pluginRootRow(adapter, env) {
29137
29517
  const own4 = bundleDir();
@@ -29146,11 +29526,11 @@ function pluginRootRow(adapter, env) {
29146
29526
  }
29147
29527
  function isCurrent(agentDir, dir) {
29148
29528
  const link = join22(agentDir, PLUGIN_CURRENT_LINK);
29149
- return existsSync19(link) && realpathSync7.native(link) === realpathSync7.native(dir);
29529
+ return existsSync20(link) && realpathSync9.native(link) === realpathSync9.native(dir);
29150
29530
  }
29151
29531
  async function checkout(adapter, deps) {
29152
29532
  const fetched = await fetchRelease(adapter.id, deps.releaseUrl, deps.env, deps.signal);
29153
- const agentDir = dirname10(fetched.dir);
29533
+ const agentDir = dirname11(fetched.dir);
29154
29534
  try {
29155
29535
  verifySums(fetched.dir);
29156
29536
  } catch (err) {
@@ -29178,7 +29558,7 @@ async function upgrade(adapter, deps, home) {
29178
29558
  return rows;
29179
29559
  } catch (err) {
29180
29560
  removal?.rollback();
29181
- if (done !== null && done.swap.previous !== null) swapPluginCurrent(done.agentDir, basename5(done.swap.previous));
29561
+ if (done !== null && done.swap.previous !== null) swapPluginCurrent(done.agentDir, basename6(done.swap.previous));
29182
29562
  throw err;
29183
29563
  }
29184
29564
  }
@@ -29266,8 +29646,8 @@ function checkCall(tool, input) {
29266
29646
 
29267
29647
  // src/entries/server.ts
29268
29648
  import { randomUUID } from "node:crypto";
29269
- import { existsSync as existsSync21, realpathSync as realpathSync9, rmSync as rmSync11 } from "node:fs";
29270
- import { dirname as dirname11, join as join24 } from "node:path";
29649
+ import { existsSync as existsSync22, realpathSync as realpathSync11, rmSync as rmSync11 } from "node:fs";
29650
+ import { dirname as dirname12, join as join24 } from "node:path";
29271
29651
  import { fileURLToPath as fileURLToPath2 } from "node:url";
29272
29652
 
29273
29653
  // node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
@@ -29564,10 +29944,10 @@ function mergeDefs(...defs) {
29564
29944
  function cloneDef(schema) {
29565
29945
  return mergeDefs(schema._zod.def);
29566
29946
  }
29567
- function getElementAtPath2(obj, path5) {
29568
- if (!path5)
29947
+ function getElementAtPath2(obj, path7) {
29948
+ if (!path7)
29569
29949
  return obj;
29570
- return path5.reduce((acc, key) => acc?.[key], obj);
29950
+ return path7.reduce((acc, key) => acc?.[key], obj);
29571
29951
  }
29572
29952
  function promiseAllObject2(promisesObj) {
29573
29953
  const keys = Object.keys(promisesObj);
@@ -29907,11 +30287,11 @@ function explicitlyAborted(x, startIndex = 0) {
29907
30287
  }
29908
30288
  return false;
29909
30289
  }
29910
- function prefixIssues2(path5, issues) {
30290
+ function prefixIssues2(path7, issues) {
29911
30291
  return issues.map((iss) => {
29912
30292
  var _a5;
29913
30293
  (_a5 = iss).path ?? (_a5.path = []);
29914
- iss.path.unshift(path5);
30294
+ iss.path.unshift(path7);
29915
30295
  return iss;
29916
30296
  });
29917
30297
  }
@@ -30372,16 +30752,16 @@ function flattenError2(error42, mapper = (issue4) => issue4.message) {
30372
30752
  }
30373
30753
  function formatError3(error42, mapper = (issue4) => issue4.message) {
30374
30754
  const fieldErrors = { _errors: [] };
30375
- const processError = (error43, path5 = []) => {
30755
+ const processError = (error43, path7 = []) => {
30376
30756
  for (const issue4 of error43.issues) {
30377
30757
  if (issue4.code === "invalid_union" && issue4.errors.length) {
30378
- issue4.errors.map((issues) => processError({ issues }, [...path5, ...issue4.path]));
30758
+ issue4.errors.map((issues) => processError({ issues }, [...path7, ...issue4.path]));
30379
30759
  } else if (issue4.code === "invalid_key") {
30380
- processError({ issues: issue4.issues }, [...path5, ...issue4.path]);
30760
+ processError({ issues: issue4.issues }, [...path7, ...issue4.path]);
30381
30761
  } else if (issue4.code === "invalid_element") {
30382
- processError({ issues: issue4.issues }, [...path5, ...issue4.path]);
30762
+ processError({ issues: issue4.issues }, [...path7, ...issue4.path]);
30383
30763
  } else {
30384
- const fullpath = [...path5, ...issue4.path];
30764
+ const fullpath = [...path7, ...issue4.path];
30385
30765
  if (fullpath.length === 0) {
30386
30766
  fieldErrors._errors.push(mapper(issue4));
30387
30767
  } else {
@@ -32746,7 +33126,7 @@ var recursive = /* @__PURE__ */ new WeakMap();
32746
33126
  var NONE3 = 0;
32747
33127
  var ASSUMED = 1;
32748
33128
  var PROVEN = 2;
32749
- function isRecursive(inst, stack, resolve7) {
33129
+ function isRecursive(inst, stack, resolve8) {
32750
33130
  const cached4 = recursive.get(inst);
32751
33131
  if (cached4 !== void 0)
32752
33132
  return cached4 ? PROVEN : NONE3;
@@ -32756,7 +33136,7 @@ function isRecursive(inst, stack, resolve7) {
32756
33136
  let result = NONE3;
32757
33137
  const check2 = (child) => {
32758
33138
  if (result !== PROVEN && child?._zod) {
32759
- const answer2 = isRecursive(child, stack, resolve7);
33139
+ const answer2 = isRecursive(child, stack, resolve8);
32760
33140
  if (answer2 > result)
32761
33141
  result = answer2;
32762
33142
  }
@@ -32767,7 +33147,7 @@ function isRecursive(inst, stack, resolve7) {
32767
33147
  const desc = Object.getOwnPropertyDescriptor(sh, key);
32768
33148
  if (spread && !desc.enumerable)
32769
33149
  continue;
32770
- const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve7) : NONE3;
33150
+ const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack, resolve8) : NONE3;
32771
33151
  if (child > answer2)
32772
33152
  answer2 = child;
32773
33153
  }
@@ -32831,7 +33211,7 @@ function isRecursive(inst, stack, resolve7) {
32831
33211
  break;
32832
33212
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
32833
33213
  case "lazy": {
32834
- const inner = def._cachedInner ?? (resolve7 ? inst._zod.innerType : void 0);
33214
+ const inner = def._cachedInner ?? (resolve8 ? inst._zod.innerType : void 0);
32835
33215
  merge5(inner ? isRecursive(inner, stack, false) : ASSUMED);
32836
33216
  break;
32837
33217
  }
@@ -37145,10 +37525,10 @@ function mergeDefs2(...defs) {
37145
37525
  function cloneDef2(schema) {
37146
37526
  return mergeDefs2(schema._zod.def);
37147
37527
  }
37148
- function getElementAtPath3(obj, path5) {
37149
- if (!path5)
37528
+ function getElementAtPath3(obj, path7) {
37529
+ if (!path7)
37150
37530
  return obj;
37151
- return path5.reduce((acc, key) => acc?.[key], obj);
37531
+ return path7.reduce((acc, key) => acc?.[key], obj);
37152
37532
  }
37153
37533
  function promiseAllObject3(promisesObj) {
37154
37534
  const keys = Object.keys(promisesObj);
@@ -37488,11 +37868,11 @@ function explicitlyAborted2(x, startIndex = 0) {
37488
37868
  }
37489
37869
  return false;
37490
37870
  }
37491
- function prefixIssues3(path5, issues) {
37871
+ function prefixIssues3(path7, issues) {
37492
37872
  return issues.map((iss) => {
37493
37873
  var _a5;
37494
37874
  (_a5 = iss).path ?? (_a5.path = []);
37495
- iss.path.unshift(path5);
37875
+ iss.path.unshift(path7);
37496
37876
  return iss;
37497
37877
  });
37498
37878
  }
@@ -37950,16 +38330,16 @@ function flattenError3(error42, mapper = (issue4) => issue4.message) {
37950
38330
  }
37951
38331
  function formatError4(error42, mapper = (issue4) => issue4.message) {
37952
38332
  const fieldErrors = { _errors: [] };
37953
- const processError = (error43, path5 = []) => {
38333
+ const processError = (error43, path7 = []) => {
37954
38334
  for (const issue4 of error43.issues) {
37955
38335
  if (issue4.code === "invalid_union" && issue4.errors.length) {
37956
- issue4.errors.map((issues) => processError({ issues }, [...path5, ...issue4.path]));
38336
+ issue4.errors.map((issues) => processError({ issues }, [...path7, ...issue4.path]));
37957
38337
  } else if (issue4.code === "invalid_key") {
37958
- processError({ issues: issue4.issues }, [...path5, ...issue4.path]);
38338
+ processError({ issues: issue4.issues }, [...path7, ...issue4.path]);
37959
38339
  } else if (issue4.code === "invalid_element") {
37960
- processError({ issues: issue4.issues }, [...path5, ...issue4.path]);
38340
+ processError({ issues: issue4.issues }, [...path7, ...issue4.path]);
37961
38341
  } else {
37962
- const fullpath = [...path5, ...issue4.path];
38342
+ const fullpath = [...path7, ...issue4.path];
37963
38343
  if (fullpath.length === 0) {
37964
38344
  fieldErrors._errors.push(mapper(issue4));
37965
38345
  } else {
@@ -40275,7 +40655,7 @@ var recursive2 = /* @__PURE__ */ new WeakMap();
40275
40655
  var NONE4 = 0;
40276
40656
  var ASSUMED2 = 1;
40277
40657
  var PROVEN2 = 2;
40278
- function isRecursive2(inst, stack, resolve7) {
40658
+ function isRecursive2(inst, stack, resolve8) {
40279
40659
  const cached4 = recursive2.get(inst);
40280
40660
  if (cached4 !== void 0)
40281
40661
  return cached4 ? PROVEN2 : NONE4;
@@ -40285,7 +40665,7 @@ function isRecursive2(inst, stack, resolve7) {
40285
40665
  let result = NONE4;
40286
40666
  const check2 = (child) => {
40287
40667
  if (result !== PROVEN2 && child?._zod) {
40288
- const answer2 = isRecursive2(child, stack, resolve7);
40668
+ const answer2 = isRecursive2(child, stack, resolve8);
40289
40669
  if (answer2 > result)
40290
40670
  result = answer2;
40291
40671
  }
@@ -40296,7 +40676,7 @@ function isRecursive2(inst, stack, resolve7) {
40296
40676
  const desc = Object.getOwnPropertyDescriptor(sh, key);
40297
40677
  if (spread && !desc.enumerable)
40298
40678
  continue;
40299
- const child = desc.get ? ASSUMED2 : desc.value?._zod ? isRecursive2(desc.value, stack, resolve7) : NONE4;
40679
+ const child = desc.get ? ASSUMED2 : desc.value?._zod ? isRecursive2(desc.value, stack, resolve8) : NONE4;
40300
40680
  if (child > answer2)
40301
40681
  answer2 = child;
40302
40682
  }
@@ -40360,7 +40740,7 @@ function isRecursive2(inst, stack, resolve7) {
40360
40740
  break;
40361
40741
  // `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
40362
40742
  case "lazy": {
40363
- const inner = def._cachedInner ?? (resolve7 ? inst._zod.innerType : void 0);
40743
+ const inner = def._cachedInner ?? (resolve8 ? inst._zod.innerType : void 0);
40364
40744
  merge5(inner ? isRecursive2(inner, stack, false) : ASSUMED2);
40365
40745
  break;
40366
40746
  }
@@ -46175,9 +46555,9 @@ var rev2026Codec = {
46175
46555
  });
46176
46556
  const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta3);
46177
46557
  if (!parsed.success) for (const issue4 of parsed.error.issues) {
46178
- const path5 = issue4.path.map(String);
46179
- const key = path5.length > 0 ? path5.join(".") : "_meta";
46180
- if (path5.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue;
46558
+ const path7 = issue4.path.map(String);
46559
+ const key = path7.length > 0 ? path7.join(".") : "_meta";
46560
+ if (path7.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue;
46181
46561
  issues.push({
46182
46562
  key,
46183
46563
  problem: issue4.message
@@ -46504,29 +46884,29 @@ var PERMITTED_X_MCP_HEADER_TYPES = /* @__PURE__ */ new Set([
46504
46884
  function scanXMcpHeaderDeclarations(inputSchema) {
46505
46885
  const declarations = [];
46506
46886
  const seenLower = /* @__PURE__ */ new Map();
46507
- const visit2 = (node3, path5, reachable) => {
46887
+ const visit2 = (node3, path7, reachable) => {
46508
46888
  if (node3 === null || typeof node3 !== "object") return void 0;
46509
46889
  const schema = node3;
46510
46890
  if (X_MCP_HEADER_KEY in schema) {
46511
- if (!reachable || path5.length === 0) return `${pathName(path5)}: 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)`;
46891
+ 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)`;
46512
46892
  const raw = schema[X_MCP_HEADER_KEY];
46513
- if (typeof raw !== "string" || raw.length === 0) return `${pathName(path5)}: x-mcp-header MUST be a non-empty string`;
46514
- if (!RFC9110_TOKEN.test(raw)) return `${pathName(path5)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`;
46893
+ if (typeof raw !== "string" || raw.length === 0) return `${pathName(path7)}: x-mcp-header MUST be a non-empty string`;
46894
+ 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)`;
46515
46895
  const type = typeof schema.type === "string" ? schema.type : void 0;
46516
- if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path5)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? "<none>"}`;
46896
+ 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>"}`;
46517
46897
  const lower = raw.toLowerCase();
46518
46898
  const prior = seenLower.get(lower);
46519
46899
  if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`;
46520
46900
  seenLower.set(lower, raw);
46521
46901
  declarations.push({
46522
- path: path5,
46902
+ path: path7,
46523
46903
  headerName: raw,
46524
46904
  type
46525
46905
  });
46526
46906
  }
46527
46907
  const properties = schema.properties;
46528
46908
  if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) {
46529
- const fault$1 = visit2(child, [...path5, key], reachable);
46909
+ const fault$1 = visit2(child, [...path7, key], reachable);
46530
46910
  if (fault$1 !== void 0) return fault$1;
46531
46911
  }
46532
46912
  for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) {
@@ -46534,7 +46914,7 @@ function scanXMcpHeaderDeclarations(inputSchema) {
46534
46914
  if (sub === void 0) continue;
46535
46915
  const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub];
46536
46916
  for (const branch of branches) {
46537
- const fault$1 = visit2(branch, [...path5, `<${k}>`], false);
46917
+ const fault$1 = visit2(branch, [...path7, `<${k}>`], false);
46538
46918
  if (fault$1 !== void 0) return fault$1;
46539
46919
  }
46540
46920
  }
@@ -46574,8 +46954,8 @@ var OBJECT_VALUED_SUBSCHEMA_KEYWORDS = /* @__PURE__ */ new Set([
46574
46954
  "$defs",
46575
46955
  "definitions"
46576
46956
  ]);
46577
- function pathName(path5) {
46578
- return path5.length === 0 ? "<root>" : path5.join(".");
46957
+ function pathName(path7) {
46958
+ return path7.length === 0 ? "<root>" : path7.join(".");
46579
46959
  }
46580
46960
  var HEADER_MISMATCH_ERROR_CODE = -32020;
46581
46961
  var INBOUND_VALIDATION_LADDER = [
@@ -46864,7 +47244,7 @@ var PROPERTY_KEYS_BY_TYPE = {
46864
47244
  array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema])
46865
47245
  };
46866
47246
  var SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options);
46867
- function walkProperty(node3, path5, vendor, unsupported) {
47247
+ function walkProperty(node3, path7, vendor, unsupported) {
46868
47248
  if (!isJsonObject(node3)) return node3;
46869
47249
  const allowedKeys = typeof node3.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node3.type) ? PROPERTY_KEYS_BY_TYPE[node3.type] : void 0;
46870
47250
  if (allowedKeys === void 0) return node3;
@@ -46872,8 +47252,8 @@ function walkProperty(node3, path5, vendor, unsupported) {
46872
47252
  for (const [key, value] of Object.entries(node3)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value;
46873
47253
  else if (key === "pattern" && node3.type === "string" && typeof node3.format === "string") {
46874
47254
  if (!SUPPORTED_STRING_FORMATS.has(node3.format)) pruned[key] = value;
46875
- else if (typeof value !== "string" || !isLibraryFormatPattern(node3.format, value, vendor)) unsupported.push(`${path5}.${key}`);
46876
- } else unsupported.push(`${path5}.${key}`);
47255
+ else if (typeof value !== "string" || !isLibraryFormatPattern(node3.format, value, vendor)) unsupported.push(`${path7}.${key}`);
47256
+ } else unsupported.push(`${path7}.${key}`);
46877
47257
  return pruned;
46878
47258
  }
46879
47259
  function walkRequestedSchema(converted, vendor) {
@@ -46890,11 +47270,11 @@ function describeUnsupportedProperties(pruned, fallback) {
46890
47270
  const offenders = Object.entries(pruned.properties).filter(([, node3]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node3).success).map(([name]) => `properties.${name}`);
46891
47271
  return offenders.length > 0 ? offenders.join(", ") : fallback;
46892
47272
  }
46893
- function findDroppedConstraintPaths(original, parsed, path5 = "") {
46894
- if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path5}[${index}]`));
47273
+ function findDroppedConstraintPaths(original, parsed, path7 = "") {
47274
+ if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path7}[${index}]`));
46895
47275
  if (!isJsonObject(original) || !isJsonObject(parsed)) return [];
46896
47276
  return Object.entries(original).flatMap(([key, value]) => {
46897
- const childPath = path5 ? `${path5}.${key}` : key;
47277
+ const childPath = path7 ? `${path7}.${key}` : key;
46898
47278
  if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath];
46899
47279
  return findDroppedConstraintPaths(value, parsed[key], childPath);
46900
47280
  });
@@ -46964,14 +47344,14 @@ function inputRequiredRoundsExceededMessage(method, maxRounds) {
46964
47344
  return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`;
46965
47345
  }
46966
47346
  function sleep(ms, signal) {
46967
- return new Promise((resolve7, reject) => {
47347
+ return new Promise((resolve8, reject) => {
46968
47348
  if (signal?.aborted) {
46969
47349
  reject(signal.reason instanceof SdkError ? signal.reason : new SdkError(SdkErrorCode.RequestTimeout, String(signal.reason)));
46970
47350
  return;
46971
47351
  }
46972
47352
  const timer = setTimeout(() => {
46973
47353
  signal?.removeEventListener("abort", onAbort);
46974
- resolve7();
47354
+ resolve8();
46975
47355
  }, ms);
46976
47356
  const onAbort = () => {
46977
47357
  clearTimeout(timer);
@@ -47770,7 +48150,7 @@ var Protocol = class {
47770
48150
  const flowStartedAt = Date.now();
47771
48151
  let onAbort;
47772
48152
  let cleanupMessageId;
47773
- return new Promise((resolve7, reject) => {
48153
+ return new Promise((resolve8, reject) => {
47774
48154
  const earlyReject = (error42) => {
47775
48155
  reject(error42);
47776
48156
  };
@@ -47839,7 +48219,7 @@ var Protocol = class {
47839
48219
  }
47840
48220
  if (decoded.kind === "invalid") return reject(decoded.error);
47841
48221
  if (decoded.kind === "input_required") {
47842
- if (options?.allowInputRequired === true) return resolve7(manualInputRequiredValue(decoded));
48222
+ if (options?.allowInputRequired === true) return resolve8(manualInputRequiredValue(decoded));
47843
48223
  const flow = {
47844
48224
  codec,
47845
48225
  request: request2,
@@ -47851,11 +48231,11 @@ var Protocol = class {
47851
48231
  params
47852
48232
  }, resultSchema, legOptions)
47853
48233
  };
47854
- return resolve7(this._resolveNonCompleteResult(decoded, flow));
48234
+ return resolve8(this._resolveNonCompleteResult(decoded, flow));
47855
48235
  }
47856
48236
  const result = decoded.result;
47857
48237
  validateStandardSchema(resultSchema, result).then((parseResult) => {
47858
- if (parseResult.success) resolve7(parseResult.data);
48238
+ if (parseResult.success) resolve8(parseResult.data);
47859
48239
  else reject(new SdkError(SdkErrorCode.InvalidResult, `Invalid result for ${request2.method}: ${parseResult.error}`));
47860
48240
  }, reject);
47861
48241
  });
@@ -50771,7 +51151,7 @@ var require_compile = /* @__PURE__ */ __commonJSMin((exports) => {
50771
51151
  ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
50772
51152
  const schOrFunc = root.refs[ref];
50773
51153
  if (schOrFunc) return schOrFunc;
50774
- let _sch = resolve7.call(this, root, ref);
51154
+ let _sch = resolve8.call(this, root, ref);
50775
51155
  if (_sch === void 0) {
50776
51156
  const schema = (_a5 = root.localRefs) === null || _a5 === void 0 ? void 0 : _a5[ref];
50777
51157
  const { schemaId } = this.opts;
@@ -50797,7 +51177,7 @@ var require_compile = /* @__PURE__ */ __commonJSMin((exports) => {
50797
51177
  function sameSchemaEnv(s1, s2) {
50798
51178
  return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
50799
51179
  }
50800
- function resolve7(root, ref) {
51180
+ function resolve8(root, ref) {
50801
51181
  let sch;
50802
51182
  while (typeof (sch = this.refs[ref]) == "string") ref = sch;
50803
51183
  return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
@@ -50982,8 +51362,8 @@ var require_utils = /* @__PURE__ */ __commonJSMin((exports, module) => {
50982
51362
  for (let i = 0; i < str4.length; i++) if (str4[i] === token) ind++;
50983
51363
  return ind;
50984
51364
  }
50985
- function removeDotSegments(path5) {
50986
- let input = path5;
51365
+ function removeDotSegments(path7) {
51366
+ let input = path7;
50987
51367
  const output = [];
50988
51368
  let nextSlash = -1;
50989
51369
  let len = 0;
@@ -51136,8 +51516,8 @@ var require_schemes = /* @__PURE__ */ __commonJSMin((exports, module) => {
51136
51516
  wsComponent.secure = void 0;
51137
51517
  }
51138
51518
  if (wsComponent.resourceName) {
51139
- const [path5, query] = wsComponent.resourceName.split("?");
51140
- wsComponent.path = path5 && path5 !== "/" ? path5 : void 0;
51519
+ const [path7, query] = wsComponent.resourceName.split("?");
51520
+ wsComponent.path = path7 && path7 !== "/" ? path7 : void 0;
51141
51521
  wsComponent.query = query;
51142
51522
  wsComponent.resourceName = void 0;
51143
51523
  }
@@ -51247,7 +51627,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin((exports, module) => {
51247
51627
  else if (typeof uri === "object") uri = parse6(serialize(uri, options), options);
51248
51628
  return uri;
51249
51629
  }
51250
- function resolve7(baseURI, relativeURI, options) {
51630
+ function resolve8(baseURI, relativeURI, options) {
51251
51631
  const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
51252
51632
  const resolved = resolveComponent(parse6(baseURI, schemelessOptions), parse6(relativeURI, schemelessOptions), schemelessOptions, true);
51253
51633
  schemelessOptions.skipEscape = true;
@@ -51421,7 +51801,7 @@ var require_fast_uri = /* @__PURE__ */ __commonJSMin((exports, module) => {
51421
51801
  const fastUri = {
51422
51802
  SCHEMES,
51423
51803
  normalize: normalize2,
51424
- resolve: resolve7,
51804
+ resolve: resolve8,
51425
51805
  resolveComponent,
51426
51806
  equal,
51427
51807
  serialize,
@@ -56886,7 +57266,7 @@ var StdioServerTransport = class {
56886
57266
  }
56887
57267
  send(message3) {
56888
57268
  if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed"));
56889
- return new Promise((resolve7, reject) => {
57269
+ return new Promise((resolve8, reject) => {
56890
57270
  const json2 = serializeMessage(message3);
56891
57271
  let settled = false;
56892
57272
  const onError = (error42) => {
@@ -56901,14 +57281,14 @@ var StdioServerTransport = class {
56901
57281
  settled = true;
56902
57282
  this._stdout.off("error", onError);
56903
57283
  this._stdout.off("drain", onDrain);
56904
- resolve7();
57284
+ resolve8();
56905
57285
  };
56906
57286
  this._stdout.once("error", onError);
56907
57287
  if (this._stdout.write(json2)) {
56908
57288
  if (settled) return;
56909
57289
  settled = true;
56910
57290
  this._stdout.off("error", onError);
56911
- resolve7();
57291
+ resolve8();
56912
57292
  } else if (!settled) this._stdout.once("drain", onDrain);
56913
57293
  });
56914
57294
  }
@@ -56962,14 +57342,14 @@ var StdioConnectionChannel = class {
56962
57342
  */
56963
57343
  async whenRequestsAnswered(timeoutMs) {
56964
57344
  if (this._closed || this._pendingRequests.size === 0) return true;
56965
- return await new Promise((resolve7) => {
57345
+ return await new Promise((resolve8) => {
56966
57346
  const waiter = () => {
56967
57347
  clearTimeout(timer);
56968
- resolve7(true);
57348
+ resolve8(true);
56969
57349
  };
56970
57350
  const timer = setTimeout(() => {
56971
57351
  this._drainWaiters = this._drainWaiters.filter((pending) => pending !== waiter);
56972
- resolve7(false);
57352
+ resolve8(false);
56973
57353
  }, timeoutMs);
56974
57354
  this._drainWaiters.push(waiter);
56975
57355
  });
@@ -57332,7 +57712,7 @@ function installExitGuard(opts) {
57332
57712
  }
57333
57713
 
57334
57714
  // src/core/store/cleanup.ts
57335
- import { existsSync as existsSync20, readdirSync as readdirSync10, rmSync as rmSync10 } from "node:fs";
57715
+ import { existsSync as existsSync21, readdirSync as readdirSync10, rmSync as rmSync10 } from "node:fs";
57336
57716
  import { join as join23 } from "node:path";
57337
57717
  function deleteSource(raw, id) {
57338
57718
  raw.prepare("DELETE FROM sources WHERE id = ?").run(id);
@@ -57368,7 +57748,7 @@ function userVersion(raw) {
57368
57748
  return raw.prepare("PRAGMA user_version").get().user_version;
57369
57749
  }
57370
57750
  function openForSweep(dbPath, projectKey) {
57371
- if (!existsSync20(dbPath) && (existsSync20(dbPath + DB_WAL_SUFFIX) || existsSync20(dbPath + DB_SHM_SUFFIX))) {
57751
+ if (!existsSync21(dbPath) && (existsSync21(dbPath + DB_WAL_SUFFIX) || existsSync21(dbPath + DB_SHM_SUFFIX))) {
57372
57752
  throw new CtxError("DB_GONE");
57373
57753
  }
57374
57754
  const sqlite = process.getBuiltinModule("node:sqlite");
@@ -57422,12 +57802,12 @@ function sweepDeadProjects(configDir) {
57422
57802
  }
57423
57803
 
57424
57804
  // src/entries/is-entry.ts
57425
- import { realpathSync as realpathSync8 } from "node:fs";
57805
+ import { realpathSync as realpathSync10 } from "node:fs";
57426
57806
  function isEntry(main, argv1, self) {
57427
57807
  if (main !== void 0) return main;
57428
57808
  if (argv1 === void 0 || argv1 === "") return false;
57429
57809
  try {
57430
- return realpathSync8(argv1) === realpathSync8(self);
57810
+ return realpathSync10(argv1) === realpathSync10(self);
57431
57811
  } catch {
57432
57812
  return false;
57433
57813
  }
@@ -57503,7 +57883,7 @@ function workspaceFromMeta(meta3) {
57503
57883
  }
57504
57884
  function realOrSame(p) {
57505
57885
  try {
57506
- return realpathSync9.native(p);
57886
+ return realpathSync11.native(p);
57507
57887
  } catch {
57508
57888
  return p;
57509
57889
  }
@@ -57512,7 +57892,7 @@ function workspaceCwdOf(meta3, spawnCwd, script) {
57512
57892
  const fromHost = workspaceFromMeta(meta3);
57513
57893
  if (fromHost !== void 0) return fromHost;
57514
57894
  if (script === void 0 || script === "") return spawnCwd;
57515
- return realOrSame(spawnCwd) === realOrSame(dirname11(script)) ? "" : spawnCwd;
57895
+ return realOrSame(spawnCwd) === realOrSame(dirname12(script)) ? "" : spawnCwd;
57516
57896
  }
57517
57897
  function errorReply(err) {
57518
57898
  if (err instanceof CtxError) return { text: err.toLine(), isError: true, sandboxBytes: 0 };
@@ -57551,7 +57931,7 @@ async function startServer(argv, env) {
57551
57931
  opening.catch(() => pending.delete(project.dbPath));
57552
57932
  }
57553
57933
  const db = await opening;
57554
- if (!existsSync21(db.path)) throw new CtxError("DB_GONE");
57934
+ if (!existsSync22(db.path)) throw new CtxError("DB_GONE");
57555
57935
  return db;
57556
57936
  }
57557
57937
  function stopMarker(configDir, projectKey) {
@@ -57559,7 +57939,7 @@ async function startServer(argv, env) {
57559
57939
  }
57560
57940
  function stopRequested() {
57561
57941
  const configDir = resolveConfigDir(process.env);
57562
- return held.some((db) => existsSync21(stopMarker(configDir, db.projectKey)));
57942
+ return held.some((db) => existsSync22(stopMarker(configDir, db.projectKey)));
57563
57943
  }
57564
57944
  async function journal(project, ctx, name, reply4) {
57565
57945
  const db = await ownDb(project);
@@ -57666,7 +58046,7 @@ async function startServer(argv, env) {
57666
58046
  }
57667
58047
  installExitGuard({ onShutdown: shutdown, isTTY: process.stdin.isTTY === true });
57668
58048
  handle = serveStdio(createServer);
57669
- await new Promise((resolve7) => process.once("exit", () => resolve7()));
58049
+ await new Promise((resolve8) => process.once("exit", () => resolve8()));
57670
58050
  }
57671
58051
  if (isEntry(import.meta.main, process.argv[1], fileURLToPath2(import.meta.url))) {
57672
58052
  const [, , ...cliArgs] = process.argv;