context-mode 2.2.2 → 2.2.3

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/server.mjs CHANGED
@@ -17700,6 +17700,29 @@ var inputRequired = Object.assign(buildInputRequired, {
17700
17700
  return { method: "roots/list" };
17701
17701
  }
17702
17702
  });
17703
+ function inputResponse(responses, key) {
17704
+ if (responses === void 0 || typeof responses !== "object" || responses === null) return { kind: "missing" };
17705
+ const entry = responses[key];
17706
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return { kind: "missing" };
17707
+ const candidate2 = entry;
17708
+ if (candidate2["action"] === "accept" || candidate2["action"] === "decline" || candidate2["action"] === "cancel") {
17709
+ const content = candidate2["content"];
17710
+ return {
17711
+ kind: "elicit",
17712
+ action: candidate2["action"],
17713
+ ...content !== null && typeof content === "object" && !Array.isArray(content) && { content }
17714
+ };
17715
+ }
17716
+ if (Array.isArray(candidate2["roots"])) return {
17717
+ kind: "roots",
17718
+ roots: candidate2["roots"]
17719
+ };
17720
+ if (typeof candidate2["role"] === "string" && candidate2["content"] !== void 0) return {
17721
+ kind: "sampling",
17722
+ result: candidate2
17723
+ };
17724
+ return { kind: "missing" };
17725
+ }
17703
17726
  var REQUEST_STATE_ONLY_LEG_PACING_MS = 250;
17704
17727
  function inputRequiredRoundsExceededMessage(method, maxRounds) {
17705
17728
  return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`;
@@ -28065,14 +28088,8 @@ var REPORT_CAP = 4096;
28065
28088
  var POINTER_MIN = 640;
28066
28089
  var STATE_CLOSE_TAG = "</context_mode_state>";
28067
28090
  var INDEX_WRITE_CHUNK = 1048576;
28068
- var REPLACE_TRIGGER_BYTES_DEFAULT = 4096;
28091
+ var REPLACE_TRIGGER_BYTES = 4096;
28069
28092
  var REPLACE_TRIGGER_ENV = "CTX_REPLACE_TRIGGER_BYTES";
28070
- function readReplaceTrigger(raw) {
28071
- if (raw === void 0 || raw.trim() === "") return REPLACE_TRIGGER_BYTES_DEFAULT;
28072
- const n = Number(raw);
28073
- return Number.isSafeInteger(n) && n > 0 ? n : REPLACE_TRIGGER_BYTES_DEFAULT;
28074
- }
28075
- var REPLACE_TRIGGER_BYTES = readReplaceTrigger(process.env[REPLACE_TRIGGER_ENV]);
28076
28093
  var RANGE_READ_TOOLS = Object.freeze(["Read", "view"]);
28077
28094
  var READ_RANGE_KEYS = Object.freeze(["offset", "limit", "view_range"]);
28078
28095
  var SKILL_LOAD_TOOLS = Object.freeze(["Skill"]);
@@ -28243,7 +28260,7 @@ var TOOLS_TTL_MS = 36e5;
28243
28260
  var IN_PROCESS_TIMEOUT_MS = 0;
28244
28261
  var MS_PER_DAY = 864e5;
28245
28262
  var PROJECT_KEY_HEX_LEN = 16;
28246
- var SCHEMA_VERSION = 6;
28263
+ var SCHEMA_VERSION = 7;
28247
28264
  var RETENTION_IDLE_DAYS = 30;
28248
28265
  var RETENTION_SIZE_CAP_BYTES = 524288e3;
28249
28266
  var PROJECT_DEAD_IDLE_DAYS = 14;
@@ -28285,6 +28302,7 @@ var SETTINGS_LOCAL_FILE = "settings.local.json";
28285
28302
  var DEFAULT_PLUGIN_SCOPE = "user";
28286
28303
  var PROJECT_PLUGIN_SCOPES = Object.freeze(["local", "project"]);
28287
28304
  var PLUGIN_SCOPE_RANK = Object.freeze({ local: 0, project: 1, user: 2, managed: 2 });
28305
+ var MCP_SERVER_TOOL_PREFIX = "mcp__";
28288
28306
  var MCP_HINT_EVERY_DEFAULT = 10;
28289
28307
  function readHintEvery(raw) {
28290
28308
  if (raw === void 0 || raw.trim() === "") return MCP_HINT_EVERY_DEFAULT;
@@ -28372,8 +28390,10 @@ var OWN_TOOL_PREFIX = "ctx_";
28372
28390
  var EDIT_TOOLS = Object.freeze(["Write", "Edit"]);
28373
28391
  var EDIT_PATH_KEYS = Object.freeze(["file_path", "path"]);
28374
28392
  var RECALL_MIN_SCORE = 5;
28393
+ var LOSTBET_META_PREFIX = "lostbet:";
28375
28394
  var RECALL_QUERY_MAX_TERMS = 64;
28376
28395
  var RECALL_UNIT_CANDIDATES = 64;
28396
+ var SUBAGENT_SOURCE_PREFIX = "subagent:";
28377
28397
  var AGENT_ARG = "--agent";
28378
28398
  var DECAY_SCALE = 1e3;
28379
28399
  var PERCENT_SCALE = 100;
@@ -28453,7 +28473,7 @@ function PURGE_SUMMARY(rows, scope) {
28453
28473
  var DECISION_SOURCE = "decision";
28454
28474
  var DECISION_USER_LABEL = "decision (user)";
28455
28475
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
28456
- var BUNDLE_SHA = true ? "ae2e1bb106e462a19ab3c042e371cd8a7f691074" : void 0;
28476
+ var BUNDLE_SHA = true ? "f41c429ae530a3fec5bda3c12a8ecdc2a5f14ada" : void 0;
28457
28477
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
28458
28478
  var DOCTOR_LABEL = Object.freeze({
28459
28479
  D1: "version",
@@ -28892,6 +28912,7 @@ var OMP_CONTENT_INFO = "OMP keeps tool output in content; context-mode writes it
28892
28912
  var OMP_PRINT_MODE_INFO = "Print mode sends no prompt event. Use omp or omp --mode rpc to keep prompts.";
28893
28913
  var OMP_SCRIPTS_INFO = "Add < /dev/null in scripts.";
28894
28914
  var OMP_IMPORT_INFO = (claude, mcp) => `OMP also imports context-mode from ${claude}. To run it once, add "context-mode" to disabledServers in ${mcp}.`;
28915
+ var REPLACE_TRIGGER_RETIRED_INFO = (where) => `${REPLACE_TRIGGER_ENV} in ${where} is no longer read: context-mode stores every tool output over ${REPLACE_TRIGGER_BYTES} B whole and ctx_search reads it back. You can remove that line from ${where}.`;
28895
28916
  var PI_CURRENT_MAJOR = 2;
28896
28917
  var V1_OPENCODE_PLUGIN_SPEC = "context-mode";
28897
28918
  var V1_TMP_PREFIX = "context-mode-";
@@ -28911,6 +28932,10 @@ var OPENCODE_CONFIG_DIR_ENV = "OPENCODE_CONFIG_DIR";
28911
28932
  var APPDATA_ENV = "APPDATA";
28912
28933
  var VSCODE_USER_DIR_SEGMENTS = Object.freeze(["Code", "User"]);
28913
28934
  var XDG_CONFIG_HOME_ENV = "XDG_CONFIG_HOME";
28935
+ var XDG_DATA_HOME_ENV = "XDG_DATA_HOME";
28936
+ var PI_CONFIG_DIR_ENV = "PI_CONFIG_DIR";
28937
+ var OMP_APP_DIR = "omp";
28938
+ var OMP_PLUGINS_DIR = "plugins";
28914
28939
  var CONFIG_TOML_FILE = "config.toml";
28915
28940
  var CONFIG_JSON_FILE = "config.json";
28916
28941
  var ZCODE_CLI_DIR = "cli";
@@ -29128,7 +29153,8 @@ var ERROR_TEXT = Object.freeze({
29128
29153
  NO_RUNTIME: "No <lang> runtime on PATH. Fix: install it or pick another language.",
29129
29154
  FETCH_FAILED: "Fetch failed: <code>. Fix: check the URL or proxy.",
29130
29155
  SSRF: "Blocked private address <host>. Fix: use a public URL.",
29131
- OUTSIDE_ROOT: "Path <p> is outside the project. Fix: use a path inside <root>.",
29156
+ OUTSIDE_ROOT: "Path <p> is outside the project and the folders added to this session. Fix: use a path inside <root>, or add its folder to the session (Claude Code /add-dir, Codex --add-dir).",
29157
+ // #1398 D-1398-HOST-ROOTS-1
29132
29158
  INVALID_ARGS: "Invalid argument <field>. Fix: <action>.",
29133
29159
  ONE_OF_INPUT: "Pass exactly one of <names>. Fix: drop the extra field.",
29134
29160
  SPAWN_FAILED: "Failed to start the process: <detail>. Fix: check the command and PATH.",
@@ -29287,13 +29313,22 @@ CREATE VIRTUAL TABLE line_units USING fts5(
29287
29313
  var DDL_V6 = `
29288
29314
  UPDATE sources SET label = replace(label, char(92), '/') WHERE kind = 'path' AND instr(label, char(92)) > 0;
29289
29315
  `;
29316
+ var DDL_V7 = `
29317
+ ALTER TABLE sources ADD COLUMN unit_lo INTEGER;
29318
+ ALTER TABLE sources ADD COLUMN unit_hi INTEGER;
29319
+ CREATE INDEX IF NOT EXISTS idx_sources_session ON sources(session_id, id);
29320
+ UPDATE sources SET unit_lo = g.lo, unit_hi = g.hi
29321
+ FROM (SELECT source_id, MIN(rowid) AS lo, MAX(rowid) AS hi FROM line_units GROUP BY source_id) AS g
29322
+ WHERE g.source_id = sources.id;
29323
+ `;
29290
29324
  var MIGRATIONS = [
29291
29325
  { version: 1, sql: DDL },
29292
29326
  { version: 2, sql: DDL_V2 },
29293
29327
  { version: 3, sql: DDL_V3 },
29294
29328
  { version: 4, sql: DDL_V4 },
29295
29329
  { version: 5, sql: DDL_V5 },
29296
- { version: 6, sql: DDL_V6 }
29330
+ { version: 6, sql: DDL_V6 },
29331
+ { version: 7, sql: DDL_V7 }
29297
29332
  ];
29298
29333
  function applyMigrations(db, fromVersion) {
29299
29334
  if (fromVersion === SCHEMA_VERSION2) return;
@@ -29474,6 +29509,18 @@ function closeDb(db) {
29474
29509
  } catch {
29475
29510
  }
29476
29511
  }
29512
+ function inWrite(db, fn) {
29513
+ return db.raw.isTransaction ? fn(db) : withWrite(db, fn);
29514
+ }
29515
+ function metaGet(db, key) {
29516
+ const row5 = db.raw.prepare("SELECT value FROM meta WHERE key = ?").get(key);
29517
+ return row5 === void 0 ? null : row5.value;
29518
+ }
29519
+ function metaSet(db, key, v) {
29520
+ inWrite(db, (h) => {
29521
+ h.raw.prepare("INSERT INTO meta(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(key, v);
29522
+ });
29523
+ }
29477
29524
 
29478
29525
  // src/core/journal/append.ts
29479
29526
  var COLUMNS = "events(session_id, worktree, agent, kind, tool, key, path, ok, exit_code, bytes, body, turn, sandbox_bytes, returned_bytes, created_at, accessed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
@@ -29695,6 +29742,24 @@ function piAgentDirOf(env, home) {
29695
29742
  const dir = env[PI_AGENT_DIR_ENV];
29696
29743
  return dir !== void 0 && dir !== "" ? dir : join(home, ...AGENT_HOME_DIR.pi, PI_AGENT_DIR);
29697
29744
  }
29745
+ function ompConfigRootOf(env, home) {
29746
+ const dir = env[PI_CONFIG_DIR_ENV];
29747
+ return dir !== void 0 && dir !== "" ? join(home, dir) : join(home, ...AGENT_HOME_DIR.omp);
29748
+ }
29749
+ function ompAgentDirOf(env, home) {
29750
+ return join(ompConfigRootOf(env, home), PI_AGENT_DIR);
29751
+ }
29752
+ function ompPluginsDirOf(env, home, platform = process.platform) {
29753
+ const root = ompConfigRootOf(env, home);
29754
+ const xdg = env[XDG_DATA_HOME_ENV];
29755
+ const agent = env[PI_AGENT_DIR_ENV];
29756
+ const defaultAgent = agent === void 0 || agent === "" || resolve(agent) === join(root, PI_AGENT_DIR);
29757
+ if ((platform === "linux" || platform === "darwin") && defaultAgent && xdg !== void 0 && xdg !== "") {
29758
+ const app = join(xdg, OMP_APP_DIR);
29759
+ if (existsSync2(app)) return join(app, OMP_PLUGINS_DIR);
29760
+ }
29761
+ return join(root, OMP_PLUGINS_DIR);
29762
+ }
29698
29763
  function vscodeUserDirOf(env, home, platform = process.platform) {
29699
29764
  const set3 = (v) => v !== void 0 && v !== "";
29700
29765
  const p = platform === "win32" ? win32 : posix;
@@ -29750,6 +29815,10 @@ function isInside(root, p) {
29750
29815
  }
29751
29816
  return true;
29752
29817
  }
29818
+ function allowedRootOf(containmentRoot, hostRoots, p) {
29819
+ if (isInside(containmentRoot, p)) return containmentRoot;
29820
+ return hostRoots?.find((r) => isInside(r, p));
29821
+ }
29753
29822
  function commonRoot(paths) {
29754
29823
  const reals = paths.map(real).filter((r) => r !== void 0);
29755
29824
  if (reals.length === 0) throw new RangeError("commonRoot needs at least one existing path");
@@ -32059,11 +32128,13 @@ function deleteChunkRows(raw, scope) {
32059
32128
  if (scope === "all") {
32060
32129
  raw.exec("INSERT INTO chunks_tri(chunks_tri) VALUES ('delete-all')");
32061
32130
  raw.exec("DELETE FROM line_units");
32131
+ raw.exec("UPDATE sources SET unit_lo = NULL, unit_hi = NULL WHERE unit_lo IS NOT NULL");
32062
32132
  return Number(raw.prepare("DELETE FROM chunks").run().changes);
32063
32133
  }
32064
- const [where, arg] = "sourceId" in scope ? ["source_id = ?", scope.sourceId] : ["source_id IN (SELECT id FROM sources WHERE label = ?)", scope.label];
32134
+ const [where, arg, own4] = "sourceId" in scope ? ["source_id = ?", scope.sourceId, "id = ?"] : ["source_id IN (SELECT id FROM sources WHERE label = ?)", scope.label, "label = ?"];
32065
32135
  raw.prepare(TRI_DELETE + " WHERE " + where).run(arg);
32066
32136
  raw.prepare("DELETE FROM line_units WHERE " + where).run(arg);
32137
+ raw.prepare("UPDATE sources SET unit_lo = NULL, unit_hi = NULL WHERE " + own4).run(arg);
32067
32138
  return Number(raw.prepare("DELETE FROM chunks WHERE " + where).run(arg).changes);
32068
32139
  }
32069
32140
  function toMatch(q) {
@@ -32591,9 +32662,15 @@ function recallQueryText(prompt) {
32591
32662
  function queryUnits(db, sessionId, q, limit, maxSourceId = Number.MAX_SAFE_INTEGER) {
32592
32663
  const match = searchTerms(q).join(" OR ");
32593
32664
  if (match === "" || sessionId === "") return [];
32594
- const rows = db.raw.prepare(
32595
- "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 ?"
32596
- ).all(match, sessionId, maxSourceId, limit);
32665
+ const span2 = stmt(
32666
+ db.raw,
32667
+ "SELECT MIN(unit_lo) AS lo, MAX(unit_hi) AS hi FROM sources WHERE session_id = ? AND id <= ? AND unit_lo IS NOT NULL"
32668
+ ).get(sessionId, maxSourceId);
32669
+ if (span2 === void 0 || span2.lo === null || span2.hi === null) return [];
32670
+ const rows = stmt(
32671
+ db.raw,
32672
+ "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.rowid BETWEEN ? AND ? AND u.session_id = ? AND s.id <= ? ORDER BY bm25(line_units) LIMIT ?"
32673
+ ).all(match, span2.lo, span2.hi, sessionId, maxSourceId, limit);
32597
32674
  return rows.map((r) => ({ sourceId: Number(r.source_id), ord: Number(r.ord), label: r.label, body: r.body, score: r.score }));
32598
32675
  }
32599
32676
 
@@ -43887,7 +43964,7 @@ var TOOL_DESCRIPTIONS = Object.freeze({
43887
43964
  ctx_execute: 'Example: `ctx_execute({language:"shell",code:"git log --oneline -5"})`. Required: language, code.\nWrite code that prints only the answer, not the raw data. Runs code in a sandboxed subprocess in the project directory (shell, powershell, javascript, typescript, python, or another runtime on PATH); only what the code prints comes back. For a large file, set `file` to its local path: the code gets it in the CTX_FILE environment variable. Set `intent` when output may be large: the matching sections come back and the full output is indexed for ctx_search. `timeoutMs` defaults to and caps at 600000; then the whole process tree is killed.',
43888
43965
  ctx_batch: 'Example: `ctx_batch({commands:["git log --oneline -5"],queries:["recent changes"]})`. Required: commands, queries.\nRuns several shell commands, then answers several search queries over their combined output, in one call. Use it to collect facts from more than one command at once, for example test results plus recent commits, when you need specific answers rather than the full text. Returns the matching sections and a one-line footer.',
43889
43966
  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.',
43890
- ctx_search: 'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Memory files such as AGENTS.md are searched too. 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.',
43967
+ ctx_search: 'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. Memory files such as AGENTS.md are searched too. 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. Set `source` with queries `[""]` to read that source whole, in order, a full page per call; `More:` gives the next `offset`. When nothing matches, the reply states the scope and how many sources are indexed.',
43891
43968
  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.",
43892
43969
  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.",
43893
43970
  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, the fix and a docs link. Use it when the user asks whether context-mode works, or after a context-mode error. Run each Fix first, then call ctx_doctor again. If a FAIL stays, show the user the report file it names (it holds paths and environment details) and ask before you run the printed gh issue command.\n",
@@ -44516,6 +44593,31 @@ function runProcess(argv, o) {
44516
44593
  });
44517
44594
  }
44518
44595
 
44596
+ // src/core/store/lost-bet.ts
44597
+ function lostKey(sessionId, key) {
44598
+ return LOSTBET_META_PREFIX + sessionId + ":" + key;
44599
+ }
44600
+ function isLostBet(db, sessionId, key) {
44601
+ return sessionId !== "" && metaGet(db, lostKey(sessionId, key)) !== null;
44602
+ }
44603
+ function markLostBet(db, sessionId, key, reason, source) {
44604
+ if (sessionId === "" || key === "") return;
44605
+ try {
44606
+ metaSet(db, lostKey(sessionId, key), JSON.stringify({ at: Date.now(), reason, source }));
44607
+ } catch {
44608
+ }
44609
+ }
44610
+ function betKeyOfLabel(label2) {
44611
+ if (label2.startsWith(SUBAGENT_SOURCE_PREFIX)) return null;
44612
+ const hash = label2.lastIndexOf("#");
44613
+ if (hash <= 0) return null;
44614
+ const stem = label2.slice(0, hash);
44615
+ const colon = stem.indexOf(":");
44616
+ if (colon <= 0) return null;
44617
+ if (colon + 1 < stem.length || stem.startsWith(MCP_SERVER_TOOL_PREFIX)) return stem;
44618
+ return null;
44619
+ }
44620
+
44519
44621
  // src/core/index/auto-memory.ts
44520
44622
  import { readdirSync as readdirSync4, readFileSync as readFileSync4, statSync as statSync4 } from "node:fs";
44521
44623
  import { join as join6 } from "node:path";
@@ -44701,9 +44803,9 @@ function unknownSource(db, scope, ctx, given) {
44701
44803
  return line + "\nStored sources, newest first: " + names.join(", ") + more + ". " + callText([], scope, void 0, 'sort:"timeline"') + " lists them all.";
44702
44804
  }
44703
44805
  function named(given, pick4) {
44704
- if (given === void 0 || pick4 === null) return { arg: given, note: null, pick: null };
44806
+ if (given === void 0 || pick4 === null) return { arg: given, note: null, pick: null, lost: null };
44705
44807
  const arg = pick4.id !== null && isLongLabel(given) ? sourceHandle(pick4.id) : given;
44706
- return { arg, note: collisionLine(given, pick4), pick: pick4 };
44808
+ return { arg, note: collisionLine(given, pick4), pick: pick4, lost: null };
44707
44809
  }
44708
44810
  function sourceCard(db, id, input, scope, arg) {
44709
44811
  const row5 = sourceCardRow(db, id);
@@ -44727,7 +44829,7 @@ function decisionQueries(input) {
44727
44829
  function pageSize(input) {
44728
44830
  return input.source === DECISION_SOURCE ? SEARCH_PAGE_SIZE : SEARCH_REPLY_HITS;
44729
44831
  }
44730
- function page(db, q, input, scope, ctx, offset, extra = 0) {
44832
+ function page(db, q, input, scope, ctx, offset, extra = 0, h9 = { n: 0, list: true }) {
44731
44833
  const size = pageSize(input) + extra;
44732
44834
  if (input.source === DECISION_SOURCE && q.trim() === "") {
44733
44835
  return ftsListSource(db, DECISION_SOURCE, scope, ctx.project, ctx.sessionId, size, offset);
@@ -44736,6 +44838,8 @@ function page(db, q, input, scope, ctx, offset, extra = 0) {
44736
44838
  if (hits.length > 0 || input.source === void 0) return hits;
44737
44839
  const any3 = offset === 0 ? hits : ftsQuery(db, q, scope, ctx.project, ctx.sessionId, 1, 0, input.source);
44738
44840
  if (any3.length > 0) return hits;
44841
+ h9.n++;
44842
+ if (!h9.list) return [];
44739
44843
  return ftsListSource(db, input.source, scope, ctx.project, ctx.sessionId, size, offset);
44740
44844
  }
44741
44845
  var JSON_ROWS_PAGE = 5;
@@ -44824,15 +44928,27 @@ function relevance(db, given, scope, ctx, nm, ms, indexed) {
44824
44928
  const size = pageSize(input);
44825
44929
  const mem = ms.named || offset === 0 ? memoryChunks(ms.rows) : [];
44826
44930
  const count2 = (hits, n) => ms.named ? Math.min(n, hits.length) : contentIn(hits, n);
44827
- const fetched = input.queries.map((q) => {
44931
+ const h9 = { n: 0, list: false };
44932
+ const listed = [];
44933
+ const fetched = input.queries.map((q, qi) => {
44828
44934
  if (ms.named) {
44829
44935
  const want = offset + size + 1;
44830
44936
  const content2 = indexed ? ftsQuery(db, q, scope, ctx.project, ctx.sessionId, want, 0, input.source) : [];
44831
44937
  return mergeMemory(content2, memoryHits(mem, q, want)).slice(offset, want);
44832
44938
  }
44833
- const content = page(db, q, input, scope, ctx, offset, 1);
44939
+ const before = h9.n;
44940
+ const content = page(db, q, input, scope, ctx, offset, 1, h9);
44941
+ if (h9.n > before) listed.push(qi);
44834
44942
  return mem.length === 0 ? content : mergeMemory(content, memoryHits(mem, q, MEMORY_HITS));
44835
44943
  });
44944
+ if (listed.length > 0 && listed.length === input.queries.length) {
44945
+ const ordered = orderedRead(db, input, scope, ctx, nm);
44946
+ if (ordered !== null) return ordered;
44947
+ }
44948
+ for (const qi of listed) {
44949
+ const content = ftsListSource(db, input.source, scope, ctx.project, ctx.sessionId, size + 1, offset);
44950
+ fetched[qi] = mem.length === 0 ? content : mergeMemory(content, memoryHits(mem, input.queries[qi], MEMORY_HITS));
44951
+ }
44836
44952
  const take = fetched.map((h) => replyHits(h, size));
44837
44953
  const pages = fetched.map((h, i) => h.slice(0, take[i]));
44838
44954
  if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source, ms, nm, input.queries, offset);
@@ -44897,6 +45013,49 @@ function relevance(db, given, scope, ctx, nm, ms, indexed) {
44897
45013
  for (const [pos, qs] of byPos) moreLines.push("More: " + callText(qs, scope, nm.arg, "offset:" + pos));
44898
45014
  return reply(lines.concat(moreLines).join("\n"), false);
44899
45015
  }
45016
+ var ORDERED_LINE_BACK = 512;
45017
+ var SOURCE_IN_SCOPE = `
45018
+ SELECT session_id FROM sources WHERE id = :id
45019
+ AND (:scope <> 'session' OR session_id = :session_id)
45020
+ AND (:scope <> 'worktree' OR worktree = :worktree)`;
45021
+ function sourceText(db, id) {
45022
+ const rows = db.raw.prepare("SELECT body FROM chunks WHERE source_id = ? ORDER BY CAST(ord AS INTEGER)").all(id);
45023
+ const parts = [];
45024
+ for (let i = 0; i < rows.length; i++) {
45025
+ const body = rows[i].body;
45026
+ parts.push(body);
45027
+ if (i + 1 < rows.length && !body.endsWith("\n") && bytes2(body) < MAX_CHUNK_BYTES - 3) parts.push("\n\n");
45028
+ }
45029
+ return parts.join("");
45030
+ }
45031
+ function orderedRead(db, input, scope, ctx, nm) {
45032
+ const pick4 = nm.pick;
45033
+ if (pick4 === null || pick4.id === null || input.source === void 0 || input.source === DECISION_SOURCE) return null;
45034
+ const where = { id: pick4.id, scope, session_id: ctx.sessionId, worktree: ctx.project.worktree };
45035
+ const row5 = db.raw.prepare(SOURCE_IN_SCOPE).get(where);
45036
+ if (row5 === void 0) return null;
45037
+ const buf = Buffer.from(sourceText(db, pick4.id), "utf8");
45038
+ const total = buf.length;
45039
+ if (total === 0) return null;
45040
+ const name = isLongLabel(pick4.label) ? shownLabel(pick4.label, pick4.id) : JSON.stringify(pick4.label);
45041
+ let start = Math.min(input.offset ?? 0, total);
45042
+ while (start < total && (buf[start] & 192) === 128) start++;
45043
+ if (start >= total) return reply("No more text past offset " + start + " in source " + name + " (" + total + " B).", false);
45044
+ const note = nm.note === null ? "" : " " + nm.note;
45045
+ const headOf2 = (end2) => "Source " + name + " in order, bytes " + start + "-" + end2 + " of " + total + ":" + note;
45046
+ const moreOf = (end2) => "More: " + callText([""], scope, nm.arg, "offset:" + end2);
45047
+ let end = total;
45048
+ if (bytes2(headOf2(total)) + 1 + (total - start) > OUTPUT_CAP) {
45049
+ end = start + OUTPUT_CAP - bytes2(headOf2(total)) - 1 - bytes2(moreOf(total)) - 1;
45050
+ while (end > start && (buf[end] & 192) === 128) end--;
45051
+ const nl = buf.lastIndexOf(10, end - 1);
45052
+ if (nl >= start && nl + 1 > end - ORDERED_LINE_BACK) end = nl + 1;
45053
+ }
45054
+ const text = buf.subarray(start, end).toString("utf8");
45055
+ const key = end * 2 >= total ? betKeyOfLabel(pick4.label) : null;
45056
+ if (key !== null && !isLostBet(db, row5.session_id, key)) nm.lost = { sessionId: row5.session_id, key, source: sourceHandle(pick4.id) };
45057
+ return reply(headOf2(end) + "\n" + text + (end < total ? "\n" + moreOf(end) : ""), false);
45058
+ }
44900
45059
  function timelineLine(r) {
44901
45060
  const nl = r.text.indexOf("\n");
44902
45061
  const first = nl < 0 ? r.text : r.text.slice(0, nl);
@@ -44957,6 +45116,7 @@ async function handler(input, ctx) {
44957
45116
  }
44958
45117
  const scope = input.scope ?? "worktree";
44959
45118
  const db = await openDb(ctx.project, { readOnly: true });
45119
+ let lost = null;
44960
45120
  try {
44961
45121
  const given = input.source;
44962
45122
  const within = { scope, sessionId: ctx.sessionId, worktree: ctx.project.worktree };
@@ -44972,11 +45132,24 @@ async function handler(input, ctx) {
44972
45132
  nm.note = nm.note === null ? both : nm.note + "\n" + both;
44973
45133
  }
44974
45134
  const out = answer(db, input, scope, ctx, nm, ms, indexed, sort, pick4);
45135
+ lost = nm.lost;
44975
45136
  if (file2 === null || scope !== "session") return out;
44976
45137
  const call = callText(input.queries, "worktree", nm.arg, sort === "timeline" ? 'sort:"timeline"' : "");
44977
45138
  return reply(out.text + "\nMemory file " + file2.label + ' is in scope "worktree": ' + call + " searches it.", out.isError);
44978
45139
  } finally {
44979
45140
  closeDb(db);
45141
+ if (lost !== null) await recordLostBet(ctx, lost);
45142
+ }
45143
+ }
45144
+ async function recordLostBet(ctx, lost) {
45145
+ try {
45146
+ const w = await openDb(ctx.project);
45147
+ try {
45148
+ markLostBet(w, lost.sessionId, lost.key, "ordered-read", lost.source);
45149
+ } finally {
45150
+ closeDb(w);
45151
+ }
45152
+ } catch {
44980
45153
  }
44981
45154
  }
44982
45155
  var ctxSearch = Object.freeze({
@@ -49640,8 +49813,8 @@ var ENABLED_PROVIDERS = "enabledProviders";
49640
49813
  var DISABLED_PROVIDERS = "disabledProviders";
49641
49814
  var CLAUDE_PROVIDER = "claude";
49642
49815
  var ALL_PROVIDERS = ["*", "all"];
49643
- function ompImportFiles(home) {
49644
- const agentDir = join12(home, ...AGENT_HOME_DIR.omp, PI_AGENT_DIR);
49816
+ function ompImportFiles(env, home) {
49817
+ const agentDir = ompAgentDirOf(env, home);
49645
49818
  return { config: join12(agentDir, OMP_CONFIG_FILE), mcp: join12(agentDir, OMP_MCP_FILE), claude: join12(home, CLAUDE_USER_CONFIG_FILE) };
49646
49819
  }
49647
49820
  function readText2(file2) {
@@ -50024,7 +50197,7 @@ function checkHostConfig(row5, env, worktree) {
50024
50197
  if ("installs" in choice) return fail2("D3", D3_ROOT_DETAIL(choice.installs.map((r) => r.installPath)), D3_ROOT_FIX(choice.installs));
50025
50198
  }
50026
50199
  if (row5.id === "pi") return checkPiInstall(env, home, worktree);
50027
- if (row5.id === "omp") return checkOmpInstall(home);
50200
+ if (row5.id === "omp") return checkOmpInstall(env, home);
50028
50201
  const parts = [...mcpWrong(row5, home, env, worktree) ? [PART_MCP] : [], ...hookParts(row5, home, env, worktree)];
50029
50202
  if (parts.length === 0) return pass2("D3");
50030
50203
  const detail = D3_DETAIL(parts);
@@ -50036,7 +50209,6 @@ function checkPiInstall(env, home, worktree) {
50036
50209
  if (found !== void 0) return { ...pass2("D3"), detail: found };
50037
50210
  return fail2("D3", D3_DETAIL([PART_MCP]) + D4_REASON_JOIN + join13(piAgentDirOf(env, home), SETTINGS_FILE), NATIVE_INSTALL.pi[0]);
50038
50211
  }
50039
- var OMP_PLUGINS_DIR = "plugins";
50040
50212
  var OMP_LOCK_FILE = "omp-plugins.lock.json";
50041
50213
  function readJson2(file2) {
50042
50214
  try {
@@ -50050,8 +50222,8 @@ function ownEntry(doc, key) {
50050
50222
  const map2 = doc?.[key];
50051
50223
  return typeof map2 === "object" && map2 !== null ? map2[SERVER_KEY] : void 0;
50052
50224
  }
50053
- function checkOmpInstall(home) {
50054
- const dir = join13(home, ...AGENT_HOME_DIR.omp, OMP_PLUGINS_DIR);
50225
+ function checkOmpInstall(env, home) {
50226
+ const dir = ompPluginsDirOf(env, home);
50055
50227
  const lock = join13(dir, OMP_LOCK_FILE);
50056
50228
  const pkg = join13(dir, PI_PACKAGE_JSON_FILE);
50057
50229
  const entry = ownEntry(readJson2(lock), "plugins");
@@ -50067,12 +50239,26 @@ function ompInfoLines(env, version4) {
50067
50239
  out.push(OMP_CONTENT_INFO, OMP_PRINT_MODE_INFO, OMP_SCRIPTS_INFO);
50068
50240
  const home = homeDirOf(env);
50069
50241
  if (home === null) return out;
50070
- const files = ompImportFiles(home);
50242
+ const files = ompImportFiles(env, home);
50071
50243
  if (!ompImportsUs(files, env)) return out;
50072
50244
  const listed = readJson2(files.mcp)?.[OMP_DISABLED_SERVERS_KEY];
50073
50245
  if (!(Array.isArray(listed) && listed.includes(SERVER_KEY))) out.push(OMP_IMPORT_INFO(files.claude, files.mcp));
50074
50246
  return out;
50075
50247
  }
50248
+ function replaceTriggerInfoLines(agent, env, project) {
50249
+ const files = [];
50250
+ const home = homeDirOf(env);
50251
+ if (agent === "claude-code") {
50252
+ if (home !== null) files.push(join13(claudeDirOf(env, home), SETTINGS_FILE));
50253
+ if (project !== void 0 && project !== "") files.push(join13(project, HOST_CONFIG_DIR_NAME, SETTINGS_FILE));
50254
+ }
50255
+ const where = [...new Set(files)].filter((f) => {
50256
+ const block = readJson2(f)?.env;
50257
+ return typeof block === "object" && block !== null && REPLACE_TRIGGER_ENV in block;
50258
+ });
50259
+ if (where.length > 0) return [REPLACE_TRIGGER_RETIRED_INFO(where.join(" and "))];
50260
+ return env[REPLACE_TRIGGER_ENV] === void 0 ? [] : [REPLACE_TRIGGER_RETIRED_INFO("the process env")];
50261
+ }
50076
50262
  function checkV1Leftovers(agent, home, scope = {}) {
50077
50263
  const findings = detectV1(agent, home, scope);
50078
50264
  if (findings.length === 0) return pass2("D4");
@@ -53146,10 +53332,12 @@ async function doctorReply(ctx, host) {
53146
53332
  const look = rows.find((r) => r.status === "FAIL") ?? rows.find((r) => r.status !== "PASS");
53147
53333
  const docs = look === void 0 ? [] : [DOCTOR_DOCS_LABEL + DOCTOR_DOCS_LINK(look.id)];
53148
53334
  const info = adapter.id === "omp" ? ompInfoLines(host.env, ctx.clientInfo?.version) : [];
53335
+ const known = projectOrMissing(ctx);
53336
+ info.push(...replaceTriggerInfoLines(adapter.id, host.env, "missing" in known ? host.env.CLAUDE_PROJECT_DIR : known.project.worktree));
53149
53337
  const whole2 = [envLine2, table3, ...docs, ...info, ...notes].join("\n");
53150
53338
  const bytes5 = Buffer.byteLength(whole2, "utf8");
53151
53339
  if (bytes5 <= REPORT_CAP) return { text: whole2, isError: false, sandboxBytes: bytes5 };
53152
- const p = projectOrMissing(ctx);
53340
+ const p = known;
53153
53341
  if ("missing" in p) return { text: whole2, isError: false, sandboxBytes: bytes5 };
53154
53342
  const db = await openDb(p.project);
53155
53343
  try {
@@ -53300,11 +53488,11 @@ function schemaLine(issue4) {
53300
53488
  if (issue4.code === "unrecognized_keys") return new CtxError("UNKNOWN_FIELD", { f: issue4.keys[0] }).toLine();
53301
53489
  return issue4.message;
53302
53490
  }
53303
- function fileError(given, abs, root) {
53491
+ function fileError(given, abs, root, hostRoots) {
53304
53492
  let dir = abs;
53305
53493
  while (!existsSync19(dir) && dirname11(dir) !== dir) dir = dirname11(dir);
53306
- if (isInside(root, dir)) return null;
53307
- return new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine();
53494
+ if (allowedRootOf(root, hostRoots, dir) !== void 0) return null;
53495
+ return { ...fail4(new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine()), outsideRoot: true };
53308
53496
  }
53309
53497
  function takesDashC(language, runtime) {
53310
53498
  if (language === "shell") return true;
@@ -53367,8 +53555,8 @@ async function handler3(raw, ctx) {
53367
53555
  const extra = { ...PLAIN_OUTPUT_ENV2 };
53368
53556
  if (input.file !== void 0) {
53369
53557
  const abs = resolve8(cwd, input.file);
53370
- const bad = fileError(input.file, abs, ctx.project.containmentRoot);
53371
- if (bad !== null) return fail4(bad);
53558
+ const bad = fileError(input.file, abs, ctx.project.containmentRoot, ctx.hostRoots);
53559
+ if (bad !== null) return bad;
53372
53560
  extra.CTX_FILE = abs;
53373
53561
  }
53374
53562
  let runtime;
@@ -57685,18 +57873,19 @@ function readUtf8(absPath) {
57685
57873
  return void 0;
57686
57874
  }
57687
57875
  }
57688
- function missingOrOutside(given, abs, root) {
57876
+ function missingOrOutside(given, abs, root, hostRoots) {
57689
57877
  let dir = abs;
57690
57878
  while (!existsSync20(dir) && dirname12(dir) !== dir) dir = dirname12(dir);
57691
- if (dir !== abs && isInside(root, dir)) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
57879
+ if (dir !== abs && allowedRootOf(root, hostRoots, dir) !== void 0) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
57692
57880
  return new CtxError("OUTSIDE_ROOT", { p: given, root });
57693
57881
  }
57694
- function pathItems(input, project) {
57882
+ function pathItems(input, project, hostRoots) {
57695
57883
  const abs = resolve9(project.worktree, input.path);
57696
- if (!isInside(project.containmentRoot, abs)) throw missingOrOutside(input.path, abs, project.containmentRoot);
57884
+ const allowed = allowedRootOf(project.containmentRoot, hostRoots, abs);
57885
+ if (allowed === void 0) throw missingOrOutside(input.path, abs, project.containmentRoot, hostRoots);
57697
57886
  const base = relative3(project.worktree, abs);
57698
57887
  if (statSync8(abs).isDirectory()) {
57699
- return walkDir(abs, project.containmentRoot).map((f) => ({
57888
+ return walkDir(abs, allowed).map((f) => ({
57700
57889
  sourceKind: "path",
57701
57890
  label: pathLabel(join22(base, f.relPath)),
57702
57891
  kind: kindOfPath(f.relPath),
@@ -57713,7 +57902,7 @@ async function itemsOf(input, ctx) {
57713
57902
  return { items: [{ sourceKind: "content", label: label3, kind, read: () => text2 }], from: label3 };
57714
57903
  }
57715
57904
  if (input.path !== void 0) {
57716
- const items = pathItems({ ...input, path: input.path }, ctx.project);
57905
+ const items = pathItems({ ...input, path: input.path }, ctx.project, ctx.hostRoots);
57717
57906
  return { items, from: items.length === 1 ? items[0].label : pathLabel(input.path) };
57718
57907
  }
57719
57908
  const res = await safeFetch(input.url ?? "", AbortSignal.any([ctx.signal, AbortSignal.timeout(EXEC_TIMEOUT_MS)]));
@@ -57780,7 +57969,7 @@ async function handler4(input, ctx) {
57780
57969
  journal: { kind: "index", key: from, path: from, exit_code: null }
57781
57970
  };
57782
57971
  } catch (err) {
57783
- if (err instanceof CtxError) return { text: err.toLine(), isError: true, sandboxBytes: 0 };
57972
+ if (err instanceof CtxError) return { text: err.toLine(), isError: true, sandboxBytes: 0, ...err.code === "OUTSIDE_ROOT" ? { outsideRoot: true } : {} };
57784
57973
  throw err;
57785
57974
  }
57786
57975
  }
@@ -58673,7 +58862,7 @@ function ownEntries2(agent, env) {
58673
58862
  }
58674
58863
  if (agent === "omp") {
58675
58864
  return [{
58676
- file: ompImportFiles(home).mcp,
58865
+ file: ompImportFiles(env, home).mcp,
58677
58866
  key: OMP_DISABLED_SERVERS_KEY,
58678
58867
  shown: OMP_DISABLED_SERVERS_KEY,
58679
58868
  has: (v) => Array.isArray(v) && v.includes(SERVER_KEY),
@@ -59055,6 +59244,38 @@ function workspaceFromMeta(meta3) {
59055
59244
  return void 0;
59056
59245
  }
59057
59246
  }
59247
+ var HOST_ROOTS_INPUT_KEY = "roots";
59248
+ var WRITE_ACCESS = "write";
59249
+ function grantedFromMeta(meta3) {
59250
+ const state = meta3?.[CODEX_SANDBOX_STATE_META];
59251
+ const profile = typeof state === "object" && state !== null ? state.permissionProfile : void 0;
59252
+ const fs2 = typeof profile === "object" && profile !== null ? profile.file_system : void 0;
59253
+ const entries = typeof fs2 === "object" && fs2 !== null ? fs2.entries : void 0;
59254
+ if (!Array.isArray(entries)) return [];
59255
+ const out = [];
59256
+ for (const e of entries) {
59257
+ const path8 = e?.path;
59258
+ if (e?.access === WRITE_ACCESS && path8?.type === "path" && typeof path8.path === "string" && path8.path !== "") out.push(path8.path);
59259
+ }
59260
+ return out;
59261
+ }
59262
+ function grantedFromInput(responses) {
59263
+ const view = inputResponse(responses, HOST_ROOTS_INPUT_KEY);
59264
+ if (view.kind !== "roots") return void 0;
59265
+ const out = [];
59266
+ for (const root of view.roots) {
59267
+ if (!root.uri.startsWith(FILE_URL_PREFIX2)) continue;
59268
+ try {
59269
+ out.push(fileURLToPath3(root.uri));
59270
+ } catch {
59271
+ }
59272
+ }
59273
+ return out;
59274
+ }
59275
+ function listsRoots(envelope) {
59276
+ const caps = envelope?.[CLIENT_CAPABILITIES_META_KEY];
59277
+ return typeof caps === "object" && caps !== null && caps.roots !== void 0;
59278
+ }
59058
59279
  function realOrSame(p) {
59059
59280
  try {
59060
59281
  return realpathSync12.native(p);
@@ -59142,6 +59363,8 @@ async function startServer(argv, env) {
59142
59363
  const agent = resolveAgent(argv, env);
59143
59364
  const fromRoots = agent === "vscode" && !hasWorkspaceFolder(argv) ? await workspaceFromRoots(server) : void 0;
59144
59365
  const callArgv = fromRoots === void 0 ? argv : [...argv, WORKSPACE_FOLDER_FLAG, fromRoots];
59366
+ const fromInput = grantedFromInput(req.mcpReq.inputResponses);
59367
+ const hostRoots = [...grantedFromMeta(meta3), ...fromInput ?? []];
59145
59368
  let project;
59146
59369
  const projectOf = () => {
59147
59370
  if (agent === void 0) throw new CtxError("NO_PROJECT", { kind: "--agent" });
@@ -59154,6 +59377,8 @@ async function startServer(argv, env) {
59154
59377
  },
59155
59378
  ...agent === void 0 ? {} : { agent },
59156
59379
  // D-1410-DOCTOR-NO-PROJECT-1
59380
+ ...hostRoots.length === 0 ? {} : { hostRoots },
59381
+ // D-1398-HOST-ROOTS-1
59157
59382
  sessionId: sessionIdOf(meta3, agent, env, serverId),
59158
59383
  turn: metaNumber(meta3, "turn") ?? 0,
59159
59384
  signal: req.mcpReq.signal,
@@ -59171,6 +59396,9 @@ async function startServer(argv, env) {
59171
59396
  reply4 = errorReply(err);
59172
59397
  }
59173
59398
  }
59399
+ if (reply4.outsideRoot === true && fromInput === void 0 && listsRoots(req.mcpReq.envelope)) {
59400
+ return inputRequired({ inputRequests: { [HOST_ROOTS_INPUT_KEY]: inputRequired.listRoots() } });
59401
+ }
59174
59402
  if (stopRequested()) {
59175
59403
  setTimeout(stopSelf, UPGRADE_STOP_DELAY_MS);
59176
59404
  return { content: [{ type: "text", text: reply4.text }], isError: reply4.isError };