context-mode 2.0.0-next.29 → 2.0.0-next.30

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
@@ -3840,8 +3840,8 @@ function az_default() {
3840
3840
  }
3841
3841
 
3842
3842
  // node_modules/zod/v4/locales/be.js
3843
- function getBelarusianPlural(count, one, few, many) {
3844
- const absCount = Math.abs(count);
3843
+ function getBelarusianPlural(count2, one, few, many) {
3844
+ const absCount = Math.abs(count2);
3845
3845
  const lastDigit = absCount % 10;
3846
3846
  const lastTwoDigits = absCount % 100;
3847
3847
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -6986,8 +6986,8 @@ function pt_default() {
6986
6986
  }
6987
6987
 
6988
6988
  // node_modules/zod/v4/locales/ru.js
6989
- function getRussianPlural(count, one, few, many) {
6990
- const absCount = Math.abs(count);
6989
+ function getRussianPlural(count2, one, few, many) {
6990
+ const absCount = Math.abs(count2);
6991
6991
  const lastDigit = absCount % 10;
6992
6992
  const lastTwoDigits = absCount % 100;
6993
6993
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
@@ -11166,9 +11166,9 @@ var REPLACE_TRIGGER_BYTES = 4096;
11166
11166
  var REPLACE_RETURN_BYTES = 96;
11167
11167
  var SHAPE_RETURN_BYTES = 256;
11168
11168
  var REPLACE_CHUNK_BYTES = 48;
11169
- function REPLACE_HANDLE_LINE(intent, handle, bytes4, prefix = "", asked = "") {
11169
+ function REPLACE_HANDLE_LINE(intent, handle, bytes5, prefix = "", asked = "") {
11170
11170
  const queries = asked === "" ? [intent] : [intent, asked];
11171
- return prefix + "ctx_search({queries:[" + queries.map((q) => JSON.stringify(q)).join(",") + "], source:" + JSON.stringify(handle) + "}) searches the whole output (" + bytes4 + " B).";
11171
+ return prefix + "ctx_search({queries:[" + queries.map((q) => JSON.stringify(q)).join(",") + "], source:" + JSON.stringify(handle) + "}) searches the whole output (" + bytes5 + " B).";
11172
11172
  }
11173
11173
  var HANDLE_PROMPT_WORDS = 3;
11174
11174
  var MAX_CHUNK_BYTES = 4096;
@@ -11419,8 +11419,8 @@ var HOOK_FAIL_TOOLS = Object.freeze({
11419
11419
  grep: Object.freeze(["Grep", "grep_search"]),
11420
11420
  fetch: Object.freeze(["WebFetch", "web_fetch", "fetch"])
11421
11421
  });
11422
- function HOOK_FAIL_LINE(label, prefix) {
11423
- return `${DENY_PREFIX}the hook failed (${label}). Fix: run ${prefix}ctx_doctor.`;
11422
+ function HOOK_FAIL_LINE(label2, prefix) {
11423
+ return `${DENY_PREFIX}the hook failed (${label2}). Fix: run ${prefix}ctx_doctor.`;
11424
11424
  }
11425
11425
  var HOOK_FAIL_REDIRECT = Object.freeze({
11426
11426
  read: "Read the file in parts with offset and limit, or process it with ctx_execute(language, code); only what you print comes back.",
@@ -11428,11 +11428,11 @@ var HOOK_FAIL_REDIRECT = Object.freeze({
11428
11428
  grep: "Search with ctx_execute(language, code), or index the files with ctx_index and query them with ctx_search.",
11429
11429
  fetch: "Index the URL with ctx_index and query it with ctx_search."
11430
11430
  });
11431
- function D5_LAST_HOOK_ERROR(ts, stage, label) {
11432
- return `; last hook error ${ts} at ${stage} (${label}), stack in ${HOOK_ERROR_LOG_FILE}`;
11431
+ function D5_LAST_HOOK_ERROR(ts, stage, label2) {
11432
+ return `; last hook error ${ts} at ${stage} (${label2}), stack in ${HOOK_ERROR_LOG_FILE}`;
11433
11433
  }
11434
- function D5_PAST_HOOK_ERROR(ts, stage, label) {
11435
- return `; past hook error ${ts} at ${stage} (${label}), before this run, stack in ${HOOK_ERROR_LOG_FILE}`;
11434
+ function D5_PAST_HOOK_ERROR(ts, stage, label2) {
11435
+ return `; past hook error ${ts} at ${stage} (${label2}), before this run, stack in ${HOOK_ERROR_LOG_FILE}`;
11436
11436
  }
11437
11437
  var BOUNDED_COMMANDS = Object.freeze(["pwd", "whoami", "uname", "id", "realpath", "ln"]);
11438
11438
  var BOUNDED_GIT_SUBCOMMANDS = Object.freeze(["status"]);
@@ -11501,6 +11501,42 @@ function STATS_SUMMARY(allTimePct, sessionPct) {
11501
11501
  }
11502
11502
  var STATS_COLUMNS = Object.freeze(["Scope", "Produced", "Returned", "Saved", "Reduction %"]);
11503
11503
  var STATS_NO_DATA = "no data \u2014 no tool calls recorded yet";
11504
+ var STATS_WIDTH = 80;
11505
+ var STATS_BYTES_PER_TOKEN = 4;
11506
+ var STATS_MAX_TOOL_ROWS = 12;
11507
+ var STATS_LABEL_W = 21;
11508
+ var STATS_LABEL_MAX = 20;
11509
+ var STATS_CALLS_W = 7;
11510
+ var STATS_NUM_W = 11;
11511
+ var STATS_PCT_W = 8;
11512
+ var STATS_KIND_W = 9;
11513
+ var STATS_HEAD_BAR = 40;
11514
+ var STATS_ROW_BAR = 8;
11515
+ var STATS_KIND_BAR = 20;
11516
+ var STATS_KIB = 1024;
11517
+ var STATS_MILLION = 1e6;
11518
+ var STATS_MS_PER_MINUTE = 6e4;
11519
+ var STATS_MINUTES_PER_HOUR = 60;
11520
+ var STATS_HOURS_PER_DAY = 24;
11521
+ var STATS_CLOCK_DIGITS = 2;
11522
+ var STATS_REPORT_TITLE = "context-mode stats";
11523
+ var STATS_EMPTY_LINES = Object.freeze([
11524
+ "Ready. Your savings show up here after the first tool call.",
11525
+ "Large outputs from ctx_execute, ctx_batch and ctx_index stay in the",
11526
+ "sandbox, and only the short answer goes to the chat."
11527
+ ]);
11528
+ var STATS_KIND_LABELS = Object.freeze([
11529
+ ["cmd", "Tool runs"],
11530
+ ["index", "Content indexed"],
11531
+ ["edit", "File edits"],
11532
+ ["toolerr", "Errors kept"],
11533
+ ["decision", "Your decisions"],
11534
+ ["prompt", "Your prompts"]
11535
+ ]);
11536
+ var STATS_JOURNAL_HINTS = Object.freeze([
11537
+ "ctx_resume brings back your last task, files changed and open errors",
11538
+ "after a compact or a restart; ctx_search finds indexed content by words."
11539
+ ]);
11504
11540
  var PURGE_SCOPES = Object.freeze(["session", "source", "project"]);
11505
11541
  var PURGE_NO_SCOPE_LINE = "ctx_purge: pick one scope \u2014 session, source, or project.";
11506
11542
  var PURGE_MANY_SCOPES_LINE = "ctx_purge: pick only one scope \u2014 session, source, or project.";
@@ -11516,7 +11552,7 @@ var DECISION_OPTION_KEY = "option";
11516
11552
  var DECISION_LABEL_JOIN = " | ";
11517
11553
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
11518
11554
  var RELEASE_BRANCH = "release";
11519
- var BUNDLE_SHA = true ? "805cc5b3a3d908b9ac4b76ab326176eecef10dad" : void 0;
11555
+ var BUNDLE_SHA = true ? "dd54e208f8debb1c4601659ee632ada9a3612e45" : void 0;
11520
11556
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
11521
11557
  var DOCTOR_LABEL = Object.freeze({
11522
11558
  D1: "version",
@@ -11546,9 +11582,49 @@ function DOCTOR_FAIL_LINE(host, check2, cause, command) {
11546
11582
  return `FAIL ${host}: ${check2} \u2014 ${cause}. Fix: ${command}`;
11547
11583
  }
11548
11584
  var DOCTOR_FIX_UPGRADE = "run ctx_upgrade";
11549
- var D1_NO_NETWORK_DETAIL = "no network";
11550
11585
  var D1_DEV_BUILD_DETAIL = "dev build";
11551
11586
  var D1_UPDATE_DETAIL = "update available";
11587
+ var D1_SHORT_SHA_LEN = 7;
11588
+ var D1_PACKAGE_FILE = "package.json";
11589
+ function D1_PREFIX(version4, sha) {
11590
+ return `${version4 ?? "bundle"} (${sha.slice(0, D1_SHORT_SHA_LEN)})`;
11591
+ }
11592
+ var D1_GIT_PASS = "latest on the release branch";
11593
+ function D1_NPM_PASS(tag2) {
11594
+ return `latest ${tag2} on npm`;
11595
+ }
11596
+ function D1_NPM_UPDATE(tag2, latest) {
11597
+ return `${D1_UPDATE_DETAIL}, ${tag2} on npm is ${latest}`;
11598
+ }
11599
+ var D1_LATEST_UNKNOWN = "latest unknown";
11600
+ var D1_GIT_MISSING = "git not found on PATH";
11601
+ function D1_GIT_EXIT(code, stderrLine) {
11602
+ return stderrLine === "" ? `git exit ${code}` : `git exit ${code}: ${stderrLine}`;
11603
+ }
11604
+ function D1_GIT_TIMEOUT(ms) {
11605
+ return `git timed out after ${ms} ms`;
11606
+ }
11607
+ var D1_GIT_CANCEL = "git stopped by cancel";
11608
+ var D1_GIT_NO_START = "git did not start";
11609
+ var D1_GIT_NO_SHA = "git answered no sha";
11610
+ function D1_NPM_TIMEOUT(ms) {
11611
+ return `npm registry timed out after ${ms} ms`;
11612
+ }
11613
+ function D1_NPM_HTTP(status) {
11614
+ return `npm registry answered HTTP ${status}`;
11615
+ }
11616
+ function D1_NPM_ERROR(cause) {
11617
+ return `npm registry: ${cause}`;
11618
+ }
11619
+ function D1_NPM_NO_TAG(tag2) {
11620
+ return `npm registry answered no ${tag2} version`;
11621
+ }
11622
+ var D1_CAUSE_JOIN = "; ";
11623
+ var D1_GIT_CHECK_FIX = `git ls-remote ${RELEASE_REPO_URL} ${RELEASE_BRANCH}`;
11624
+ var D1_NPM_CHECK_FIX = "npm view context-mode dist-tags";
11625
+ var D1_REGISTRY_URL = "https://registry.npmjs.org/-/package/context-mode/dist-tags";
11626
+ var D1_PRERELEASE_SEP = "-";
11627
+ var D1_DEFAULT_TAG = "latest";
11552
11628
  var GIT_LS_REMOTE = "ls-remote";
11553
11629
  var D2_NODE_FIX = `install Node ${NODE_MIN} or later`;
11554
11630
  function D2_NODE_DETAIL(version4) {
@@ -13484,11 +13560,11 @@ function jqPath(s) {
13484
13560
  function jqWhitelisted(filter2) {
13485
13561
  const s = filter2.trim();
13486
13562
  if (s === JQ_WHITELIST.identity || s === JQ_WHITELIST.length) return true;
13487
- const bar = s.indexOf(JQ_WHITELIST.pipeLength.charAt(0));
13488
- if (bar < 0) return jqPath(s);
13489
- const left = s.slice(0, bar).trim();
13563
+ const bar2 = s.indexOf(JQ_WHITELIST.pipeLength.charAt(0));
13564
+ if (bar2 < 0) return jqPath(s);
13565
+ const left = s.slice(0, bar2).trim();
13490
13566
  const right = JQ_WHITELIST.pipeLength.slice(1).trim();
13491
- return (left === JQ_WHITELIST.identity || jqPath(left)) && s.slice(bar + 1).trim() === right;
13567
+ return (left === JQ_WHITELIST.identity || jqPath(left)) && s.slice(bar2 + 1).trim() === right;
13492
13568
  }
13493
13569
  function isBoundedSink(c) {
13494
13570
  const name = c.argv0.toLowerCase();
@@ -14695,7 +14771,7 @@ var TOOL_DESCRIPTIONS = Object.freeze({
14695
14771
  ctx_index: 'Example: `ctx_index({path:"docs/api.md"})`. Required: one of path, content, url.\nStores content so it can be searched later: a local file or folder (nested .gitignore files are respected), raw text, or a URL, which is fetched and converted to Markdown. Use it for documentation or large files you will query more than once, then use ctx_search instead of reading the content again. Returns the source label and how many chunks were stored.',
14696
14772
  ctx_search: 'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Pass several queries in one call. By default it searches the current worktree; set `scope` to `project` for all worktrees or `session` for this session only. Results from the current session rank first, then by relevance, ranked with measurably better recall than plain keyword search. Set `sort` to `timeline` for oldest-first order across this session, prior sessions and memory, paged with `after`; `offset` is for relevance order only. Set `source` to `decision` to search only rows where the user answered a question. Every hit names its source. When nothing matches, the reply states the scope and how many sources are indexed.',
14697
14773
  ctx_resume: "Example: `ctx_resume({})`. Required: none.\nReturns a summary of up to 2 KB for this session: the last task and user request, files changed, open errors, and search terms for ctx_search. A large row is shown as a pointer line instead of its full text; call `ctx_resume(seq: N)` with that line's number to read the full row. Call it with no `seq` to get the state block on demand. Use it after the conversation was compacted or resumed, before you repeat earlier work.",
14698
- ctx_stats: "Example: `ctx_stats({})`. Required: none.\nReports how many bytes context-mode kept out of the conversation in this session and in this project, per agent, as a Markdown table. Show the table to the user as it is. Use it when the user asks what context-mode saved.",
14774
+ ctx_stats: "Example: `ctx_stats({})`. Required: none.\nReports the bytes context-mode kept out of the chat: a text report (bars, per tool, per agent) and a Markdown table. Show the text block to the user unchanged, in a code block. Use it when the user asks what it saved.",
14699
14775
  ctx_doctor: "Example: `ctx_doctor({})`. Required: none.\nChecks this context-mode install and reports a table with one row per check: version, Node and node:sqlite, host config and hooks for this agent, MCP connection, project and worktree, database health, index contents, and hook timing. Each failed row names its cause and the fix in one line. It changes nothing. Use it when the user asks whether context-mode works, or after a context-mode error.",
14700
14776
  ctx_upgrade: "Example: `ctx_upgrade({})`. Required: none.\nUpdates context-mode to the latest release for this agent and rewrites only context-mode's own entries in the host config. User entries and user settings such as hook timeouts are kept, and old entries are erased. Returns a table of what changed and whether a restart is needed. Use it only when the user asks to update context-mode.",
14701
14777
  ctx_purge: 'Example: `ctx_purge({source:"old-docs"})`. Required: one of session, source, project.\nDeletes stored data: one session, one indexed source, or everything stored for this project. This cannot be undone. Use it only when the user asks to forget or reset data.'
@@ -15774,7 +15850,7 @@ function buildSnippet(row5, given, maxBytes, codeMaxBytes = SNIPPET_CODE_MAX_BYT
15774
15850
  terms = given.filter((t) => t.text.length >= 5).map((t) => ({ ...t, text: t.text.slice(0, Math.max(4, t.text.length - 2)) }));
15775
15851
  pos = terms.map(find2);
15776
15852
  }
15777
- const count = (ti, a, b) => {
15853
+ const count2 = (ti, a, b) => {
15778
15854
  const ps = pos[ti];
15779
15855
  let lo = 0, hi = ps.length;
15780
15856
  while (lo < hi) {
@@ -15789,7 +15865,7 @@ function buildSnippet(row5, given, maxBytes, codeMaxBytes = SNIPPET_CODE_MAX_BYT
15789
15865
  const N = blocks.length;
15790
15866
  const blen = blocks.map((bk2) => rangeBytes(bk2.first, bk2.last));
15791
15867
  const avg = blen.reduce((a, b) => a + b, 0) / N || 1;
15792
- const tf = blocks.map((bk2) => terms.map((_, ti) => count(ti, ls[bk2.first], le[bk2.last])));
15868
+ const tf = blocks.map((bk2) => terms.map((_, ti) => count2(ti, ls[bk2.first], le[bk2.last])));
15793
15869
  const idf = terms.map((_, ti) => {
15794
15870
  let df = 0;
15795
15871
  for (let k = 0; k < N; k++) if (tf[k][ti] > 0) df++;
@@ -15811,7 +15887,7 @@ function buildSnippet(row5, given, maxBytes, codeMaxBytes = SNIPPET_CODE_MAX_BYT
15811
15887
  const lineScore = (i) => {
15812
15888
  let s = 0;
15813
15889
  terms.forEach((_, ti) => {
15814
- if (count(ti, ls[i], le[i]) > 0) s += weight(ti, bk.code);
15890
+ if (count2(ti, ls[i], le[i]) > 0) s += weight(ti, bk.code);
15815
15891
  });
15816
15892
  return s;
15817
15893
  };
@@ -15819,7 +15895,7 @@ function buildSnippet(row5, given, maxBytes, codeMaxBytes = SNIPPET_CODE_MAX_BYT
15819
15895
  let at2 = -1;
15820
15896
  let w = -1;
15821
15897
  terms.forEach((_, ti) => {
15822
- const c = count(ti, ls[i], le[i]);
15898
+ const c = count2(ti, ls[i], le[i]);
15823
15899
  if (c === 0 || weight(ti, bk.code) <= w) return;
15824
15900
  const ps = pos[ti];
15825
15901
  let lo = 0, hi = ps.length;
@@ -18069,8 +18145,8 @@ function parseSourceHandle(s) {
18069
18145
  function pathLabel(p) {
18070
18146
  return p.includes("\\") ? p.split("\\").join("/") : p;
18071
18147
  }
18072
- function labelStored(db, label) {
18073
- return stmt(db.raw, "SELECT 1 AS x FROM sources WHERE label = ? LIMIT 1").get(label) !== void 0;
18148
+ function labelStored(db, label2) {
18149
+ return stmt(db.raw, "SELECT 1 AS x FROM sources WHERE label = ? LIMIT 1").get(label2) !== void 0;
18074
18150
  }
18075
18151
  function storedLabel(db, source) {
18076
18152
  if (labelStored(db, source)) return source;
@@ -18100,9 +18176,9 @@ function insertUnits(db, sourceId, sessionId, units) {
18100
18176
  let start = 0;
18101
18177
  while (start < units.length) {
18102
18178
  let end = start;
18103
- let bytes4 = 0;
18104
- while (end < units.length && (end === start || bytes4 + units[end].body.length <= INDEX_WRITE_CHUNK)) {
18105
- bytes4 += units[end].body.length;
18179
+ let bytes5 = 0;
18180
+ while (end < units.length && (end === start || bytes5 + units[end].body.length <= INDEX_WRITE_CHUNK)) {
18181
+ bytes5 += units[end].body.length;
18106
18182
  end++;
18107
18183
  }
18108
18184
  const from = start;
@@ -18155,9 +18231,9 @@ function firstLine2(body) {
18155
18231
  return (nl < 0 ? body : body.slice(0, nl)).replaceAll("\r", " ");
18156
18232
  }
18157
18233
  function make(section, row5, text, repeatCount, query) {
18158
- const bytes4 = Buffer.byteLength(text, "utf8");
18159
- if (bytes4 < 1) throw new Error("compaction: empty candidate line (DECISIONS-r9 M9).");
18160
- return { section, seq: row5.seq, turn: row5.turn, text, bytes: bytes4, repeatCount, pinned: section === "last_request", query };
18234
+ const bytes5 = Buffer.byteLength(text, "utf8");
18235
+ if (bytes5 < 1) throw new Error("compaction: empty candidate line (DECISIONS-r9 M9).");
18236
+ return { section, seq: row5.seq, turn: row5.turn, text, bytes: bytes5, repeatCount, pinned: section === "last_request", query };
18161
18237
  }
18162
18238
  function capSection(list4) {
18163
18239
  return list4.length > MAX_CANDIDATES ? list4.slice(list4.length - MAX_CANDIDATES) : list4;
@@ -18449,8 +18525,8 @@ function mdChunks(src, cap, lineCut) {
18449
18525
  const stack = [];
18450
18526
  let title = "";
18451
18527
  let run = [];
18452
- const push2 = (text, bytes4) => {
18453
- out.push({ ord: out.length, text, bytes: bytes4, title });
18528
+ const push2 = (text, bytes5) => {
18529
+ out.push({ ord: out.length, text, bytes: bytes5, title });
18454
18530
  };
18455
18531
  const flush = () => {
18456
18532
  if (run.length === 0) return;
@@ -18500,19 +18576,19 @@ function lineBlocks(src, md) {
18500
18576
  let fenceInfo;
18501
18577
  const close = () => {
18502
18578
  if (start >= 0) {
18503
- const span = { start, end };
18504
- if (heading !== void 0) span.heading = heading;
18505
- if (fenceInfo !== void 0) span.fence = fenceInfo;
18506
- out.push(span);
18579
+ const span2 = { start, end };
18580
+ if (heading !== void 0) span2.heading = heading;
18581
+ if (fenceInfo !== void 0) span2.fence = fenceInfo;
18582
+ out.push(span2);
18507
18583
  }
18508
18584
  start = -1;
18509
18585
  heading = void 0;
18510
18586
  fenceInfo = void 0;
18511
18587
  };
18512
- const add = (from, to, table2) => {
18588
+ const add = (from, to, table3) => {
18513
18589
  if (start < 0) start = from;
18514
18590
  end = to;
18515
- inTable = table2;
18591
+ inTable = table3;
18516
18592
  };
18517
18593
  let pos = 0;
18518
18594
  while (pos <= src.length) {
@@ -18533,9 +18609,9 @@ function lineBlocks(src, md) {
18533
18609
  } else {
18534
18610
  const opener = md ? fenceOf(line) : "";
18535
18611
  const head = md && opener === "" ? headingOf(line) : void 0;
18536
- const table2 = md && opener === "" && head === void 0 && line.includes("|");
18537
- if (md && start >= 0 && (table2 !== inTable || opener !== "" || head !== void 0)) close();
18538
- add(pos, eol, table2);
18612
+ const table3 = md && opener === "" && head === void 0 && line.includes("|");
18613
+ if (md && start >= 0 && (table3 !== inTable || opener !== "" || head !== void 0)) close();
18614
+ add(pos, eol, table3);
18539
18615
  fence = opener;
18540
18616
  if (opener !== "") fenceInfo = { fence: opener, openEnd: eol, closeStart: -1 };
18541
18617
  if (head !== void 0) {
@@ -18695,17 +18771,17 @@ function cutPoint(src, start, end, scratch) {
18695
18771
  const r = encoder.encodeInto(src.slice(start, limit), scratch);
18696
18772
  return { end: start + r.read, written: r.written };
18697
18773
  }
18698
- function merge2(src, blocks, join25, cap, lineCut) {
18774
+ function merge2(src, blocks, join26, cap, lineCut) {
18699
18775
  const out = [];
18700
18776
  const scratch = new Uint8Array(cap);
18701
18777
  let wide;
18702
18778
  let cur;
18703
18779
  let curBytes = 0;
18704
- const emit = (start, end, bytes4) => {
18705
- out.push({ ord: out.length, text: src.slice(start, end), bytes: bytes4 });
18780
+ const emit = (start, end, bytes5) => {
18781
+ out.push({ ord: out.length, text: src.slice(start, end), bytes: bytes5 });
18706
18782
  };
18707
18783
  for (const b of blocks) {
18708
- if (cur !== void 0 && !join25) {
18784
+ if (cur !== void 0 && !join26) {
18709
18785
  emit(cur.start, cur.end, curBytes);
18710
18786
  cur = void 0;
18711
18787
  }
@@ -18720,15 +18796,15 @@ function merge2(src, blocks, join25, cap, lineCut) {
18720
18796
  cur = void 0;
18721
18797
  }
18722
18798
  let start = b.start;
18723
- let bytes4 = utf8Bytes(src.slice(b.start, b.end));
18724
- while (bytes4 > cap) {
18799
+ let bytes5 = utf8Bytes(src.slice(b.start, b.end));
18800
+ while (bytes5 > cap) {
18725
18801
  const cut = cutPoint(src, start, b.end, scratch);
18726
18802
  const nl = lineCut ? src.lastIndexOf("\n", cut.end - 1) : -1;
18727
18803
  if (nl > start) {
18728
18804
  const w = utf8Bytes(src.slice(start, nl + 1));
18729
18805
  emit(start, nl + 1, w);
18730
18806
  start = nl + 1;
18731
- bytes4 -= w;
18807
+ bytes5 -= w;
18732
18808
  continue;
18733
18809
  }
18734
18810
  if (lineCut) {
@@ -18738,23 +18814,23 @@ function merge2(src, blocks, join25, cap, lineCut) {
18738
18814
  if (w <= MAX_CHUNK_BYTES) {
18739
18815
  emit(start, lineEnd, w);
18740
18816
  start = lineEnd;
18741
- bytes4 -= w;
18817
+ bytes5 -= w;
18742
18818
  continue;
18743
18819
  }
18744
18820
  wide ??= new Uint8Array(MAX_CHUNK_BYTES);
18745
18821
  const big = cutPoint(src, start, lineEnd, wide);
18746
18822
  emit(start, big.end, big.written);
18747
18823
  start = big.end;
18748
- bytes4 -= big.written;
18824
+ bytes5 -= big.written;
18749
18825
  continue;
18750
18826
  }
18751
18827
  emit(start, cut.end, cut.written);
18752
18828
  start = cut.end;
18753
- bytes4 -= cut.written;
18829
+ bytes5 -= cut.written;
18754
18830
  }
18755
18831
  if (start >= b.end) continue;
18756
18832
  cur = { start, end: b.end };
18757
- curBytes = bytes4;
18833
+ curBytes = bytes5;
18758
18834
  }
18759
18835
  if (cur !== void 0) emit(cur.start, cur.end, curBytes);
18760
18836
  return out;
@@ -18775,7 +18851,7 @@ function selectChunks(db, sourceId, intent, budget) {
18775
18851
  function selectChunksInMemory(chunks, intent, budget, source, rankQuery) {
18776
18852
  return select(chunks, intent, budget, source, rankQuery);
18777
18853
  }
18778
- function select(chunks, intent, budget, label, rankQuery) {
18854
+ function select(chunks, intent, budget, label2, rankQuery) {
18779
18855
  if (chunks.length === 0) return { text: "", more: null };
18780
18856
  const texts = chunks.map((c) => c.text);
18781
18857
  const scores = rankQuery === void 0 ? rankTexts(texts, intent) : rankTexts(texts, rankQuery, "any");
@@ -18794,10 +18870,10 @@ function select(chunks, intent, budget, label, rankQuery) {
18794
18870
  }
18795
18871
  picked.sort((a, b) => a.ord - b.ord);
18796
18872
  const text = picked.map((c) => c.text).join(SEP);
18797
- return { text, more: skipped ? moreLine2(intent, label) : null };
18873
+ return { text, more: skipped ? moreLine2(intent, label2) : null };
18798
18874
  }
18799
- function moreLine2(intent, label) {
18800
- const source = label === void 0 ? "" : ", source:" + JSON.stringify(label);
18875
+ function moreLine2(intent, label2) {
18876
+ const source = label2 === void 0 ? "" : ", source:" + JSON.stringify(label2);
18801
18877
  const query = Buffer.byteLength(intent, "utf8") > ECHO_MAX_BYTES ? "..." : JSON.stringify(intent);
18802
18878
  return "ctx_search({queries:[" + query + "]" + source + "})";
18803
18879
  }
@@ -18845,10 +18921,10 @@ function firstNonSpace(s) {
18845
18921
  function isPlainObject2(v) {
18846
18922
  return typeof v === "object" && v !== null && !Array.isArray(v);
18847
18923
  }
18848
- function rareOfSkewed(n, counts, totals) {
18849
- if (totals.size < 2 || totals.size > SHAPE_CATEGORICAL_MAX) return [];
18850
- const sorted = [...totals.entries()].sort((a, b) => b[1] - a[1]);
18851
- if (totals.size <= SHAPE_RARE_MAX + 1) {
18924
+ function rareOfSkewed(n, counts, totals2) {
18925
+ if (totals2.size < 2 || totals2.size > SHAPE_CATEGORICAL_MAX) return [];
18926
+ const sorted = [...totals2.entries()].sort((a, b) => b[1] - a[1]);
18927
+ if (totals2.size <= SHAPE_RARE_MAX + 1) {
18852
18928
  if (sorted[0][1] < SHAPE_DOMINANT * n || n - sorted[0][1] > SHAPE_RARE_MAX) return [];
18853
18929
  return sorted.slice(1).flatMap(([v]) => counts.get(v) ?? []);
18854
18930
  }
@@ -18883,7 +18959,7 @@ function jsonShape(text, query) {
18883
18959
  const outliers = /* @__PURE__ */ new Map();
18884
18960
  for (const k of keys) {
18885
18961
  const counts = /* @__PURE__ */ new Map();
18886
- const totals = /* @__PURE__ */ new Map();
18962
+ const totals2 = /* @__PURE__ */ new Map();
18887
18963
  let scalar = true;
18888
18964
  for (let i = 0; i < objs.length && scalar; i++) {
18889
18965
  const v = k in objs[i] ? objs[i][k] : void 0;
@@ -18892,14 +18968,14 @@ function jsonShape(text, query) {
18892
18968
  break;
18893
18969
  }
18894
18970
  const s = v === void 0 ? ABSENT : JSON.stringify(v);
18895
- totals.set(s, (totals.get(s) ?? 0) + 1);
18971
+ totals2.set(s, (totals2.get(s) ?? 0) + 1);
18896
18972
  const at2 = counts.get(s) ?? [];
18897
18973
  if (at2.length <= SHAPE_RARE_MAX) at2.push(i);
18898
18974
  counts.set(s, at2);
18899
- if (totals.size > SHAPE_CATEGORICAL_MAX) break;
18975
+ if (totals2.size > SHAPE_CATEGORICAL_MAX) break;
18900
18976
  }
18901
18977
  if (!scalar) continue;
18902
- for (const i of rareOfSkewed(objs.length, counts, totals)) outliers.set(i, [...outliers.get(i) ?? [], k]);
18978
+ for (const i of rareOfSkewed(objs.length, counts, totals2)) outliers.set(i, [...outliers.get(i) ?? [], k]);
18903
18979
  }
18904
18980
  if (outliers.size === 0 || outliers.size > SHAPE_RARE_UNITS_MAX) return null;
18905
18981
  const keyScore = rankTexts(keys, query, "any");
@@ -19027,14 +19103,14 @@ function lineShape(text) {
19027
19103
  }
19028
19104
 
19029
19105
  // src/core/index/text.ts
19030
- function storeText(db, project, sessionId, sourceKind, label, text, kind, chunks = chunkText(text, kind)) {
19106
+ function storeText(db, project, sessionId, sourceKind, label2, text, kind, chunks = chunkText(text, kind)) {
19031
19107
  const sourceId = ftsInsert(db, {
19032
19108
  projectKey: project.projectKey,
19033
19109
  sessionId,
19034
19110
  worktree: project.worktree,
19035
19111
  agent: project.agent,
19036
19112
  kind: sourceKind,
19037
- label,
19113
+ label: label2,
19038
19114
  bytes: Buffer.byteLength(text, "utf8"),
19039
19115
  chunkCount: chunks.length,
19040
19116
  createdAt: Date.now()
@@ -19097,9 +19173,9 @@ function answerDecisions(responseText) {
19097
19173
  if (!isObject3(parsed)) return [];
19098
19174
  const out = [];
19099
19175
  for (const [question, value] of answerPairs(parsed[DECISION_ANSWERS_KEY])) {
19100
- const label = labelText(value);
19101
- if (question === "" || label === "") continue;
19102
- out.push({ key: question, body: "Q: " + question + " \u2192 A: " + label });
19176
+ const label2 = labelText(value);
19177
+ if (question === "" || label2 === "") continue;
19178
+ out.push({ key: question, body: "Q: " + question + " \u2192 A: " + label2 });
19103
19179
  }
19104
19180
  return out;
19105
19181
  }
@@ -19119,9 +19195,9 @@ function fold(s) {
19119
19195
  function optionEchoDecision(prompt, labels, refSeq) {
19120
19196
  const p = fold(prompt);
19121
19197
  if (p === "") return null;
19122
- const label = labels.find((l) => fold(l) === p);
19123
- if (label === void 0) return null;
19124
- return { key: DECISION_OPTION_KEY, body: "A: " + label + "\nref: #" + refSeq };
19198
+ const label2 = labels.find((l) => fold(l) === p);
19199
+ if (label2 === void 0) return null;
19200
+ return { key: DECISION_OPTION_KEY, body: "A: " + label2 + "\nref: #" + refSeq };
19125
19201
  }
19126
19202
 
19127
19203
  // src/core/hooks/throttle.ts
@@ -19135,9 +19211,9 @@ function takeOnce(db, key) {
19135
19211
  }
19136
19212
  function takeEvery(db, key, everyN) {
19137
19213
  const stored = metaGet(db, key);
19138
- const count = (stored === null ? 0 : Number.parseInt(stored, 10)) + 1;
19139
- metaSet(db, key, String(count));
19140
- return (count - 1) % everyN === 0;
19214
+ const count2 = (stored === null ? 0 : Number.parseInt(stored, 10)) + 1;
19215
+ metaSet(db, key, String(count2));
19216
+ return (count2 - 1) % everyN === 0;
19141
19217
  }
19142
19218
  function shouldHint(db, sessionId, onceKey, everyN) {
19143
19219
  if (sessionId === "") return false;
@@ -19630,33 +19706,33 @@ async function postReplace(ev, row5, project, env, tool, result, text) {
19630
19706
  if (result.bytes <= REPLACE_TRIGGER_BYTES) return ALLOW2;
19631
19707
  if (result.keep === true) return ALLOW2;
19632
19708
  if (!hasReplace(row5)) return ALLOW2;
19633
- let label;
19709
+ let label2;
19634
19710
  if (isSubagentCall(ev)) {
19635
19711
  const subCase = pickSubagentCase(ev, toolSetForAgentType(ev, { projectDir: project.worktree, env }));
19636
19712
  if (subCase === "A") return ALLOW2;
19637
- label = SUBAGENT_SOURCE_PREFIX + tool.canonicalName + ":" + String(ev.turn ?? 0);
19713
+ label2 = SUBAGENT_SOURCE_PREFIX + tool.canonicalName + ":" + String(ev.turn ?? 0);
19638
19714
  } else {
19639
- label = mainLabel(tool, ev);
19715
+ label2 = mainLabel(tool, ev);
19640
19716
  }
19641
19717
  const intent = [tool.input.description, tool.input.command, tool.input.file_path, tool.input.pattern, tool.input.url].map(str2).find((v) => v.trim() !== "") ?? "";
19642
19718
  const chunks = chunkText(text, "text", REPLACE_CHUNK_BYTES);
19643
19719
  const db = await openDb(project);
19644
19720
  let sourceId;
19645
19721
  if (result.bytes <= SYNC_INDEX_MAX_BYTES) {
19646
- sourceId = indexText(db, project, ev.sessionId, label, text, "text", chunks).sourceId;
19722
+ sourceId = indexText(db, project, ev.sessionId, label2, text, "text", chunks).sourceId;
19647
19723
  insertUnits(db, sourceId, ev.sessionId, buildUnits(text));
19648
19724
  } else {
19649
- sourceId = reserveSource(db, sourceRowOf(project, ev.sessionId, label), chunks);
19650
- indexDetached(project, ev.sessionId, sourceId, label, text, chunks);
19725
+ sourceId = reserveSource(db, sourceRowOf(project, ev.sessionId, label2), chunks);
19726
+ indexDetached(project, ev.sessionId, sourceId, label2, text, chunks);
19651
19727
  }
19652
19728
  const handle = sourceHandle(sourceId);
19653
19729
  const prompt = await lastPrompt(project, ev.sessionId);
19654
19730
  const rankQuery = prompt.trim() === "" ? void 0 : intent + " " + prompt;
19655
19731
  const handleLine = REPLACE_HANDLE_LINE(intent, handle, result.bytes, row5.toolNamePrefix, askedWords(intent, prompt, text));
19656
- const budget = replaceBudget(handleLine, moreLine2(intent, label));
19732
+ const budget = replaceBudget(handleLine, moreLine2(intent, label2));
19657
19733
  const digest = shapeDigest(text, rankQuery ?? intent, SHAPE_RETURN_BYTES);
19658
19734
  if (digest !== null) return { kind: "replace", output: replaceOutput(digest, handleLine) };
19659
- const selected = selectChunksInMemory(chunks, intent, budget, label, rankQuery);
19735
+ const selected = selectChunksInMemory(chunks, intent, budget, label2, rankQuery);
19660
19736
  return { kind: "replace", output: selected.more !== null ? replaceOutput(selected.text, handleLine) : selected.text };
19661
19737
  }
19662
19738
  function replaceOutput(body, handleLine) {
@@ -19687,15 +19763,15 @@ function mainLabel(tool, ev) {
19687
19763
  const head = (tool.canonicalName + ":" + (nl < 0 ? cmd : cmd.slice(0, nl))).slice(0, SOURCE_LABEL_MAX_CHARS);
19688
19764
  return head + "#" + (tool.callId ?? String(ev.turn ?? 0));
19689
19765
  }
19690
- function indexDetached(project, sessionId, sourceId, label, text, chunks) {
19766
+ function indexDetached(project, sessionId, sourceId, label2, text, chunks) {
19691
19767
  void openDb(project).then((db) => {
19692
- finishReserved(db, sourceId, sourceRowOf(project, sessionId, label), chunks, buildUnits(text));
19768
+ finishReserved(db, sourceId, sourceRowOf(project, sessionId, label2), chunks, buildUnits(text));
19693
19769
  }).catch((err) => {
19694
19770
  process.stderr.write("hooks: index write failed: " + message(err) + "\n");
19695
19771
  });
19696
19772
  }
19697
- function sourceRowOf(project, sessionId, label) {
19698
- return { sessionId, worktree: project.worktree, agent: project.agent, kind: "content", label, createdAt: Date.now() };
19773
+ function sourceRowOf(project, sessionId, label2) {
19774
+ return { sessionId, worktree: project.worktree, agent: project.agent, kind: "content", label: label2, createdAt: Date.now() };
19699
19775
  }
19700
19776
  async function preCompact(ev, row5, project) {
19701
19777
  const db = await openDb(project);
@@ -20156,7 +20232,7 @@ function relevance(db, given, scope, ctx) {
20156
20232
  mine.add(hit.sourceId);
20157
20233
  }
20158
20234
  if (again.size > 0) {
20159
- const line = "Same as above: " + [...again].map(([label, ords]) => label + " (chunk " + ords.join(",") + ")").join("; ");
20235
+ const line = "Same as above: " + [...again].map(([label2, ords]) => label2 + " (chunk " + ords.join(",") + ")").join("; ");
20160
20236
  lines.push(line);
20161
20237
  used += bytes2(line) + 1;
20162
20238
  }
@@ -20303,7 +20379,7 @@ function shown(chunks, heads) {
20303
20379
  return c.text;
20304
20380
  });
20305
20381
  }
20306
- function indexCombined(db, ctx, label, ran, deadline, budgetBytes) {
20382
+ function indexCombined(db, ctx, label2, ran, deadline, budgetBytes) {
20307
20383
  const chunks = chunkText(ran.map((r) => r.block).join(BLOCK_SEP), "text");
20308
20384
  const display = shown(chunks, ran.map((r) => r.head));
20309
20385
  const bodies = /* @__PURE__ */ new Map();
@@ -20323,7 +20399,7 @@ function indexCombined(db, ctx, label, ran, deadline, budgetBytes) {
20323
20399
  worktree: ctx.project.worktree,
20324
20400
  agent: ctx.project.agent,
20325
20401
  kind: "content",
20326
- label,
20402
+ label: label2,
20327
20403
  bytes: groupBytes,
20328
20404
  chunkCount: group.length,
20329
20405
  createdAt: Date.now()
@@ -20353,12 +20429,12 @@ function indexCombined(db, ctx, label, ran, deadline, budgetBytes) {
20353
20429
  function bytes3(s) {
20354
20430
  return Buffer.byteLength(s, "utf8");
20355
20431
  }
20356
- function answer(db, ctx, label, queries, share, own4) {
20432
+ function answer(db, ctx, label2, queries, share, own4) {
20357
20433
  const seen = /* @__PURE__ */ new Set();
20358
20434
  const lines = [];
20359
20435
  for (const [qi, q] of queries.entries()) {
20360
20436
  if (ctx.signal.aborted) break;
20361
- let hits = ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0, label);
20437
+ let hits = ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0, label2);
20362
20438
  if (hits.length === 0) hits = ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0);
20363
20439
  const head = "## " + (bytes3(q) > ECHO_MAX_BYTES ? "query " + (qi + 1) : q);
20364
20440
  let used = bytes3(head) + 1;
@@ -20397,17 +20473,17 @@ async function runBatch(input, ctx, boundMs, budgetBytes) {
20397
20473
  const ran = pool.results;
20398
20474
  const last2 = ran[ran.length - 1];
20399
20475
  const sandboxBytes = ran.reduce((n, r) => n + r.bytes, 0);
20400
- const label = LABEL_PREFIX + ctx.turn;
20476
+ const label2 = LABEL_PREFIX + ctx.turn;
20401
20477
  try {
20402
20478
  const db = await openDb(ctx.project);
20403
20479
  let sections;
20404
20480
  let idx;
20405
20481
  const exitLine = last2.exitCode === null || last2.exitCode === 0 ? null : "exit " + last2.exitCode;
20406
- const footer = "more: ctx_search({queries:[...], source:" + JSON.stringify(label) + "})";
20482
+ const footer = "more: ctx_search({queries:[...], source:" + JSON.stringify(label2) + "})";
20407
20483
  let notice;
20408
20484
  let showMore;
20409
20485
  try {
20410
- idx = indexCombined(db, ctx, label, ran, deadline, budgetBytes);
20486
+ idx = indexCombined(db, ctx, label2, ran, deadline, budgetBytes);
20411
20487
  const stop = last2.error;
20412
20488
  const cut = idx.indexed < idx.total ? "Indexed " + idx.indexed + " of " + idx.total + " B." : null;
20413
20489
  const timeout = formatError2("TIMEOUT", { ms: boundMs });
@@ -20415,7 +20491,7 @@ async function runBatch(input, ctx, boundMs, budgetBytes) {
20415
20491
  notice = cut === null ? stop : cause === null ? cut : cause + " " + cut;
20416
20492
  const fixed = (exitLine === null ? 0 : bytes3(exitLine) + 1) + (notice === null ? 0 : bytes3(notice) + 1) + bytes3(footer);
20417
20493
  const share = Math.floor((OUTPUT_CAP - fixed) / queries.length);
20418
- const answered = answer(db, ctx, label, queries, share, idx.bodies);
20494
+ const answered = answer(db, ctx, label2, queries, share, idx.bodies);
20419
20495
  sections = answered.lines;
20420
20496
  const unseen = [...idx.bodies].filter(([k, text]) => text !== "" && !answered.seen.has(k)).map(([k]) => idx.raw.get(k));
20421
20497
  const unseenBytes = unseen.reduce((n, t) => n + bytes3(t) + 1, 0);
@@ -20451,8 +20527,8 @@ var ctxBatch = Object.freeze({
20451
20527
  });
20452
20528
 
20453
20529
  // src/core/tools/doctor.ts
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";
20530
+ import { readdirSync as readdirSync5, readFileSync as readFileSync12, existsSync as existsSync12 } from "node:fs";
20531
+ import { basename as basename4, dirname as dirname7, join as join14 } from "node:path";
20456
20532
 
20457
20533
  // src/core/ops/doctor-config.ts
20458
20534
  import { existsSync as existsSync6, readdirSync as readdirSync3 } from "node:fs";
@@ -21622,7 +21698,7 @@ var Tokenizer = class {
21622
21698
  hasUnderscore
21623
21699
  };
21624
21700
  }
21625
- parseUnicode(count) {
21701
+ parseUnicode(count2) {
21626
21702
  const startLoc = this.codePointIterator.start;
21627
21703
  const start = this.codePointIterator.end;
21628
21704
  let charCount = 0;
@@ -21633,7 +21709,7 @@ var Tokenizer = class {
21633
21709
  return this.reportParseError("invalid-char-in-escape-sequence");
21634
21710
  }
21635
21711
  charCount++;
21636
- if (charCount >= count) break;
21712
+ if (charCount >= count2) break;
21637
21713
  }
21638
21714
  const end = this.codePointIterator.end;
21639
21715
  const code = this.text.slice(start, end);
@@ -22399,17 +22475,17 @@ function generateConvertTOMLValue(convertValue) {
22399
22475
  return baseTable;
22400
22476
  },
22401
22477
  TOMLTable(node3, baseTable = {}) {
22402
- const table2 = getTable(baseTable, resolveValue(node3.key), node3.kind === "array");
22403
- for (const body of node3.body) resolveValue(body, table2);
22478
+ const table3 = getTable(baseTable, resolveValue(node3.key), node3.kind === "array");
22479
+ for (const body of node3.body) resolveValue(body, table3);
22404
22480
  return baseTable;
22405
22481
  },
22406
22482
  TOMLArray(node3) {
22407
22483
  return node3.elements.map((e) => resolveValue(e));
22408
22484
  },
22409
22485
  TOMLInlineTable(node3) {
22410
- const table2 = {};
22411
- for (const body of node3.body) resolveValue(body, table2);
22412
- return table2;
22486
+ const table3 = {};
22487
+ for (const body of node3.body) resolveValue(body, table3);
22488
+ return table3;
22413
22489
  },
22414
22490
  TOMLKey(node3) {
22415
22491
  return node3.keys.map((key) => resolveValue(key));
@@ -23149,10 +23225,10 @@ function scanCodex(agentHome, out) {
23149
23225
  }
23150
23226
  const tomlFile = join9(agentHome, CONFIG_TOML_FILE);
23151
23227
  const config4 = readTomlValue(tomlFile);
23152
- for (const span of readTomlTables(tomlFile)) {
23153
- if (span.path[0] !== V1_TOML_SECTION_ROOT || span.path[1] !== SERVER_KEY) continue;
23154
- if (span.path.length === 2 && isV2McpTable(hostConfigValueAt(config4, span.path))) continue;
23155
- out.push(finding(tomlFile, span.header.trim(), V1_REASON.codexToml));
23228
+ for (const span2 of readTomlTables(tomlFile)) {
23229
+ if (span2.path[0] !== V1_TOML_SECTION_ROOT || span2.path[1] !== SERVER_KEY) continue;
23230
+ if (span2.path.length === 2 && isV2McpTable(hostConfigValueAt(config4, span2.path))) continue;
23231
+ out.push(finding(tomlFile, span2.header.trim(), V1_REASON.codexToml));
23156
23232
  }
23157
23233
  dataDir(join9(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
23158
23234
  }
@@ -23741,29 +23817,92 @@ async function checkIndex(project) {
23741
23817
  }
23742
23818
 
23743
23819
  // src/core/ops/doctor-env.ts
23744
- import { existsSync as existsSync8, realpathSync as realpathSync5 } from "node:fs";
23745
- import { isAbsolute as isAbsolute3, relative as relative2 } from "node:path";
23820
+ import { existsSync as existsSync8, readFileSync as readFileSync9, realpathSync as realpathSync5 } from "node:fs";
23821
+ import { isAbsolute as isAbsolute3, join as join12, relative as relative2 } from "node:path";
23746
23822
  function pass3(id, detail = DOCTOR_PASS_DETAIL) {
23747
23823
  return { id, label: DOCTOR_LABEL[id], status: "PASS", detail };
23748
23824
  }
23749
- function unknown3(id, detail) {
23750
- return { id, label: DOCTOR_LABEL[id], status: "UNKNOWN", detail };
23825
+ function unknown3(id, detail, fixCommand) {
23826
+ return fixCommand === void 0 ? { id, label: DOCTOR_LABEL[id], status: "UNKNOWN", detail } : { id, label: DOCTOR_LABEL[id], status: "UNKNOWN", detail, fixCommand };
23751
23827
  }
23752
23828
  function fail4(id, detail, fixCommand) {
23753
23829
  return { id, label: DOCTOR_LABEL[id], status: "FAIL", detail, fixCommand };
23754
23830
  }
23831
+ function bundleVersion(bundleDir2) {
23832
+ try {
23833
+ const v = JSON.parse(readFileSync9(join12(bundleDir2, D1_PACKAGE_FILE), "utf8")).version;
23834
+ return typeof v === "string" && v !== "" ? v : void 0;
23835
+ } catch {
23836
+ return void 0;
23837
+ }
23838
+ }
23839
+ function channelOf(version4) {
23840
+ const at2 = version4.indexOf(D1_PRERELEASE_SEP);
23841
+ if (at2 < 0) return D1_DEFAULT_TAG;
23842
+ const pre = version4.slice(at2 + 1);
23843
+ const dot = pre.indexOf(".");
23844
+ const tag2 = dot < 0 ? pre : pre.slice(0, dot);
23845
+ return tag2 === "" ? D1_DEFAULT_TAG : tag2;
23846
+ }
23847
+ function firstLine3(b) {
23848
+ const text = b.toString("utf8").trim();
23849
+ const nl = text.indexOf("\n");
23850
+ return (nl < 0 ? text : text.slice(0, nl)).trim();
23851
+ }
23852
+ function gitCause(r, timeoutMs) {
23853
+ if (r.killed === "timeout") return D1_GIT_TIMEOUT(timeoutMs);
23854
+ if (r.killed === "cancel") return D1_GIT_CANCEL;
23855
+ if (r.exitCode === null) return D1_GIT_NO_START;
23856
+ return D1_GIT_EXIT(r.exitCode, firstLine3(r.stderr));
23857
+ }
23858
+ function fetchCause(err, timeoutMs) {
23859
+ const name = err instanceof Error ? err.name : "";
23860
+ if (name === "TimeoutError") return D1_NPM_TIMEOUT(timeoutMs);
23861
+ const cause = err instanceof Error && err.cause instanceof Error ? err.cause : err;
23862
+ const code = typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string" ? cause.code : "";
23863
+ const msg = cause instanceof Error ? cause.message : String(cause);
23864
+ return D1_NPM_ERROR(code !== "" && !msg.includes(code) ? `${code} ${msg}` : msg);
23865
+ }
23866
+ async function npmLatest(url4, tag2, signal, timeoutMs) {
23867
+ try {
23868
+ const res = await fetch(url4, { signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) });
23869
+ if (!res.ok) return { ok: false, cause: D1_NPM_HTTP(res.status) };
23870
+ const body = await res.json();
23871
+ const v = typeof body === "object" && body !== null ? body[tag2] : void 0;
23872
+ return typeof v === "string" && v !== "" ? { ok: true, version: v } : { ok: false, cause: D1_NPM_NO_TAG(tag2) };
23873
+ } catch (err) {
23874
+ return { ok: false, cause: fetchCause(err, timeoutMs) };
23875
+ }
23876
+ }
23755
23877
  async function checkVersion(i) {
23756
23878
  if (i.bundleSha === void 0) return unknown3("D1", D1_DEV_BUILD_DETAIL);
23757
- const r = await runProcess([GIT_BIN, GIT_LS_REMOTE, RELEASE_REPO_URL, RELEASE_BRANCH], {
23758
- cwd: i.cwd,
23759
- env: { ...i.env, ...GIT_NO_PROMPT_ENV },
23760
- signal: i.signal,
23761
- timeoutMs: DOCTOR_GIT_TIMEOUT_MS
23762
- });
23763
- if (r.exitCode !== 0 || r.killed !== null) return unknown3("D1", D1_NO_NETWORK_DETAIL);
23764
- const latest = r.stdout.toString("utf8").split(LS_REMOTE_FIELD_SEP)[0];
23765
- if (latest.length !== GIT_SHA_HEX_LEN) return unknown3("D1", D1_NO_NETWORK_DETAIL);
23766
- return latest === i.bundleSha ? pass3("D1") : fail4("D1", D1_UPDATE_DETAIL, DOCTOR_FIX_UPGRADE);
23879
+ const head = D1_PREFIX(i.version, i.bundleSha) + ": ";
23880
+ const git3 = findRuntime(GIT_BIN, i.env);
23881
+ let cause = D1_GIT_MISSING;
23882
+ if (git3 !== null) {
23883
+ const r = await runProcess([git3, GIT_LS_REMOTE, RELEASE_REPO_URL, RELEASE_BRANCH], {
23884
+ cwd: i.cwd,
23885
+ env: { ...i.env, ...GIT_NO_PROMPT_ENV },
23886
+ signal: i.signal,
23887
+ timeoutMs: i.timeoutMs
23888
+ });
23889
+ if (r.exitCode === 0 && r.killed === null) {
23890
+ const latest = r.stdout.toString("utf8").split(LS_REMOTE_FIELD_SEP)[0];
23891
+ if (latest.length === GIT_SHA_HEX_LEN) {
23892
+ return latest === i.bundleSha ? pass3("D1", head + D1_GIT_PASS) : fail4("D1", head + D1_UPDATE_DETAIL, DOCTOR_FIX_UPGRADE);
23893
+ }
23894
+ cause = D1_GIT_NO_SHA;
23895
+ } else {
23896
+ cause = gitCause(r, i.timeoutMs);
23897
+ }
23898
+ }
23899
+ const handFix = git3 === null ? D1_NPM_CHECK_FIX : D1_GIT_CHECK_FIX;
23900
+ if (i.version === void 0) return unknown3("D1", head + D1_LATEST_UNKNOWN + ", " + cause, handFix);
23901
+ const tag2 = channelOf(i.version);
23902
+ const npm = await npmLatest(i.registryUrl, tag2, i.signal, i.timeoutMs);
23903
+ if (!npm.ok) return unknown3("D1", head + D1_LATEST_UNKNOWN + ", " + cause + D1_CAUSE_JOIN + npm.cause, handFix);
23904
+ if (npm.version === i.version) return pass3("D1", head + D1_NPM_PASS(tag2) + D1_CAUSE_JOIN + cause);
23905
+ return fail4("D1", head + D1_NPM_UPDATE(tag2, npm.version) + D1_CAUSE_JOIN + cause, DOCTOR_FIX_UPGRADE);
23767
23906
  }
23768
23907
  function numbers(v) {
23769
23908
  const bare2 = v.startsWith(NODE_VERSION_PREFIX) ? v.slice(NODE_VERSION_PREFIX.length) : v;
@@ -23820,7 +23959,7 @@ function checkShell(env) {
23820
23959
  }
23821
23960
 
23822
23961
  // src/core/ops/doctor-hook.ts
23823
- import { existsSync as existsSync10, readFileSync as readFileSync9, realpathSync as realpathSync7 } from "node:fs";
23962
+ import { existsSync as existsSync10, readFileSync as readFileSync10, realpathSync as realpathSync7 } from "node:fs";
23824
23963
  import path6 from "node:path";
23825
23964
 
23826
23965
  // src/setup/codex-trust.ts
@@ -24045,7 +24184,7 @@ function loadFixture(bundleDir2, agent) {
24045
24184
  if (!existsSync10(file2)) return null;
24046
24185
  let all;
24047
24186
  try {
24048
- all = JSON.parse(hostText(readFileSync9(file2, "utf8")));
24187
+ all = JSON.parse(hostText(readFileSync10(file2, "utf8")));
24049
24188
  } catch {
24050
24189
  return null;
24051
24190
  }
@@ -24141,13 +24280,13 @@ async function checkHookRoundTrip(i) {
24141
24280
  import { existsSync as existsSync11, rmSync as rmSync3 } from "node:fs";
24142
24281
 
24143
24282
  // src/core/store/owners.ts
24144
- import { mkdirSync as mkdirSync4, readdirSync as readdirSync4, readFileSync as readFileSync10, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
24145
- import { basename as basename3, join as join12 } from "node:path";
24283
+ import { mkdirSync as mkdirSync4, readdirSync as readdirSync4, readFileSync as readFileSync11, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
24284
+ import { basename as basename3, join as join13 } from "node:path";
24146
24285
  function ownersDir(configDir, projectKey) {
24147
- return join12(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
24286
+ return join13(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
24148
24287
  }
24149
24288
  function ownerFile(configDir, projectKey, serverId) {
24150
- return join12(ownersDir(configDir, projectKey), serverId + OWNER_PID_EXT);
24289
+ return join13(ownersDir(configDir, projectKey), serverId + OWNER_PID_EXT);
24151
24290
  }
24152
24291
  function errCode2(err) {
24153
24292
  return err.code;
@@ -24182,10 +24321,10 @@ function listLiveOwners(configDir, projectKey) {
24182
24321
  const live = [];
24183
24322
  for (const name of names) {
24184
24323
  if (!name.endsWith(OWNER_PID_EXT)) continue;
24185
- const file2 = join12(dir, name);
24324
+ const file2 = join13(dir, name);
24186
24325
  let text;
24187
24326
  try {
24188
- text = readFileSync10(file2, "utf8");
24327
+ text = readFileSync11(file2, "utf8");
24189
24328
  } catch (err) {
24190
24329
  if (errCode2(err) === "ENOENT") continue;
24191
24330
  throw err;
@@ -24342,11 +24481,11 @@ async function hookRow(ctx, adapter, host) {
24342
24481
  }
24343
24482
  }
24344
24483
  function ownServerId(configDir, projectKey) {
24345
- const dir = join13(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
24484
+ const dir = join14(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
24346
24485
  if (!existsSync12(dir)) return "";
24347
24486
  for (const name of readdirSync5(dir)) {
24348
24487
  if (!name.endsWith(OWNER_PID_EXT)) continue;
24349
- if (readFileSync11(join13(dir, name), "utf8").trim() === String(process.pid)) return basename4(name, OWNER_PID_EXT);
24488
+ if (readFileSync12(join14(dir, name), "utf8").trim() === String(process.pid)) return basename4(name, OWNER_PID_EXT);
24350
24489
  }
24351
24490
  return "";
24352
24491
  }
@@ -24356,7 +24495,7 @@ async function runDoctorChecks(ctx, adapter, host0) {
24356
24495
  const project = ctx.project;
24357
24496
  let integrityFailed = false;
24358
24497
  const checks = {
24359
- D1: () => checkVersion({ bundleSha: BUNDLE_SHA, env: buildChildEnv(env), cwd: project.worktree, signal: ctx.signal }),
24498
+ D1: () => checkVersion({ bundleSha: BUNDLE_SHA, version: bundleVersion(host.bundleDir), registryUrl: D1_REGISTRY_URL, timeoutMs: DOCTOR_GIT_TIMEOUT_MS, env: buildChildEnv(env), cwd: project.worktree, signal: ctx.signal }),
24360
24499
  D2: () => checkNode({ nodeVersion: process.version, bunVersion: process.versions.bun }),
24361
24500
  D3: () => checkHostConfig(adapter, env, project.worktree),
24362
24501
  D4: () => checkV1Leftovers(adapter.id, requireHomeDir(env), { project: project.worktree, piAgentDir: piAgentDirOf(env, requireHomeDir(env)), claudeDir: claudeDirOf(env, requireHomeDir(env)), codexDir: codexDirOf(env, requireHomeDir(env)), copilotDir: copilotDirOf(env, requireHomeDir(env)), kiroDir: kiroDirOf(env, requireHomeDir(env)), opencodeDir: opencodeDirOf(env, requireHomeDir(env)) }),
@@ -24398,8 +24537,8 @@ async function handler2(_input, ctx) {
24398
24537
  const command = `context-mode ${rows.some((r) => r.status === "FAIL") ? "setup" : "doctor"} --agents ${adapter.id}`;
24399
24538
  const input = { agent: adapter.id, rows, env: reportEnv(process.env), command };
24400
24539
  const whole = buildReport(input);
24401
- const bytes4 = Buffer.byteLength(whole, "utf8");
24402
- if (bytes4 <= REPORT_CAP) return { text: whole, isError: false, sandboxBytes: bytes4 };
24540
+ const bytes5 = Buffer.byteLength(whole, "utf8");
24541
+ if (bytes5 <= REPORT_CAP) return { text: whole, isError: false, sandboxBytes: bytes5 };
24403
24542
  const db = await openDb(ctx.project);
24404
24543
  try {
24405
24544
  indexText(db, ctx.project, ctx.sessionId, REPORT_SOURCE_LABEL, whole, "text");
@@ -24407,7 +24546,7 @@ async function handler2(_input, ctx) {
24407
24546
  closeDb(db);
24408
24547
  }
24409
24548
  const text = buildReportHead(input);
24410
- return { text, isError: false, sandboxBytes: bytes4 };
24549
+ return { text, isError: false, sandboxBytes: bytes5 };
24411
24550
  }
24412
24551
  var ctxDoctor = Object.freeze({
24413
24552
  name: "ctx_doctor",
@@ -24421,7 +24560,7 @@ var ctxDoctor = Object.freeze({
24421
24560
  // src/core/tools/execute.ts
24422
24561
  import { existsSync as existsSync13, mkdtempSync, rmSync as rmSync4, writeFileSync as writeFileSync3 } from "node:fs";
24423
24562
  import { tmpdir as tmpdir2 } from "node:os";
24424
- import { dirname as dirname8, join as join14, parse as parse3, resolve as resolve6 } from "node:path";
24563
+ import { dirname as dirname8, join as join15, parse as parse3, resolve as resolve6 } from "node:path";
24425
24564
 
24426
24565
  // src/core/sandbox/win-build.ts
24427
24566
  var SEPARATORS2 = ";&|(\n";
@@ -24531,8 +24670,8 @@ function sourceLabel(code) {
24531
24670
  const first = nl < 0 ? code : code.slice(0, nl);
24532
24671
  return Array.from(TOOL2 + ":" + first).slice(0, SOURCE_LABEL_MAX_CHARS).join("");
24533
24672
  }
24534
- function moreReserve(intent, label) {
24535
- return Buffer.byteLength(moreLine2(intent, label), "utf8");
24673
+ function moreReserve(intent, label2) {
24674
+ return Buffer.byteLength(moreLine2(intent, label2), "utf8");
24536
24675
  }
24537
24676
  function spawnFailed(argv0, cwd) {
24538
24677
  return new CtxError("SPAWN_FAILED", { detail: argv0 + " gave no exit code in " + cwd }).toLine();
@@ -24549,12 +24688,12 @@ async function finish(input, ctx, r, exitCode, journal) {
24549
24688
  if (intent === "" && fits) {
24550
24689
  return { text: direct, isError, sandboxBytes: fullBytes, journal };
24551
24690
  }
24552
- const label = sourceLabel(input.code);
24553
- const budget = (fits ? OUTPUT_CAP : EXEC_PREVIEW_BYTES) - Buffer.byteLength(head, "utf8") - 2 - moreReserve(intent, label);
24691
+ const label2 = sourceLabel(input.code);
24692
+ const budget = (fits ? OUTPUT_CAP : EXEC_PREVIEW_BYTES) - Buffer.byteLength(head, "utf8") - 2 - moreReserve(intent, label2);
24554
24693
  const db = await openDb(ctx.project);
24555
24694
  let picked;
24556
24695
  try {
24557
- const { sourceId } = indexText(db, ctx.project, ctx.sessionId, label, combined, "text");
24696
+ const { sourceId } = indexText(db, ctx.project, ctx.sessionId, label2, combined, "text");
24558
24697
  picked = selectChunks(db, sourceId, intent, budget);
24559
24698
  } finally {
24560
24699
  closeDb(db);
@@ -24586,8 +24725,8 @@ async function handler3(raw, ctx) {
24586
24725
  if (takesDashC(input.language, runtime)) {
24587
24726
  argv = [runtime, "-c", input.language === "shell" ? rewriteWindowsBuildTools(input.code, process.platform) : input.code];
24588
24727
  } else {
24589
- tmpDir = mkdtempSync(join14(tmpdir2(), TMP_PREFIX));
24590
- const file2 = join14(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
24728
+ tmpDir = mkdtempSync(join15(tmpdir2(), TMP_PREFIX));
24729
+ const file2 = join15(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
24591
24730
  writeFileSync3(file2, scriptText(input.language, input.code), "utf8");
24592
24731
  argv = scriptArgv(input.language, runtime, file2);
24593
24732
  }
@@ -24622,12 +24761,12 @@ var ctxExecute = {
24622
24761
  };
24623
24762
 
24624
24763
  // src/core/tools/index.ts
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";
24764
+ import { existsSync as existsSync14, readFileSync as readFileSync14, statSync as statSync7 } from "node:fs";
24765
+ import { dirname as dirname9, extname, join as join17, relative as relative3, resolve as resolve7 } from "node:path";
24627
24766
 
24628
24767
  // src/core/index/walk.ts
24629
- import { readdirSync as readdirSync6, readFileSync as readFileSync12, realpathSync as realpathSync8, statSync as statSync6 } from "node:fs";
24630
- import { join as join15 } from "node:path";
24768
+ import { readdirSync as readdirSync6, readFileSync as readFileSync13, realpathSync as realpathSync8, statSync as statSync6 } from "node:fs";
24769
+ import { join as join16 } from "node:path";
24631
24770
  var GITIGNORE = ".gitignore";
24632
24771
  var GIT_DIR = ".git";
24633
24772
  function walkDir(root, containmentRoot) {
@@ -24636,7 +24775,7 @@ function walkDir(root, containmentRoot) {
24636
24775
  const found = [];
24637
24776
  visit(real2, [], [], containmentRoot, /* @__PURE__ */ new Set([real2]), found);
24638
24777
  found.sort(compareFound);
24639
- return found.map((f) => ({ absPath: f.absPath, relPath: join15(...f.dir, f.name) }));
24778
+ return found.map((f) => ({ absPath: f.absPath, relPath: join16(...f.dir, f.name) }));
24640
24779
  }
24641
24780
  function visit(abs, rel, parent, contain, seen, found) {
24642
24781
  let entries;
@@ -24645,10 +24784,10 @@ function visit(abs, rel, parent, contain, seen, found) {
24645
24784
  } catch {
24646
24785
  return;
24647
24786
  }
24648
- const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join15(abs, GITIGNORE), rel)) : parent;
24787
+ const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join16(abs, GITIGNORE), rel)) : parent;
24649
24788
  for (const e of entries) {
24650
24789
  if (e.name === GIT_DIR) continue;
24651
- const path7 = join15(abs, e.name);
24790
+ const path7 = join16(abs, e.name);
24652
24791
  let isDir = e.isDirectory();
24653
24792
  let isFile = e.isFile();
24654
24793
  let target = path7;
@@ -24688,7 +24827,7 @@ function compareFound(a, b) {
24688
24827
  function readRules(file2, base) {
24689
24828
  let body;
24690
24829
  try {
24691
- body = readFileSync12(file2, "utf8");
24830
+ body = readFileSync13(file2, "utf8");
24692
24831
  } catch {
24693
24832
  return [];
24694
24833
  }
@@ -24998,14 +25137,14 @@ function replaceCodePointXML(codePoint) {
24998
25137
 
24999
25138
  // node_modules/entities/dist/internal/decode-shared.js
25000
25139
  var BASE91_INVERSE = /* @__PURE__ */ (() => {
25001
- const table2 = new Uint8Array(127);
25140
+ const table3 = new Uint8Array(127);
25002
25141
  let code = 0;
25003
25142
  for (let char = 33; char <= 126; char++) {
25004
25143
  if (char !== 34 && char !== 36 && char !== 92) {
25005
- table2[char] = code++;
25144
+ table3[char] = code++;
25006
25145
  }
25007
25146
  }
25008
- return table2;
25147
+ return table3;
25009
25148
  })();
25010
25149
  function decodeTrieDict(input, resultLength, atomCount, dict1AtomCount, ngramCount, dictSize) {
25011
25150
  const base = 91;
@@ -25023,10 +25162,10 @@ function decodeTrieDict(input, resultLength, atomCount, dict1AtomCount, ngramCou
25023
25162
  single.fill(-1, dictSize + dict2AtomCount, slotCount);
25024
25163
  const start = new Int32Array(slotCount);
25025
25164
  const length = new Int32Array(slotCount);
25026
- function decodeDelta(count, off) {
25165
+ function decodeDelta(count2, off) {
25027
25166
  let previous = 0;
25028
25167
  let slot = off;
25029
- const end = off + count;
25168
+ const end = off + count2;
25030
25169
  while (slot < end) {
25031
25170
  const code = BASE91_INVERSE[input.charCodeAt(pos++)];
25032
25171
  if (code < 89) {
@@ -25049,8 +25188,8 @@ function decodeTrieDict(input, resultLength, atomCount, dict1AtomCount, ngramCou
25049
25188
  const references = new Int32Array(ngramCount * 2);
25050
25189
  let poolSize = 0;
25051
25190
  let ngramIndex = 0;
25052
- function readNgramReferences(count, startSlot) {
25053
- for (let index = 0; index < count; index++) {
25191
+ function readNgramReferences(count2, startSlot) {
25192
+ for (let index = 0; index < count2; index++) {
25054
25193
  const slot = startSlot + index;
25055
25194
  const a = readSlotCode();
25056
25195
  const b = readSlotCode();
@@ -28758,8 +28897,8 @@ var EXT_KIND = Object.freeze({ ".md": "md", ".html": "html", ".htm": "html" });
28758
28897
  var TYPE_KIND = Object.freeze({ "text/html": "html", "text/markdown": "md" });
28759
28898
  var DEFAULT_CONTENT_LABEL = "content";
28760
28899
  var utf8 = new TextDecoder("utf-8", { fatal: true });
28761
- function userLabel(label) {
28762
- return label === DECISION_SOURCE ? DECISION_USER_LABEL : label;
28900
+ function userLabel(label2) {
28901
+ return label2 === DECISION_SOURCE ? DECISION_USER_LABEL : label2;
28763
28902
  }
28764
28903
  function kindOfPath(p) {
28765
28904
  return EXT_KIND[extname(p).toLowerCase()] ?? "text";
@@ -28771,7 +28910,7 @@ function kindOfType(contentType) {
28771
28910
  }
28772
28911
  function readUtf8(absPath) {
28773
28912
  try {
28774
- return utf8.decode(readFileSync13(absPath));
28913
+ return utf8.decode(readFileSync14(absPath));
28775
28914
  } catch {
28776
28915
  return void 0;
28777
28916
  }
@@ -28789,7 +28928,7 @@ function pathItems(input, project) {
28789
28928
  if (statSync7(abs).isDirectory()) {
28790
28929
  return walkDir(abs, project.containmentRoot).map((f) => ({
28791
28930
  sourceKind: "path",
28792
- label: pathLabel(join16(base, f.relPath)),
28931
+ label: pathLabel(join17(base, f.relPath)),
28793
28932
  kind: kindOfPath(f.relPath),
28794
28933
  read: () => readUtf8(f.absPath)
28795
28934
  }));
@@ -28799,9 +28938,9 @@ function pathItems(input, project) {
28799
28938
  async function itemsOf(input, ctx) {
28800
28939
  if (input.content !== void 0) {
28801
28940
  const text2 = input.content;
28802
- const label2 = input.source ?? DEFAULT_CONTENT_LABEL;
28941
+ const label3 = input.source ?? DEFAULT_CONTENT_LABEL;
28803
28942
  const kind = hasMdStructure(text2) ? "md" : "text";
28804
- return { items: [{ sourceKind: "content", label: label2, kind, read: () => text2 }], from: label2 };
28943
+ return { items: [{ sourceKind: "content", label: label3, kind, read: () => text2 }], from: label3 };
28805
28944
  }
28806
28945
  if (input.path !== void 0) {
28807
28946
  const items = pathItems({ ...input, path: input.path }, ctx.project);
@@ -28809,8 +28948,8 @@ async function itemsOf(input, ctx) {
28809
28948
  }
28810
28949
  const res = await safeFetch(input.url ?? "", AbortSignal.any([ctx.signal, AbortSignal.timeout(EXEC_TIMEOUT_MS)]));
28811
28950
  const text = res.body.toString("utf8");
28812
- const label = res.finalUrl;
28813
- return { items: [{ sourceKind: "url", label, kind: kindOfType(res.contentType), read: () => text, base: label }], from: label };
28951
+ const label2 = res.finalUrl;
28952
+ return { items: [{ sourceKind: "url", label: label2, kind: kindOfType(res.contentType), read: () => text, base: label2 }], from: label2 };
28814
28953
  }
28815
28954
  async function handler4(input, ctx) {
28816
28955
  const given = INPUT_FIELDS.filter((f) => input[f] !== void 0);
@@ -28822,14 +28961,14 @@ async function handler4(input, ctx) {
28822
28961
  const db = await openDb(ctx.project);
28823
28962
  let sources = 0;
28824
28963
  let chunks = 0;
28825
- let bytes4 = 0;
28964
+ let bytes5 = 0;
28826
28965
  let lastId = 0;
28827
28966
  const notes = [];
28828
28967
  try {
28829
28968
  for (const it of items) {
28830
28969
  const text = it.read();
28831
28970
  if (text === void 0) continue;
28832
- bytes4 += Buffer.byteLength(text, "utf8");
28971
+ bytes5 += Buffer.byteLength(text, "utf8");
28833
28972
  if (it.kind === "html") {
28834
28973
  let readable;
28835
28974
  try {
@@ -28866,7 +29005,7 @@ async function handler4(input, ctx) {
28866
29005
  return {
28867
29006
  text: capBytes(line, OUTPUT_CAP).text,
28868
29007
  isError: false,
28869
- sandboxBytes: bytes4,
29008
+ sandboxBytes: bytes5,
28870
29009
  journal: { kind: "index", key: from, path: from, exit_code: null }
28871
29010
  };
28872
29011
  } catch (err) {
@@ -28906,8 +29045,8 @@ function purgeScope(db, scope, input) {
28906
29045
  const raw = db.raw;
28907
29046
  if (scope === "session") return changes(raw, "DELETE FROM events WHERE session_id = ?", input.session);
28908
29047
  if (scope === "source") {
28909
- const label = storedLabel(db, input.source);
28910
- return deleteChunkRows(raw, { label }) + changes(raw, "DELETE FROM sources WHERE label = ?", label);
29048
+ const label2 = storedLabel(db, input.source);
29049
+ return deleteChunkRows(raw, { label: label2 }) + changes(raw, "DELETE FROM sources WHERE label = ?", label2);
28911
29050
  }
28912
29051
  const chunks = deleteChunkRows(raw, "all");
28913
29052
  return changes(raw, "DELETE FROM events") + chunks + changes(raw, "DELETE FROM sources");
@@ -28989,14 +29128,40 @@ var ctxResume = Object.freeze({
28989
29128
  var ctxStatsSchema = external_exports.object({}, {
28990
29129
  error: (issue4) => issue4.code === "unrecognized_keys" ? STATS_UNKNOWN_FIELD_LINE : void 0
28991
29130
  }).strict();
28992
- var GROUPS = "SELECT session_id, agent, COUNT(*) AS calls, COALESCE(SUM(sandbox_bytes), 0) AS produced, COALESCE(SUM(returned_bytes), 0) AS returned FROM events WHERE tool IS NOT NULL AND kind <> 'cost' GROUP BY session_id, agent ORDER BY agent, session_id";
29131
+ var CALLS = "tool IS NOT NULL AND kind <> 'cost' AND tool <> 'ctx_stats'";
29132
+ var GROUPS = `SELECT session_id, agent, COUNT(*) AS calls, COALESCE(SUM(sandbox_bytes), 0) AS produced, COALESCE(SUM(returned_bytes), 0) AS returned FROM events WHERE ${CALLS} GROUP BY session_id, agent ORDER BY agent, session_id`;
29133
+ var TOOLS = `SELECT tool, COUNT(*) AS calls, COALESCE(SUM(sandbox_bytes), 0) AS produced, COALESCE(SUM(returned_bytes), 0) AS returned FROM events WHERE ${CALLS} GROUP BY tool`;
29134
+ var KINDS = "SELECT kind, COALESCE(SUM(session_id = ?), 0) AS s, COUNT(*) AS p FROM events WHERE kind <> 'cost' AND (tool IS NULL OR tool <> 'ctx_stats') GROUP BY kind";
29135
+ var META = `SELECT COUNT(DISTINCT session_id) AS sessions, COUNT(DISTINCT agent) AS agents, COUNT(DISTINCT created_at / ${MS_PER_DAY}) AS days FROM events WHERE ${CALLS}`;
29136
+ var SPAN = "SELECT COALESCE(MAX(created_at) - MIN(created_at), 0) AS span FROM events WHERE session_id = ? AND kind <> 'cost'";
29137
+ var SOURCES = "SELECT COUNT(*) AS n, COALESCE(SUM(chunk_count), 0) AS chunks, COALESCE(SUM(bytes_total), 0) AS bytes FROM sources";
28993
29138
  var EMPTY5 = Object.freeze({ calls: 0, produced: 0, returned: 0, saved: 0 });
28994
- function readGroups(raw) {
28995
- return raw.prepare(GROUPS).all().map((r) => {
28996
- const produced = Number(r.produced);
28997
- const returned = Number(r.returned);
28998
- return { session: String(r.session_id), agent: String(r.agent), calls: Number(r.calls), produced, returned, saved: Math.max(0, produced - returned) };
28999
- });
29139
+ function totals(r) {
29140
+ const produced = Number(r.produced);
29141
+ const returned = Number(r.returned);
29142
+ return { calls: Number(r.calls), produced, returned, saved: Math.max(0, produced - returned) };
29143
+ }
29144
+ function readFacts(raw, sessionId) {
29145
+ const groups = raw.prepare(GROUPS).all().map((r) => ({ session: String(r.session_id), agent: String(r.agent), ...totals(r) }));
29146
+ const tools = raw.prepare(TOOLS).all().map((r) => ({ name: String(r.tool), ...totals(r) }));
29147
+ const kinds = /* @__PURE__ */ new Map();
29148
+ for (const r of raw.prepare(KINDS).all(sessionId)) kinds.set(String(r.kind), { session: Number(r.s), project: Number(r.p) });
29149
+ const meta3 = raw.prepare(META).get();
29150
+ const span2 = Number(raw.prepare(SPAN).get(sessionId).span);
29151
+ const src = raw.prepare(SOURCES).get();
29152
+ const pages = raw.prepare("PRAGMA page_count").get();
29153
+ const size = raw.prepare("PRAGMA page_size").get();
29154
+ return {
29155
+ groups,
29156
+ tools,
29157
+ kinds,
29158
+ span: span2,
29159
+ sessions: Number(meta3.sessions),
29160
+ agents: Number(meta3.agents),
29161
+ days: Number(meta3.days),
29162
+ sources: { count: Number(src.n), chunks: Number(src.chunks), bytes: Number(src.bytes) },
29163
+ dbBytes: Number(pages.page_count) * Number(size.page_size)
29164
+ };
29000
29165
  }
29001
29166
  function sum(groups) {
29002
29167
  return groups.reduce((t, g) => ({
@@ -29010,23 +29175,123 @@ function reductionPct(t) {
29010
29175
  if (t.calls === 0) return 0;
29011
29176
  return Number((t.saved * PERCENT_SCALE / Math.max(1, t.produced)).toFixed(1));
29012
29177
  }
29013
- function tableRow(label, t) {
29178
+ function tableRow(label2, t) {
29014
29179
  const last2 = t.calls === 0 ? STATS_NO_DATA : String(reductionPct(t));
29015
- return "| " + [label, t.produced + " B", t.returned + " B", t.saved + " B", last2].join(" | ") + " |";
29180
+ return "| " + [label2, t.produced + " B", t.returned + " B", t.saved + " B", last2].join(" | ") + " |";
29181
+ }
29182
+ var UNITS = ["KB", "MB", "GB", "TB"];
29183
+ var LABEL_W = STATS_LABEL_W;
29184
+ var NUM_W = STATS_NUM_W;
29185
+ var PCT_W = STATS_PCT_W;
29186
+ var INT = new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 });
29187
+ function int2(n) {
29188
+ return INT.format(Math.round(n));
29189
+ }
29190
+ function count(n) {
29191
+ return n < STATS_MILLION ? int2(n) : (n / STATS_MILLION).toFixed(1) + "M";
29192
+ }
29193
+ function bytes4(n) {
29194
+ if (n < STATS_KIB) return int2(n) + " B";
29195
+ let v = n / STATS_KIB;
29196
+ let u = 0;
29197
+ while (v >= STATS_KIB && u < UNITS.length - 1) {
29198
+ v /= STATS_KIB;
29199
+ u++;
29200
+ }
29201
+ return v.toFixed(1) + " " + UNITS[u];
29202
+ }
29203
+ function pct(t) {
29204
+ return (t.saved * PERCENT_SCALE / Math.max(1, t.produced)).toFixed(1) + "%";
29205
+ }
29206
+ function bar(value, max, width, fill = "\u2588", rest = "") {
29207
+ const n = value <= 0 || max <= 0 ? 0 : Math.min(width, Math.max(1, Math.round(value / max * width)));
29208
+ return fill.repeat(n) + rest.repeat(width - n);
29209
+ }
29210
+ function label(s) {
29211
+ const chars = [...s];
29212
+ return (chars.length > STATS_LABEL_MAX ? chars.slice(0, STATS_LABEL_MAX - 1).join("") + "\u2026" : s).padEnd(LABEL_W);
29213
+ }
29214
+ function span(ms) {
29215
+ const min = Math.floor(ms / STATS_MS_PER_MINUTE);
29216
+ if (min < 1) return "<1m";
29217
+ if (min < STATS_MINUTES_PER_HOUR) return min + "m";
29218
+ const h = Math.floor(min / STATS_MINUTES_PER_HOUR);
29219
+ return h < STATS_HOURS_PER_DAY ? `${h}h ${String(min % STATS_MINUTES_PER_HOUR).padStart(STATS_CLOCK_DIGITS, "0")}m` : `${Math.floor(h / STATS_HOURS_PER_DAY)}d ${h % STATS_HOURS_PER_DAY}h`;
29220
+ }
29221
+ function plural(n, word) {
29222
+ return `${int2(n)} ${word}${n === 1 ? "" : "s"}`;
29223
+ }
29224
+ function table2(title, rows) {
29225
+ const max = Math.max(0, ...rows.map((r) => r.saved));
29226
+ const head = " " + title.padEnd(LABEL_W) + "Calls".padStart(STATS_CALLS_W) + "Produced".padStart(NUM_W) + "Returned".padStart(NUM_W) + "Saved".padStart(NUM_W) + "%".padStart(PCT_W);
29227
+ return [head, ...rows.map((r) => (" " + label(r.name) + count(r.calls).padStart(STATS_CALLS_W) + bytes4(r.produced).padStart(NUM_W) + bytes4(r.returned).padStart(NUM_W) + bytes4(r.saved).padStart(NUM_W) + pct(r).padStart(PCT_W) + " " + bar(r.saved, max, STATS_ROW_BAR)).trimEnd())];
29228
+ }
29229
+ function bySaved(a, b) {
29230
+ return b.saved - a.saved || b.produced - a.produced || a.returned - b.returned || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
29231
+ }
29232
+ function toolRows(tools) {
29233
+ const named = tools.map((t) => ({ ...t, name: t.name.startsWith("ctx_") ? t.name : "hook " + t.name })).sort(bySaved);
29234
+ if (named.length <= STATS_MAX_TOOL_ROWS) return named;
29235
+ const rest = named.slice(STATS_MAX_TOOL_ROWS - 1);
29236
+ return [...named.slice(0, STATS_MAX_TOOL_ROWS - 1), { name: `other (${rest.length} tools)`, ...sum(rest) }];
29237
+ }
29238
+ function fit(line) {
29239
+ const chars = [...line];
29240
+ return chars.length <= STATS_WIDTH ? line : chars.slice(0, STATS_WIDTH - 1).join("") + "\u2026";
29241
+ }
29242
+ function report(f, sessionId, agent) {
29243
+ const head = [STATS_REPORT_TITLE, "\u2500".repeat(STATS_WIDTH), ""];
29244
+ const project = sum(f.groups);
29245
+ if (project.calls === 0) return [...head, ...STATS_EMPTY_LINES].join("\n");
29246
+ const session = sum(f.groups.filter((g) => g.session === sessionId));
29247
+ const [scopeName, focus] = session.calls > 0 ? ["This session", session] : ["This project", project];
29248
+ const top = Math.max(focus.produced, focus.returned);
29249
+ const extra = session.calls > 0 ? ` \xB7 ${span(f.span)} active` : "";
29250
+ const lines = [
29251
+ ...head,
29252
+ `${scopeName} \xB7 ${plural(focus.calls, "call")}${extra}`,
29253
+ " " + "Without context-mode".padEnd(LABEL_W) + "|" + bar(focus.produced, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + bytes4(focus.produced).padStart(NUM_W),
29254
+ " " + "With context-mode".padEnd(LABEL_W) + "|" + bar(focus.returned, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + bytes4(focus.returned).padStart(NUM_W),
29255
+ ` ${bytes4(focus.saved)} saved (${pct(focus)}) \xB7 about ${int2(focus.saved / STATS_BYTES_PER_TOKEN)} tokens kept out of the chat`,
29256
+ "",
29257
+ ...table2("Scope", [{ name: "session", ...session }, { name: "project", ...project }, { name: "all-time", ...project }]),
29258
+ "",
29259
+ "Where the savings came from (this project)",
29260
+ ...table2("Tool", toolRows(f.tools)),
29261
+ ""
29262
+ ];
29263
+ const agents = /* @__PURE__ */ new Map();
29264
+ for (const g of f.groups) agents.set(g.agent, sum([agents.get(g.agent) ?? EMPTY5, g]));
29265
+ if (!agents.has(agent)) agents.set(agent, EMPTY5);
29266
+ lines.push(...table2("Agent", [...agents].map(([name, t]) => ({ name, ...t })).sort(bySaved)), "");
29267
+ const maxKind = Math.max(0, ...[...f.kinds.values()].map((k) => k.project));
29268
+ lines.push("Kept in the session journal", " " + "Journal".padEnd(LABEL_W) + "Session".padStart(STATS_KIND_W) + "Project".padStart(STATS_KIND_W));
29269
+ for (const [kind, name] of STATS_KIND_LABELS) {
29270
+ const k = f.kinds.get(kind) ?? { session: 0, project: 0 };
29271
+ lines.push((" " + label(name) + int2(k.session).padStart(STATS_KIND_W) + int2(k.project).padStart(STATS_KIND_W) + " " + bar(k.project, maxKind, STATS_KIND_BAR)).trimEnd());
29272
+ }
29273
+ lines.push("", ...STATS_JOURNAL_HINTS.map((h) => " " + h), "");
29274
+ lines.push(
29275
+ " " + "Indexed sources".padEnd(LABEL_W) + `${int2(f.sources.count)} \xB7 ${plural(f.sources.chunks, "chunk")} \xB7 ${bytes4(f.sources.bytes)} of content`,
29276
+ " " + "Database file".padEnd(LABEL_W) + bytes4(f.dbBytes),
29277
+ " " + "Sessions".padEnd(LABEL_W) + `${int2(f.sessions)} \xB7 agents ${int2(f.agents)} \xB7 active days ${int2(f.days)}`
29278
+ );
29279
+ return lines.map(fit).join("\n");
29016
29280
  }
29017
29281
  async function handler7(_input, ctx) {
29018
29282
  const db = await openDb(ctx.project, { readOnly: true });
29019
- let groups;
29283
+ let facts;
29020
29284
  try {
29021
- groups = readGroups(db.raw);
29285
+ facts = readFacts(db.raw, ctx.sessionId);
29022
29286
  } finally {
29023
29287
  closeDb(db);
29024
29288
  }
29289
+ const groups = facts.groups;
29025
29290
  const session = sum(groups.filter((g) => g.session === ctx.sessionId));
29026
29291
  const project = sum(groups);
29027
29292
  const allTime = project;
29028
29293
  const agentIds = [.../* @__PURE__ */ new Set([...groups.map((g) => g.agent), ctx.project.agent])].sort();
29029
- const table2 = [
29294
+ const mdTable = [
29030
29295
  "| " + STATS_COLUMNS.join(" | ") + " |",
29031
29296
  "|" + STATS_COLUMNS.map(() => "---").join("|") + "|",
29032
29297
  tableRow("session", session),
@@ -29035,7 +29300,8 @@ async function handler7(_input, ctx) {
29035
29300
  ...agentIds.map((a) => tableRow("agent " + a, sum(groups.filter((g) => g.agent === a))))
29036
29301
  ].join("\n");
29037
29302
  const summary = STATS_SUMMARY(reductionPct(allTime), reductionPct(session));
29038
- return { text: capBytes(summary + "\n\n" + table2, OUTPUT_CAP).text, isError: false, sandboxBytes: 0 };
29303
+ const text = summary + "\n\n```text\n" + report(facts, ctx.sessionId, ctx.project.agent) + "\n```\n\n" + mdTable;
29304
+ return { text: capBytes(text, OUTPUT_CAP).text, isError: false, sandboxBytes: 0 };
29039
29305
  }
29040
29306
  var ctxStats = Object.freeze({
29041
29307
  name: "ctx_stats",
@@ -29047,11 +29313,11 @@ var ctxStats = Object.freeze({
29047
29313
 
29048
29314
  // src/core/tools/upgrade.ts
29049
29315
  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";
29316
+ import { basename as basename6, dirname as dirname11, join as join23 } from "node:path";
29051
29317
 
29052
29318
  // src/core/ops/host-write.ts
29053
29319
  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";
29320
+ import { dirname as dirname10, join as join18 } from "node:path";
29055
29321
  function defaultWrite(file2, text) {
29056
29322
  writeFileSync4(file2, text, "utf8");
29057
29323
  }
@@ -29060,14 +29326,14 @@ function hostConfigPath(agent, home, env) {
29060
29326
  if (own4 !== void 0) return ownMcpFileOf(agent, own4.file, env, home);
29061
29327
  switch (agent) {
29062
29328
  case "opencode":
29063
- return join17(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
29329
+ return join18(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
29064
29330
  // D-WIN-OPENCODE-DIR-1
29065
29331
  case "pi":
29066
- return join17(piAgentDirOf(env, home), SETTINGS_FILE);
29332
+ return join18(piAgentDirOf(env, home), SETTINGS_FILE);
29067
29333
  case "copilot-cli":
29068
29334
  return null;
29069
29335
  default:
29070
- return join17(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
29336
+ return join18(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
29071
29337
  }
29072
29338
  }
29073
29339
  function cell3(value) {
@@ -29118,7 +29384,7 @@ function regenerateHostConfig(row5, home, opts = {}) {
29118
29384
 
29119
29385
  // src/core/ops/plugin-swap.ts
29120
29386
  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";
29387
+ import { basename as basename5, join as join19, win32 as win322 } from "node:path";
29122
29388
  function linkTarget(path7, win) {
29123
29389
  if (!isLink(path7)) return null;
29124
29390
  const target = readlinkSync(path7);
@@ -29137,11 +29403,11 @@ function settleLinks(link, tmp, old, opts) {
29137
29403
  else renameWithRetry(old, link, opts);
29138
29404
  }
29139
29405
  function swapPluginCurrent(agentDir, sha, opts = {}) {
29140
- const next = join18(agentDir, sha);
29406
+ const next = join19(agentDir, sha);
29141
29407
  if (!existsSync16(next) || !lstatSync(next).isDirectory()) {
29142
29408
  throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename5(agentDir), path: next });
29143
29409
  }
29144
- const link = join18(agentDir, PLUGIN_CURRENT_LINK);
29410
+ const link = join19(agentDir, PLUGIN_CURRENT_LINK);
29145
29411
  const tmp = link + PLUGIN_LINK_TMP_SUFFIX;
29146
29412
  const old = link + PLUGIN_LINK_OLD_SUFFIX;
29147
29413
  settleLinks(link, tmp, old, opts);
@@ -29156,15 +29422,15 @@ function swapPluginCurrent(agentDir, sha, opts = {}) {
29156
29422
  if (before !== null) unlinkSync2(old);
29157
29423
  const keep = /* @__PURE__ */ new Set([sha]);
29158
29424
  if (before !== null) keep.add(before);
29159
- const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join18(agentDir, name));
29425
+ const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join19(agentDir, name));
29160
29426
  for (const dir of removed) rmSync5(dir, { recursive: true, force: true });
29161
- const previous = before !== null && existsSync16(join18(agentDir, before)) ? join18(agentDir, before) : null;
29427
+ const previous = before !== null && existsSync16(join19(agentDir, before)) ? join19(agentDir, before) : null;
29162
29428
  return { current: next, previous, removed };
29163
29429
  }
29164
29430
 
29165
29431
  // src/core/ops/release-fetch.ts
29166
29432
  import { existsSync as existsSync17, mkdirSync as mkdirSync6, rmSync as rmSync6 } from "node:fs";
29167
- import { join as join19 } from "node:path";
29433
+ import { join as join20 } from "node:path";
29168
29434
  function failed(r) {
29169
29435
  if (r.exitCode === null && r.killed === null) return new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
29170
29436
  const status = r.killed ?? String(r.exitCode);
@@ -29176,9 +29442,9 @@ async function git2(bin, args, cwd, env, signal) {
29176
29442
  return r.stdout.toString().trim();
29177
29443
  }
29178
29444
  async function fetchRelease(agent, url4, env, signal, opts = {}) {
29179
- const agentDir = join19(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, agent);
29445
+ const agentDir = join20(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, agent);
29180
29446
  mkdirSync6(agentDir, { recursive: true });
29181
- const fetchDir = join19(agentDir, UPGRADE_FETCH_DIR_PREFIX + process.pid);
29447
+ const fetchDir = join20(agentDir, UPGRADE_FETCH_DIR_PREFIX + process.pid);
29182
29448
  rmSync6(fetchDir, { recursive: true, force: true });
29183
29449
  const gitBin = findRuntime(GIT_BIN, env);
29184
29450
  if (gitBin === null) throw new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
@@ -29186,7 +29452,7 @@ async function fetchRelease(agent, url4, env, signal, opts = {}) {
29186
29452
  try {
29187
29453
  await git2(gitBin, [...GIT_CLONE_ARGS, RELEASE_BRANCH, url4, fetchDir], agentDir, childEnv, signal);
29188
29454
  const sha = await git2(gitBin, GIT_HEAD_SHA_ARGS, fetchDir, childEnv, signal);
29189
- const dir = join19(agentDir, sha);
29455
+ const dir = join20(agentDir, sha);
29190
29456
  if (existsSync17(dir)) rmSync6(fetchDir, { recursive: true, force: true });
29191
29457
  else renameWithRetry(fetchDir, dir, opts);
29192
29458
  return { sha, dir };
@@ -29198,14 +29464,14 @@ async function fetchRelease(agent, url4, env, signal, opts = {}) {
29198
29464
 
29199
29465
  // src/core/ops/uninstall.ts
29200
29466
  import { existsSync as existsSync18, readdirSync as readdirSync8, rmSync as rmSync7, writeFileSync as writeFileSync5 } from "node:fs";
29201
- import { join as join20 } from "node:path";
29467
+ import { join as join21 } from "node:path";
29202
29468
  function row2(area, before, after) {
29203
29469
  return { area, before, after };
29204
29470
  }
29205
29471
  function stopServers(configDir, projectKey) {
29206
29472
  const stopped = listLiveOwners(configDir, projectKey);
29207
- const dir = join20(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
29208
- for (const serverId of stopped) writeFileSync5(join20(dir, serverId + OWNER_STOP_EXT), "", "utf8");
29473
+ const dir = join21(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
29474
+ for (const serverId of stopped) writeFileSync5(join21(dir, serverId + OWNER_STOP_EXT), "", "utf8");
29209
29475
  return stopped.length === 0 ? { row: row2(UPGRADE_SERVER_AREA, "", UPGRADE_NOT_FOUND), stopped } : { row: row2(UPGRADE_SERVER_AREA, UPGRADE_SERVER_RUNNING, UPGRADE_SERVER_STOPPED), stopped };
29210
29476
  }
29211
29477
  function rootOrNull(adapter, env) {
@@ -29223,14 +29489,14 @@ function removeCache(adapter, env, configDir) {
29223
29489
  const root = rootOrNull(adapter, env);
29224
29490
  if (root === null) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
29225
29491
  if (adapter.installMode === "marketplace") {
29226
- const cache = join20(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
29492
+ const cache = join21(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
29227
29493
  if (!isInside(cache, root) || isInside(root, cache)) return row2(UPGRADE_CACHE_AREA, root, UPGRADE_CACHE_BY_HAND);
29228
29494
  }
29229
29495
  rmSync7(root, { recursive: true, force: true });
29230
29496
  return row2(UPGRADE_CACHE_AREA, root, UPGRADE_REMOVED);
29231
29497
  }
29232
29498
  case "plugin": {
29233
- const agentDir = join20(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
29499
+ const agentDir = join21(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
29234
29500
  if (!existsSync18(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
29235
29501
  rmSync7(agentDir, { recursive: true, force: true });
29236
29502
  return row2(UPGRADE_CACHE_AREA, agentDir, UPGRADE_REMOVED);
@@ -29276,7 +29542,7 @@ function ownEntries(agent, env) {
29276
29542
  }
29277
29543
  if (agent === "opencode") {
29278
29544
  return [{
29279
- file: join20(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
29545
+ file: join21(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
29280
29546
  // D-WIN-OPENCODE-DIR-1
29281
29547
  key: OPENCODE_PLUGIN_KEY,
29282
29548
  shown: OPENCODE_PLUGIN_KEY,
@@ -29287,7 +29553,7 @@ function ownEntries(agent, env) {
29287
29553
  if (agent === "pi") {
29288
29554
  const agentDir = piAgentDirOf(env, home);
29289
29555
  return [{
29290
- file: join20(agentDir, SETTINGS_FILE),
29556
+ file: join21(agentDir, SETTINGS_FILE),
29291
29557
  key: PI_PACKAGES_KEY,
29292
29558
  shown: PI_PACKAGES_KEY,
29293
29559
  has: (v) => Array.isArray(v) && v.some((x) => piSource(x) === PI_GIT_PACKAGE),
@@ -29309,12 +29575,12 @@ function removeOwnEntries(agent, env) {
29309
29575
  return rows.length === 0 ? [row2(UPGRADE_CONFIG_AREA, "", UPGRADE_NOT_FOUND)] : rows;
29310
29576
  }
29311
29577
  function removeProjectData(configDir, projectKey) {
29312
- const projects = join20(configDir, PROJECTS_DIR_NAME);
29313
- const dir = join20(projects, projectKey);
29578
+ const projects = join21(configDir, PROJECTS_DIR_NAME);
29579
+ const dir = join21(projects, projectKey);
29314
29580
  if (!existsSync18(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
29315
29581
  if (dir === projects || !isInside(projects, dir)) throw new CtxError("OUTSIDE_ROOT", { p: dir, root: projects });
29316
29582
  for (const name of readdirSync8(dir)) {
29317
- if (name !== OWNERS_DIR_NAME) rmSync7(join20(dir, name), { recursive: true, force: true });
29583
+ if (name !== OWNERS_DIR_NAME) rmSync7(join21(dir, name), { recursive: true, force: true });
29318
29584
  }
29319
29585
  return row2(UPGRADE_DATA_AREA, dir, UPGRADE_DATA_DELETED);
29320
29586
  }
@@ -29322,12 +29588,12 @@ function runUninstall(input) {
29322
29588
  const configDir = resolveConfigDir(input.env);
29323
29589
  const stop = stopServers(configDir, input.project.projectKey);
29324
29590
  const rows = [stop.row, removeCache(input.adapter, input.env, configDir), ...removeOwnEntries(input.adapter.id, input.env)];
29325
- rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join20(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
29591
+ rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join21(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
29326
29592
  return { rows, stopped: stop.stopped };
29327
29593
  }
29328
29594
 
29329
29595
  // src/core/ops/v1-remove.ts
29330
- import { copyFileSync as copyFileSync2, existsSync as existsSync19, readFileSync as readFileSync14, rmSync as rmSync8 } from "node:fs";
29596
+ import { copyFileSync as copyFileSync2, existsSync as existsSync19, readFileSync as readFileSync15, rmSync as rmSync8 } from "node:fs";
29331
29597
  var isObj4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
29332
29598
  var areaOf = (f) => f.path === "" ? f.file : f.file + UPGRADE_AREA_KEY_SEP + f.path;
29333
29599
  var row3 = (f, after) => ({ area: areaOf(f), before: f.reason, after });
@@ -29346,13 +29612,13 @@ function keepOriginal(file2, kept, undo) {
29346
29612
  undo.push({ trash, target: file2 });
29347
29613
  }
29348
29614
  function cutTomlTable(text, header) {
29349
- let span;
29615
+ let span2;
29350
29616
  try {
29351
- span = tomlTableSpans(text).find((t) => t.header.trim() === header);
29617
+ span2 = tomlTableSpans(text).find((t) => t.header.trim() === header);
29352
29618
  } catch {
29353
29619
  return null;
29354
29620
  }
29355
- return span === void 0 ? null : text.slice(0, span.start) + text.slice(span.end);
29621
+ return span2 === void 0 ? null : text.slice(0, span2.start) + text.slice(span2.end);
29356
29622
  }
29357
29623
  function writeAtomic(file2, text) {
29358
29624
  atomicWriteFile(file2, text);
@@ -29371,8 +29637,8 @@ function locate(doc, path7) {
29371
29637
  return null;
29372
29638
  }
29373
29639
  function stripJsonEntries(agent, file2, findings, kept, undo) {
29374
- const layout = hostLayout(readFileSync14(file2, "utf8"));
29375
- const text = hostText(readFileSync14(file2, "utf8"));
29640
+ const layout = hostLayout(readFileSync15(file2, "utf8"));
29641
+ const text = hostText(readFileSync15(file2, "utf8"));
29376
29642
  const doc = parseHostConfig(agent, file2, text, "jsonc");
29377
29643
  const hit = /* @__PURE__ */ new Set();
29378
29644
  const byContainer = /* @__PURE__ */ new Map();
@@ -29420,7 +29686,7 @@ function removeV1(agent, findings) {
29420
29686
  continue;
29421
29687
  }
29422
29688
  if (file2.endsWith(TOML_EXT)) {
29423
- const rawToml = readFileSync14(file2, "utf8");
29689
+ const rawToml = readFileSync15(file2, "utf8");
29424
29690
  const tomlLayout = hostLayout(rawToml);
29425
29691
  let text = hostText(rawToml);
29426
29692
  for (const f of list4) {
@@ -29458,8 +29724,8 @@ function removeV1(agent, findings) {
29458
29724
 
29459
29725
  // src/core/ops/verify-sums.ts
29460
29726
  import { createHash as createHash2 } from "node:crypto";
29461
- import { lstatSync as lstatSync2, readdirSync as readdirSync9, readFileSync as readFileSync15 } from "node:fs";
29462
- import { join as join21 } from "node:path";
29727
+ import { lstatSync as lstatSync2, readdirSync as readdirSync9, readFileSync as readFileSync16 } from "node:fs";
29728
+ import { join as join22 } from "node:path";
29463
29729
  function mismatch() {
29464
29730
  return new CtxError("BUNDLE_HASH_MISMATCH");
29465
29731
  }
@@ -29480,24 +29746,24 @@ function walk3(dir, prefix, out) {
29480
29746
  for (const entry of readdirSync9(dir, { withFileTypes: true })) {
29481
29747
  const rel = prefix === "" ? entry.name : prefix + "/" + entry.name;
29482
29748
  if (prefix === "" && (entry.name === GIT_DIR_NAME || entry.name === RELEASE_SUMS_FILE)) continue;
29483
- const abs = join21(dir, entry.name);
29749
+ const abs = join22(dir, entry.name);
29484
29750
  if (entry.isDirectory()) walk3(abs, rel, out);
29485
29751
  else if (entry.isFile()) out.set(rel, abs);
29486
29752
  else throw mismatch();
29487
29753
  }
29488
29754
  }
29489
29755
  function verifySums(dir) {
29490
- const sumsPath = join21(dir, RELEASE_SUMS_FILE);
29756
+ const sumsPath = join22(dir, RELEASE_SUMS_FILE);
29491
29757
  const sumsStat = lstatSync2(sumsPath, { throwIfNoEntry: false });
29492
29758
  if (sumsStat === void 0 || !sumsStat.isFile()) throw mismatch();
29493
- const sums = parseSums(readFileSync15(sumsPath, "utf8"));
29759
+ const sums = parseSums(readFileSync16(sumsPath, "utf8"));
29494
29760
  const files = /* @__PURE__ */ new Map();
29495
29761
  walk3(dir, "", files);
29496
29762
  if (files.size !== sums.size) throw mismatch();
29497
29763
  for (const [rel, abs] of files) {
29498
29764
  const want = sums.get(rel);
29499
29765
  if (want === void 0) throw mismatch();
29500
- const got = createHash2(SUMS_HASH_ALGORITHM).update(readFileSync15(abs)).digest(HASH_ENCODING);
29766
+ const got = createHash2(SUMS_HASH_ALGORITHM).update(readFileSync16(abs)).digest(HASH_ENCODING);
29501
29767
  if (got !== want) throw mismatch();
29502
29768
  }
29503
29769
  }
@@ -29525,7 +29791,7 @@ function pluginRootRow(adapter, env) {
29525
29791
  return root === own4 ? [] : [row4(UPGRADE_PLUGIN_ROOT_AREA, root, own4)];
29526
29792
  }
29527
29793
  function isCurrent(agentDir, dir) {
29528
- const link = join22(agentDir, PLUGIN_CURRENT_LINK);
29794
+ const link = join23(agentDir, PLUGIN_CURRENT_LINK);
29529
29795
  return existsSync20(link) && realpathSync9.native(link) === realpathSync9.native(dir);
29530
29796
  }
29531
29797
  async function checkout(adapter, deps) {
@@ -29622,7 +29888,7 @@ function define(name) {
29622
29888
  handler: built.handler
29623
29889
  };
29624
29890
  }
29625
- var TOOLS = Object.freeze(TOOL_ORDER.map(define));
29891
+ var TOOLS2 = Object.freeze(TOOL_ORDER.map(define));
29626
29892
  function callExample(tool) {
29627
29893
  const a = tool.description.indexOf("`");
29628
29894
  const b = tool.description.indexOf("`", a + 1);
@@ -29647,7 +29913,7 @@ function checkCall(tool, input) {
29647
29913
  // src/entries/server.ts
29648
29914
  import { randomUUID } from "node:crypto";
29649
29915
  import { existsSync as existsSync22, realpathSync as realpathSync11, rmSync as rmSync11 } from "node:fs";
29650
- import { dirname as dirname12, join as join24 } from "node:path";
29916
+ import { dirname as dirname12, join as join25 } from "node:path";
29651
29917
  import { fileURLToPath as fileURLToPath2 } from "node:url";
29652
29918
 
29653
29919
  // node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
@@ -30354,14 +30620,14 @@ function codePointLength(str4) {
30354
30620
  const units = str4.length;
30355
30621
  if (!highSurrogate.test(str4))
30356
30622
  return units;
30357
- let count = units;
30623
+ let count2 = units;
30358
30624
  for (let i = 0; i < units - 1; i++) {
30359
30625
  if ((str4.charCodeAt(i) & 64512) === 55296 && (str4.charCodeAt(i + 1) & 64512) === 56320) {
30360
- count--;
30626
+ count2--;
30361
30627
  i++;
30362
30628
  }
30363
30629
  }
30364
- return count;
30630
+ return count2;
30365
30631
  }
30366
30632
  function getLengthableOrigin2(input) {
30367
30633
  if (Array.isArray(input))
@@ -30410,16 +30676,16 @@ function cleanEnum2(obj) {
30410
30676
  }
30411
30677
  function base64ToUint8Array(base645) {
30412
30678
  const binaryString = atob(base645);
30413
- const bytes4 = new Uint8Array(binaryString.length);
30679
+ const bytes5 = new Uint8Array(binaryString.length);
30414
30680
  for (let i = 0; i < binaryString.length; i++) {
30415
- bytes4[i] = binaryString.charCodeAt(i);
30681
+ bytes5[i] = binaryString.charCodeAt(i);
30416
30682
  }
30417
- return bytes4;
30683
+ return bytes5;
30418
30684
  }
30419
- function uint8ArrayToBase64(bytes4) {
30685
+ function uint8ArrayToBase64(bytes5) {
30420
30686
  let binaryString = "";
30421
- for (let i = 0; i < bytes4.length; i++) {
30422
- binaryString += String.fromCharCode(bytes4[i]);
30687
+ for (let i = 0; i < bytes5.length; i++) {
30688
+ binaryString += String.fromCharCode(bytes5[i]);
30423
30689
  }
30424
30690
  return btoa(binaryString);
30425
30691
  }
@@ -30428,30 +30694,30 @@ function base64urlToUint8Array(base64url5) {
30428
30694
  const padding = "=".repeat((4 - base645.length % 4) % 4);
30429
30695
  return base64ToUint8Array(base645 + padding);
30430
30696
  }
30431
- function uint8ArrayToBase64url(bytes4) {
30432
- return uint8ArrayToBase64(bytes4).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
30697
+ function uint8ArrayToBase64url(bytes5) {
30698
+ return uint8ArrayToBase64(bytes5).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
30433
30699
  }
30434
30700
  function hexToUint8Array(hex) {
30435
30701
  const cleanHex = hex.replace(/^0x/, "");
30436
30702
  if (cleanHex.length % 2 !== 0) {
30437
30703
  throw new Error("Invalid hex string length");
30438
30704
  }
30439
- const bytes4 = new Uint8Array(cleanHex.length / 2);
30705
+ const bytes5 = new Uint8Array(cleanHex.length / 2);
30440
30706
  for (let i = 0; i < cleanHex.length; i += 2) {
30441
- bytes4[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);
30707
+ bytes5[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);
30442
30708
  }
30443
- return bytes4;
30709
+ return bytes5;
30444
30710
  }
30445
- function uint8ArrayToHex(bytes4) {
30446
- return Array.from(bytes4).map((b) => b.toString(16).padStart(2, "0")).join("");
30711
+ function uint8ArrayToHex(bytes5) {
30712
+ return Array.from(bytes5).map((b) => b.toString(16).padStart(2, "0")).join("");
30447
30713
  }
30448
30714
  var Class2 = class {
30449
30715
  constructor(..._args) {
30450
30716
  }
30451
30717
  };
30452
- function members(proto, table2) {
30453
- for (const key in table2) {
30454
- const desc = Object.getOwnPropertyDescriptor(table2, key);
30718
+ function members(proto, table3) {
30719
+ for (const key in table3) {
30720
+ const desc = Object.getOwnPropertyDescriptor(table3, key);
30455
30721
  if (desc.get)
30456
30722
  Object.defineProperty(proto, key, { ...desc, enumerable: false });
30457
30723
  else
@@ -30466,10 +30732,10 @@ function hide(inst, key, value) {
30466
30732
  return own2(inst, key, value, false);
30467
30733
  }
30468
30734
  // @__NO_SIDE_EFFECTS__
30469
- function derived(computes, table2) {
30735
+ function derived(computes, table3) {
30470
30736
  for (const key in computes) {
30471
30737
  const compute = computes[key];
30472
- Object.defineProperty(table2, key, {
30738
+ Object.defineProperty(table3, key, {
30473
30739
  configurable: true,
30474
30740
  enumerable: true,
30475
30741
  get() {
@@ -30480,7 +30746,7 @@ function derived(computes, table2) {
30480
30746
  }
30481
30747
  });
30482
30748
  }
30483
- return table2;
30749
+ return table3;
30484
30750
  }
30485
30751
  function defineBound(proto, key, fn) {
30486
30752
  Object.defineProperty(proto, key, {
@@ -35718,10 +35984,10 @@ var ZodNumber2 = /* @__PURE__ */ $constructor2(
35718
35984
  return this.check(_lte2(value, params));
35719
35985
  },
35720
35986
  int(params) {
35721
- return this.check(int2(params));
35987
+ return this.check(int3(params));
35722
35988
  },
35723
35989
  safe(params) {
35724
- return this.check(int2(params));
35990
+ return this.check(int3(params));
35725
35991
  },
35726
35992
  positive(params) {
35727
35993
  return this.check(_gt2(0, params));
@@ -35753,7 +36019,7 @@ var ZodNumberFormat2 = /* @__PURE__ */ $constructor2("ZodNumberFormat", (inst, d
35753
36019
  $ZodNumberFormat2.init(inst, def);
35754
36020
  ZodNumber2.init(inst, def);
35755
36021
  });
35756
- function int2(params) {
36022
+ function int3(params) {
35757
36023
  return _int2(ZodNumberFormat2, params);
35758
36024
  }
35759
36025
  var ZodBoolean2 = /* @__PURE__ */ $constructor2("ZodBoolean", (inst, def) => {
@@ -37935,14 +38201,14 @@ function codePointLength2(str4) {
37935
38201
  const units = str4.length;
37936
38202
  if (!highSurrogate2.test(str4))
37937
38203
  return units;
37938
- let count = units;
38204
+ let count2 = units;
37939
38205
  for (let i = 0; i < units - 1; i++) {
37940
38206
  if ((str4.charCodeAt(i) & 64512) === 55296 && (str4.charCodeAt(i + 1) & 64512) === 56320) {
37941
- count--;
38207
+ count2--;
37942
38208
  i++;
37943
38209
  }
37944
38210
  }
37945
- return count;
38211
+ return count2;
37946
38212
  }
37947
38213
  function getLengthableOrigin3(input) {
37948
38214
  if (Array.isArray(input))
@@ -37991,16 +38257,16 @@ function cleanEnum3(obj) {
37991
38257
  }
37992
38258
  function base64ToUint8Array2(base645) {
37993
38259
  const binaryString = atob(base645);
37994
- const bytes4 = new Uint8Array(binaryString.length);
38260
+ const bytes5 = new Uint8Array(binaryString.length);
37995
38261
  for (let i = 0; i < binaryString.length; i++) {
37996
- bytes4[i] = binaryString.charCodeAt(i);
38262
+ bytes5[i] = binaryString.charCodeAt(i);
37997
38263
  }
37998
- return bytes4;
38264
+ return bytes5;
37999
38265
  }
38000
- function uint8ArrayToBase642(bytes4) {
38266
+ function uint8ArrayToBase642(bytes5) {
38001
38267
  let binaryString = "";
38002
- for (let i = 0; i < bytes4.length; i++) {
38003
- binaryString += String.fromCharCode(bytes4[i]);
38268
+ for (let i = 0; i < bytes5.length; i++) {
38269
+ binaryString += String.fromCharCode(bytes5[i]);
38004
38270
  }
38005
38271
  return btoa(binaryString);
38006
38272
  }
@@ -38009,30 +38275,30 @@ function base64urlToUint8Array2(base64url5) {
38009
38275
  const padding = "=".repeat((4 - base645.length % 4) % 4);
38010
38276
  return base64ToUint8Array2(base645 + padding);
38011
38277
  }
38012
- function uint8ArrayToBase64url2(bytes4) {
38013
- return uint8ArrayToBase642(bytes4).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
38278
+ function uint8ArrayToBase64url2(bytes5) {
38279
+ return uint8ArrayToBase642(bytes5).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
38014
38280
  }
38015
38281
  function hexToUint8Array2(hex) {
38016
38282
  const cleanHex = hex.replace(/^0x/, "");
38017
38283
  if (cleanHex.length % 2 !== 0) {
38018
38284
  throw new Error("Invalid hex string length");
38019
38285
  }
38020
- const bytes4 = new Uint8Array(cleanHex.length / 2);
38286
+ const bytes5 = new Uint8Array(cleanHex.length / 2);
38021
38287
  for (let i = 0; i < cleanHex.length; i += 2) {
38022
- bytes4[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);
38288
+ bytes5[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);
38023
38289
  }
38024
- return bytes4;
38290
+ return bytes5;
38025
38291
  }
38026
- function uint8ArrayToHex2(bytes4) {
38027
- return Array.from(bytes4).map((b) => b.toString(16).padStart(2, "0")).join("");
38292
+ function uint8ArrayToHex2(bytes5) {
38293
+ return Array.from(bytes5).map((b) => b.toString(16).padStart(2, "0")).join("");
38028
38294
  }
38029
38295
  var Class3 = class {
38030
38296
  constructor(..._args) {
38031
38297
  }
38032
38298
  };
38033
- function members2(proto, table2) {
38034
- for (const key in table2) {
38035
- const desc = Object.getOwnPropertyDescriptor(table2, key);
38299
+ function members2(proto, table3) {
38300
+ for (const key in table3) {
38301
+ const desc = Object.getOwnPropertyDescriptor(table3, key);
38036
38302
  if (desc.get)
38037
38303
  Object.defineProperty(proto, key, { ...desc, enumerable: false });
38038
38304
  else
@@ -38047,10 +38313,10 @@ function hide2(inst, key, value) {
38047
38313
  return own3(inst, key, value, false);
38048
38314
  }
38049
38315
  // @__NO_SIDE_EFFECTS__
38050
- function derived2(computes, table2) {
38316
+ function derived2(computes, table3) {
38051
38317
  for (const key in computes) {
38052
38318
  const compute = computes[key];
38053
- Object.defineProperty(table2, key, {
38319
+ Object.defineProperty(table3, key, {
38054
38320
  configurable: true,
38055
38321
  enumerable: true,
38056
38322
  get() {
@@ -38061,7 +38327,7 @@ function derived2(computes, table2) {
38061
38327
  }
38062
38328
  });
38063
38329
  }
38064
- return table2;
38330
+ return table3;
38065
38331
  }
38066
38332
  function defineBound2(proto, key, fn) {
38067
38333
  Object.defineProperty(proto, key, {
@@ -43408,10 +43674,10 @@ var ZodNumber3 = /* @__PURE__ */ $constructor3(
43408
43674
  return this.check(_lte3(value, params));
43409
43675
  },
43410
43676
  int(params) {
43411
- return this.check(int3(params));
43677
+ return this.check(int4(params));
43412
43678
  },
43413
43679
  safe(params) {
43414
- return this.check(int3(params));
43680
+ return this.check(int4(params));
43415
43681
  },
43416
43682
  positive(params) {
43417
43683
  return this.check(_gt3(0, params));
@@ -43443,7 +43709,7 @@ var ZodNumberFormat3 = /* @__PURE__ */ $constructor3("ZodNumberFormat", (inst, d
43443
43709
  $ZodNumberFormat3.init(inst, def);
43444
43710
  ZodNumber3.init(inst, def);
43445
43711
  });
43446
- function int3(params) {
43712
+ function int4(params) {
43447
43713
  return _int3(ZodNumberFormat3, params);
43448
43714
  }
43449
43715
  var ZodBoolean3 = /* @__PURE__ */ $constructor3("ZodBoolean", (inst, def) => {
@@ -48997,9 +49263,9 @@ var require_codegen = /* @__PURE__ */ __commonJSMin((exports) => {
48997
49263
  }
48998
49264
  };
48999
49265
  var Label = class extends Node2 {
49000
- constructor(label) {
49266
+ constructor(label2) {
49001
49267
  super();
49002
- this.label = label;
49268
+ this.label = label2;
49003
49269
  this.names = {};
49004
49270
  }
49005
49271
  render({ _n }) {
@@ -49007,9 +49273,9 @@ var require_codegen = /* @__PURE__ */ __commonJSMin((exports) => {
49007
49273
  }
49008
49274
  };
49009
49275
  var Break = class extends Node2 {
49010
- constructor(label) {
49276
+ constructor(label2) {
49011
49277
  super();
49012
- this.label = label;
49278
+ this.label = label2;
49013
49279
  this.names = {};
49014
49280
  }
49015
49281
  render({ _n }) {
@@ -49374,11 +49640,11 @@ var require_codegen = /* @__PURE__ */ __commonJSMin((exports) => {
49374
49640
  endFor() {
49375
49641
  return this._endBlockNode(For);
49376
49642
  }
49377
- label(label) {
49378
- return this._leafNode(new Label(label));
49643
+ label(label2) {
49644
+ return this._leafNode(new Label(label2));
49379
49645
  }
49380
- break(label) {
49381
- return this._leafNode(new Break(label));
49646
+ break(label2) {
49647
+ return this._leafNode(new Break(label2));
49382
49648
  }
49383
49649
  return(value) {
49384
49650
  const node3 = new Return();
@@ -50516,15 +50782,15 @@ var require_resolve = /* @__PURE__ */ __commonJSMin((exports) => {
50516
50782
  return false;
50517
50783
  }
50518
50784
  function countKeys(schema) {
50519
- let count = 0;
50785
+ let count2 = 0;
50520
50786
  for (const key in schema) {
50521
50787
  if (key === "$ref") return Infinity;
50522
- count++;
50788
+ count2++;
50523
50789
  if (SIMPLE_INLINED.has(key)) continue;
50524
- if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));
50525
- if (count === Infinity) return Infinity;
50790
+ if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count2 += countKeys(sch));
50791
+ if (count2 === Infinity) return Infinity;
50526
50792
  }
50527
- return count;
50793
+ return count2;
50528
50794
  }
50529
50795
  function getFullPath(resolver, id = "", normalize2) {
50530
50796
  if (normalize2 !== false) id = normalizeId(id);
@@ -53124,8 +53390,8 @@ var require_contains = /* @__PURE__ */ __commonJSMin((exports) => {
53124
53390
  cxt.result(valid, () => cxt.reset());
53125
53391
  function validateItemsWithCount() {
53126
53392
  const schValid = gen.name("_valid");
53127
- const count = gen.let("count", 0);
53128
- validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
53393
+ const count2 = gen.let("count", 0);
53394
+ validateItems(schValid, () => gen.if(schValid, () => checkLimits(count2)));
53129
53395
  }
53130
53396
  function validateItems(_valid, block) {
53131
53397
  gen.forRange("i", 0, len, (i) => {
@@ -53138,13 +53404,13 @@ var require_contains = /* @__PURE__ */ __commonJSMin((exports) => {
53138
53404
  block();
53139
53405
  });
53140
53406
  }
53141
- function checkLimits(count) {
53142
- gen.code((0, codegen_1._)`${count}++`);
53143
- if (max === void 0) gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
53407
+ function checkLimits(count2) {
53408
+ gen.code((0, codegen_1._)`${count2}++`);
53409
+ if (max === void 0) gen.if((0, codegen_1._)`${count2} >= ${min}`, () => gen.assign(valid, true).break());
53144
53410
  else {
53145
- gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());
53411
+ gen.if((0, codegen_1._)`${count2} > ${max}`, () => gen.assign(valid, false).break());
53146
53412
  if (min === 1) gen.assign(valid, true);
53147
- else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));
53413
+ else gen.if((0, codegen_1._)`${count2} >= ${min}`, () => gen.assign(valid, true));
53148
53414
  }
53149
53415
  }
53150
53416
  }
@@ -55811,11 +56077,11 @@ function coerceEmbeddedInputRequest(method, key, entry) {
55811
56077
  function syntheticElicitationId() {
55812
56078
  const webCrypto = globalThis.crypto;
55813
56079
  if (webCrypto?.randomUUID !== void 0) return webCrypto.randomUUID();
55814
- const bytes4 = new Uint8Array(16);
55815
- webCrypto.getRandomValues(bytes4);
55816
- bytes4[6] = bytes4[6] & 15 | 64;
55817
- bytes4[8] = bytes4[8] & 63 | 128;
55818
- const hex = [...bytes4].map((byte) => byte.toString(16).padStart(2, "0")).join("");
56080
+ const bytes5 = new Uint8Array(16);
56081
+ webCrypto.getRandomValues(bytes5);
56082
+ bytes5[6] = bytes5[6] & 15 | 64;
56083
+ bytes5[8] = bytes5[8] & 63 | 128;
56084
+ const hex = [...bytes5].map((byte) => byte.toString(16).padStart(2, "0")).join("");
55819
56085
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
55820
56086
  }
55821
56087
  function legacyShimFailure(method, message3) {
@@ -56547,23 +56813,23 @@ function discoverAdvertisedCapabilities(capabilities) {
56547
56813
  return { ...capabilities };
56548
56814
  }
56549
56815
  function toolInputElementCount(value, max) {
56550
- let count = 0;
56816
+ let count2 = 0;
56551
56817
  const stack = [value];
56552
56818
  while (stack.length > 0) {
56553
56819
  const node3 = stack.pop();
56554
56820
  if (node3 === null || typeof node3 !== "object") continue;
56555
56821
  if (Array.isArray(node3)) for (const child of node3) {
56556
- if (++count > max) return count;
56822
+ if (++count2 > max) return count2;
56557
56823
  if (child !== null && typeof child === "object") stack.push(child);
56558
56824
  }
56559
56825
  else for (const key in node3) {
56560
56826
  if (!Object.prototype.hasOwnProperty.call(node3, key)) continue;
56561
- if (++count > max) return count;
56827
+ if (++count2 > max) return count2;
56562
56828
  const child = node3[key];
56563
56829
  if (child !== null && typeof child === "object") stack.push(child);
56564
56830
  }
56565
56831
  }
56566
- return count;
56832
+ return count2;
56567
56833
  }
56568
56834
  function resolveMaxToolInputElements(value) {
56569
56835
  if (value === void 0 || value === Infinity) return void 0;
@@ -57713,7 +57979,7 @@ function installExitGuard(opts) {
57713
57979
 
57714
57980
  // src/core/store/cleanup.ts
57715
57981
  import { existsSync as existsSync21, readdirSync as readdirSync10, rmSync as rmSync10 } from "node:fs";
57716
- import { join as join23 } from "node:path";
57982
+ import { join as join24 } from "node:path";
57717
57983
  function deleteSource(raw, id) {
57718
57984
  raw.prepare("DELETE FROM sources WHERE id = ?").run(id);
57719
57985
  deleteChunkRows(raw, { sourceId: id });
@@ -57769,8 +58035,8 @@ function lastAccess(raw) {
57769
58035
  return row5.t;
57770
58036
  }
57771
58037
  function sweepOne(configDir, projectKey, cutoff) {
57772
- const dir = join23(configDir, PROJECTS_DIR_NAME, projectKey);
57773
- const db = openForSweep(join23(dir, DB_FILE_NAME), projectKey);
58038
+ const dir = join24(configDir, PROJECTS_DIR_NAME, projectKey);
58039
+ const db = openForSweep(join24(dir, DB_FILE_NAME), projectKey);
57774
58040
  let dead;
57775
58041
  try {
57776
58042
  dead = withWrite(db, (h) => listLiveOwners(configDir, projectKey).length === 0 && lastAccess(h.raw) < cutoff);
@@ -57783,7 +58049,7 @@ function sweepOne(configDir, projectKey, cutoff) {
57783
58049
  function sweepDeadProjects(configDir) {
57784
58050
  let entries;
57785
58051
  try {
57786
- entries = readdirSync10(join23(configDir, PROJECTS_DIR_NAME), { withFileTypes: true });
58052
+ entries = readdirSync10(join24(configDir, PROJECTS_DIR_NAME), { withFileTypes: true });
57787
58053
  } catch (err) {
57788
58054
  if (err.code === "ENOENT") return [];
57789
58055
  throw err;
@@ -57902,7 +58168,7 @@ function errorReply(err) {
57902
58168
  async function startServer(argv, env) {
57903
58169
  const serverId = randomUUID();
57904
58170
  const degraded = await isDegraded();
57905
- const tools = degraded ? TOOLS.filter((t) => t.name === "ctx_doctor") : TOOLS;
58171
+ const tools = degraded ? TOOLS2.filter((t) => t.name === "ctx_doctor") : TOOLS2;
57906
58172
  const pending = /* @__PURE__ */ new Map();
57907
58173
  const held = [];
57908
58174
  let cleaned = false;
@@ -57935,7 +58201,7 @@ async function startServer(argv, env) {
57935
58201
  return db;
57936
58202
  }
57937
58203
  function stopMarker(configDir, projectKey) {
57938
- return join24(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME, serverId + OWNER_STOP_EXT);
58204
+ return join25(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME, serverId + OWNER_STOP_EXT);
57939
58205
  }
57940
58206
  function stopRequested() {
57941
58207
  const configDir = resolveConfigDir(process.env);
@@ -58124,7 +58390,7 @@ function piExtension(pi) {
58124
58390
  function registerTools() {
58125
58391
  if (toolsRegistered) return;
58126
58392
  try {
58127
- for (const tool of TOOLS) pi.registerTool(piTool(tool));
58393
+ for (const tool of TOOLS2) pi.registerTool(piTool(tool));
58128
58394
  toolsRegistered = true;
58129
58395
  } catch {
58130
58396
  }