context-mode 2.2.0 → 2.2.1

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
@@ -11342,6 +11342,10 @@ var DB_TIMEOUT_MS = 5e3;
11342
11342
  var DB_WAL_SUFFIX = "-wal";
11343
11343
  var DB_SHM_SUFFIX = "-shm";
11344
11344
  var DB_TMP_SUFFIX = ".tmp";
11345
+ var DB_LINK_DENIED_CODES = ["EACCES", "EPERM", "ENOSYS", "ENOTSUP", "EOPNOTSUPP"];
11346
+ var DB_PUBLISH_CLAIM_SUFFIX = ".publish";
11347
+ var DB_CLAIM_BUSY_CODES = ["EEXIST", "EPERM"];
11348
+ var DB_PUBLISH_POLL_MS = 5;
11345
11349
  var SQLITE_PRIMARY_CODE_MASK = 255;
11346
11350
  var SQLITE_CORRUPT_CODE = 11;
11347
11351
  var SQLITE_NOTADB_CODE = 26;
@@ -11626,7 +11630,7 @@ var DECISION_ANSWERS_KEY = "answers";
11626
11630
  var DECISION_OPTION_KEY = "option";
11627
11631
  var DECISION_LABEL_JOIN = " | ";
11628
11632
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
11629
- var BUNDLE_SHA = true ? "9cb2aaa5ebb63491960b3f3e9655a5821383eae4" : void 0;
11633
+ var BUNDLE_SHA = true ? "1fce537096e8e2b7d1924c2b5ff2b83287f157ee" : void 0;
11630
11634
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
11631
11635
  var DOCTOR_LABEL = Object.freeze({
11632
11636
  D1: "version",
@@ -14886,8 +14890,12 @@ var CC_READ_ONLY_DENY = Object.freeze(["Agent", "Artifact", "ArtifactComments",
14886
14890
  var CLAUDE_CODE_BUILT_INS = Object.freeze({
14887
14891
  "general-purpose": { tools: null, disallowed: [] },
14888
14892
  fork: { tools: null, disallowed: [] },
14893
+ claude: { tools: null, disallowed: [] },
14889
14894
  Explore: { tools: null, disallowed: [...CC_READ_ONLY_DENY] },
14890
- Plan: { tools: null, disallowed: [...CC_READ_ONLY_DENY] }
14895
+ Plan: { tools: null, disallowed: [...CC_READ_ONLY_DENY] },
14896
+ "claude-code-guide": { tools: ["Glob", "Grep", "Read", "WebFetch", "WebSearch"], disallowed: [] },
14897
+ "statusline-setup": { tools: ["Read", "Edit"], disallowed: [] },
14898
+ "web-fetch": { tools: ["WebFetch"], disallowed: [] }
14891
14899
  });
14892
14900
  var BUILT_IN_AGENT = "claude-code";
14893
14901
  function isSubagentCall(ev) {
@@ -15088,13 +15096,15 @@ function unique(names) {
15088
15096
  // src/core/policy/unwrap.ts
15089
15097
  var NONE = "";
15090
15098
  var WRAPPERS = Object.freeze({
15091
- sudo: { valueShorts: "ugpChDrtUTR", valueLongs: ["--user", "--group", "--prompt", "--chdir", "--host"], assignments: true, duration: false, refuseShorts: NONE },
15092
- env: { valueShorts: "uCS", valueLongs: ["--unset", "--chdir", "--split-string"], assignments: true, duration: false, refuseShorts: NONE },
15093
- time: { valueShorts: "fo", valueLongs: ["--format", "--output"], assignments: false, duration: false, refuseShorts: NONE },
15094
- nice: { valueShorts: "n", valueLongs: ["--adjustment"], assignments: false, duration: false, refuseShorts: NONE },
15095
- timeout: { valueShorts: "sk", valueLongs: ["--signal", "--kill-after"], assignments: false, duration: true, refuseShorts: NONE },
15096
- command: { valueShorts: NONE, valueLongs: [], assignments: false, duration: false, refuseShorts: "vV" },
15097
- xargs: { valueShorts: "aEdILnPs", valueLongs: ["--arg-file", "--delimiter", "--max-args", "--max-procs", "--max-chars"], assignments: false, duration: false, refuseShorts: NONE }
15099
+ sudo: { valueShorts: "ugpChDrtUTR", valueLongs: ["--user", "--group", "--prompt", "--chdir", "--host"], assignments: true, duration: false, refuseShorts: NONE, subcommands: [] },
15100
+ env: { valueShorts: "uCS", valueLongs: ["--unset", "--chdir", "--split-string"], assignments: true, duration: false, refuseShorts: NONE, subcommands: [] },
15101
+ time: { valueShorts: "fo", valueLongs: ["--format", "--output"], assignments: false, duration: false, refuseShorts: NONE, subcommands: [] },
15102
+ nice: { valueShorts: "n", valueLongs: ["--adjustment"], assignments: false, duration: false, refuseShorts: NONE, subcommands: [] },
15103
+ timeout: { valueShorts: "sk", valueLongs: ["--signal", "--kill-after"], assignments: false, duration: true, refuseShorts: NONE, subcommands: [] },
15104
+ command: { valueShorts: NONE, valueLongs: [], assignments: false, duration: false, refuseShorts: "vV", subcommands: [] },
15105
+ xargs: { valueShorts: "aEdILnPs", valueLongs: ["--arg-file", "--delimiter", "--max-args", "--max-procs", "--max-chars"], assignments: false, duration: false, refuseShorts: NONE, subcommands: [] },
15106
+ // #1388: rtk (rtk-ai/rtk) runs the inner command as-is under `proxy` / `bypass`; its other subcommands are rtk's own.
15107
+ rtk: { valueShorts: NONE, valueLongs: [], assignments: false, duration: false, refuseShorts: NONE, subcommands: ["proxy", "bypass"] }
15098
15108
  });
15099
15109
  var SHELLS = ["bash", "sh", "zsh"];
15100
15110
  var SCRIPT_FLAG = "c";
@@ -15117,6 +15127,10 @@ function isDuration(s) {
15117
15127
  }
15118
15128
  function peel(w, args) {
15119
15129
  let k = 0;
15130
+ if (w.subcommands.length > 0) {
15131
+ if (args.length === 0 || !w.subcommands.includes(args[0])) return null;
15132
+ k = 1;
15133
+ }
15120
15134
  while (k < args.length) {
15121
15135
  const a = args[k];
15122
15136
  if (a === LONG_OPT2) {
@@ -16252,7 +16266,7 @@ function openReadOnlyHandle(sqlite, path8, opts = {}) {
16252
16266
  }
16253
16267
 
16254
16268
  // src/core/store/db.ts
16255
- var { existsSync: existsSync3, linkSync, mkdirSync: mkdirSync2, rmSync } = process.getBuiltinModule("node:fs");
16269
+ var { existsSync: existsSync3, linkSync, mkdirSync: mkdirSync2, renameSync, rmSync, statSync: statSync3 } = process.getBuiltinModule("node:fs");
16256
16270
  function versionParts(v) {
16257
16271
  const bare2 = v.startsWith("v") ? v.slice(1) : v;
16258
16272
  return bare2.split(".").map((p) => Number.parseInt(p, 10));
@@ -16284,6 +16298,34 @@ function readUserVersion(raw) {
16284
16298
  const row5 = raw.prepare("PRAGMA user_version").get();
16285
16299
  return row5.user_version;
16286
16300
  }
16301
+ function errCode(err) {
16302
+ return err.code ?? "";
16303
+ }
16304
+ function publishWithoutLink(tmp, path8) {
16305
+ const claim3 = path8 + DB_PUBLISH_CLAIM_SUFFIX;
16306
+ const start = Date.now();
16307
+ for (; ; ) {
16308
+ if (existsSync3(path8)) return;
16309
+ try {
16310
+ mkdirSync2(claim3);
16311
+ } catch (err) {
16312
+ if (!DB_CLAIM_BUSY_CODES.includes(errCode(err))) throw err;
16313
+ if (Date.now() - start < DB_TIMEOUT_MS) {
16314
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, DB_PUBLISH_POLL_MS);
16315
+ continue;
16316
+ }
16317
+ const held = statSync3(claim3, { throwIfNoEntry: false });
16318
+ if (held !== void 0 && held.mtimeMs < start) rmSync(claim3, { recursive: true, force: true });
16319
+ throw new Error(`context.db was not published within ${DB_TIMEOUT_MS} ms: ${claim3} was held; open again`);
16320
+ }
16321
+ try {
16322
+ if (!existsSync3(path8)) renameSync(tmp, path8);
16323
+ } finally {
16324
+ rmSync(claim3, { recursive: true, force: true });
16325
+ }
16326
+ return;
16327
+ }
16328
+ }
16287
16329
  function createAtomically(sqlite, path8) {
16288
16330
  const { randomUUID: randomUUID2 } = process.getBuiltinModule("node:crypto");
16289
16331
  const tmp = path8 + "." + randomUUID2() + DB_TMP_SUFFIX;
@@ -16297,7 +16339,9 @@ function createAtomically(sqlite, path8) {
16297
16339
  try {
16298
16340
  linkSync(tmp, path8);
16299
16341
  } catch (err) {
16300
- if (err.code !== "EEXIST") throw err;
16342
+ const code = errCode(err);
16343
+ if (DB_LINK_DENIED_CODES.includes(code)) publishWithoutLink(tmp, path8);
16344
+ else if (code !== "EEXIST") throw err;
16301
16345
  }
16302
16346
  } finally {
16303
16347
  for (const suffix of ["", DB_WAL_SUFFIX, DB_SHM_SUFFIX]) rmSync(tmp + suffix, { force: true });
@@ -16488,9 +16532,15 @@ function readLastPrompt(db, sessionId) {
16488
16532
  const row5 = db.raw.prepare("SELECT body FROM events WHERE session_id = ? AND kind = 'prompt' ORDER BY seq DESC LIMIT 1").get(sessionId);
16489
16533
  return row5 === void 0 ? "" : row5.body;
16490
16534
  }
16491
- function readRecallRows(db, sessionId, worktree, limit) {
16535
+ function readRecallRows(db, sessionId, worktree, limit, maxSeq = Number.MAX_SAFE_INTEGER) {
16492
16536
  if (sessionId === "") return [];
16493
- return db.raw.prepare("SELECT * FROM events WHERE kind <> 'cost' AND (session_id = ? OR worktree = ?) ORDER BY seq DESC LIMIT ?").all(sessionId, worktree, limit);
16537
+ return db.raw.prepare(
16538
+ "SELECT * FROM events WHERE kind <> 'cost' AND ((session_id = ? AND seq <= ?) OR (worktree = ? AND session_id <> ?)) ORDER BY seq DESC LIMIT ?"
16539
+ ).all(sessionId, maxSeq, worktree, sessionId, limit);
16540
+ }
16541
+ function readMaxSeq(db) {
16542
+ const row5 = db.raw.prepare("SELECT COALESCE(MAX(seq), 0) AS n FROM events").get();
16543
+ return Number(row5.n);
16494
16544
  }
16495
16545
  function hasAgentRows(db, worktree, agent) {
16496
16546
  return db.raw.prepare("SELECT 1 FROM events WHERE worktree = ? AND agent = ? LIMIT 1").get(worktree, agent) !== void 0;
@@ -16498,6 +16548,10 @@ function hasAgentRows(db, worktree, agent) {
16498
16548
  function hasSessionRows(db, sessionId) {
16499
16549
  return db.raw.prepare("SELECT 1 FROM events WHERE session_id = ? LIMIT 1").get(sessionId) !== void 0;
16500
16550
  }
16551
+ function lastSessionSeq(db, sessionId) {
16552
+ const row5 = db.raw.prepare("SELECT MAX(seq) AS m FROM events WHERE session_id = ?").get(sessionId);
16553
+ return row5?.m ?? 0;
16554
+ }
16501
16555
 
16502
16556
  // src/core/store/snippet.ts
16503
16557
  var K1 = 1.2;
@@ -19075,12 +19129,16 @@ function recallQueryText(prompt) {
19075
19129
  if (cur !== "" && kept.size < RECALL_QUERY_MAX_TERMS) add(cur);
19076
19130
  return [...kept.size > 0 ? kept : all].join(" ");
19077
19131
  }
19078
- function queryUnits(db, sessionId, q, limit) {
19132
+ function readMaxSourceId(db) {
19133
+ const row5 = db.raw.prepare("SELECT COALESCE(MAX(id), 0) AS n FROM sources").get();
19134
+ return Number(row5.n);
19135
+ }
19136
+ function queryUnits(db, sessionId, q, limit, maxSourceId = Number.MAX_SAFE_INTEGER) {
19079
19137
  const match = searchTerms(q).join(" OR ");
19080
19138
  if (match === "" || sessionId === "") return [];
19081
19139
  const rows = db.raw.prepare(
19082
- "SELECT u.source_id AS source_id, u.ord AS ord, u.body AS body, -bm25(line_units) AS score, s.label AS label FROM line_units u JOIN sources s ON s.id = u.source_id WHERE line_units MATCH ? AND u.session_id = ? ORDER BY bm25(line_units) LIMIT ?"
19083
- ).all(match, sessionId, limit);
19140
+ "SELECT u.source_id AS source_id, u.ord AS ord, u.body AS body, -bm25(line_units) AS score, s.label AS label FROM line_units u JOIN sources s ON s.id = u.source_id WHERE line_units MATCH ? AND u.session_id = ? AND s.id <= ? ORDER BY bm25(line_units) LIMIT ?"
19141
+ ).all(match, sessionId, maxSourceId, limit);
19084
19142
  return rows.map((r) => ({ sourceId: Number(r.source_id), ord: Number(r.ord), label: r.label, body: r.body, score: r.score }));
19085
19143
  }
19086
19144
 
@@ -20364,8 +20422,9 @@ async function sessionStart(ev, row5, project) {
20364
20422
  if (ev.source === "compact" && hasRecall(row5)) markCompacted(await openDb(project), ev.sessionId);
20365
20423
  if (ev.source === "compact" && row5.compactDelivery === "sessionstart") {
20366
20424
  const db2 = await openDb(project);
20367
- if (!shouldHint(db2, ev.sessionId, COMPACT_STATE_KEY)) return ALLOW2;
20368
- return { kind: "hint", text: compactText(db2, ev, row5), onceKey: COMPACT_STATE_KEY };
20425
+ const onceKey = COMPACT_STATE_KEY + ":" + lastSessionSeq(db2, ev.sessionId);
20426
+ if (!shouldHint(db2, ev.sessionId, onceKey)) return ALLOW2;
20427
+ return { kind: "hint", text: compactText(db2, ev, row5), onceKey };
20369
20428
  }
20370
20429
  const db = await openDb(project);
20371
20430
  if (row5.compactDelivery === "opencode-cache" && metaTake(db, PENDING_COMPACT_META_PREFIX + ev.sessionId) !== null) {
@@ -20412,7 +20471,22 @@ async function firstTurnResume(ev, row5, project) {
20412
20471
  return { kind: "hint", text: withPrefix(RESUME_HINT, row5), onceKey: RESUME_HINT_KEY };
20413
20472
  }
20414
20473
  function markCompacted(db, sessionId) {
20415
- if (sessionId !== "") metaSet(db, COMPACTED_META_PREFIX + sessionId, PENDING_COMPACT_FLAG);
20474
+ if (sessionId === "") return;
20475
+ metaSet(db, COMPACTED_META_PREFIX + sessionId, JSON.stringify({ seq: readMaxSeq(db), source: readMaxSourceId(db) }));
20476
+ }
20477
+ function compactBoundary(value) {
20478
+ const all = { seq: Number.MAX_SAFE_INTEGER, source: Number.MAX_SAFE_INTEGER };
20479
+ try {
20480
+ const v = JSON.parse(value);
20481
+ if (typeof v !== "object" || v === null) return all;
20482
+ const { seq, source } = v;
20483
+ return {
20484
+ seq: typeof seq === "number" ? seq : all.seq,
20485
+ source: typeof source === "number" ? source : all.source
20486
+ };
20487
+ } catch {
20488
+ return all;
20489
+ }
20416
20490
  }
20417
20491
  function seenSeqs(value) {
20418
20492
  if (value === null) return [];
@@ -20435,13 +20509,16 @@ function seenUnitKeys(value) {
20435
20509
  async function recall(ev, row5, project, prompt) {
20436
20510
  if (!hasRecall(row5) || ev.sessionId === "") return ALLOW2;
20437
20511
  const db = await openDb(project);
20438
- if (metaGet(db, COMPACTED_META_PREFIX + ev.sessionId) === null) return ALLOW2;
20512
+ const compacted = metaGet(db, COMPACTED_META_PREFIX + ev.sessionId);
20513
+ if (compacted === null) return ALLOW2;
20514
+ const boundary = compactBoundary(compacted);
20439
20515
  const seenKey = RECALL_SEEN_META_PREFIX + ev.sessionId;
20440
20516
  const seen = seenSeqs(metaGet(db, seenKey));
20441
20517
  const unitsKey = RECALL_UNITS_SEEN_META_PREFIX + ev.sessionId;
20442
20518
  const seenUnits = seenUnitKeys(metaGet(db, unitsKey));
20443
- const units = queryUnits(db, ev.sessionId, recallQueryText(prompt), RECALL_UNIT_CANDIDATES);
20444
- const picked = pickRecall(readRecallRows(db, ev.sessionId, project.worktree, RECALL_MAX_ROWS), prompt, new Set(seen), units, new Set(seenUnits));
20519
+ const units = queryUnits(db, ev.sessionId, recallQueryText(prompt), RECALL_UNIT_CANDIDATES, boundary.source);
20520
+ const rows = readRecallRows(db, ev.sessionId, project.worktree, RECALL_MAX_ROWS, boundary.seq);
20521
+ const picked = pickRecall(rows, prompt, new Set(seen), units, new Set(seenUnits));
20445
20522
  if (picked.text === "") return ALLOW2;
20446
20523
  if (picked.seqs.length > 0) metaSet(db, seenKey, JSON.stringify([...seen, ...picked.seqs]));
20447
20524
  if (picked.units !== void 0) metaSet(db, unitsKey, JSON.stringify([...seenUnits, ...picked.units]));
@@ -20628,6 +20705,7 @@ function ownRead(ev, tool, env) {
20628
20705
  async function postReplace(ev, row5, project, env, tool, result, text) {
20629
20706
  if (result.bytes <= REPLACE_TRIGGER_BYTES) return ALLOW2;
20630
20707
  if (boundedRead(tool)) return ALLOW2;
20708
+ if (ompRangedRead(ev, tool)) return ALLOW2;
20631
20709
  if (ownRead(ev, tool, env)) return ALLOW2;
20632
20710
  if (result.keep === true) return ALLOW2;
20633
20711
  if (!hasReplace(row5)) return ALLOW2;
@@ -20642,6 +20720,7 @@ async function postReplace(ev, row5, project, env, tool, result, text) {
20642
20720
  shell: has3(row5.nativeTools.shell),
20643
20721
  read: RANGE_READ_TOOLS.includes(tool.canonicalName) && has3(row5.nativeTools.read ?? [])
20644
20722
  };
20723
+ if (set3 !== null && !caller.ctx && !caller.shell && !caller.read) return ALLOW2;
20645
20724
  label2 = SUBAGENT_SOURCE_PREFIX + tool.canonicalName + ":" + (tool.callId ?? String(ev.turn ?? 0));
20646
20725
  } else {
20647
20726
  label2 = mainLabel(tool, ev);
@@ -20675,6 +20754,53 @@ function searchTwin(handle, intent, project) {
20675
20754
  function boundedRead(tool) {
20676
20755
  return RANGE_READ_TOOLS.includes(tool.canonicalName) && READ_RANGE_KEYS.some((k) => tool.input[k] !== void 0 && tool.input[k] !== null);
20677
20756
  }
20757
+ function ompRangedRead(ev, tool) {
20758
+ if (ev.agent !== "omp" || !RANGE_READ_TOOLS.includes(tool.canonicalName)) return false;
20759
+ const p = READ_PATH_KEYS.map((k) => tool.input[k]).find((v) => typeof v === "string" && v !== "");
20760
+ if (p === void 0 || !rangedPathSuffix(p)) return false;
20761
+ try {
20762
+ return lstatSync2(resolve8(ev.cwd, p), { throwIfNoEntry: false }) === void 0;
20763
+ } catch {
20764
+ return false;
20765
+ }
20766
+ }
20767
+ function rangedPathSuffix(path8) {
20768
+ let cut = path8.lastIndexOf(":");
20769
+ let sel = path8.slice(cut + 1);
20770
+ if (sel.toLowerCase() === "raw") {
20771
+ cut = path8.lastIndexOf(":", cut - 1);
20772
+ sel = path8.slice(cut + 1, path8.length - 4);
20773
+ }
20774
+ if (cut <= 0 || !rangeList(sel)) return false;
20775
+ let file2 = path8.slice(0, cut);
20776
+ if (file2.toLowerCase().endsWith(":raw")) file2 = file2.slice(0, -4);
20777
+ return file2.length > 1 || !asciiLetter(file2);
20778
+ }
20779
+ function rangeList(sel) {
20780
+ return sel !== "" && sel.split(",").every(rangeItem);
20781
+ }
20782
+ function rangeItem(item) {
20783
+ if (item.startsWith("-")) return digitsOnly(item.slice(1));
20784
+ let i = 0;
20785
+ while (i < item.length && digit(item[i])) i++;
20786
+ if (i === 0) return false;
20787
+ if (i === item.length) return true;
20788
+ const op = item[i];
20789
+ const rest = item.slice(i + 1);
20790
+ return op === "-" && (rest === "" || digitsOnly(rest)) || op === "+" && digitsOnly(rest);
20791
+ }
20792
+ function digitsOnly(s) {
20793
+ if (s === "") return false;
20794
+ for (const c of s) if (!digit(c)) return false;
20795
+ return true;
20796
+ }
20797
+ function digit(c) {
20798
+ return c >= "0" && c <= "9";
20799
+ }
20800
+ function asciiLetter(s) {
20801
+ const c = s.toLowerCase();
20802
+ return c.length === 1 && c >= "a" && c <= "z";
20803
+ }
20678
20804
  function replaceOutput(body, handleLine) {
20679
20805
  return body === "" ? handleLine : body + "\n" + handleLine;
20680
20806
  }
@@ -20809,7 +20935,7 @@ function buildChildEnv(parent, extra) {
20809
20935
  }
20810
20936
 
20811
20937
  // src/core/sandbox/runtimes.ts
20812
- import { accessSync, constants as fsConstants, statSync as statSync3 } from "node:fs";
20938
+ import { accessSync, constants as fsConstants, statSync as statSync4 } from "node:fs";
20813
20939
  import path from "node:path";
20814
20940
 
20815
20941
  // src/core/sandbox/path-entries.ts
@@ -20854,7 +20980,7 @@ function fileNames(name, pathExt) {
20854
20980
  function probe(full) {
20855
20981
  let st;
20856
20982
  try {
20857
- st = statSync3(full, { throwIfNoEntry: false });
20983
+ st = statSync4(full, { throwIfNoEntry: false });
20858
20984
  } catch {
20859
20985
  return "unreadable";
20860
20986
  }
@@ -21049,7 +21175,7 @@ function runProcess(argv, o) {
21049
21175
  }
21050
21176
 
21051
21177
  // src/core/index/auto-memory.ts
21052
- import { readdirSync as readdirSync3, readFileSync as readFileSync6, statSync as statSync4 } from "node:fs";
21178
+ import { readdirSync as readdirSync3, readFileSync as readFileSync6, statSync as statSync5 } from "node:fs";
21053
21179
  import { join as join9 } from "node:path";
21054
21180
  var MEMORY_FILES = Object.freeze([
21055
21181
  Object.freeze(["CLAUDE.md"]),
@@ -21075,7 +21201,7 @@ function readAutoMemory(project) {
21075
21201
  const path8 = join9(project.worktree, ...segs);
21076
21202
  if (!isInside(project.worktree, path8)) continue;
21077
21203
  try {
21078
- const st = statSync4(path8);
21204
+ const st = statSync5(path8);
21079
21205
  if (!st.isFile()) continue;
21080
21206
  rows.push({
21081
21207
  origin: "memory",
@@ -21145,15 +21271,42 @@ function sourceCount(db, scope, ctx, source) {
21145
21271
  });
21146
21272
  return Number(row5.n);
21147
21273
  }
21148
- function zeroHits(db, scope, ctx, source, mem, offset = 0) {
21149
- const n = sourceCount(db, scope, ctx, source) + mem.rows.length;
21274
+ function zeroHits(db, scope, ctx, source, mem, nm, queries, offset = 0) {
21275
+ const inScope = sourceCount(db, scope, ctx, source);
21276
+ const n = inScope + mem.rows.length;
21150
21277
  if (offset > 0) return reply("No more hits past offset " + offset + ' in scope "' + scope + '" across ' + n + " source(s).", false);
21151
- return reply('No hits in scope "' + scope + '" across ' + n + " source(s).", false);
21278
+ const head2 = 'No hits in scope "' + scope + '" across ' + n + " source(s).";
21279
+ const pick4 = nm.pick;
21280
+ if (pick4 === null || mem.named || inScope > 0) return reply(head2, false);
21281
+ if (pick4.id !== null) {
21282
+ const wider = scope === "session" && sourceCount(db, "worktree", ctx, source) > 0 ? "worktree" : "project";
21283
+ return reply(head2 + "\nSource " + JSON.stringify(nm.arg) + ' is stored in scope "' + wider + '": ' + callText(queries, wider, nm.arg, "") + " searches it.", false);
21284
+ }
21285
+ return reply(head2 + "\n" + unknownSource(db, scope, ctx, nm.arg), true);
21286
+ }
21287
+ var STORED_SOURCES = `
21288
+ SELECT MAX(id) AS id, label FROM sources
21289
+ WHERE (:scope <> 'session' OR session_id = :session_id)
21290
+ AND (:scope <> 'worktree' OR worktree = :worktree)
21291
+ GROUP BY label ORDER BY MAX(id) DESC LIMIT :limit`;
21292
+ var STORED_SOURCES_SHOWN = 5;
21293
+ function unknownSource(db, scope, ctx, given) {
21294
+ const line = "Source " + JSON.stringify(given) + ' is not a stored source in scope "' + scope + '".';
21295
+ const rows = db.raw.prepare(STORED_SOURCES).all({
21296
+ scope,
21297
+ session_id: ctx.sessionId,
21298
+ worktree: ctx.project.worktree,
21299
+ limit: STORED_SOURCES_SHOWN + 1
21300
+ });
21301
+ if (rows.length === 0) return line + '\nctx_index stores one: ctx_index({content:"...", source:' + JSON.stringify(given) + "}).";
21302
+ const names = rows.slice(0, STORED_SOURCES_SHOWN).map((r) => isLongLabel(r.label) ? sourceHandle(Number(r.id)) : JSON.stringify(r.label));
21303
+ const more = rows.length > STORED_SOURCES_SHOWN ? ", ..." : "";
21304
+ return line + "\nStored sources, newest first: " + names.join(", ") + more + ". " + callText([], scope, void 0, 'sort:"timeline"') + " lists them all.";
21152
21305
  }
21153
21306
  function named(given, pick4) {
21154
- if (given === void 0 || pick4 === null) return { arg: given, note: null };
21307
+ if (given === void 0 || pick4 === null) return { arg: given, note: null, pick: null };
21155
21308
  const arg = pick4.id !== null && isLongLabel(given) ? sourceHandle(pick4.id) : given;
21156
- return { arg, note: collisionLine(given, pick4) };
21309
+ return { arg, note: collisionLine(given, pick4), pick: pick4 };
21157
21310
  }
21158
21311
  function sourceCard(db, id, input, scope, arg) {
21159
21312
  const row5 = sourceCardRow(db, id);
@@ -21285,7 +21438,7 @@ function relevance(db, given, scope, ctx, nm, ms, indexed) {
21285
21438
  });
21286
21439
  const take = fetched.map((h) => replyHits(h, size));
21287
21440
  const pages = fetched.map((h, i) => h.slice(0, take[i]));
21288
- if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source, ms, offset);
21441
+ if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source, ms, nm, input.queries, offset);
21289
21442
  const moreLine3 = (q, pos) => "More: " + callText([q], scope, nm.arg, "offset:" + pos);
21290
21443
  let reserve = 0;
21291
21444
  for (const q of input.queries) reserve += bytes2(moreLine3(q, offset + size)) + 1;
@@ -21355,7 +21508,7 @@ function timelineLine(r) {
21355
21508
  }
21356
21509
  function timeline(db, input, scope, ctx, nm, ms) {
21357
21510
  const page2 = ftsQueryTimeline(db, scope, ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, input.after ?? null, input.source, ms.rows);
21358
- if (page2.rows.length === 0) return zeroHits(db, scope, ctx, input.source, ms);
21511
+ if (page2.rows.length === 0) return zeroHits(db, scope, ctx, input.source, ms, nm, input.queries);
21359
21512
  const moreLine3 = (ts) => "more: " + callText(input.queries, scope, nm.arg, 'sort:"timeline", after:' + ts);
21360
21513
  const reserve = bytes2(moreLine3(page2.rows[page2.rows.length - 1].ts)) + 1;
21361
21514
  const lines = nm.note === null ? [] : [nm.note];
@@ -23740,16 +23893,16 @@ function parseTOML(code, options) {
23740
23893
  }
23741
23894
 
23742
23895
  // src/core/ops/atomic-file.ts
23743
- import { mkdirSync as mkdirSync3, renameSync, unlinkSync, writeFileSync } from "node:fs";
23896
+ import { mkdirSync as mkdirSync3, renameSync as renameSync2, unlinkSync, writeFileSync } from "node:fs";
23744
23897
  import path3 from "node:path";
23745
23898
  function sleepSync(ms) {
23746
23899
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
23747
23900
  }
23748
- function errCode(e) {
23901
+ function errCode2(e) {
23749
23902
  return e.code;
23750
23903
  }
23751
23904
  function renameWithRetry(from, to, opts = {}) {
23752
- const rename = opts.rename ?? renameSync;
23905
+ const rename = opts.rename ?? renameSync2;
23753
23906
  const sleep2 = opts.sleep ?? sleepSync;
23754
23907
  const win = (opts.platform ?? process.platform) === "win32";
23755
23908
  for (let attempt = 0; ; attempt += 1) {
@@ -23757,7 +23910,7 @@ function renameWithRetry(from, to, opts = {}) {
23757
23910
  rename(from, to);
23758
23911
  return;
23759
23912
  } catch (e) {
23760
- const busy = win && ATOMIC_RENAME_BUSY_CODES.includes(errCode(e) ?? "");
23913
+ const busy = win && ATOMIC_RENAME_BUSY_CODES.includes(errCode2(e) ?? "");
23761
23914
  if (!busy || attempt >= ATOMIC_RENAME_RETRIES) throw e;
23762
23915
  sleep2(ATOMIC_RENAME_DELAY_MS);
23763
23916
  }
@@ -23772,15 +23925,15 @@ function unlinkWithRetry(file2, opts = {}) {
23772
23925
  unlink(file2);
23773
23926
  return;
23774
23927
  } catch (e) {
23775
- if (errCode(e) === "ENOENT") return;
23776
- const busy = win && ATOMIC_RENAME_BUSY_CODES.includes(errCode(e) ?? "");
23928
+ if (errCode2(e) === "ENOENT") return;
23929
+ const busy = win && ATOMIC_RENAME_BUSY_CODES.includes(errCode2(e) ?? "");
23777
23930
  if (!busy || attempt >= ATOMIC_RENAME_RETRIES) throw replaceFailure(file2, e);
23778
23931
  sleep2(ATOMIC_RENAME_DELAY_MS);
23779
23932
  }
23780
23933
  }
23781
23934
  }
23782
23935
  function replaceFailure(file2, e) {
23783
- const busy = ATOMIC_RENAME_BUSY_CODES.includes(errCode(e) ?? "");
23936
+ const busy = ATOMIC_RENAME_BUSY_CODES.includes(errCode2(e) ?? "");
23784
23937
  const cause = e.message;
23785
23938
  return new Error(busy ? `Could not replace ${file2}: ${cause}. Fix: close the program using ${file2}, then re-run` : `Could not write ${file2}: ${cause}. Fix: check the path and its permissions, then re-run`, { cause: e });
23786
23939
  }
@@ -25470,7 +25623,7 @@ function configPaths(row5, env, worktree) {
25470
25623
  }
25471
25624
 
25472
25625
  // src/core/ops/doctor-db.ts
25473
- import { existsSync as existsSync12, statSync as statSync5 } from "node:fs";
25626
+ import { existsSync as existsSync12, statSync as statSync6 } from "node:fs";
25474
25627
  var unknown3 = (id, detail) => ({ id, label: DOCTOR_LABEL[id], status: "UNKNOWN", detail });
25475
25628
  var pass3 = (id, detail) => ({ id, label: DOCTOR_LABEL[id], status: "PASS", detail });
25476
25629
  var fail4 = (detail, fixCommand) => ({ id: "D8", label: DOCTOR_LABEL.D8, status: "FAIL", detail, fixCommand });
@@ -25512,7 +25665,7 @@ function orphanFiles(dbPath) {
25512
25665
  const files = [];
25513
25666
  for (const suffix of [DB_WAL_SUFFIX, DB_SHM_SUFFIX]) {
25514
25667
  const path8 = dbPath + suffix;
25515
- if (existsSync12(path8)) files.push({ path: path8, bytes: statSync5(path8).size });
25668
+ if (existsSync12(path8)) files.push({ path: path8, bytes: statSync6(path8).size });
25516
25669
  }
25517
25670
  return files.length > 0 && !existsSync12(dbPath) ? files : [];
25518
25671
  }
@@ -27397,7 +27550,7 @@ import { spawn as spawn3, spawnSync as spawnSync2 } from "node:child_process";
27397
27550
 
27398
27551
  // src/setup/spawn-bin.ts
27399
27552
  import { spawnSync } from "node:child_process";
27400
- import { accessSync as accessSync2, constants as fsc, statSync as statSync6 } from "node:fs";
27553
+ import { accessSync as accessSync2, constants as fsc, statSync as statSync7 } from "node:fs";
27401
27554
  import path5 from "node:path";
27402
27555
  var WIN_EXT = ".COM;.EXE;.BAT;.CMD";
27403
27556
  var WIN_SHIM_EXTS = Object.freeze([".cmd", ".bat"]);
@@ -27415,7 +27568,7 @@ function whichBin(bin, env, platform = process.platform) {
27415
27568
  const f = path5.join(dir, n);
27416
27569
  try {
27417
27570
  accessSync2(f, fsc.X_OK);
27418
- if (statSync6(f).isFile()) return f;
27571
+ if (statSync7(f).isFile()) return f;
27419
27572
  } catch {
27420
27573
  }
27421
27574
  }
@@ -27904,7 +28057,7 @@ function ownersDir(configDir, projectKey) {
27904
28057
  function ownerFile(configDir, projectKey, serverId) {
27905
28058
  return join17(ownersDir(configDir, projectKey), serverId + OWNER_PID_EXT);
27906
28059
  }
27907
- function errCode2(err) {
28060
+ function errCode3(err) {
27908
28061
  return err.code;
27909
28062
  }
27910
28063
  function writeOwnerPid(configDir, projectKey, serverId) {
@@ -27920,8 +28073,8 @@ function isLive(pid) {
27920
28073
  process.kill(pid, 0);
27921
28074
  return true;
27922
28075
  } catch (err) {
27923
- if (errCode2(err) === "ESRCH") return false;
27924
- if (errCode2(err) === "EPERM") return true;
28076
+ if (errCode3(err) === "ESRCH") return false;
28077
+ if (errCode3(err) === "EPERM") return true;
27925
28078
  throw err;
27926
28079
  }
27927
28080
  }
@@ -27931,7 +28084,7 @@ function listLiveOwners(configDir, projectKey) {
27931
28084
  try {
27932
28085
  names = readdirSync7(dir);
27933
28086
  } catch (err) {
27934
- if (errCode2(err) === "ENOENT") return [];
28087
+ if (errCode3(err) === "ENOENT") return [];
27935
28088
  throw err;
27936
28089
  }
27937
28090
  const live = [];
@@ -27942,7 +28095,7 @@ function listLiveOwners(configDir, projectKey) {
27942
28095
  try {
27943
28096
  text = readFileSync15(file2, "utf8");
27944
28097
  } catch (err) {
27945
- if (errCode2(err) === "ENOENT") continue;
28098
+ if (errCode3(err) === "ENOENT") continue;
27946
28099
  throw err;
27947
28100
  }
27948
28101
  const serverId = basename3(name, OWNER_PID_EXT);
@@ -28044,8 +28197,8 @@ function keyIsTyped(key) {
28044
28197
  if (key.length === 0) return false;
28045
28198
  for (const ch of key) {
28046
28199
  const upper = ch >= "A" && ch <= "Z";
28047
- const digit = ch >= "0" && ch <= "9";
28048
- if (!upper && !digit && ch !== "_") return false;
28200
+ const digit2 = ch >= "0" && ch <= "9";
28201
+ if (!upper && !digit2 && ch !== "_") return false;
28049
28202
  }
28050
28203
  return true;
28051
28204
  }
@@ -28695,11 +28848,11 @@ var ctxExecute = {
28695
28848
  };
28696
28849
 
28697
28850
  // src/core/tools/index.ts
28698
- import { existsSync as existsSync19, readFileSync as readFileSync20, statSync as statSync8 } from "node:fs";
28851
+ import { existsSync as existsSync19, readFileSync as readFileSync20, statSync as statSync9 } from "node:fs";
28699
28852
  import { dirname as dirname13, extname as extname3, join as join24, relative as relative5, resolve as resolve12 } from "node:path";
28700
28853
 
28701
28854
  // src/core/index/walk.ts
28702
- import { readdirSync as readdirSync9, readFileSync as readFileSync18, realpathSync as realpathSync10, statSync as statSync7 } from "node:fs";
28855
+ import { readdirSync as readdirSync9, readFileSync as readFileSync18, realpathSync as realpathSync10, statSync as statSync8 } from "node:fs";
28703
28856
  import { join as join22 } from "node:path";
28704
28857
  var GITIGNORE = ".gitignore";
28705
28858
  var GIT_DIR = ".git";
@@ -28733,7 +28886,7 @@ function visit(abs, rel, parent, contain, seen, found) {
28733
28886
  continue;
28734
28887
  }
28735
28888
  if (!isInside(contain, resolved)) continue;
28736
- const st = statSync7(resolved);
28889
+ const st = statSync8(resolved);
28737
28890
  isDir = st.isDirectory();
28738
28891
  isFile = st.isFile();
28739
28892
  target = resolved;
@@ -29436,8 +29589,8 @@ var EntityDecoder = class {
29436
29589
  while (offset < inputLength) {
29437
29590
  const char = input.charCodeAt(offset);
29438
29591
  if (isNumber2(char) || isHexadecimalCharacter(char)) {
29439
- const digit = char <= CharCodes.NINE ? char - CharCodes.ZERO : (char | TO_LOWER_BIT) - CharCodes.LOWER_A + 10;
29440
- result = result * 16 + digit;
29592
+ const digit2 = char <= CharCodes.NINE ? char - CharCodes.ZERO : (char | TO_LOWER_BIT) - CharCodes.LOWER_A + 10;
29593
+ result = result * 16 + digit2;
29441
29594
  consumed += 1;
29442
29595
  offset += 1;
29443
29596
  } else {
@@ -29465,13 +29618,13 @@ var EntityDecoder = class {
29465
29618
  let { result } = this;
29466
29619
  let { consumed } = this;
29467
29620
  while (offset < inputLength) {
29468
- const digit = input.charCodeAt(offset) - CharCodes.ZERO;
29469
- if (digit >>> 0 > 9) {
29621
+ const digit2 = input.charCodeAt(offset) - CharCodes.ZERO;
29622
+ if (digit2 >>> 0 > 9) {
29470
29623
  this.result = result;
29471
29624
  this.consumed = consumed;
29472
- return this.emitNumericEntity(digit + CharCodes.ZERO, 2);
29625
+ return this.emitNumericEntity(digit2 + CharCodes.ZERO, 2);
29473
29626
  }
29474
- result = result * 10 + digit;
29627
+ result = result * 10 + digit2;
29475
29628
  consumed += 1;
29476
29629
  offset += 1;
29477
29630
  }
@@ -32921,7 +33074,7 @@ function pathItems(input, project) {
32921
33074
  const abs = resolve12(project.worktree, input.path);
32922
33075
  if (!isInside(project.containmentRoot, abs)) throw missingOrOutside(input.path, abs, project.containmentRoot);
32923
33076
  const base = relative5(project.worktree, abs);
32924
- if (statSync8(abs).isDirectory()) {
33077
+ if (statSync9(abs).isDirectory()) {
32925
33078
  return walkDir(abs, project.containmentRoot).map((f) => ({
32926
33079
  sourceKind: "path",
32927
33080
  label: pathLabel(join24(base, f.relPath)),
@@ -62372,6 +62525,18 @@ function appendPayload(base, payload) {
62372
62525
  const text = str3(base);
62373
62526
  return text === "" ? payload : text + "\n\n" + payload;
62374
62527
  }
62528
+ var SECTION = "context_mode";
62529
+ function deliver(event, payload) {
62530
+ const options = event.systemPromptOptions;
62531
+ const sections = field(options, "sections");
62532
+ if (typeof sections === "object" && sections !== null && !Array.isArray(sections) && field(options, "forceSystemPrompt") === void 0) {
62533
+ const named2 = sections;
62534
+ if (payload === "") delete named2[SECTION];
62535
+ else named2[SECTION] = payload;
62536
+ return {};
62537
+ }
62538
+ return payload === "" ? {} : { systemPrompt: appendPayload(event.systemPrompt, payload) };
62539
+ }
62375
62540
  function textOf2(content) {
62376
62541
  if (typeof content === "string") return content;
62377
62542
  if (!Array.isArray(content)) return "";
@@ -62475,13 +62640,13 @@ function hostExtension(pi, host = "pi") {
62475
62640
  openPrompt = prompt;
62476
62641
  if (!rerun) turn += 1;
62477
62642
  registerTools();
62478
- const withPayload = () => ({ systemPrompt: appendPayload(event.systemPrompt, payload) });
62643
+ const withPayload = () => deliver(event, payload);
62479
62644
  if (rerun && payload !== "") return withPayload();
62480
62645
  let out;
62481
62646
  try {
62482
62647
  out = await hook({ type: compactPending ? "session_compact" : "session_start" }, turn);
62483
62648
  } catch {
62484
- return payload === "" ? {} : withPayload();
62649
+ return withPayload();
62485
62650
  }
62486
62651
  const compactTurn = compactPending;
62487
62652
  compactPending = false;
@@ -12,5 +12,5 @@
12
12
  }
13
13
  },
14
14
  "name": "context-mode",
15
- "version": "2.2.0"
15
+ "version": "2.2.1"
16
16
  }