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

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.
@@ -15,6 +15,7 @@ function prefixToolNames(text, prefix) {
15
15
  return out;
16
16
  }
17
17
  var OUTPUT_CAP = 16384;
18
+ var EXEC_PREVIEW_BYTES = 4096;
18
19
  var STATE_BUDGET = 2048;
19
20
  var RESUME_CAP = 2048;
20
21
  var REPORT_CAP = 4096;
@@ -188,7 +189,7 @@ var HOOK_P95_MS = 40;
188
189
  var HOOK_TIMEOUT_MS = 5e3;
189
190
  var IN_PROCESS_TIMEOUT_MS = 0;
190
191
  var PROJECT_KEY_HEX_LEN = 16;
191
- var SCHEMA_VERSION = 5;
192
+ var SCHEMA_VERSION = 6;
192
193
  var RETENTION_SIZE_CAP_BYTES = 524288e3;
193
194
  var PROJECTS_DIR_NAME = "projects";
194
195
  var DB_FILE_NAME = "context.db";
@@ -362,7 +363,7 @@ var DECISION_OPTION_KEY = "option";
362
363
  var DECISION_LABEL_JOIN = " | ";
363
364
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
364
365
  var RELEASE_BRANCH = "release";
365
- var BUNDLE_SHA = true ? "68e0af5aafeaa4c61af68ee8d8e347cddb887f81" : void 0;
366
+ var BUNDLE_SHA = true ? "baaa3149e881980288944e90179895fa6a2be13e" : void 0;
366
367
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
367
368
  var DOCTOR_LABEL = Object.freeze({
368
369
  D1: "version",
@@ -3145,10 +3146,10 @@ function readPluginAgent(claudeDir, type) {
3145
3146
  }
3146
3147
  return null;
3147
3148
  }
3148
- function readAgentFile(path5) {
3149
+ function readAgentFile(path7) {
3149
3150
  let text;
3150
3151
  try {
3151
- text = readFileSync(path5, "utf8");
3152
+ text = readFileSync(path7, "utf8");
3152
3153
  } catch {
3153
3154
  return null;
3154
3155
  }
@@ -3411,12 +3412,12 @@ function readUserDeny(projectDir, agent) {
3411
3412
  }
3412
3413
  return out;
3413
3414
  }
3414
- function tokenize(glob, path5) {
3415
+ function tokenize(glob, path7) {
3415
3416
  const toks = [];
3416
3417
  let i = 0;
3417
3418
  while (i < glob.length) {
3418
3419
  const c = glob[i];
3419
- if (c === "*" && path5 && glob[i + 1] === "*") {
3420
+ if (c === "*" && path7 && glob[i + 1] === "*") {
3420
3421
  const dir = glob[i + "**".length] === "/";
3421
3422
  toks.push({ t: dir ? "globstarDir" : "globstar" });
3422
3423
  i += dir ? "**/".length : "**".length;
@@ -3430,8 +3431,8 @@ function tokenize(glob, path5) {
3430
3431
  }
3431
3432
  return toks;
3432
3433
  }
3433
- function globMatch(glob, text, path5) {
3434
- const toks = tokenize(glob, path5);
3434
+ function globMatch(glob, text, path7) {
3435
+ const toks = tokenize(glob, path7);
3435
3436
  const n = text.length;
3436
3437
  let next = new Uint8Array(n + 1);
3437
3438
  next[n] = 1;
@@ -3447,10 +3448,10 @@ function globMatch(glob, text, path5) {
3447
3448
  cur[j] = has3 && ch === tok.c ? next[j + 1] : 0;
3448
3449
  break;
3449
3450
  case "any1":
3450
- cur[j] = has3 && !(path5 && ch === "/") ? next[j + 1] : 0;
3451
+ cur[j] = has3 && !(path7 && ch === "/") ? next[j + 1] : 0;
3451
3452
  break;
3452
3453
  case "star":
3453
- cur[j] = next[j] || (has3 && !(path5 && ch === "/") ? cur[j + 1] : 0);
3454
+ cur[j] = next[j] || (has3 && !(path7 && ch === "/") ? cur[j + 1] : 0);
3454
3455
  break;
3455
3456
  case "globstar":
3456
3457
  cur[j] = next[j] || (has3 ? cur[j + 1] : 0);
@@ -3530,8 +3531,8 @@ var READ_DENY_TEMPLATE = 'context-mode: {size}-byte file, over the one-read limi
3530
3531
  // src/core/policy/read-deny.ts
3531
3532
  var SIZE = "{size}";
3532
3533
  var PATH = "{path}";
3533
- function READ_DENY_MESSAGE(path5, size, prefix = "") {
3534
- return prefixToolNames(READ_DENY_TEMPLATE, prefix).split(SIZE).join(String(size)).split(PATH).join(path5);
3534
+ function READ_DENY_MESSAGE(path7, size, prefix = "") {
3535
+ return prefixToolNames(READ_DENY_TEMPLATE, prefix).split(SIZE).join(String(size)).split(PATH).join(path7);
3535
3536
  }
3536
3537
 
3537
3538
  // src/core/policy/decide.ts
@@ -4034,8 +4035,8 @@ function firstLine(file2) {
4034
4035
  return line === "" ? null : line;
4035
4036
  }
4036
4037
  function git(dir, args) {
4037
- const { spawnSync } = process.getBuiltinModule("node:child_process");
4038
- const r = spawnSync("git", args, { cwd: dir, shell: false, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
4038
+ const { spawnSync: spawnSync3 } = process.getBuiltinModule("node:child_process");
4039
+ const r = spawnSync3("git", args, { cwd: dir, shell: false, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
4039
4040
  if (r.error !== void 0 || r.status !== 0) throw new CtxError("NO_GIT_DIR", { path: dir });
4040
4041
  return r.stdout.split("\n").filter((l) => l !== "");
4041
4042
  }
@@ -4176,12 +4177,16 @@ CREATE VIRTUAL TABLE line_units USING fts5(
4176
4177
  ${FTS_TOKENIZE}
4177
4178
  );
4178
4179
  `;
4180
+ var DDL_V6 = `
4181
+ UPDATE sources SET label = replace(label, char(92), '/') WHERE kind = 'path' AND instr(label, char(92)) > 0;
4182
+ `;
4179
4183
  var MIGRATIONS = [
4180
4184
  { version: 1, sql: DDL },
4181
4185
  { version: 2, sql: DDL_V2 },
4182
4186
  { version: 3, sql: DDL_V3 },
4183
4187
  { version: 4, sql: DDL_V4 },
4184
- { version: 5, sql: DDL_V5 }
4188
+ { version: 5, sql: DDL_V5 },
4189
+ { version: 6, sql: DDL_V6 }
4185
4190
  ];
4186
4191
  function applyMigrations(db, fromVersion) {
4187
4192
  if (fromVersion === SCHEMA_VERSION2) return;
@@ -4235,9 +4240,9 @@ function readUserVersion(raw) {
4235
4240
  const row5 = raw.prepare("PRAGMA user_version").get();
4236
4241
  return row5.user_version;
4237
4242
  }
4238
- function createAtomically(sqlite, path5) {
4243
+ function createAtomically(sqlite, path7) {
4239
4244
  const { randomUUID } = process.getBuiltinModule("node:crypto");
4240
- const tmp = path5 + "." + randomUUID() + DB_TMP_SUFFIX;
4245
+ const tmp = path7 + "." + randomUUID() + DB_TMP_SUFFIX;
4241
4246
  try {
4242
4247
  const raw = new sqlite.DatabaseSync(tmp, { timeout: DB_TIMEOUT_MS });
4243
4248
  try {
@@ -4246,7 +4251,7 @@ function createAtomically(sqlite, path5) {
4246
4251
  raw.close();
4247
4252
  }
4248
4253
  try {
4249
- linkSync(tmp, path5);
4254
+ linkSync(tmp, path7);
4250
4255
  } catch (err) {
4251
4256
  if (err.code !== "EEXIST") throw err;
4252
4257
  }
@@ -4254,11 +4259,11 @@ function createAtomically(sqlite, path5) {
4254
4259
  for (const suffix of ["", DB_WAL_SUFFIX, DB_SHM_SUFFIX]) rmSync(tmp + suffix, { force: true });
4255
4260
  }
4256
4261
  }
4257
- function openWritable(sqlite, path5) {
4262
+ function openWritable(sqlite, path7) {
4258
4263
  let raw = null;
4259
4264
  try {
4260
- if (!existsSync2(path5)) createAtomically(sqlite, path5);
4261
- raw = new sqlite.DatabaseSync(path5, { timeout: DB_TIMEOUT_MS });
4265
+ if (!existsSync2(path7)) createAtomically(sqlite, path7);
4266
+ raw = new sqlite.DatabaseSync(path7, { timeout: DB_TIMEOUT_MS });
4262
4267
  applyMigrations(raw, readUserVersion(raw));
4263
4268
  return raw;
4264
4269
  } catch (err) {
@@ -4266,8 +4271,8 @@ function openWritable(sqlite, path5) {
4266
4271
  throw err;
4267
4272
  }
4268
4273
  }
4269
- function openReadOnly(sqlite, path5) {
4270
- const raw = new sqlite.DatabaseSync(path5, { timeout: DB_TIMEOUT_MS, readOnly: true });
4274
+ function openReadOnly(sqlite, path7) {
4275
+ const raw = new sqlite.DatabaseSync(path7, { timeout: DB_TIMEOUT_MS, readOnly: true });
4271
4276
  try {
4272
4277
  const found = readUserVersion(raw);
4273
4278
  if (found !== SCHEMA_VERSION) throw new CtxError("SCHEMA_STALE", { found, want: SCHEMA_VERSION });
@@ -4281,20 +4286,20 @@ async function openDb(project, opts) {
4281
4286
  if (isBelow(process.version, NODE_MIN)) throw new CtxError("NODE_TOO_OLD", { v: process.version });
4282
4287
  const sqlite = await loadSqlite();
4283
4288
  mkdirSync2(project.projectDir, { recursive: true });
4284
- const path5 = project.dbPath;
4285
- const sibling = existsSync2(path5 + DB_WAL_SUFFIX) || existsSync2(path5 + DB_SHM_SUFFIX);
4286
- if (sibling && !existsSync2(path5)) {
4289
+ const path7 = project.dbPath;
4290
+ const sibling = existsSync2(path7 + DB_WAL_SUFFIX) || existsSync2(path7 + DB_SHM_SUFFIX);
4291
+ if (sibling && !existsSync2(path7)) {
4287
4292
  throw new CtxError("DB_GONE");
4288
4293
  }
4289
4294
  try {
4290
4295
  let raw;
4291
4296
  if (opts?.readOnly === true) {
4292
- if (!existsSync2(path5)) openWritable(sqlite, path5).close();
4293
- raw = openReadOnly(sqlite, path5);
4297
+ if (!existsSync2(path7)) openWritable(sqlite, path7).close();
4298
+ raw = openReadOnly(sqlite, path7);
4294
4299
  } else {
4295
- raw = openWritable(sqlite, path5);
4300
+ raw = openWritable(sqlite, path7);
4296
4301
  }
4297
- return { raw, projectKey: project.projectKey, path: path5, ...opts?.readOnly === true ? { readOnly: true } : {} };
4302
+ return { raw, projectKey: project.projectKey, path: path7, ...opts?.readOnly === true ? { readOnly: true } : {} };
4298
4303
  } catch (err) {
4299
4304
  if (isCorrupt(err)) throw new CtxError("DB_CORRUPT");
4300
4305
  throw err;
@@ -6718,7 +6723,7 @@ function ftsQuery(db, q, scope, ctx, sessionId, limit, offset, source) {
6718
6723
  }
6719
6724
  return page2.map((e) => {
6720
6725
  const r = rows.get(Number(e.r.rid));
6721
- return { sourceId: Number(r.source_id), label: r.label, ord: Number(r.ord), snippet: highlight(r.body, q, SNIPPET_MAX_BYTES), score: e.s };
6726
+ 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 };
6722
6727
  });
6723
6728
  }
6724
6729
  var LIST = `
@@ -6887,17 +6892,29 @@ function parseSourceHandle(s) {
6887
6892
  }
6888
6893
  return n > 0 && sourceHandle(n) === s ? n : null;
6889
6894
  }
6895
+ function pathLabel(p) {
6896
+ return p.includes("\\") ? p.split("\\").join("/") : p;
6897
+ }
6898
+ function labelStored(db, label) {
6899
+ return stmt(db.raw, "SELECT 1 AS x FROM sources WHERE label = ? LIMIT 1").get(label) !== void 0;
6900
+ }
6901
+ function storedLabel(db, source) {
6902
+ if (labelStored(db, source)) return source;
6903
+ const canon = pathLabel(source);
6904
+ return canon !== source && labelStored(db, canon) ? canon : source;
6905
+ }
6890
6906
  function resolveSourceLabel(db, source) {
6891
6907
  const id2 = parseSourceHandle(source);
6892
6908
  if (id2 !== null) {
6893
6909
  const row5 = stmt(db.raw, "SELECT label FROM sources WHERE id = ?").get(id2);
6894
6910
  if (row5 !== void 0) return row5.label;
6895
6911
  }
6896
- if (stmt(db.raw, "SELECT 1 AS x FROM sources WHERE label = ? LIMIT 1").get(source) !== void 0) return source;
6897
- const prefix = source + LABEL_SUFFIX_SEP;
6912
+ const named = storedLabel(db, source);
6913
+ if (labelStored(db, named)) return named;
6914
+ const prefix = named + LABEL_SUFFIX_SEP;
6898
6915
  const rows = stmt(db.raw, "SELECT label FROM sources WHERE substr(label, 1, ?) = ? ORDER BY id DESC").all(prefix.length, prefix);
6899
6916
  for (const r of rows) {
6900
- if (r.label.lastIndexOf(LABEL_SUFFIX_SEP) === source.length) return r.label;
6917
+ if (r.label.lastIndexOf(LABEL_SUFFIX_SEP) === named.length) return r.label;
6901
6918
  }
6902
6919
  return source;
6903
6920
  }
@@ -7003,8 +7020,8 @@ function buildCandidates(rows, sessionId) {
7003
7020
  edits.set(r.path, { row: r, count: (edits.get(r.path)?.count ?? 0) + 1 });
7004
7021
  }
7005
7022
  const changedFiles = [];
7006
- for (const [path5, e] of edits) {
7007
- const c = make("changed_files", e.row, "edited " + path5 + " x" + e.count, e.count, path5);
7023
+ for (const [path7, e] of edits) {
7024
+ const c = make("changed_files", e.row, "edited " + path7 + " x" + e.count, e.count, path7);
7008
7025
  changedFiles.push({ ...c, editCount: e.count });
7009
7026
  }
7010
7027
  changedFiles.sort((a, b) => a.seq - b.seq);
@@ -9185,10 +9202,10 @@ function assignProp(target, prop, value) {
9185
9202
  configurable: true
9186
9203
  });
9187
9204
  }
9188
- function getElementAtPath(obj, path5) {
9189
- if (!path5)
9205
+ function getElementAtPath(obj, path7) {
9206
+ if (!path7)
9190
9207
  return obj;
9191
- return path5.reduce((acc, key) => acc?.[key], obj);
9208
+ return path7.reduce((acc, key) => acc?.[key], obj);
9192
9209
  }
9193
9210
  function promiseAllObject(promisesObj) {
9194
9211
  const keys = Object.keys(promisesObj);
@@ -9508,11 +9525,11 @@ function aborted(x, startIndex = 0) {
9508
9525
  }
9509
9526
  return false;
9510
9527
  }
9511
- function prefixIssues(path5, issues) {
9528
+ function prefixIssues(path7, issues) {
9512
9529
  return issues.map((iss) => {
9513
9530
  var _a;
9514
9531
  (_a = iss).path ?? (_a.path = []);
9515
- iss.path.unshift(path5);
9532
+ iss.path.unshift(path7);
9516
9533
  return iss;
9517
9534
  });
9518
9535
  }
@@ -9649,7 +9666,7 @@ function treeifyError(error40, _mapper) {
9649
9666
  return issue2.message;
9650
9667
  };
9651
9668
  const result = { errors: [] };
9652
- const processError = (error41, path5 = []) => {
9669
+ const processError = (error41, path7 = []) => {
9653
9670
  var _a, _b;
9654
9671
  for (const issue2 of error41.issues) {
9655
9672
  if (issue2.code === "invalid_union" && issue2.errors.length) {
@@ -9659,7 +9676,7 @@ function treeifyError(error40, _mapper) {
9659
9676
  } else if (issue2.code === "invalid_element") {
9660
9677
  processError({ issues: issue2.issues }, issue2.path);
9661
9678
  } else {
9662
- const fullpath = [...path5, ...issue2.path];
9679
+ const fullpath = [...path7, ...issue2.path];
9663
9680
  if (fullpath.length === 0) {
9664
9681
  result.errors.push(mapper(issue2));
9665
9682
  continue;
@@ -9689,9 +9706,9 @@ function treeifyError(error40, _mapper) {
9689
9706
  processError(error40);
9690
9707
  return result;
9691
9708
  }
9692
- function toDotPath(path5) {
9709
+ function toDotPath(path7) {
9693
9710
  const segs = [];
9694
- for (const seg of path5) {
9711
+ for (const seg of path7) {
9695
9712
  if (typeof seg === "number")
9696
9713
  segs.push(`[${seg}]`);
9697
9714
  else if (typeof seg === "symbol")
@@ -19897,19 +19914,19 @@ function readAutoMemory(project) {
19897
19914
  if (project.agent !== "claude-code") return [];
19898
19915
  const rows = [];
19899
19916
  for (const segs of CLAUDE_CODE_MEMORY_FILES) {
19900
- const path5 = join7(project.worktree, ...segs);
19901
- if (!isInside(project.worktree, path5)) continue;
19917
+ const path7 = join7(project.worktree, ...segs);
19918
+ if (!isInside(project.worktree, path7)) continue;
19902
19919
  try {
19903
- const st = statSync4(path5);
19920
+ const st = statSync4(path7);
19904
19921
  if (!st.isFile()) continue;
19905
19922
  rows.push({
19906
19923
  origin: "memory",
19907
19924
  ts: Math.trunc(st.mtimeMs),
19908
19925
  seq: null,
19909
19926
  sourceId: null,
19910
- path: path5,
19927
+ path: path7,
19911
19928
  label: segs.join("/"),
19912
- text: readFileSync5(path5, "utf8")
19929
+ text: readFileSync5(path7, "utf8")
19913
19930
  });
19914
19931
  } catch {
19915
19932
  }
@@ -20025,12 +20042,20 @@ function sourceBytes(db, ids) {
20025
20042
  }
20026
20043
  return out;
20027
20044
  }
20045
+ var LEAN_HITS = 3;
20046
+ function replyHits(hits, size) {
20047
+ if (hits.length === 0 || hits[0].full !== true) return Math.min(size, hits.length);
20048
+ let n = Math.min(LEAN_HITS, size, hits.length);
20049
+ while (n < size && n < hits.length && hits[n].full === true) n++;
20050
+ return n;
20051
+ }
20028
20052
  function relevance(db, given, scope, ctx) {
20029
20053
  const input = { ...given, queries: decisionQueries(given) };
20030
20054
  const offset = input.offset ?? 0;
20031
20055
  const size = pageSize(input);
20032
20056
  const fetched = input.queries.map((q) => page(db, q, input, scope, ctx, offset, 1));
20033
- const pages = fetched.map((h) => h.slice(0, size));
20057
+ const take = fetched.map((h) => replyHits(h, size));
20058
+ const pages = fetched.map((h, i) => h.slice(0, take[i]));
20034
20059
  if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source);
20035
20060
  const moreLine3 = (q, pos) => "More: " + callText([q], scope, input.source, "offset:" + pos);
20036
20061
  let reserve = 0;
@@ -20045,7 +20070,7 @@ function relevance(db, given, scope, ctx) {
20045
20070
  input.queries.forEach((q, qi) => {
20046
20071
  const hits = pages[qi];
20047
20072
  if (stopped) {
20048
- more.push(moreLine3(q, offset));
20073
+ more.push({ q, pos: offset });
20049
20074
  return;
20050
20075
  }
20051
20076
  const head = "Query " + JSON.stringify(q) + ":";
@@ -20083,10 +20108,14 @@ function relevance(db, given, scope, ctx) {
20083
20108
  lines.push(line);
20084
20109
  used += bytes2(line) + 1;
20085
20110
  }
20086
- if (cut >= 0) more.push(moreLine3(q, cut));
20087
- else if (fetched[qi].length > size) more.push(moreLine3(q, offset + size));
20111
+ if (cut >= 0) more.push({ q, pos: cut });
20112
+ else if (fetched[qi].length > take[qi]) more.push({ q, pos: offset + take[qi] });
20088
20113
  });
20089
- return reply(lines.concat(more).join("\n"), false);
20114
+ const moreLines = [];
20115
+ const byPos = /* @__PURE__ */ new Map();
20116
+ for (const m of more) byPos.set(m.pos, [...byPos.get(m.pos) ?? [], m.q]);
20117
+ for (const [pos, qs] of byPos) moreLines.push("More: " + callText(qs, scope, input.source, "offset:" + pos));
20118
+ return reply(lines.concat(moreLines).join("\n"), false);
20090
20119
  }
20091
20120
  function timelineLine(r) {
20092
20121
  const nl = r.text.indexOf("\n");
@@ -20226,6 +20255,7 @@ function indexCombined(db, ctx, label, ran, deadline, budgetBytes) {
20226
20255
  const chunks = chunkText(ran.map((r) => r.block).join(BLOCK_SEP), "text");
20227
20256
  const display = shown(chunks, ran.map((r) => r.head));
20228
20257
  const bodies = /* @__PURE__ */ new Map();
20258
+ const raw = /* @__PURE__ */ new Map();
20229
20259
  let total = 0;
20230
20260
  for (const c of chunks) total += c.bytes;
20231
20261
  let indexed = 0;
@@ -20246,7 +20276,10 @@ function indexCombined(db, ctx, label, ran, deadline, budgetBytes) {
20246
20276
  chunkCount: group.length,
20247
20277
  createdAt: Date.now()
20248
20278
  }, group);
20249
- for (const c of group) bodies.set(chunkKey(id2, c.ord), display[c.ord]);
20279
+ for (const c of group) {
20280
+ bodies.set(chunkKey(id2, c.ord), display[c.ord]);
20281
+ raw.set(chunkKey(id2, c.ord), c.text);
20282
+ }
20250
20283
  indexed += groupBytes;
20251
20284
  group = [];
20252
20285
  groupBytes = 0;
@@ -20255,15 +20288,15 @@ function indexCombined(db, ctx, label, ran, deadline, budgetBytes) {
20255
20288
  for (const c of chunks) {
20256
20289
  if (queued + c.bytes > budgetBytes) {
20257
20290
  const stop2 = flush() ? "budget" : "deadline";
20258
- return { bodies, indexed, total, stop: stop2 };
20291
+ return { bodies, raw, indexed, total, stop: stop2 };
20259
20292
  }
20260
- if (group.length > 0 && groupBytes + c.bytes > INDEX_WRITE_CHUNK && !flush()) return { bodies, indexed, total, stop: "deadline" };
20293
+ if (group.length > 0 && groupBytes + c.bytes > INDEX_WRITE_CHUNK && !flush()) return { bodies, raw, indexed, total, stop: "deadline" };
20261
20294
  group.push(c);
20262
20295
  groupBytes += c.bytes;
20263
20296
  queued += c.bytes;
20264
20297
  }
20265
20298
  const stop = flush() ? null : "deadline";
20266
- return { bodies, indexed, total, stop };
20299
+ return { bodies, raw, indexed, total, stop };
20267
20300
  }
20268
20301
  function bytes3(s) {
20269
20302
  return Buffer.byteLength(s, "utf8");
@@ -20296,7 +20329,7 @@ function answer(db, ctx, label, queries, share, own2) {
20296
20329
  else if (body.length === 0) body.push("No new section.");
20297
20330
  lines.push(head, ...body);
20298
20331
  }
20299
- return lines;
20332
+ return { lines, seen };
20300
20333
  }
20301
20334
  async function runBatch(input, ctx, boundMs, budgetBytes) {
20302
20335
  const parsed = ctxBatchSchema.safeParse(input);
@@ -20317,9 +20350,10 @@ async function runBatch(input, ctx, boundMs, budgetBytes) {
20317
20350
  const db = await openDb(ctx.project);
20318
20351
  let sections;
20319
20352
  let idx;
20320
- const summary = commands.length + " command(s), " + queries.length + " querie(s), exit " + last2.exitCode;
20353
+ const exitLine = last2.exitCode === null || last2.exitCode === 0 ? null : "exit " + last2.exitCode;
20321
20354
  const footer = "more: ctx_search({queries:[...], source:" + JSON.stringify(label) + "})";
20322
20355
  let notice;
20356
+ let showMore;
20323
20357
  try {
20324
20358
  idx = indexCombined(db, ctx, label, ran, deadline, budgetBytes);
20325
20359
  const stop = last2.error;
@@ -20327,13 +20361,21 @@ async function runBatch(input, ctx, boundMs, budgetBytes) {
20327
20361
  const timeout = formatError("TIMEOUT", { ms: boundMs });
20328
20362
  const cause = stop ?? (ctx.signal.aborted ? CANCELLED_LINE : idx.stop === "deadline" ? timeout : null);
20329
20363
  notice = cut === null ? stop : cause === null ? cut : cause + " " + cut;
20330
- const fixed = bytes3(summary) + 1 + (notice === null ? 0 : bytes3(notice) + 1) + bytes3(footer);
20364
+ const fixed = (exitLine === null ? 0 : bytes3(exitLine) + 1) + (notice === null ? 0 : bytes3(notice) + 1) + bytes3(footer);
20331
20365
  const share = Math.floor((OUTPUT_CAP - fixed) / queries.length);
20332
- sections = answer(db, ctx, label, queries, share, idx.bodies);
20366
+ const answered = answer(db, ctx, label, queries, share, idx.bodies);
20367
+ sections = answered.lines;
20368
+ const unseen = [...idx.bodies].filter(([k, text]) => text !== "" && !answered.seen.has(k)).map(([k]) => idx.raw.get(k));
20369
+ const unseenBytes = unseen.reduce((n, t) => n + bytes3(t) + 1, 0);
20370
+ if (unseen.length === 0 && cut === null) showMore = false;
20371
+ else if (cut === null && unseenBytes <= bytes3(footer) + 1) {
20372
+ showMore = false;
20373
+ sections = [...sections, ...unseen.map((t) => t.endsWith(LINE_SEP) ? t.slice(0, -1) : t)];
20374
+ } else showMore = true;
20333
20375
  } finally {
20334
20376
  closeDb(db);
20335
20377
  }
20336
- const lines = [summary, ...notice === null ? [] : [notice], ...sections, footer];
20378
+ const lines = [...exitLine === null ? [] : [exitLine], ...notice === null ? [] : [notice], ...sections, ...showMore ? [footer] : []];
20337
20379
  return {
20338
20380
  text: capBytes(lines.join(LINE_SEP), OUTPUT_CAP).text,
20339
20381
  // step 10: final bound (D-M2-6)
@@ -20357,7 +20399,7 @@ var ctxBatch = Object.freeze({
20357
20399
  });
20358
20400
 
20359
20401
  // src/core/tools/doctor.ts
20360
- import { readdirSync as readdirSync5, readFileSync as readFileSync11, existsSync as existsSync11 } from "node:fs";
20402
+ import { readdirSync as readdirSync5, readFileSync as readFileSync11, existsSync as existsSync12 } from "node:fs";
20361
20403
  import { basename as basename3, dirname as dirname6, join as join13 } from "node:path";
20362
20404
 
20363
20405
  // src/core/ops/doctor-config.ts
@@ -22480,15 +22522,15 @@ function atomicWriteFile(file2, text, opts = {}) {
22480
22522
  }
22481
22523
 
22482
22524
  // src/core/ops/host-config.ts
22483
- function formatOf(path5) {
22484
- if (path5.endsWith(JSONC_EXT)) return "jsonc";
22485
- if (path5.endsWith(TOML_EXT)) return "toml";
22525
+ function formatOf(path7) {
22526
+ if (path7.endsWith(JSONC_EXT)) return "jsonc";
22527
+ if (path7.endsWith(TOML_EXT)) return "toml";
22486
22528
  return "json";
22487
22529
  }
22488
- function readHostConfig(agent, path5) {
22489
- let file2 = path5;
22530
+ function readHostConfig(agent, path7) {
22531
+ let file2 = path7;
22490
22532
  if (agent === "opencode") {
22491
- const jsonc = join8(dirname4(path5), OPENCODE_CONFIG_FILES[0]);
22533
+ const jsonc = join8(dirname4(path7), OPENCODE_CONFIG_FILES[0]);
22492
22534
  if (existsSync3(jsonc)) file2 = jsonc;
22493
22535
  }
22494
22536
  const raw = existsSync3(file2) ? readFileSync6(file2, "utf8") : "";
@@ -22652,14 +22694,14 @@ function scanToml(text) {
22652
22694
  continue;
22653
22695
  }
22654
22696
  if (!node.resolvedKey.every((seg) => typeof seg === "string")) continue;
22655
- const path5 = node.resolvedKey;
22656
- for (const kv of node.body) addKey(path5, kv);
22697
+ const path7 = node.resolvedKey;
22698
+ for (const kv of node.body) addKey(path7, kv);
22657
22699
  if (node.kind !== "standard") continue;
22658
22700
  const start = lineStartOf(text, node.range[0]);
22659
22701
  const headEnd = lineEndOf(text, node.key.range[1]);
22660
22702
  const last2 = node.body[node.body.length - 1];
22661
22703
  tables.push({
22662
- path: path5,
22704
+ path: path7,
22663
22705
  header: text.slice(start, text[headEnd - 1] === "\n" ? headEnd - 1 : headEnd),
22664
22706
  start,
22665
22707
  end: last2 === void 0 ? headEnd : lineEndOf(text, last2.range[1])
@@ -22670,16 +22712,16 @@ function scanToml(text) {
22670
22712
  function tomlTableSpans(text) {
22671
22713
  return scanToml(text).tables;
22672
22714
  }
22673
- function parseHostConfig(agent, path5, text, format) {
22715
+ function parseHostConfig(agent, path7, text, format) {
22674
22716
  try {
22675
22717
  return format === "toml" ? scanToml(text).value : scanJson(text, format).value;
22676
22718
  } catch {
22677
- throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path5, format });
22719
+ throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path7, format });
22678
22720
  }
22679
22721
  }
22680
- function hostConfigValueAt(value, path5) {
22722
+ function hostConfigValueAt(value, path7) {
22681
22723
  let cur = value;
22682
- for (const seg of path5) {
22724
+ for (const seg of path7) {
22683
22725
  if (!isPlainObject3(cur)) return void 0;
22684
22726
  cur = cur[seg];
22685
22727
  }
@@ -22712,32 +22754,32 @@ function indentUnit(root, clean) {
22712
22754
  function render(value, unit, base) {
22713
22755
  return JSON.stringify(value, null, unit).split("\n").join("\n" + base);
22714
22756
  }
22715
- function nest(path5, value) {
22757
+ function nest(path7, value) {
22716
22758
  let out = value;
22717
- for (let k = path5.length - 1; k >= 0; k -= 1) out = { [path5[k]]: out };
22759
+ for (let k = path7.length - 1; k >= 0; k -= 1) out = { [path7[k]]: out };
22718
22760
  return out;
22719
22761
  }
22720
- function setJsonText(text, format, path5, value) {
22762
+ function setJsonText(text, format, path7, value) {
22721
22763
  const doc = scanJson(text, format);
22722
22764
  const unit = indentUnit(doc.root, doc.clean);
22723
- if (doc.root === null) return render(nest(path5, value), unit, "") + "\n";
22765
+ if (doc.root === null) return render(nest(path7, value), unit, "") + "\n";
22724
22766
  let node = doc.root;
22725
22767
  let depth = 0;
22726
- while (depth < path5.length && node.kind === "object") {
22727
- const hit = node.members.find((m) => m.key === path5[depth]);
22768
+ while (depth < path7.length && node.kind === "object") {
22769
+ const hit = node.members.find((m) => m.key === path7[depth]);
22728
22770
  if (hit === void 0) break;
22729
22771
  node = hit.node;
22730
22772
  depth += 1;
22731
22773
  }
22732
- if (depth === path5.length) {
22774
+ if (depth === path7.length) {
22733
22775
  return text.slice(0, node.start) + render(value, unit, lineIndent(doc.clean, node.start)) + text.slice(node.end);
22734
22776
  }
22735
- if (node.kind !== "object") throw new SyntaxError("not an object at " + path5.slice(0, depth).join("."));
22736
- const rest = nest(path5.slice(depth + 1), value);
22777
+ if (node.kind !== "object") throw new SyntaxError("not an object at " + path7.slice(0, depth).join("."));
22778
+ const rest = nest(path7.slice(depth + 1), value);
22737
22779
  const last2 = node.members[node.members.length - 1];
22738
22780
  if (last2 === void 0) {
22739
22781
  const base2 = lineIndent(doc.clean, node.start);
22740
- const member2 = "\n" + base2 + unit + JSON.stringify(path5[depth]) + ": " + render(rest, unit, base2 + unit) + "\n" + base2;
22782
+ const member2 = "\n" + base2 + unit + JSON.stringify(path7[depth]) + ": " + render(rest, unit, base2 + unit) + "\n" + base2;
22741
22783
  return text.slice(0, node.start + 1) + member2 + text.slice(node.end - 1);
22742
22784
  }
22743
22785
  const base = lineIndent(doc.clean, last2.keyStart);
@@ -22745,7 +22787,7 @@ function setJsonText(text, format, path5, value) {
22745
22787
  while (" \r\n".includes(doc.clean[at2])) at2 += 1;
22746
22788
  const trailing = doc.clean[at2] === ",";
22747
22789
  const insertAt = trailing ? at2 + 1 : last2.node.end;
22748
- const member = (trailing ? "" : ",") + "\n" + base + JSON.stringify(path5[depth]) + ": " + render(rest, unit, base);
22790
+ const member = (trailing ? "" : ",") + "\n" + base + JSON.stringify(path7[depth]) + ": " + render(rest, unit, base);
22749
22791
  return text.slice(0, insertAt) + member + text.slice(insertAt);
22750
22792
  }
22751
22793
  function tomlScalar(v) {
@@ -22763,17 +22805,17 @@ function tomlHeaderKey(seg) {
22763
22805
  }
22764
22806
  return seg;
22765
22807
  }
22766
- function tomlBlock(path5, value) {
22767
- let out = "[" + path5.map(tomlHeaderKey).join(".") + "]\n";
22808
+ function tomlBlock(path7, value) {
22809
+ let out = "[" + path7.map(tomlHeaderKey).join(".") + "]\n";
22768
22810
  const subs = [];
22769
22811
  for (const [k, v] of Object.entries(value)) {
22770
- if (isPlainObject3(v)) subs.push(tomlBlock([...path5, k], v));
22812
+ if (isPlainObject3(v)) subs.push(tomlBlock([...path7, k], v));
22771
22813
  else out += tomlHeaderKey(k) + " = " + tomlScalar(v) + "\n";
22772
22814
  }
22773
22815
  return [out, ...subs].join("\n");
22774
22816
  }
22775
- function under(path5, prefix) {
22776
- return path5.length >= prefix.length && prefix.every((seg, k) => path5[k] === seg);
22817
+ function under(path7, prefix) {
22818
+ return path7.length >= prefix.length && prefix.every((seg, k) => path7[k] === seg);
22777
22819
  }
22778
22820
  function keyLineRange(text, k) {
22779
22821
  const ls = lineStartOf(text, k.start);
@@ -22790,10 +22832,10 @@ function withValueAt(root, rel, value) {
22790
22832
  else base[rel[0]] = next;
22791
22833
  return base;
22792
22834
  }
22793
- function replaceToml(text, doc, path5, value) {
22794
- const block = value === void 0 ? "" : tomlBlock(path5, value);
22795
- const owned = doc.tables.filter((t) => under(t.path, path5));
22796
- const cuts = doc.keys.filter((k) => under(k.full, path5) && !under(k.base, path5)).map((k) => [...keyLineRange(text, k), ""]);
22835
+ function replaceToml(text, doc, path7, value) {
22836
+ const block = value === void 0 ? "" : tomlBlock(path7, value);
22837
+ const owned = doc.tables.filter((t) => under(t.path, path7));
22838
+ const cuts = doc.keys.filter((k) => under(k.full, path7) && !under(k.base, path7)).map((k) => [...keyLineRange(text, k), ""]);
22797
22839
  owned.forEach((t, n) => cuts.push([t.start, t.end, n === 0 ? block : ""]));
22798
22840
  cuts.sort((a, b) => b[0] - a[0]);
22799
22841
  let out = text;
@@ -22803,27 +22845,27 @@ function replaceToml(text, doc, path5, value) {
22803
22845
  return out + sep4 + block;
22804
22846
  }
22805
22847
  var tableLike = (v) => v === void 0 || isPlainObject3(v);
22806
- function setTomlText(text, path5, value) {
22848
+ function setTomlText(text, path7, value) {
22807
22849
  if (value !== void 0 && !isPlainObject3(value)) throw new SyntaxError("TOML edits replace a whole table");
22808
22850
  const doc = scanToml(text);
22809
- const cur = hostConfigValueAt(doc.value, path5);
22851
+ const cur = hostConfigValueAt(doc.value, path7);
22810
22852
  if (sameValue(cur, value)) return text;
22811
- const inline = doc.keys.find((k) => k.inline && k.full.length < path5.length && under(path5, k.full));
22853
+ const inline = doc.keys.find((k) => k.inline && k.full.length < path7.length && under(path7, k.full));
22812
22854
  if (inline !== void 0) {
22813
- const whole = withValueAt(hostConfigValueAt(doc.value, inline.full), path5.slice(inline.full.length), value);
22855
+ const whole = withValueAt(hostConfigValueAt(doc.value, inline.full), path7.slice(inline.full.length), value);
22814
22856
  return replaceToml(text, doc, inline.full, whole);
22815
22857
  }
22816
22858
  if (isPlainObject3(cur) && isPlainObject3(value)) {
22817
22859
  const names = [.../* @__PURE__ */ new Set([...Object.keys(cur), ...Object.keys(value)])].filter((k) => !sameValue(cur[k], value[k]));
22818
22860
  if (names.every((k) => tableLike(cur[k]) && tableLike(value[k]))) {
22819
22861
  let out = text;
22820
- for (const k of names) out = setTomlText(out, [...path5, k], value[k]);
22862
+ for (const k of names) out = setTomlText(out, [...path7, k], value[k]);
22821
22863
  return out;
22822
22864
  }
22823
22865
  }
22824
- return replaceToml(text, doc, path5, value);
22866
+ return replaceToml(text, doc, path7, value);
22825
22867
  }
22826
- function setText(agent, path5, text, format, key, value) {
22868
+ function setText(agent, path7, text, format, key, value) {
22827
22869
  try {
22828
22870
  if (format !== "toml") return setJsonText(text, format, key, value);
22829
22871
  const out = setTomlText(text, key, value);
@@ -22832,7 +22874,7 @@ function setText(agent, path5, text, format, key, value) {
22832
22874
  if (!sameValue(landed, value) && !(emptyTable && landed === void 0)) throw new SyntaxError("edit did not land");
22833
22875
  return out;
22834
22876
  } catch {
22835
- throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path5, format });
22877
+ throw new CtxError("CONFIG_PARSE_FAILED", { agent, path: path7, format });
22836
22878
  }
22837
22879
  }
22838
22880
  function serverScript() {
@@ -22879,14 +22921,14 @@ function ownTargets(agent, accept) {
22879
22921
  if (agent === "pi") return [listTarget(PI_PACKAGES_KEY, PI_GIT_PACKAGE, V1_PI_PACKAGE)];
22880
22922
  return [];
22881
22923
  }
22882
- function applyEdits(agent, path5, text, format, wanted) {
22883
- const parsed = parseHostConfig(agent, path5, text, format);
22924
+ function applyEdits(agent, path7, text, format, wanted) {
22925
+ const parsed = parseHostConfig(agent, path7, text, format);
22884
22926
  let out = text;
22885
22927
  const edits = [];
22886
22928
  for (const [key, after] of wanted) {
22887
22929
  const before = hostConfigValueAt(parsed, key);
22888
22930
  if (sameValue(before, after)) continue;
22889
- out = setText(agent, path5, out, format, key, after);
22931
+ out = setText(agent, path7, out, format, key, after);
22890
22932
  edits.push({ path: key.join("."), before, after });
22891
22933
  }
22892
22934
  return { text: out, format, edits };
@@ -22907,7 +22949,7 @@ function writeHostConfigEdit(_requested, current, patch) {
22907
22949
  // src/core/ops/detect-v1.ts
22908
22950
  var isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
22909
22951
  var keyPath = (...parts) => parts.join(".");
22910
- var finding = (file2, path5, reason) => ({ file: file2, path: path5, reason });
22952
+ var finding = (file2, path7, reason) => ({ file: file2, path: path7, reason });
22911
22953
  function stripJsonc(text) {
22912
22954
  let out = "";
22913
22955
  let inStr = false;
@@ -23214,8 +23256,8 @@ function detectV1(agent, home, scope = {}) {
23214
23256
  import { existsSync as existsSync5, readdirSync as readdirSync2, readFileSync as readFileSync8, realpathSync as realpathSync4 } from "node:fs";
23215
23257
  import { dirname as dirname5, isAbsolute as isAbsolute2, join as join10, sep as sep3 } from "node:path";
23216
23258
  import { fileURLToPath } from "node:url";
23217
- function missing(agent, path5) {
23218
- return new CtxError("PLUGIN_ROOT_MISSING", { agent, path: path5 });
23259
+ function missing(agent, path7) {
23260
+ return new CtxError("PLUGIN_ROOT_MISSING", { agent, path: path7 });
23219
23261
  }
23220
23262
  function recordedInstallPaths(text) {
23221
23263
  let parsed;
@@ -23239,9 +23281,9 @@ function recordedInstallPaths(text) {
23239
23281
  }
23240
23282
  return out;
23241
23283
  }
23242
- var realOrNull = (path5) => {
23284
+ var realOrNull = (path7) => {
23243
23285
  try {
23244
- return realpathSync4.native(path5);
23286
+ return realpathSync4.native(path7);
23245
23287
  } catch {
23246
23288
  return null;
23247
23289
  }
@@ -23303,11 +23345,11 @@ function candidate(adapter, env) {
23303
23345
  }
23304
23346
  }
23305
23347
  function resolvePluginRoot(adapter, env) {
23306
- const path5 = candidate(adapter, env);
23348
+ const path7 = candidate(adapter, env);
23307
23349
  try {
23308
- return realpathSync4.native(path5);
23350
+ return realpathSync4.native(path7);
23309
23351
  } catch {
23310
- throw missing(adapter.id, path5);
23352
+ throw missing(adapter.id, path7);
23311
23353
  }
23312
23354
  }
23313
23355
 
@@ -23538,8 +23580,8 @@ async function loadSqlite2() {
23538
23580
  return null;
23539
23581
  }
23540
23582
  }
23541
- function openRead(sqlite, path5) {
23542
- return new sqlite.DatabaseSync(path5, { timeout: DB_TIMEOUT_MS, readOnly: true });
23583
+ function openRead(sqlite, path7) {
23584
+ return new sqlite.DatabaseSync(path7, { timeout: DB_TIMEOUT_MS, readOnly: true });
23543
23585
  }
23544
23586
  var cell = (row5) => Object.values(row5)[0];
23545
23587
  function readSchema(raw) {
@@ -23681,17 +23723,200 @@ function checkShell(env) {
23681
23723
  }
23682
23724
 
23683
23725
  // src/core/ops/doctor-hook.ts
23684
- import { existsSync as existsSync9, readFileSync as readFileSync9 } from "node:fs";
23726
+ import { existsSync as existsSync10, readFileSync as readFileSync9 } from "node:fs";
23727
+ import path6 from "node:path";
23728
+
23729
+ // src/setup/codex-trust.ts
23730
+ import { createHash } from "node:crypto";
23731
+ import { existsSync as existsSync9, realpathSync as realpathSync6 } from "node:fs";
23732
+ import path5 from "node:path";
23733
+ import { spawn as spawn2, spawnSync as spawnSync2 } from "node:child_process";
23734
+
23735
+ // src/setup/spawn-bin.ts
23736
+ import { spawnSync } from "node:child_process";
23737
+ import { accessSync as accessSync2, constants as fsc, statSync as statSync5 } from "node:fs";
23685
23738
  import path4 from "node:path";
23739
+ var WIN_EXT = ".COM;.EXE;.BAT;.CMD";
23740
+ var WIN_SHIM_EXTS = Object.freeze([".cmd", ".bat"]);
23741
+ var DEFAULT_COMSPEC = "cmd.exe";
23742
+ function envGet(env, k) {
23743
+ return env[Object.keys(env).find((x) => x.toUpperCase() === k) ?? k];
23744
+ }
23745
+ function whichBin(bin, env, platform = process.platform) {
23746
+ const get = (k) => envGet(env, k);
23747
+ const win = platform === "win32";
23748
+ const exts = win ? (get("PATHEXT") || WIN_EXT).split(";").filter(Boolean) : [""];
23749
+ const names = win && path4.extname(bin) ? [bin] : exts.map((e) => bin + e.toLowerCase());
23750
+ for (const dir of pathEntries(get("PATH") ?? "", platform)) {
23751
+ for (const n of names) {
23752
+ const f = path4.join(dir, n);
23753
+ try {
23754
+ accessSync2(f, fsc.X_OK);
23755
+ if (statSync5(f).isFile()) return f;
23756
+ } catch {
23757
+ }
23758
+ }
23759
+ }
23760
+ return void 0;
23761
+ }
23762
+ var CMD_QUOTE_CHARS = '"&|<>^()!';
23763
+ var CMD_PERCENT = "%";
23764
+ var CMD_SUBSTRING_MARK = ":";
23765
+ var CMD_DYNAMIC_VARS = Object.freeze(["CD", "DATE", "TIME", "RANDOM", "ERRORLEVEL", "CMDEXTVERSION", "CMDCMDLINE", "HIGHESTNUMANODENUMBER"]);
23766
+ function needsCmdQuotes(a) {
23767
+ if (a === "") return true;
23768
+ for (const c of a) if (c.trim() === "" || CMD_QUOTE_CHARS.includes(c)) return true;
23769
+ return false;
23770
+ }
23771
+ function expandablePercent(text, env) {
23772
+ const names = new Set(CMD_DYNAMIC_VARS);
23773
+ for (const k of Object.keys(env)) names.add(k.toUpperCase());
23774
+ for (let i = text.indexOf(CMD_PERCENT); i >= 0; i = text.indexOf(CMD_PERCENT, i + 1)) {
23775
+ for (let j = text.indexOf(CMD_PERCENT, i + 1); j >= 0; j = text.indexOf(CMD_PERCENT, j + 1)) {
23776
+ const inner = text.slice(i + 1, j);
23777
+ const cut = inner.indexOf(CMD_SUBSTRING_MARK);
23778
+ const name = cut < 0 ? inner : inner.slice(0, cut);
23779
+ if (name !== "" && names.has(name.toUpperCase())) return `${CMD_PERCENT}${inner}${CMD_PERCENT}`;
23780
+ }
23781
+ }
23782
+ return void 0;
23783
+ }
23784
+ function winCmdLine(file2, args, env = {}) {
23785
+ for (const a of [file2, ...args]) {
23786
+ const hit = expandablePercent(a, env);
23787
+ 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`);
23788
+ }
23789
+ const q = (a) => needsCmdQuotes(a) ? `"${a.split('"').join('""')}"` : a;
23790
+ return `"${[file2, ...args].map(q).join(" ")}"`;
23791
+ }
23792
+ function spawnForm(file2, args, env, platform = process.platform) {
23793
+ if (platform === "win32" && WIN_SHIM_EXTS.includes(path4.extname(file2).toLowerCase())) {
23794
+ return { command: envGet(env, "COMSPEC") || DEFAULT_COMSPEC, args: ["/d", "/v:off", "/s", "/c", winCmdLine(file2, args, env)], windowsVerbatimArguments: true };
23795
+ }
23796
+ return { command: file2, args, windowsVerbatimArguments: false };
23797
+ }
23798
+
23799
+ // src/setup/codex-trust.ts
23800
+ var isObj2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
23801
+ var TRUST_KEY = ["hooks", "state"];
23802
+ var CODEX_TRUST_PATH = TRUST_KEY.join(".") + ".";
23803
+ var LIST_TIMEOUT_MS = 15e3;
23804
+ var EXIT_GRACE_MS = 5e3;
23805
+ var PLUGIN_SOURCE = "plugin";
23806
+ var TRUSTED = "trusted";
23807
+ function pluginHooksFromReply(m, pluginId) {
23808
+ const out = [];
23809
+ if (!isObj2(m) || !isObj2(m.result) || !Array.isArray(m.result.data)) return out;
23810
+ for (const d of m.result.data) {
23811
+ if (!isObj2(d) || !Array.isArray(d.hooks)) continue;
23812
+ for (const h of d.hooks) {
23813
+ if (!isObj2(h) || h.source !== PLUGIN_SOURCE || h.pluginId !== pluginId) continue;
23814
+ if (typeof h.key !== "string" || typeof h.currentHash !== "string") continue;
23815
+ if (out.some((x) => x.key === h.key)) continue;
23816
+ out.push({ key: h.key, hash: h.currentHash, trusted: h.trustStatus === TRUSTED });
23817
+ }
23818
+ }
23819
+ return out;
23820
+ }
23821
+ function listPluginHooks(env, pluginId, cwd) {
23822
+ const bin = whichBin("codex", env);
23823
+ if (!bin) return Promise.resolve(void 0);
23824
+ return new Promise((resolve7) => {
23825
+ let f;
23826
+ try {
23827
+ f = spawnForm(bin, ["app-server"], env);
23828
+ } catch {
23829
+ resolve7(void 0);
23830
+ return;
23831
+ }
23832
+ const child = spawn2(f.command, f.args, { env, cwd, stdio: ["pipe", "pipe", "ignore"], windowsVerbatimArguments: f.windowsVerbatimArguments, windowsHide: true });
23833
+ let buf = "";
23834
+ let done = false;
23835
+ let exited = false;
23836
+ let result;
23837
+ const settle = () => {
23838
+ clearTimeout(grace);
23839
+ resolve7(result);
23840
+ };
23841
+ let grace;
23842
+ const finish2 = (v) => {
23843
+ if (done) return;
23844
+ done = true;
23845
+ clearTimeout(timer);
23846
+ result = v;
23847
+ child.stdin.destroy();
23848
+ if (exited) {
23849
+ settle();
23850
+ return;
23851
+ }
23852
+ grace = setTimeout(settle, EXIT_GRACE_MS);
23853
+ stopTree(child.pid, () => child.kill());
23854
+ };
23855
+ const timer = setTimeout(() => finish2(void 0), LIST_TIMEOUT_MS);
23856
+ const send = (o) => {
23857
+ try {
23858
+ child.stdin.write(JSON.stringify(o) + "\n");
23859
+ } catch {
23860
+ finish2(void 0);
23861
+ }
23862
+ };
23863
+ child.on("error", () => finish2(void 0));
23864
+ child.on("close", () => {
23865
+ exited = true;
23866
+ if (done) settle();
23867
+ else finish2(void 0);
23868
+ });
23869
+ child.stdin.on("error", () => finish2(void 0));
23870
+ child.stdout.setEncoding("utf8");
23871
+ child.stdout.on("data", (d) => {
23872
+ buf += d;
23873
+ const lines = buf.split("\n");
23874
+ buf = lines.pop() ?? "";
23875
+ for (const line of lines) {
23876
+ let m;
23877
+ try {
23878
+ m = JSON.parse(line);
23879
+ } catch {
23880
+ continue;
23881
+ }
23882
+ if (!isObj2(m)) continue;
23883
+ if (m.id === 1) {
23884
+ send({ method: "initialized" });
23885
+ send({ id: 2, method: "hooks/list", params: { cwds: [cwd] } });
23886
+ } else if (m.id === 2) finish2(pluginHooksFromReply(m, pluginId));
23887
+ }
23888
+ });
23889
+ send({ id: 1, method: "initialize", params: { clientInfo: { name: "context-mode-setup", version: "2.0.0" } } });
23890
+ });
23891
+ }
23892
+ function stopTree(pid, kill) {
23893
+ if (process.platform === "win32" && pid !== void 0) {
23894
+ try {
23895
+ spawnSync2("taskkill", ["/pid", String(pid), "/T", "/F"], { windowsHide: true, stdio: "ignore", timeout: 5e3 });
23896
+ } catch {
23897
+ }
23898
+ }
23899
+ kill();
23900
+ }
23901
+ var CODEX_PLUGIN_ID = `${SERVER_KEY}@${SERVER_KEY}`;
23902
+ var CODEX_UNTRUSTED_FIX = "run: context-mode setup";
23903
+ function untrustedPluginHooksDetail(hooks) {
23904
+ const bad = hooks.filter((h) => !h.trusted);
23905
+ if (!bad.length) return void 0;
23906
+ return `codex lists ${bad.length} of ${hooks.length} context-mode plugin hooks untrusted, so they do not run; ${CODEX_UNTRUSTED_FIX}`;
23907
+ }
23908
+
23909
+ // src/core/ops/doctor-hook.ts
23686
23910
  var D5_MIN_PAIRS = 3;
23687
23911
  var D5_MAX_PAIRS = 9;
23912
+ var D5_CODEX_TRUST_FIX = "context-mode setup --agents codex";
23688
23913
  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 };
23689
23914
  function isObject5(v) {
23690
23915
  return typeof v === "object" && v !== null && !Array.isArray(v);
23691
23916
  }
23692
23917
  function loadFixture(bundleDir2, agent) {
23693
- const file2 = path4.join(bundleDir2, HOOK_FIXTURE_DIR, HOOK_FIXTURE_FILE);
23694
- if (!existsSync9(file2)) return null;
23918
+ const file2 = path6.join(bundleDir2, HOOK_FIXTURE_DIR, HOOK_FIXTURE_FILE);
23919
+ if (!existsSync10(file2)) return null;
23695
23920
  let all;
23696
23921
  try {
23697
23922
  all = JSON.parse(hostText(readFileSync9(file2, "utf8")));
@@ -23722,7 +23947,12 @@ function codexHookJournaled(db) {
23722
23947
  return db.raw.prepare("SELECT 1 FROM events WHERE agent = ? LIMIT 1").get("codex") !== void 0;
23723
23948
  }
23724
23949
  async function checkHookRoundTrip(i) {
23725
- if (i.agent === "codex" && existsSync9(path4.join(i.codexConfigDir, HOOKS_JSON_FILE)) && !codexHookJournaled(i.db)) {
23950
+ if (i.agent === "codex") {
23951
+ const hooks = await listPluginHooks(i.env, CODEX_PLUGIN_ID, i.worktree ?? i.bundleDir);
23952
+ const detail = hooks === void 0 ? void 0 : untrustedPluginHooksDetail(hooks);
23953
+ if (detail !== void 0) return row("FAIL", detail, D5_CODEX_TRUST_FIX);
23954
+ }
23955
+ if (i.agent === "codex" && existsSync10(path6.join(i.codexConfigDir, HOOKS_JSON_FILE)) && !codexHookJournaled(i.db)) {
23726
23956
  return row("UNKNOWN", D5_CODEX_UNTRUSTED_DETAIL);
23727
23957
  }
23728
23958
  const fixture = loadFixture(i.bundleDir, i.agent);
@@ -23741,7 +23971,7 @@ async function checkHookRoundTrip(i) {
23741
23971
  let ms = 0;
23742
23972
  for (let n = 1; n <= maxPairs; n++) {
23743
23973
  const start = now();
23744
- const r = await runProcess([process.execPath, path4.join(i.bundleDir, HOOK_ENTRY_FILE), AGENT_ARG, i.agent], {
23974
+ const r = await runProcess([process.execPath, path6.join(i.bundleDir, HOOK_ENTRY_FILE), AGENT_ARG, i.agent], {
23745
23975
  cwd: i.bundleDir,
23746
23976
  env: i.env,
23747
23977
  signal: i.signal,
@@ -23759,7 +23989,7 @@ async function checkHookRoundTrip(i) {
23759
23989
  }
23760
23990
 
23761
23991
  // src/core/ops/db-heal.ts
23762
- import { existsSync as existsSync10, rmSync as rmSync3 } from "node:fs";
23992
+ import { existsSync as existsSync11, rmSync as rmSync3 } from "node:fs";
23763
23993
 
23764
23994
  // src/core/store/owners.ts
23765
23995
  import { mkdirSync as mkdirSync4, readdirSync as readdirSync4, readFileSync as readFileSync10, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
@@ -23842,7 +24072,7 @@ function renameAside(dbPath) {
23842
24072
  const ts = String(Date.now());
23843
24073
  for (const suffix of DB_SIBLING_SUFFIXES) {
23844
24074
  const file2 = dbPath + suffix;
23845
- if (existsSync10(file2)) renameWithRetry(file2, file2 + HEAL_TS_SEP + ts + HEAL_BACKUP_SUFFIX);
24075
+ if (existsSync11(file2)) renameWithRetry(file2, file2 + HEAL_TS_SEP + ts + HEAL_BACKUP_SUFFIX);
23846
24076
  }
23847
24077
  return ts;
23848
24078
  }
@@ -23923,7 +24153,7 @@ async function guard(id2, run) {
23923
24153
  }
23924
24154
  }
23925
24155
  async function codexDb(ctx, adapter) {
23926
- if (adapter.id !== "codex" || !existsSync11(ctx.project.dbPath)) return null;
24156
+ if (adapter.id !== "codex" || !existsSync12(ctx.project.dbPath)) return null;
23927
24157
  try {
23928
24158
  return await openDb(ctx.project, { readOnly: true });
23929
24159
  } catch {
@@ -23954,7 +24184,7 @@ async function hookRow(ctx, adapter, host) {
23954
24184
  }
23955
24185
  function ownServerId(configDir, projectKey) {
23956
24186
  const dir = join13(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
23957
- if (!existsSync11(dir)) return "";
24187
+ if (!existsSync12(dir)) return "";
23958
24188
  for (const name of readdirSync5(dir)) {
23959
24189
  if (!name.endsWith(OWNER_PID_EXT)) continue;
23960
24190
  if (readFileSync11(join13(dir, name), "utf8").trim() === String(process.pid)) return basename3(name, OWNER_PID_EXT);
@@ -24029,7 +24259,7 @@ var ctxDoctor = Object.freeze({
24029
24259
  });
24030
24260
 
24031
24261
  // src/core/tools/execute.ts
24032
- import { existsSync as existsSync12, mkdtempSync, rmSync as rmSync4, writeFileSync as writeFileSync3 } from "node:fs";
24262
+ import { existsSync as existsSync13, mkdtempSync, rmSync as rmSync4, writeFileSync as writeFileSync3 } from "node:fs";
24033
24263
  import { tmpdir as tmpdir2 } from "node:os";
24034
24264
  import { dirname as dirname7, join as join14, parse as parse3, resolve as resolve5 } from "node:path";
24035
24265
 
@@ -24115,7 +24345,7 @@ function schemaLine(issue2) {
24115
24345
  }
24116
24346
  function fileError(given, abs, root) {
24117
24347
  let dir = abs;
24118
- while (!existsSync12(dir) && dirname7(dir) !== dir) dir = dirname7(dir);
24348
+ while (!existsSync13(dir) && dirname7(dir) !== dir) dir = dirname7(dir);
24119
24349
  if (isInside(root, dir)) return null;
24120
24350
  return new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine();
24121
24351
  }
@@ -24153,12 +24383,14 @@ async function finish(input, ctx, r, exitCode, journal) {
24153
24383
  const fullBytes = Buffer.byteLength(combined, "utf8");
24154
24384
  const head = summaryLine(exitCode, fullBytes);
24155
24385
  const intent = input.intent ?? "";
24156
- const direct = head + "\n" + (input.summary === true ? echoBlock(input.language, input.code) + "\n" : "") + combined;
24157
- if (intent === "" && Buffer.byteLength(direct, "utf8") <= OUTPUT_CAP) {
24386
+ const bare2 = exitCode === 0 && input.summary !== true && combined !== "";
24387
+ const direct = (bare2 ? "" : head + "\n") + (input.summary === true ? echoBlock(input.language, input.code) + "\n" : "") + combined;
24388
+ const fits = Buffer.byteLength(head + "\n" + (input.summary === true ? echoBlock(input.language, input.code) + "\n" : "") + combined, "utf8") <= OUTPUT_CAP;
24389
+ if (intent === "" && fits) {
24158
24390
  return { text: direct, isError, sandboxBytes: fullBytes, journal };
24159
24391
  }
24160
24392
  const label = sourceLabel(input.code);
24161
- const budget = OUTPUT_CAP - Buffer.byteLength(head, "utf8") - 2 - moreReserve(intent, label);
24393
+ const budget = (fits ? OUTPUT_CAP : EXEC_PREVIEW_BYTES) - Buffer.byteLength(head, "utf8") - 2 - moreReserve(intent, label);
24162
24394
  const db = await openDb(ctx.project);
24163
24395
  let picked;
24164
24396
  try {
@@ -24230,16 +24462,16 @@ var ctxExecute = {
24230
24462
  };
24231
24463
 
24232
24464
  // src/core/tools/index.ts
24233
- import { existsSync as existsSync13, readFileSync as readFileSync13, statSync as statSync6 } from "node:fs";
24465
+ import { existsSync as existsSync14, readFileSync as readFileSync13, statSync as statSync7 } from "node:fs";
24234
24466
  import { dirname as dirname8, extname, join as join16, relative as relative3, resolve as resolve6 } from "node:path";
24235
24467
 
24236
24468
  // src/core/index/walk.ts
24237
- import { readdirSync as readdirSync6, readFileSync as readFileSync12, realpathSync as realpathSync6, statSync as statSync5 } from "node:fs";
24469
+ import { readdirSync as readdirSync6, readFileSync as readFileSync12, realpathSync as realpathSync7, statSync as statSync6 } from "node:fs";
24238
24470
  import { join as join15 } from "node:path";
24239
24471
  var GITIGNORE = ".gitignore";
24240
24472
  var GIT_DIR = ".git";
24241
24473
  function walkDir(root, containmentRoot) {
24242
- const real2 = realpathSync6(root);
24474
+ const real2 = realpathSync7(root);
24243
24475
  if (!isInside(containmentRoot, real2)) throw new CtxError("OUTSIDE_ROOT", { p: root, root: containmentRoot });
24244
24476
  const found = [];
24245
24477
  visit(real2, [], [], containmentRoot, /* @__PURE__ */ new Set([real2]), found);
@@ -24256,19 +24488,19 @@ function visit(abs, rel, parent, contain, seen, found) {
24256
24488
  const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join15(abs, GITIGNORE), rel)) : parent;
24257
24489
  for (const e of entries) {
24258
24490
  if (e.name === GIT_DIR) continue;
24259
- const path5 = join15(abs, e.name);
24491
+ const path7 = join15(abs, e.name);
24260
24492
  let isDir = e.isDirectory();
24261
24493
  let isFile = e.isFile();
24262
- let target = path5;
24494
+ let target = path7;
24263
24495
  if (e.isSymbolicLink()) {
24264
24496
  let resolved;
24265
24497
  try {
24266
- resolved = realpathSync6(path5);
24498
+ resolved = realpathSync7(path7);
24267
24499
  } catch {
24268
24500
  continue;
24269
24501
  }
24270
24502
  if (!isInside(contain, resolved)) continue;
24271
- const st = statSync5(resolved);
24503
+ const st = statSync6(resolved);
24272
24504
  isDir = st.isDirectory();
24273
24505
  isFile = st.isFile();
24274
24506
  target = resolved;
@@ -24276,12 +24508,12 @@ function visit(abs, rel, parent, contain, seen, found) {
24276
24508
  const segs = rel.concat(e.name);
24277
24509
  if (ignored(rules, segs, isDir)) continue;
24278
24510
  if (isFile) {
24279
- found.push({ dir: rel, name: e.name, absPath: path5 });
24511
+ found.push({ dir: rel, name: e.name, absPath: path7 });
24280
24512
  } else if (isDir) {
24281
- const key = e.isSymbolicLink() ? target : realpathSync6(path5);
24513
+ const key = e.isSymbolicLink() ? target : realpathSync7(path7);
24282
24514
  if (seen.has(key)) continue;
24283
24515
  seen.add(key);
24284
- visit(path5, segs, rules, contain, seen, found);
24516
+ visit(path7, segs, rules, contain, seen, found);
24285
24517
  }
24286
24518
  }
24287
24519
  }
@@ -24472,12 +24704,12 @@ function tlsName(host) {
24472
24704
  function request(u, conn, proxy, signal) {
24473
24705
  const host = bare(u.hostname);
24474
24706
  const port = u.port === "" ? defaultPort(u.protocol) : Number(u.port);
24475
- const path5 = u.pathname + u.search;
24707
+ const path7 = u.pathname + u.search;
24476
24708
  return new Promise((resolve7, reject) => {
24477
24709
  const onErr = (err) => reject(fail6(causeCode(err)));
24478
24710
  if (proxy === void 0) {
24479
24711
  const mod = u.protocol === "https:" ? https : http;
24480
- const req = mod.request({ host: conn.address, port, path: path5, signal, servername: tlsName(host), headers: { host: u.host } });
24712
+ const req = mod.request({ host: conn.address, port, path: path7, signal, servername: tlsName(host), headers: { host: u.host } });
24481
24713
  req.on("response", resolve7).on("error", onErr).end();
24482
24714
  return;
24483
24715
  }
@@ -24499,7 +24731,7 @@ function request(u, conn, proxy, signal) {
24499
24731
  const req = https.request({
24500
24732
  host,
24501
24733
  port,
24502
- path: path5,
24734
+ path: path7,
24503
24735
  signal,
24504
24736
  headers: { host: u.host },
24505
24737
  createConnection: () => tlsConnect({ socket, host, servername: tlsName(host) })
@@ -28386,7 +28618,7 @@ function readUtf8(absPath) {
28386
28618
  }
28387
28619
  function missingOrOutside(given, abs, root) {
28388
28620
  let dir = abs;
28389
- while (!existsSync13(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
28621
+ while (!existsSync14(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
28390
28622
  if (dir !== abs && isInside(root, dir)) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
28391
28623
  return new CtxError("OUTSIDE_ROOT", { p: given, root });
28392
28624
  }
@@ -28394,15 +28626,15 @@ function pathItems(input, project) {
28394
28626
  const abs = resolve6(project.worktree, input.path);
28395
28627
  if (!isInside(project.containmentRoot, abs)) throw missingOrOutside(input.path, abs, project.containmentRoot);
28396
28628
  const base = relative3(project.worktree, abs);
28397
- if (statSync6(abs).isDirectory()) {
28629
+ if (statSync7(abs).isDirectory()) {
28398
28630
  return walkDir(abs, project.containmentRoot).map((f) => ({
28399
28631
  sourceKind: "path",
28400
- label: join16(base, f.relPath),
28632
+ label: pathLabel(join16(base, f.relPath)),
28401
28633
  kind: kindOfPath(f.relPath),
28402
28634
  read: () => readUtf8(f.absPath)
28403
28635
  }));
28404
28636
  }
28405
- return [{ sourceKind: "path", label: base === "" ? input.path : base, kind: kindOfPath(abs), read: () => readUtf8(abs) }];
28637
+ return [{ sourceKind: "path", label: pathLabel(base === "" ? input.path : base), kind: kindOfPath(abs), read: () => readUtf8(abs) }];
28406
28638
  }
28407
28639
  async function itemsOf(input, ctx) {
28408
28640
  if (input.content !== void 0) {
@@ -28413,7 +28645,7 @@ async function itemsOf(input, ctx) {
28413
28645
  }
28414
28646
  if (input.path !== void 0) {
28415
28647
  const items = pathItems({ ...input, path: input.path }, ctx.project);
28416
- return { items, from: items.length === 1 ? items[0].label : input.path };
28648
+ return { items, from: items.length === 1 ? items[0].label : pathLabel(input.path) };
28417
28649
  }
28418
28650
  const res = await safeFetch(input.url ?? "", AbortSignal.any([ctx.signal, AbortSignal.timeout(EXEC_TIMEOUT_MS)]));
28419
28651
  const text = res.body.toString("utf8");
@@ -28510,10 +28742,11 @@ function scopesOf(input) {
28510
28742
  function changes(raw, sql, ...args) {
28511
28743
  return Number(raw.prepare(sql).run(...args).changes);
28512
28744
  }
28513
- function purgeScope(raw, scope, input) {
28745
+ function purgeScope(db, scope, input) {
28746
+ const raw = db.raw;
28514
28747
  if (scope === "session") return changes(raw, "DELETE FROM events WHERE session_id = ?", input.session);
28515
28748
  if (scope === "source") {
28516
- const label = input.source;
28749
+ const label = storedLabel(db, input.source);
28517
28750
  return deleteChunkRows(raw, { label }) + changes(raw, "DELETE FROM sources WHERE label = ?", label);
28518
28751
  }
28519
28752
  const chunks = deleteChunkRows(raw, "all");
@@ -28531,7 +28764,7 @@ async function handler5(input, ctx) {
28531
28764
  try {
28532
28765
  const db = await openDb(ctx.project);
28533
28766
  try {
28534
- const rows = withWrite(db, (h) => purgeScope(h.raw, scope, input));
28767
+ const rows = withWrite(db, (h) => purgeScope(h, scope, input));
28535
28768
  return reply2(PURGE_SUMMARY(rows, scope), false);
28536
28769
  } finally {
28537
28770
  closeDb(db);
@@ -28653,11 +28886,11 @@ var ctxStats = Object.freeze({
28653
28886
  });
28654
28887
 
28655
28888
  // src/core/tools/upgrade.ts
28656
- import { existsSync as existsSync19, realpathSync as realpathSync7, rmSync as rmSync9 } from "node:fs";
28889
+ import { existsSync as existsSync20, realpathSync as realpathSync8, rmSync as rmSync9 } from "node:fs";
28657
28890
  import { basename as basename5, dirname as dirname10, join as join22 } from "node:path";
28658
28891
 
28659
28892
  // src/core/ops/host-write.ts
28660
- import { copyFileSync, existsSync as existsSync14, mkdirSync as mkdirSync5, writeFileSync as writeFileSync4 } from "node:fs";
28893
+ import { copyFileSync, existsSync as existsSync15, mkdirSync as mkdirSync5, writeFileSync as writeFileSync4 } from "node:fs";
28661
28894
  import { dirname as dirname9, join as join17 } from "node:path";
28662
28895
  function defaultWrite(file2, text) {
28663
28896
  writeFileSync4(file2, text, "utf8");
@@ -28686,7 +28919,7 @@ function toRow(file2, edit) {
28686
28919
  function writeWithRollback(file2, text, write2, atomic) {
28687
28920
  const trash = file2 + UPGRADE_TRASH_SUFFIX;
28688
28921
  const tmp = `${file2}${HOST_CONFIG_TMP_SUFFIX}.${process.pid}`;
28689
- const had = existsSync14(file2);
28922
+ const had = existsSync15(file2);
28690
28923
  mkdirSync5(dirname9(file2), { recursive: true });
28691
28924
  if (had) copyFileSync(file2, trash);
28692
28925
  try {
@@ -28716,7 +28949,7 @@ function regenerateHostConfig(row5, home, opts = {}) {
28716
28949
  if (requested === null) return [];
28717
28950
  const current = readHostConfig(row5.id, requested);
28718
28951
  const result = mergeOwnEntries(row5.id, current.text, current.format, row5);
28719
- const exists = existsSync14(current.path);
28952
+ const exists = existsSync15(current.path);
28720
28953
  if (exists && result.text === current.text) return [];
28721
28954
  const text = result.text === "" && current.format !== "toml" ? JSON.stringify({}) : result.text;
28722
28955
  writeWithRollback(current.path, current.layout === void 0 ? text : withLayout(text, current.layout), opts.write ?? defaultWrite, opts.atomic ?? {});
@@ -28724,15 +28957,15 @@ function regenerateHostConfig(row5, home, opts = {}) {
28724
28957
  }
28725
28958
 
28726
28959
  // src/core/ops/plugin-swap.ts
28727
- import { existsSync as existsSync15, lstatSync, readdirSync as readdirSync7, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
28960
+ import { existsSync as existsSync16, lstatSync, readdirSync as readdirSync7, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
28728
28961
  import { basename as basename4, join as join18, win32 as win322 } from "node:path";
28729
- function linkTarget(path5, win) {
28730
- if (!isLink(path5)) return null;
28731
- const target = readlinkSync(path5);
28962
+ function linkTarget(path7, win) {
28963
+ if (!isLink(path7)) return null;
28964
+ const target = readlinkSync(path7);
28732
28965
  return win ? win322.basename(target) : target;
28733
28966
  }
28734
- function isLink(path5) {
28735
- return lstatSync(path5, { throwIfNoEntry: false })?.isSymbolicLink() === true;
28967
+ function isLink(path7) {
28968
+ return lstatSync(path7, { throwIfNoEntry: false })?.isSymbolicLink() === true;
28736
28969
  }
28737
28970
  function generations(agentDir) {
28738
28971
  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();
@@ -28745,7 +28978,7 @@ function settleLinks(link, tmp, old, opts) {
28745
28978
  }
28746
28979
  function swapPluginCurrent(agentDir, sha, opts = {}) {
28747
28980
  const next = join18(agentDir, sha);
28748
- if (!existsSync15(next) || !lstatSync(next).isDirectory()) {
28981
+ if (!existsSync16(next) || !lstatSync(next).isDirectory()) {
28749
28982
  throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename4(agentDir), path: next });
28750
28983
  }
28751
28984
  const link = join18(agentDir, PLUGIN_CURRENT_LINK);
@@ -28765,12 +28998,12 @@ function swapPluginCurrent(agentDir, sha, opts = {}) {
28765
28998
  if (before !== null) keep.add(before);
28766
28999
  const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join18(agentDir, name));
28767
29000
  for (const dir of removed) rmSync5(dir, { recursive: true, force: true });
28768
- const previous = before !== null && existsSync15(join18(agentDir, before)) ? join18(agentDir, before) : null;
29001
+ const previous = before !== null && existsSync16(join18(agentDir, before)) ? join18(agentDir, before) : null;
28769
29002
  return { current: next, previous, removed };
28770
29003
  }
28771
29004
 
28772
29005
  // src/core/ops/release-fetch.ts
28773
- import { existsSync as existsSync16, mkdirSync as mkdirSync6, rmSync as rmSync6 } from "node:fs";
29006
+ import { existsSync as existsSync17, mkdirSync as mkdirSync6, rmSync as rmSync6 } from "node:fs";
28774
29007
  import { join as join19 } from "node:path";
28775
29008
  function failed(r) {
28776
29009
  if (r.exitCode === null && r.killed === null) return new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
@@ -28794,7 +29027,7 @@ async function fetchRelease(agent, url2, env, signal, opts = {}) {
28794
29027
  await git2(gitBin, [...GIT_CLONE_ARGS, RELEASE_BRANCH, url2, fetchDir], agentDir, childEnv, signal);
28795
29028
  const sha = await git2(gitBin, GIT_HEAD_SHA_ARGS, fetchDir, childEnv, signal);
28796
29029
  const dir = join19(agentDir, sha);
28797
- if (existsSync16(dir)) rmSync6(fetchDir, { recursive: true, force: true });
29030
+ if (existsSync17(dir)) rmSync6(fetchDir, { recursive: true, force: true });
28798
29031
  else renameWithRetry(fetchDir, dir, opts);
28799
29032
  return { sha, dir };
28800
29033
  } catch (e) {
@@ -28804,7 +29037,7 @@ async function fetchRelease(agent, url2, env, signal, opts = {}) {
28804
29037
  }
28805
29038
 
28806
29039
  // src/core/ops/uninstall.ts
28807
- import { existsSync as existsSync17, readdirSync as readdirSync8, rmSync as rmSync7, writeFileSync as writeFileSync5 } from "node:fs";
29040
+ import { existsSync as existsSync18, readdirSync as readdirSync8, rmSync as rmSync7, writeFileSync as writeFileSync5 } from "node:fs";
28808
29041
  import { join as join20 } from "node:path";
28809
29042
  function row2(area, before, after) {
28810
29043
  return { area, before, after };
@@ -28834,7 +29067,7 @@ function removeCache(adapter, env, configDir) {
28834
29067
  }
28835
29068
  case "plugin": {
28836
29069
  const agentDir = join20(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
28837
- if (!existsSync17(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
29070
+ if (!existsSync18(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
28838
29071
  rmSync7(agentDir, { recursive: true, force: true });
28839
29072
  return row2(UPGRADE_CACHE_AREA, agentDir, UPGRADE_REMOVED);
28840
29073
  }
@@ -28847,11 +29080,11 @@ function removeCache(adapter, env, configDir) {
28847
29080
  }
28848
29081
  }
28849
29082
  }
28850
- function isObj2(v) {
29083
+ function isObj3(v) {
28851
29084
  return typeof v === "object" && v !== null && !Array.isArray(v);
28852
29085
  }
28853
29086
  function piSource(entry) {
28854
- return isObj2(entry) ? entry[PI_PACKAGE_SOURCE_KEY] : entry;
29087
+ return isObj3(entry) ? entry[PI_PACKAGE_SOURCE_KEY] : entry;
28855
29088
  }
28856
29089
  function ownEntries(agent, env) {
28857
29090
  const home = requireHomeDir(env);
@@ -28860,11 +29093,11 @@ function ownEntries(agent, env) {
28860
29093
  const top = mcp.key[0];
28861
29094
  const inner = mcp.key.slice(1, -1);
28862
29095
  const own2 = mcp.key[mcp.key.length - 1];
28863
- const holder = (v) => inner.reduce((cur, k) => isObj2(cur) ? cur[k] : void 0, v);
28864
- const without = (v, path5) => {
29096
+ const holder = (v) => inner.reduce((cur, k) => isObj3(cur) ? cur[k] : void 0, v);
29097
+ const without = (v, path7) => {
28865
29098
  const o = v;
28866
- if (path5.length === 0) return Object.fromEntries(Object.entries(o).filter(([k]) => k !== own2));
28867
- return { ...o, [path5[0]]: without(o[path5[0]], path5.slice(1)) };
29099
+ if (path7.length === 0) return Object.fromEntries(Object.entries(o).filter(([k]) => k !== own2));
29100
+ return { ...o, [path7[0]]: without(o[path7[0]], path7.slice(1)) };
28868
29101
  };
28869
29102
  return [{
28870
29103
  file: ownMcpFileOf(agent, mcp.file, env, home),
@@ -28872,7 +29105,7 @@ function ownEntries(agent, env) {
28872
29105
  shown: mcp.key.join(V1_KEY_PATH_SEP),
28873
29106
  has: (v) => {
28874
29107
  const h = holder(v);
28875
- return isObj2(h) && Object.hasOwn(h, own2);
29108
+ return isObj3(h) && Object.hasOwn(h, own2);
28876
29109
  },
28877
29110
  drop: (v) => without(v, inner)
28878
29111
  }];
@@ -28914,7 +29147,7 @@ function removeOwnEntries(agent, env) {
28914
29147
  function removeProjectData(configDir, projectKey) {
28915
29148
  const projects = join20(configDir, PROJECTS_DIR_NAME);
28916
29149
  const dir = join20(projects, projectKey);
28917
- if (!existsSync17(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
29150
+ if (!existsSync18(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
28918
29151
  if (dir === projects || !isInside(projects, dir)) throw new CtxError("OUTSIDE_ROOT", { p: dir, root: projects });
28919
29152
  for (const name of readdirSync8(dir)) {
28920
29153
  if (name !== OWNERS_DIR_NAME) rmSync7(join20(dir, name), { recursive: true, force: true });
@@ -28930,8 +29163,8 @@ function runUninstall(input) {
28930
29163
  }
28931
29164
 
28932
29165
  // src/core/ops/v1-remove.ts
28933
- import { copyFileSync as copyFileSync2, existsSync as existsSync18, readFileSync as readFileSync14, rmSync as rmSync8 } from "node:fs";
28934
- var isObj3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
29166
+ import { copyFileSync as copyFileSync2, existsSync as existsSync19, readFileSync as readFileSync14, rmSync as rmSync8 } from "node:fs";
29167
+ var isObj4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
28935
29168
  var areaOf = (f) => f.path === "" ? f.file : f.file + UPGRADE_AREA_KEY_SEP + f.path;
28936
29169
  var row3 = (f, after) => ({ area: areaOf(f), before: f.reason, after });
28937
29170
  function moveAside(target, undo) {
@@ -28960,17 +29193,17 @@ function cutTomlTable(text, header) {
28960
29193
  function writeAtomic(file2, text) {
28961
29194
  atomicWriteFile(file2, text);
28962
29195
  }
28963
- function locate(doc, path5) {
28964
- const segs = path5.split(V1_KEY_PATH_SEP);
29196
+ function locate(doc, path7) {
29197
+ const segs = path7.split(V1_KEY_PATH_SEP);
28965
29198
  let cur = doc;
28966
29199
  for (const seg of segs.slice(0, -1)) {
28967
29200
  if (Array.isArray(cur)) cur = cur[Number(seg)];
28968
- else if (isObj3(cur)) cur = cur[seg];
29201
+ else if (isObj4(cur)) cur = cur[seg];
28969
29202
  else return null;
28970
29203
  }
28971
29204
  const last2 = segs[segs.length - 1];
28972
29205
  if (Array.isArray(cur)) return Number(last2) < cur.length ? [cur, last2] : null;
28973
- if (isObj3(cur)) return Object.hasOwn(cur, last2) ? [cur, last2] : null;
29206
+ if (isObj4(cur)) return Object.hasOwn(cur, last2) ? [cur, last2] : null;
28974
29207
  return null;
28975
29208
  }
28976
29209
  function stripJsonEntries(agent, file2, findings, kept, undo) {
@@ -29011,14 +29244,14 @@ function removeV1(agent, findings) {
29011
29244
  for (const f of findings) {
29012
29245
  if (UPGRADE_REPORT_ONLY_REASONS.includes(f.reason)) done.set(f, UPGRADE_REPORT_ONLY);
29013
29246
  else if (f.path === "") {
29014
- if (existsSync18(f.file)) {
29247
+ if (existsSync19(f.file)) {
29015
29248
  moveAside(f.file, undo);
29016
29249
  done.set(f, UPGRADE_REMOVED);
29017
29250
  } else done.set(f, UPGRADE_NOT_FOUND);
29018
29251
  } else entries.set(f.file, [...entries.get(f.file) ?? [], f]);
29019
29252
  }
29020
29253
  for (const [file2, list4] of entries) {
29021
- if (!existsSync18(file2)) {
29254
+ if (!existsSync19(file2)) {
29022
29255
  for (const f of list4) done.set(f, UPGRADE_NOT_FOUND);
29023
29256
  continue;
29024
29257
  }
@@ -29051,7 +29284,7 @@ function removeV1(agent, findings) {
29051
29284
  },
29052
29285
  rollback() {
29053
29286
  for (const u of undo.splice(0).reverse()) {
29054
- if (!existsSync18(u.trash)) continue;
29287
+ if (!existsSync19(u.trash)) continue;
29055
29288
  rmSync8(u.target, { recursive: true, force: true });
29056
29289
  renameWithRetry(u.trash, u.target);
29057
29290
  }
@@ -29060,7 +29293,7 @@ function removeV1(agent, findings) {
29060
29293
  }
29061
29294
 
29062
29295
  // src/core/ops/verify-sums.ts
29063
- import { createHash } from "node:crypto";
29296
+ import { createHash as createHash2 } from "node:crypto";
29064
29297
  import { lstatSync as lstatSync2, readdirSync as readdirSync9, readFileSync as readFileSync15 } from "node:fs";
29065
29298
  import { join as join21 } from "node:path";
29066
29299
  function mismatch() {
@@ -29100,7 +29333,7 @@ function verifySums(dir) {
29100
29333
  for (const [rel, abs] of files) {
29101
29334
  const want = sums.get(rel);
29102
29335
  if (want === void 0) throw mismatch();
29103
- const got = createHash(SUMS_HASH_ALGORITHM).update(readFileSync15(abs)).digest(HASH_ENCODING);
29336
+ const got = createHash2(SUMS_HASH_ALGORITHM).update(readFileSync15(abs)).digest(HASH_ENCODING);
29104
29337
  if (got !== want) throw mismatch();
29105
29338
  }
29106
29339
  }
@@ -29129,7 +29362,7 @@ function pluginRootRow(adapter, env) {
29129
29362
  }
29130
29363
  function isCurrent(agentDir, dir) {
29131
29364
  const link = join22(agentDir, PLUGIN_CURRENT_LINK);
29132
- return existsSync19(link) && realpathSync7.native(link) === realpathSync7.native(dir);
29365
+ return existsSync20(link) && realpathSync8.native(link) === realpathSync8.native(dir);
29133
29366
  }
29134
29367
  async function checkout(adapter, deps) {
29135
29368
  const fetched = await fetchRelease(adapter.id, deps.releaseUrl, deps.env, deps.signal);