context-mode 2.2.1 → 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,16 +28088,11 @@ 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"]);
28095
+ var SKILL_LOAD_TOOLS = Object.freeze(["Skill"]);
28078
28096
  var MAX_CHUNK_BYTES = 4096;
28079
28097
  var SEARCH_PAGE_SIZE = 20;
28080
28098
  var MEMORY_LABEL_PREFIX = "memory ";
@@ -28242,7 +28260,7 @@ var TOOLS_TTL_MS = 36e5;
28242
28260
  var IN_PROCESS_TIMEOUT_MS = 0;
28243
28261
  var MS_PER_DAY = 864e5;
28244
28262
  var PROJECT_KEY_HEX_LEN = 16;
28245
- var SCHEMA_VERSION = 6;
28263
+ var SCHEMA_VERSION = 7;
28246
28264
  var RETENTION_IDLE_DAYS = 30;
28247
28265
  var RETENTION_SIZE_CAP_BYTES = 524288e3;
28248
28266
  var PROJECT_DEAD_IDLE_DAYS = 14;
@@ -28268,6 +28286,7 @@ var PLAIN_OUTPUT_ENV = Object.freeze({ NO_COLOR: "1", FORCE_COLOR: "0" });
28268
28286
  var RUN_LABEL_PREFIX = "run.mjs:";
28269
28287
  var RUN_SESSION_PREFIX = "mcp:";
28270
28288
  var HOST_SESSION_ENV = Object.freeze({ "claude-code": "CLAUDE_CODE_SESSION_ID" });
28289
+ var HOST_SESSION_META = Object.freeze({ zcode: "session_id" });
28271
28290
  var NODE_MIN = "24.15.0";
28272
28291
  var DATA_ROOT = "~/.context-mode";
28273
28292
  var DATA_DIR_ENV = "CONTEXT_MODE_DATA_DIR";
@@ -28283,6 +28302,7 @@ var SETTINGS_LOCAL_FILE = "settings.local.json";
28283
28302
  var DEFAULT_PLUGIN_SCOPE = "user";
28284
28303
  var PROJECT_PLUGIN_SCOPES = Object.freeze(["local", "project"]);
28285
28304
  var PLUGIN_SCOPE_RANK = Object.freeze({ local: 0, project: 1, user: 2, managed: 2 });
28305
+ var MCP_SERVER_TOOL_PREFIX = "mcp__";
28286
28306
  var MCP_HINT_EVERY_DEFAULT = 10;
28287
28307
  function readHintEvery(raw) {
28288
28308
  if (raw === void 0 || raw.trim() === "") return MCP_HINT_EVERY_DEFAULT;
@@ -28370,8 +28390,10 @@ var OWN_TOOL_PREFIX = "ctx_";
28370
28390
  var EDIT_TOOLS = Object.freeze(["Write", "Edit"]);
28371
28391
  var EDIT_PATH_KEYS = Object.freeze(["file_path", "path"]);
28372
28392
  var RECALL_MIN_SCORE = 5;
28393
+ var LOSTBET_META_PREFIX = "lostbet:";
28373
28394
  var RECALL_QUERY_MAX_TERMS = 64;
28374
28395
  var RECALL_UNIT_CANDIDATES = 64;
28396
+ var SUBAGENT_SOURCE_PREFIX = "subagent:";
28375
28397
  var AGENT_ARG = "--agent";
28376
28398
  var DECAY_SCALE = 1e3;
28377
28399
  var PERCENT_SCALE = 100;
@@ -28451,7 +28473,7 @@ function PURGE_SUMMARY(rows, scope) {
28451
28473
  var DECISION_SOURCE = "decision";
28452
28474
  var DECISION_USER_LABEL = "decision (user)";
28453
28475
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
28454
- var BUNDLE_SHA = true ? "1fce537096e8e2b7d1924c2b5ff2b83287f157ee" : void 0;
28476
+ var BUNDLE_SHA = true ? "f41c429ae530a3fec5bda3c12a8ecdc2a5f14ada" : void 0;
28455
28477
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
28456
28478
  var DOCTOR_LABEL = Object.freeze({
28457
28479
  D1: "version",
@@ -28562,6 +28584,10 @@ function D7_DETAIL(got) {
28562
28584
  return `resolved project source ${got} does not match the host's actual cwd`;
28563
28585
  }
28564
28586
  var D7_FIX = "restart the agent in the correct directory";
28587
+ function D7_NO_PROJECT_DETAIL(kind) {
28588
+ return `Project source ${kind} is missing`;
28589
+ }
28590
+ var DOCTOR_NEEDS_PROJECT_DETAIL = "runs once the project resolves; D7 names the project source";
28565
28591
  function D8_STALE_SCHEMA_DETAIL(got, want) {
28566
28592
  return `stale schema (v${got}, expected v${want})`;
28567
28593
  }
@@ -28886,6 +28912,7 @@ var OMP_CONTENT_INFO = "OMP keeps tool output in content; context-mode writes it
28886
28912
  var OMP_PRINT_MODE_INFO = "Print mode sends no prompt event. Use omp or omp --mode rpc to keep prompts.";
28887
28913
  var OMP_SCRIPTS_INFO = "Add < /dev/null in scripts.";
28888
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}.`;
28889
28916
  var PI_CURRENT_MAJOR = 2;
28890
28917
  var V1_OPENCODE_PLUGIN_SPEC = "context-mode";
28891
28918
  var V1_TMP_PREFIX = "context-mode-";
@@ -28905,6 +28932,10 @@ var OPENCODE_CONFIG_DIR_ENV = "OPENCODE_CONFIG_DIR";
28905
28932
  var APPDATA_ENV = "APPDATA";
28906
28933
  var VSCODE_USER_DIR_SEGMENTS = Object.freeze(["Code", "User"]);
28907
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";
28908
28939
  var CONFIG_TOML_FILE = "config.toml";
28909
28940
  var CONFIG_JSON_FILE = "config.json";
28910
28941
  var ZCODE_CLI_DIR = "cli";
@@ -29122,7 +29153,8 @@ var ERROR_TEXT = Object.freeze({
29122
29153
  NO_RUNTIME: "No <lang> runtime on PATH. Fix: install it or pick another language.",
29123
29154
  FETCH_FAILED: "Fetch failed: <code>. Fix: check the URL or proxy.",
29124
29155
  SSRF: "Blocked private address <host>. Fix: use a public URL.",
29125
- 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
29126
29158
  INVALID_ARGS: "Invalid argument <field>. Fix: <action>.",
29127
29159
  ONE_OF_INPUT: "Pass exactly one of <names>. Fix: drop the extra field.",
29128
29160
  SPAWN_FAILED: "Failed to start the process: <detail>. Fix: check the command and PATH.",
@@ -29281,13 +29313,22 @@ CREATE VIRTUAL TABLE line_units USING fts5(
29281
29313
  var DDL_V6 = `
29282
29314
  UPDATE sources SET label = replace(label, char(92), '/') WHERE kind = 'path' AND instr(label, char(92)) > 0;
29283
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
+ `;
29284
29324
  var MIGRATIONS = [
29285
29325
  { version: 1, sql: DDL },
29286
29326
  { version: 2, sql: DDL_V2 },
29287
29327
  { version: 3, sql: DDL_V3 },
29288
29328
  { version: 4, sql: DDL_V4 },
29289
29329
  { version: 5, sql: DDL_V5 },
29290
- { version: 6, sql: DDL_V6 }
29330
+ { version: 6, sql: DDL_V6 },
29331
+ { version: 7, sql: DDL_V7 }
29291
29332
  ];
29292
29333
  function applyMigrations(db, fromVersion) {
29293
29334
  if (fromVersion === SCHEMA_VERSION2) return;
@@ -29468,15 +29509,27 @@ function closeDb(db) {
29468
29509
  } catch {
29469
29510
  }
29470
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
+ }
29471
29524
 
29472
29525
  // src/core/journal/append.ts
29473
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
29474
29527
  var INSERT_SQL = "INSERT INTO " + COLUMNS;
29475
29528
  var INSERT_COST_SQL = "INSERT OR IGNORE INTO " + COLUMNS;
29476
29529
  var COST_SEQ_SQL = "SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";
29477
- function appendEvent(db, row5) {
29530
+ function appendEvent(db, row5, at) {
29478
29531
  return withWrite(db, (h) => {
29479
- const now = Date.now();
29532
+ const now = at ?? Date.now();
29480
29533
  const isCost = row5.kind === "cost";
29481
29534
  const res = h.raw.prepare(isCost ? INSERT_COST_SQL : INSERT_SQL).run(
29482
29535
  row5.session_id,
@@ -29689,6 +29742,24 @@ function piAgentDirOf(env, home) {
29689
29742
  const dir = env[PI_AGENT_DIR_ENV];
29690
29743
  return dir !== void 0 && dir !== "" ? dir : join(home, ...AGENT_HOME_DIR.pi, PI_AGENT_DIR);
29691
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
+ }
29692
29763
  function vscodeUserDirOf(env, home, platform = process.platform) {
29693
29764
  const set3 = (v) => v !== void 0 && v !== "";
29694
29765
  const p = platform === "win32" ? win32 : posix;
@@ -29717,7 +29788,7 @@ function resolveConfigDir(env) {
29717
29788
  }
29718
29789
 
29719
29790
  // src/core/project/resolve.ts
29720
- import { basename as basename2, dirname as dirname3, join as join3, resolve as resolve3 } from "node:path";
29791
+ import { basename as basename2, dirname as dirname3, isAbsolute as isAbsolute2, join as join3, resolve as resolve3 } from "node:path";
29721
29792
 
29722
29793
  // src/core/project/contain.ts
29723
29794
  import { dirname as dirname2, isAbsolute, join as join2, relative, resolve as resolve2, sep } from "node:path";
@@ -29744,6 +29815,10 @@ function isInside(root, p) {
29744
29815
  }
29745
29816
  return true;
29746
29817
  }
29818
+ function allowedRootOf(containmentRoot, hostRoots, p) {
29819
+ if (isInside(containmentRoot, p)) return containmentRoot;
29820
+ return hostRoots?.find((r) => isInside(r, p));
29821
+ }
29747
29822
  function commonRoot(paths) {
29748
29823
  const reals = paths.map(real).filter((r) => r !== void 0);
29749
29824
  if (reals.length === 0) throw new RangeError("commonRoot needs at least one existing path");
@@ -29929,12 +30004,7 @@ function dirOf(kind, src) {
29929
30004
  }
29930
30005
  }
29931
30006
  function gitDirs(dir) {
29932
- let cur;
29933
- try {
29934
- cur = realpathSync3.native(dir);
29935
- } catch {
29936
- throw new CtxError("NO_GIT_DIR", { path: dir });
29937
- }
30007
+ let cur = nearestRealDir(dir);
29938
30008
  const start = cur;
29939
30009
  for (; ; ) {
29940
30010
  const gitDir = gitDirAt(join3(cur, GIT_DIR_NAME));
@@ -29947,6 +30017,18 @@ function gitDirs(dir) {
29947
30017
  cur = up;
29948
30018
  }
29949
30019
  }
30020
+ function nearestRealDir(dir) {
30021
+ const walk2 = isAbsolute2(dir);
30022
+ for (let d = walk2 ? resolve3(dir) : dir; ; ) {
30023
+ try {
30024
+ return realpathSync3.native(d);
30025
+ } catch {
30026
+ const up = dirname3(d);
30027
+ if (!walk2 || up === d) throw new CtxError("NO_GIT_DIR", { path: dir });
30028
+ d = up;
30029
+ }
30030
+ }
30031
+ }
29950
30032
  function gitDirAt(dotGit) {
29951
30033
  let gitDir;
29952
30034
  try {
@@ -30009,7 +30091,7 @@ function resolveProject(agent, src) {
30009
30091
  },
30010
30092
  worktree,
30011
30093
  get containmentRoot() {
30012
- root ??= plain ?? containmentRootOf(dir, commonDir);
30094
+ root ??= plain ?? containmentRootOf(worktree, commonDir);
30013
30095
  return root;
30014
30096
  },
30015
30097
  agent,
@@ -32046,11 +32128,13 @@ function deleteChunkRows(raw, scope) {
32046
32128
  if (scope === "all") {
32047
32129
  raw.exec("INSERT INTO chunks_tri(chunks_tri) VALUES ('delete-all')");
32048
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");
32049
32132
  return Number(raw.prepare("DELETE FROM chunks").run().changes);
32050
32133
  }
32051
- 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 = ?"];
32052
32135
  raw.prepare(TRI_DELETE + " WHERE " + where).run(arg);
32053
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);
32054
32138
  return Number(raw.prepare("DELETE FROM chunks WHERE " + where).run(arg).changes);
32055
32139
  }
32056
32140
  function toMatch(q) {
@@ -32454,43 +32538,53 @@ function parseSourceHandle(s) {
32454
32538
  function pathLabel(p) {
32455
32539
  return p.includes("\\") ? p.split("\\").join("/") : p;
32456
32540
  }
32457
- function labelStored(db, label2) {
32458
- return stmt(db.raw, "SELECT 1 AS x FROM sources WHERE label = ? LIMIT 1").get(label2) !== void 0;
32541
+ var EVERY_ROW = { scope: "project", sessionId: "", worktree: "" };
32542
+ var IN_SCOPE = "(:scope <> 'session' OR session_id = :session_id) AND (:scope <> 'worktree' OR worktree = :worktree)";
32543
+ var scopeArgs = (w) => ({ scope: w.scope, session_id: w.sessionId, worktree: w.worktree });
32544
+ function labelStored(db, label2, w) {
32545
+ return stmt(db.raw, "SELECT 1 AS x FROM sources WHERE label = :label AND " + IN_SCOPE + " LIMIT 1").get({ label: label2, ...scopeArgs(w) }) !== void 0;
32459
32546
  }
32460
- function storedLabel(db, source) {
32461
- if (labelStored(db, source)) return source;
32547
+ function storedLabel(db, source, w = EVERY_ROW) {
32548
+ if (labelStored(db, source, w)) return source;
32462
32549
  const canon = pathLabel(source);
32463
- return canon !== source && labelStored(db, canon) ? canon : source;
32550
+ return canon !== source && labelStored(db, canon, w) ? canon : source;
32464
32551
  }
32465
- function newestId(db, label2) {
32466
- const row5 = stmt(db.raw, "SELECT id FROM sources WHERE label = ? ORDER BY id DESC LIMIT 1").get(label2);
32552
+ function newestId(db, label2, w) {
32553
+ const row5 = stmt(db.raw, "SELECT id FROM sources WHERE label = :label AND " + IN_SCOPE + " ORDER BY id DESC LIMIT 1").get({ label: label2, ...scopeArgs(w) });
32467
32554
  return row5 === void 0 ? null : Number(row5.id);
32468
32555
  }
32469
- function labelOfId(db, id) {
32470
- const row5 = stmt(db.raw, "SELECT label FROM sources WHERE id = ?").get(id);
32556
+ function labelOfId(db, id, w) {
32557
+ const row5 = stmt(db.raw, "SELECT label FROM sources WHERE id = :id AND " + IN_SCOPE).get({ id, ...scopeArgs(w) });
32471
32558
  return row5 === void 0 ? null : row5.label;
32472
32559
  }
32473
- function pickSource(db, source, suffix = true) {
32474
- const named2 = storedLabel(db, source);
32560
+ function pickIn(db, source, suffix, w) {
32561
+ const named2 = storedLabel(db, source, w);
32475
32562
  const id = parseSourceHandle(source);
32476
- const own4 = newestId(db, named2);
32563
+ const own4 = newestId(db, named2, w);
32477
32564
  if (own4 !== null) {
32478
- const otherLabel = id === null || id === own4 ? null : labelOfId(db, id);
32565
+ const otherLabel = id === null || id === own4 ? null : labelOfId(db, id, EVERY_ROW);
32479
32566
  return { label: named2, id: own4, via: "label", other: otherLabel === null || otherLabel === named2 ? null : { id, label: otherLabel } };
32480
32567
  }
32481
32568
  if (id !== null) {
32482
- const label2 = labelOfId(db, id);
32569
+ const label2 = labelOfId(db, id, w);
32483
32570
  if (label2 !== null) return { label: label2, id, via: "handle", other: null };
32484
32571
  }
32485
32572
  if (suffix) {
32486
32573
  const prefix = named2 + LABEL_SUFFIX_SEP;
32487
- const rows = stmt(db.raw, "SELECT id, label FROM sources WHERE substr(label, 1, ?) = ? ORDER BY id DESC").all(prefix.length, prefix);
32574
+ const rows = stmt(db.raw, "SELECT id, label FROM sources WHERE substr(label, 1, :n) = :prefix AND " + IN_SCOPE + " ORDER BY id DESC").all({ n: prefix.length, prefix, ...scopeArgs(w) });
32488
32575
  for (const r of rows) {
32489
32576
  if (r.label.lastIndexOf(LABEL_SUFFIX_SEP) === named2.length) return { label: r.label, id: Number(r.id), via: "suffix", other: null };
32490
32577
  }
32491
32578
  }
32492
32579
  return { label: source, id: null, via: "none", other: null };
32493
32580
  }
32581
+ function pickSource(db, source, suffix = true, w = EVERY_ROW) {
32582
+ if (w.scope !== "project") {
32583
+ const here = pickIn(db, source, suffix, w);
32584
+ if (here.via !== "none") return here;
32585
+ }
32586
+ return pickIn(db, source, suffix, EVERY_ROW);
32587
+ }
32494
32588
  function collisionLine(value, pick4) {
32495
32589
  if (pick4.other === null || pick4.id === null) return null;
32496
32590
  return "Source " + JSON.stringify(value) + ": used the label " + shownLabel(pick4.label, null) + " (" + sourceHandle(pick4.id) + "); handle " + sourceHandle(pick4.other.id) + " is " + shownLabel(pick4.other.label, null) + (isLongLabel(pick4.other.label) ? ", search it by its full label." : ", search it with source:" + JSON.stringify(pick4.other.label) + ".");
@@ -32568,9 +32662,15 @@ function recallQueryText(prompt) {
32568
32662
  function queryUnits(db, sessionId, q, limit, maxSourceId = Number.MAX_SAFE_INTEGER) {
32569
32663
  const match = searchTerms(q).join(" OR ");
32570
32664
  if (match === "" || sessionId === "") return [];
32571
- const rows = db.raw.prepare(
32572
- "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 ?"
32573
- ).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);
32574
32674
  return rows.map((r) => ({ sourceId: Number(r.source_id), ord: Number(r.ord), label: r.label, body: r.body, score: r.score }));
32575
32675
  }
32576
32676
 
@@ -43864,7 +43964,7 @@ var TOOL_DESCRIPTIONS = Object.freeze({
43864
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.',
43865
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.',
43866
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.',
43867
- 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.',
43868
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.",
43869
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.",
43870
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",
@@ -44493,6 +44593,31 @@ function runProcess(argv, o) {
44493
44593
  });
44494
44594
  }
44495
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
+
44496
44621
  // src/core/index/auto-memory.ts
44497
44622
  import { readdirSync as readdirSync4, readFileSync as readFileSync4, statSync as statSync4 } from "node:fs";
44498
44623
  import { join as join6 } from "node:path";
@@ -44647,10 +44772,11 @@ function sourceCount(db, scope, ctx, source) {
44647
44772
  function zeroHits(db, scope, ctx, source, mem, nm, queries, offset = 0) {
44648
44773
  const inScope = sourceCount(db, scope, ctx, source);
44649
44774
  const n = inScope + mem.rows.length;
44650
- if (offset > 0) return reply("No more hits past offset " + offset + ' in scope "' + scope + '" across ' + n + " source(s).", false);
44651
44775
  const head = 'No hits in scope "' + scope + '" across ' + n + " source(s).";
44652
44776
  const pick4 = nm.pick;
44653
- if (pick4 === null || mem.named || inScope > 0) return reply(head, false);
44777
+ if (pick4 === null || mem.named || inScope > 0) {
44778
+ return reply(offset > 0 ? "No more hits past offset " + offset + ' in scope "' + scope + '" across ' + n + " source(s)." : head, false);
44779
+ }
44654
44780
  if (pick4.id !== null) {
44655
44781
  const wider = scope === "session" && sourceCount(db, "worktree", ctx, source) > 0 ? "worktree" : "project";
44656
44782
  return reply(head + "\nSource " + JSON.stringify(nm.arg) + ' is stored in scope "' + wider + '": ' + callText(queries, wider, nm.arg, "") + " searches it.", false);
@@ -44677,9 +44803,9 @@ function unknownSource(db, scope, ctx, given) {
44677
44803
  return line + "\nStored sources, newest first: " + names.join(", ") + more + ". " + callText([], scope, void 0, 'sort:"timeline"') + " lists them all.";
44678
44804
  }
44679
44805
  function named(given, pick4) {
44680
- 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 };
44681
44807
  const arg = pick4.id !== null && isLongLabel(given) ? sourceHandle(pick4.id) : given;
44682
- return { arg, note: collisionLine(given, pick4), pick: pick4 };
44808
+ return { arg, note: collisionLine(given, pick4), pick: pick4, lost: null };
44683
44809
  }
44684
44810
  function sourceCard(db, id, input, scope, arg) {
44685
44811
  const row5 = sourceCardRow(db, id);
@@ -44703,7 +44829,7 @@ function decisionQueries(input) {
44703
44829
  function pageSize(input) {
44704
44830
  return input.source === DECISION_SOURCE ? SEARCH_PAGE_SIZE : SEARCH_REPLY_HITS;
44705
44831
  }
44706
- 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 }) {
44707
44833
  const size = pageSize(input) + extra;
44708
44834
  if (input.source === DECISION_SOURCE && q.trim() === "") {
44709
44835
  return ftsListSource(db, DECISION_SOURCE, scope, ctx.project, ctx.sessionId, size, offset);
@@ -44712,6 +44838,8 @@ function page(db, q, input, scope, ctx, offset, extra = 0) {
44712
44838
  if (hits.length > 0 || input.source === void 0) return hits;
44713
44839
  const any3 = offset === 0 ? hits : ftsQuery(db, q, scope, ctx.project, ctx.sessionId, 1, 0, input.source);
44714
44840
  if (any3.length > 0) return hits;
44841
+ h9.n++;
44842
+ if (!h9.list) return [];
44715
44843
  return ftsListSource(db, input.source, scope, ctx.project, ctx.sessionId, size, offset);
44716
44844
  }
44717
44845
  var JSON_ROWS_PAGE = 5;
@@ -44800,15 +44928,27 @@ function relevance(db, given, scope, ctx, nm, ms, indexed) {
44800
44928
  const size = pageSize(input);
44801
44929
  const mem = ms.named || offset === 0 ? memoryChunks(ms.rows) : [];
44802
44930
  const count2 = (hits, n) => ms.named ? Math.min(n, hits.length) : contentIn(hits, n);
44803
- const fetched = input.queries.map((q) => {
44931
+ const h9 = { n: 0, list: false };
44932
+ const listed = [];
44933
+ const fetched = input.queries.map((q, qi) => {
44804
44934
  if (ms.named) {
44805
44935
  const want = offset + size + 1;
44806
44936
  const content2 = indexed ? ftsQuery(db, q, scope, ctx.project, ctx.sessionId, want, 0, input.source) : [];
44807
44937
  return mergeMemory(content2, memoryHits(mem, q, want)).slice(offset, want);
44808
44938
  }
44809
- 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);
44810
44942
  return mem.length === 0 ? content : mergeMemory(content, memoryHits(mem, q, MEMORY_HITS));
44811
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
+ }
44812
44952
  const take = fetched.map((h) => replyHits(h, size));
44813
44953
  const pages = fetched.map((h, i) => h.slice(0, take[i]));
44814
44954
  if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source, ms, nm, input.queries, offset);
@@ -44873,6 +45013,49 @@ function relevance(db, given, scope, ctx, nm, ms, indexed) {
44873
45013
  for (const [pos, qs] of byPos) moreLines.push("More: " + callText(qs, scope, nm.arg, "offset:" + pos));
44874
45014
  return reply(lines.concat(moreLines).join("\n"), false);
44875
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
+ }
44876
45059
  function timelineLine(r) {
44877
45060
  const nl = r.text.indexOf("\n");
44878
45061
  const first = nl < 0 ? r.text : r.text.slice(0, nl);
@@ -44933,9 +45116,11 @@ async function handler(input, ctx) {
44933
45116
  }
44934
45117
  const scope = input.scope ?? "worktree";
44935
45118
  const db = await openDb(ctx.project, { readOnly: true });
45119
+ let lost = null;
44936
45120
  try {
44937
45121
  const given = input.source;
44938
- const pick4 = given !== void 0 && given !== DECISION_SOURCE ? pickSource(db, given) : null;
45122
+ const within = { scope, sessionId: ctx.sessionId, worktree: ctx.project.worktree };
45123
+ const pick4 = given !== void 0 && given !== DECISION_SOURCE ? pickSource(db, given, true, within) : null;
44939
45124
  if (pick4 !== null) input = { ...input, source: pick4.label };
44940
45125
  const nm = named(given, pick4);
44941
45126
  const indexed = pick4 !== null && pick4.id !== null;
@@ -44947,11 +45132,24 @@ async function handler(input, ctx) {
44947
45132
  nm.note = nm.note === null ? both : nm.note + "\n" + both;
44948
45133
  }
44949
45134
  const out = answer(db, input, scope, ctx, nm, ms, indexed, sort, pick4);
45135
+ lost = nm.lost;
44950
45136
  if (file2 === null || scope !== "session") return out;
44951
45137
  const call = callText(input.queries, "worktree", nm.arg, sort === "timeline" ? 'sort:"timeline"' : "");
44952
45138
  return reply(out.text + "\nMemory file " + file2.label + ' is in scope "worktree": ' + call + " searches it.", out.isError);
44953
45139
  } finally {
44954
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 {
44955
45153
  }
44956
45154
  }
44957
45155
  var ctxSearch = Object.freeze({
@@ -45193,6 +45391,7 @@ var SHELL_TOOL_NAMES = Object.freeze(["Bash", "PowerShell"]);
45193
45391
  var POWERSHELL_TOOL = "PowerShell";
45194
45392
  var SHELL_CANONICAL = "Bash";
45195
45393
  var CLAUDE_SHAPE_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse"];
45394
+ var FAILURE_EVENT = "PostToolUseFailure";
45196
45395
  var MCP_PREFIX = "mcp__";
45197
45396
  var MCP_SEP = "__";
45198
45397
  var CLAUDE_SOURCES = { startup: "startup", resume: "resume", clear: "clear", compact: "compact" };
@@ -45366,7 +45565,14 @@ function requireFields(raw) {
45366
45565
  }
45367
45566
  function decode3(raw) {
45368
45567
  requireFields(raw);
45369
- const ev = decodeClaudeShape(raw, "claude-code", TOOL_NAME_PREFIX, CLAUDE_SOURCES);
45568
+ const failure3 = typeof raw === "object" && raw !== null && !Array.isArray(raw) && raw.hook_event_name === FAILURE_EVENT;
45569
+ const payload = failure3 ? { ...raw, hook_event_name: "PostToolUse" } : raw;
45570
+ const ev = decodeClaudeShape(payload, "claude-code", TOOL_NAME_PREFIX, CLAUDE_SOURCES);
45571
+ if (failure3) {
45572
+ const error42 = raw.error;
45573
+ const text = typeof error42 === "string" ? error42 : error42 === void 0 ? "" : JSON.stringify(error42);
45574
+ ev.result = { isError: true, bytes: Buffer.byteLength(text), text, keep: true };
45575
+ }
45370
45576
  if (ev.tool !== void 0 && ev.tool.name === POWERSHELL_TOOL) ev.tool.canonicalName = SHELL_CANONICAL;
45371
45577
  if (ev.cwd === "") ev.cwd = process.env.CLAUDE_PROJECT_DIR || process.cwd();
45372
45578
  if (ev.event === "PostToolUse" && ev.tool !== void 0 && ev.tool.callId === void 0) {
@@ -45545,9 +45751,9 @@ var NATIVE_TO_CANONICAL2 = {
45545
45751
  grep_search: "Grep",
45546
45752
  web_fetch: "WebFetch"
45547
45753
  };
45548
- var FAILURE_EVENT = "PostToolUseFailure";
45754
+ var FAILURE_EVENT2 = "PostToolUseFailure";
45549
45755
  function decode6(raw) {
45550
- const failure3 = typeof raw === "object" && raw !== null && !Array.isArray(raw) && raw.hook_event_name === FAILURE_EVENT;
45756
+ const failure3 = typeof raw === "object" && raw !== null && !Array.isArray(raw) && raw.hook_event_name === FAILURE_EVENT2;
45551
45757
  const payload = failure3 ? { ...raw, hook_event_name: "PostToolUse" } : raw;
45552
45758
  const ev = decodeClaudeShape(payload, "qwen", TOOL_NAME_PREFIX4, QWEN_SOURCES);
45553
45759
  if (ev.tool !== void 0 && Object.hasOwn(NATIVE_TO_CANONICAL2, ev.tool.name)) ev.tool.canonicalName = NATIVE_TO_CANONICAL2[ev.tool.name];
@@ -45867,12 +46073,12 @@ var TOOL_NAME_PREFIX8 = "mcp__context-mode__";
45867
46073
  var PLUGIN_TOOL_NAME_PREFIX = "mcp__plugin_context-mode_context-mode__";
45868
46074
  var ZCODE_SOURCES = { startup: "startup", resume: "resume", clear: "clear", compact: "compact" };
45869
46075
  var TWINS = { hook_event_name: "hookEventName", session_id: "sessionId" };
45870
- var FAILURE_EVENT2 = "PostToolUseFailure";
46076
+ var FAILURE_EVENT3 = "PostToolUseFailure";
45871
46077
  function decode10(raw) {
45872
46078
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("zcode: hook payload is not a JSON object");
45873
46079
  const p = { ...raw };
45874
46080
  for (const [snake, camel] of Object.entries(TWINS)) if (p[snake] === void 0) p[snake] = p[camel];
45875
- const failure3 = p.hook_event_name === FAILURE_EVENT2;
46081
+ const failure3 = p.hook_event_name === FAILURE_EVENT3;
45876
46082
  if (failure3) p.hook_event_name = "PostToolUse";
45877
46083
  const toolName2 = typeof p.tool_name === "string" ? p.tool_name : "";
45878
46084
  const prefix = toolName2.startsWith(PLUGIN_TOOL_NAME_PREFIX) ? PLUGIN_TOOL_NAME_PREFIX : TOOL_NAME_PREFIX8;
@@ -45963,7 +46169,8 @@ var OPENCODE_EVENTS = {
45963
46169
  var SHELL_TOOL_NAME = "bash";
45964
46170
  var READ_TOOL_NAME = "read";
45965
46171
  var SHELL_TOOL_NAMES5 = Object.freeze([SHELL_TOOL_NAME, "shell"]);
45966
- var NATIVE_TO_CANONICAL7 = { webfetch: "WebFetch", [READ_TOOL_NAME]: "Read", ...Object.fromEntries(SHELL_TOOL_NAMES5.map((n) => [n, "Bash"])) };
46172
+ var SKILL_TOOL_NAME = "skill";
46173
+ var NATIVE_TO_CANONICAL7 = { webfetch: "WebFetch", [READ_TOOL_NAME]: "Read", [SKILL_TOOL_NAME]: "Skill", ...Object.fromEntries(SHELL_TOOL_NAMES5.map((n) => [n, "Bash"])) };
45967
46174
  function toCanonicalTool(name) {
45968
46175
  if (name.startsWith(OWN_WIRE_PREFIX)) return name.slice(OWN_WIRE_PREFIX.length);
45969
46176
  return Object.prototype.hasOwnProperty.call(NATIVE_TO_CANONICAL7, name) ? NATIVE_TO_CANONICAL7[name] : name;
@@ -46268,7 +46475,7 @@ function ownBundleDir() {
46268
46475
 
46269
46476
  // src/core/ops/doctor-config.ts
46270
46477
  import { existsSync as existsSync12, readdirSync as readdirSync7, readFileSync as readFileSync11 } from "node:fs";
46271
- import { dirname as dirname7, isAbsolute as isAbsolute4, join as join13, resolve as resolve4 } from "node:path";
46478
+ import { dirname as dirname7, isAbsolute as isAbsolute5, join as join13, resolve as resolve4 } from "node:path";
46272
46479
 
46273
46480
  // src/core/ops/host-text.ts
46274
46481
  var BOM_CODE = 65279;
@@ -49165,7 +49372,7 @@ function detectV1(agent, home, scope = {}) {
49165
49372
 
49166
49373
  // src/core/ops/plugin-root.ts
49167
49374
  import { existsSync as existsSync8, readdirSync as readdirSync6, readFileSync as readFileSync7, realpathSync as realpathSync4 } from "node:fs";
49168
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join10, sep as sep2 } from "node:path";
49375
+ import { dirname as dirname6, isAbsolute as isAbsolute3, join as join10, sep as sep2 } from "node:path";
49169
49376
  import { fileURLToPath as fileURLToPath2 } from "node:url";
49170
49377
  function missing(agent, path8) {
49171
49378
  return new CtxError("PLUGIN_ROOT_MISSING", { agent, path: path8 });
@@ -49277,7 +49484,7 @@ function configEntryRoot(adapter, env) {
49277
49484
  const value = parseHostConfig(adapter.id, file2, current.text, current.format);
49278
49485
  const args = hostConfigValueAt(value, [...spec.key, MCP_ARGS_FIELD]);
49279
49486
  const script = Array.isArray(args) ? args[0] : void 0;
49280
- if (typeof script !== "string" || !isAbsolute2(script)) throw missing(adapter.id, file2);
49487
+ if (typeof script !== "string" || !isAbsolute3(script)) throw missing(adapter.id, file2);
49281
49488
  return dirname6(script);
49282
49489
  }
49283
49490
  function packageDirOf(dir) {
@@ -49384,7 +49591,7 @@ function piInstalledIn(env, home, pkgDir, cwd) {
49384
49591
 
49385
49592
  // src/core/ops/doctor-env.ts
49386
49593
  import { existsSync as existsSync10, readFileSync as readFileSync9, realpathSync as realpathSync6 } from "node:fs";
49387
- import { isAbsolute as isAbsolute3, join as join11, relative as relative2 } from "node:path";
49594
+ import { isAbsolute as isAbsolute4, join as join11, relative as relative2 } from "node:path";
49388
49595
  function pass(id, detail = DOCTOR_PASS_DETAIL) {
49389
49596
  return { id, label: DOCTOR_LABEL[id], status: "PASS", detail };
49390
49597
  }
@@ -49553,7 +49760,7 @@ function checkMcp(ctx, adapter) {
49553
49760
  function piCwdInside(worktree, piCwd) {
49554
49761
  if (piCwd === void 0 || !existsSync10(piCwd)) return false;
49555
49762
  const rel = relative2(worktree, realpathSync6.native(piCwd));
49556
- return rel === "" || !rel.startsWith("..") && !isAbsolute3(rel);
49763
+ return rel === "" || !rel.startsWith("..") && !isAbsolute4(rel);
49557
49764
  }
49558
49765
  function checkProject(i) {
49559
49766
  const bad = fail("D7", D7_DETAIL(i.project.source), D7_FIX);
@@ -49561,6 +49768,20 @@ function checkProject(i) {
49561
49768
  if (i.adapter.projectSource === "pi:ctx.cwd" && !piCwdInside(i.project.worktree, i.piCwd)) return bad;
49562
49769
  return pass("D7");
49563
49770
  }
49771
+ function projectOrMissing(ctx) {
49772
+ try {
49773
+ return { project: ctx.project };
49774
+ } catch (err) {
49775
+ if (err instanceof CtxError && err.code === "NO_PROJECT") return { missing: String(err.vars.kind) };
49776
+ throw err;
49777
+ }
49778
+ }
49779
+ function noProjectRow(kind) {
49780
+ return fail("D7", D7_NO_PROJECT_DETAIL(kind), D7_FIX);
49781
+ }
49782
+ function needsProjectRow(id) {
49783
+ return unknown4(id, DOCTOR_NEEDS_PROJECT_DETAIL);
49784
+ }
49564
49785
  function checkMode(adapter, hostPermission) {
49565
49786
  if (hostPermission === "missing") return fail("D10", D10_PERMISSION_MISSING_DETAIL, D10_PERMISSION_FIX);
49566
49787
  if (hostPermission === "wired") return pass("D10", D10_PERMISSION_DETAIL(adapter.denyChannel));
@@ -49592,8 +49813,8 @@ var ENABLED_PROVIDERS = "enabledProviders";
49592
49813
  var DISABLED_PROVIDERS = "disabledProviders";
49593
49814
  var CLAUDE_PROVIDER = "claude";
49594
49815
  var ALL_PROVIDERS = ["*", "all"];
49595
- function ompImportFiles(home) {
49596
- const agentDir = join12(home, ...AGENT_HOME_DIR.omp, PI_AGENT_DIR);
49816
+ function ompImportFiles(env, home) {
49817
+ const agentDir = ompAgentDirOf(env, home);
49597
49818
  return { config: join12(agentDir, OMP_CONFIG_FILE), mcp: join12(agentDir, OMP_MCP_FILE), claude: join12(home, CLAUDE_USER_CONFIG_FILE) };
49598
49819
  }
49599
49820
  function readText2(file2) {
@@ -49878,7 +50099,7 @@ function opencodeDirPlugins(dirs) {
49878
50099
  const loads = lits.some((p) => {
49879
50100
  if (isModule(p)) return packageResolves(dirname7(f));
49880
50101
  const bare2 = p.startsWith(FILE_URL_PREFIX) ? p.slice(FILE_URL_PREFIX.length) : p;
49881
- return existsSync12(isAbsolute4(bare2) ? bare2 : resolve4(dirname7(f), bare2));
50102
+ return existsSync12(isAbsolute5(bare2) ? bare2 : resolve4(dirname7(f), bare2));
49882
50103
  });
49883
50104
  out.push({ file: f, loads });
49884
50105
  }
@@ -49976,7 +50197,7 @@ function checkHostConfig(row5, env, worktree) {
49976
50197
  if ("installs" in choice) return fail2("D3", D3_ROOT_DETAIL(choice.installs.map((r) => r.installPath)), D3_ROOT_FIX(choice.installs));
49977
50198
  }
49978
50199
  if (row5.id === "pi") return checkPiInstall(env, home, worktree);
49979
- if (row5.id === "omp") return checkOmpInstall(home);
50200
+ if (row5.id === "omp") return checkOmpInstall(env, home);
49980
50201
  const parts = [...mcpWrong(row5, home, env, worktree) ? [PART_MCP] : [], ...hookParts(row5, home, env, worktree)];
49981
50202
  if (parts.length === 0) return pass2("D3");
49982
50203
  const detail = D3_DETAIL(parts);
@@ -49988,7 +50209,6 @@ function checkPiInstall(env, home, worktree) {
49988
50209
  if (found !== void 0) return { ...pass2("D3"), detail: found };
49989
50210
  return fail2("D3", D3_DETAIL([PART_MCP]) + D4_REASON_JOIN + join13(piAgentDirOf(env, home), SETTINGS_FILE), NATIVE_INSTALL.pi[0]);
49990
50211
  }
49991
- var OMP_PLUGINS_DIR = "plugins";
49992
50212
  var OMP_LOCK_FILE = "omp-plugins.lock.json";
49993
50213
  function readJson2(file2) {
49994
50214
  try {
@@ -50002,8 +50222,8 @@ function ownEntry(doc, key) {
50002
50222
  const map2 = doc?.[key];
50003
50223
  return typeof map2 === "object" && map2 !== null ? map2[SERVER_KEY] : void 0;
50004
50224
  }
50005
- function checkOmpInstall(home) {
50006
- const dir = join13(home, ...AGENT_HOME_DIR.omp, OMP_PLUGINS_DIR);
50225
+ function checkOmpInstall(env, home) {
50226
+ const dir = ompPluginsDirOf(env, home);
50007
50227
  const lock = join13(dir, OMP_LOCK_FILE);
50008
50228
  const pkg = join13(dir, PI_PACKAGE_JSON_FILE);
50009
50229
  const entry = ownEntry(readJson2(lock), "plugins");
@@ -50019,12 +50239,26 @@ function ompInfoLines(env, version4) {
50019
50239
  out.push(OMP_CONTENT_INFO, OMP_PRINT_MODE_INFO, OMP_SCRIPTS_INFO);
50020
50240
  const home = homeDirOf(env);
50021
50241
  if (home === null) return out;
50022
- const files = ompImportFiles(home);
50242
+ const files = ompImportFiles(env, home);
50023
50243
  if (!ompImportsUs(files, env)) return out;
50024
50244
  const listed = readJson2(files.mcp)?.[OMP_DISABLED_SERVERS_KEY];
50025
50245
  if (!(Array.isArray(listed) && listed.includes(SERVER_KEY))) out.push(OMP_IMPORT_INFO(files.claude, files.mcp));
50026
50246
  return out;
50027
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
+ }
50028
50262
  function checkV1Leftovers(agent, home, scope = {}) {
50029
50263
  const findings = detectV1(agent, home, scope);
50030
50264
  if (findings.length === 0) return pass2("D4");
@@ -52805,9 +53039,11 @@ function hookLogTail(env) {
52805
53039
  }
52806
53040
  async function journalRows(ctx) {
52807
53041
  const head = ["| kind | tool | bytes | ok | exit_code | created_at |", "|---|---|---|---|---|---|"];
52808
- if (!existsSync17(ctx.project.dbPath)) return [`(context.db is absent at ${ctx.project.dbPath})`];
53042
+ const p = projectOrMissing(ctx);
53043
+ if ("missing" in p) return [`(no project: ${D7_NO_PROJECT_DETAIL(p.missing)})`];
53044
+ if (!existsSync17(p.project.dbPath)) return [`(context.db is absent at ${p.project.dbPath})`];
52809
53045
  try {
52810
- const db = await openDb(ctx.project, { readOnly: true });
53046
+ const db = await openDb(p.project, { readOnly: true });
52811
53047
  try {
52812
53048
  const rows = db.raw.prepare(`SELECT kind, tool, bytes, ok, exit_code, created_at FROM events ORDER BY seq DESC LIMIT ${DOCTOR_JOURNAL_ROWS}`).all();
52813
53049
  const cell5 = (v) => v === null || v === void 0 ? "" : String(v);
@@ -52866,6 +53102,7 @@ async function buildIssueBody(i) {
52866
53102
  const failRows = i.rows.filter((r) => r.status !== "PASS");
52867
53103
  const envNames = DOCTOR_ENV_NAMES.map((n) => i.env[n] === void 0 ? `${n} (unset)` : `${n}=${i.env[n]}`);
52868
53104
  const pathTools = DOCTOR_PATH_TOOLS.map((t) => `PATH holds ${t}: ${onPath(i.env, t).join(", ") || "(absent)"}`);
53105
+ const p = projectOrMissing(i.ctx);
52869
53106
  const sections = {
52870
53107
  "Summary": [summaryOf(agent, i.rows, i.unsupported)],
52871
53108
  "ctx-report": [i.table],
@@ -52876,7 +53113,7 @@ async function buildIssueBody(i) {
52876
53113
  ],
52877
53114
  "Hook errors": ["hook-errors.log, last " + DOCTOR_HOOK_LOG_LINES + " lines (UTC):", "```", ...hookLogTail(i.env), "```"],
52878
53115
  "Journal rows": ["events, newest first, last " + DOCTOR_JOURNAL_ROWS + " (bodies stay local):", ...await journalRows(i.ctx)],
52879
- "Agent config": agentConfig(i.adapter, i.env, i.ctx.project.worktree),
53116
+ "Agent config": agentConfig(i.adapter, i.env, "project" in p ? p.project.worktree : process.cwd()),
52880
53117
  "Expected": ["Expected: <the agent fills this in: what should happen, with the byte count>"],
52881
53118
  "Steps": [
52882
53119
  "Reproduced: <yes (2 of 2) or 1 of 2>",
@@ -52897,7 +53134,7 @@ async function buildIssueBody(i) {
52897
53134
  `git: ${gitVersion(i.env)}`,
52898
53135
  ...pathTools,
52899
53136
  ...envNames,
52900
- `Project: ${i.ctx.project.worktree} (key ${i.ctx.project.projectKey})`,
53137
+ "project" in p ? `Project: ${p.project.worktree} (key ${p.project.projectKey})` : `Project: ${D7_NO_PROJECT_DETAIL(p.missing)}`,
52901
53138
  "Filed by: <your agent name, version, model id>"
52902
53139
  ]
52903
53140
  };
@@ -52955,10 +53192,10 @@ async function guard(id, run) {
52955
53192
  return { id, label: DOCTOR_LABEL[id], status: "UNKNOWN", detail: lineOf(err) };
52956
53193
  }
52957
53194
  }
52958
- async function codexDb(ctx, adapter) {
52959
- if (adapter.id !== "codex" || !existsSync18(ctx.project.dbPath)) return null;
53195
+ async function codexDb(project, adapter) {
53196
+ if (adapter.id !== "codex" || !existsSync18(project.dbPath)) return null;
52960
53197
  try {
52961
- return await openDb(ctx.project, { readOnly: true });
53198
+ return await openDb(project, { readOnly: true });
52962
53199
  } catch {
52963
53200
  return null;
52964
53201
  }
@@ -52969,12 +53206,12 @@ function d1UpdateCommand(agent, env, other) {
52969
53206
  function unsupportedRow(id, h) {
52970
53207
  return { id, label: DOCTOR_LABEL[id], status: "WARN", detail: UNSUPPORTED_HOST_LINE(h.name) };
52971
53208
  }
52972
- async function hookRow(ctx, adapter, host) {
52973
- const db = await codexDb(ctx, adapter);
53209
+ async function hookRow(ctx, project, adapter, host) {
53210
+ const db = await codexDb(project, adapter);
52974
53211
  const runStart = Date.now();
52975
53212
  try {
52976
53213
  const row5 = await checkHookRoundTrip({
52977
- worktree: ctx.project.worktree,
53214
+ worktree: project.worktree,
52978
53215
  agent: adapter.id,
52979
53216
  bundleDir: host.bundleDir,
52980
53217
  env: buildChildEnv(host.env),
@@ -53003,7 +53240,9 @@ function ownServerId(configDir, projectKey) {
53003
53240
  async function runDoctorChecks(ctx, adapter, host0) {
53004
53241
  const host = adapter.id === "codex" ? { ...host0, env: { ...host0.env, CODEX_HOME: codexRunDirOf(host0.env, homeDirOf(host0.env) ?? "", host0.bundleDir) } } : host0;
53005
53242
  const env = host.env;
53006
- const project = ctx.project;
53243
+ const p = projectOrMissing(ctx);
53244
+ if ("missing" in p) return noProjectRows(ctx, adapter, host, p.missing);
53245
+ const project = p.project;
53007
53246
  const other = adapter.installMode === "in-process" ? void 0 : unsupportedHostOf({ clientName: ctx.clientInfo?.name, bundleDir: host.bundleDir, env });
53008
53247
  let integrityFailed = false;
53009
53248
  let orphan = [];
@@ -53013,7 +53252,7 @@ async function runDoctorChecks(ctx, adapter, host0) {
53013
53252
  D3: () => other !== void 0 ? unsupportedRow("D3", other) : checkHostConfig(adapter, env, project.worktree),
53014
53253
  // D-UNSUPPORTED-HOSTS-1
53015
53254
  D4: () => checkV1Leftovers(adapter.id, requireHomeDir(env), { project: project.worktree, piAgentDir: piAgentDirOf(env, requireHomeDir(env)), claudeDir: claudeDirOf(env, requireHomeDir(env)), codexDir: codexDirOf(env, requireHomeDir(env)), geminiDir: geminiDirOf(env, requireHomeDir(env)), copilotDir: copilotDirOf(env, requireHomeDir(env)), kiroDir: kiroDirOf(env, requireHomeDir(env)), opencodeDir: opencodeDirOf(env, requireHomeDir(env)) }),
53016
- D5: () => other !== void 0 ? unsupportedRow("D5", other) : hookRow(ctx, adapter, host),
53255
+ D5: () => other !== void 0 ? unsupportedRow("D5", other) : hookRow(ctx, project, adapter, host),
53017
53256
  D5b: () => checkDoubleFire(adapter.id, project.worktree),
53018
53257
  D6: () => checkMcp(ctx, adapter),
53019
53258
  D7: () => checkProject({ project, adapter, piCwd: host.piCwd }),
@@ -53043,6 +53282,28 @@ async function runDoctorChecks(ctx, adapter, host0) {
53043
53282
  });
53044
53283
  return rows;
53045
53284
  }
53285
+ async function noProjectRows(ctx, adapter, host, missing2) {
53286
+ const env = host.env;
53287
+ const other = adapter.installMode === "in-process" ? void 0 : unsupportedHostOf({ clientName: ctx.clientInfo?.name, bundleDir: host.bundleDir, env });
53288
+ const wait = (id) => () => needsProjectRow(id);
53289
+ const checks = {
53290
+ D1: () => checkVersion({ bundleSha: BUNDLE_SHA, version: bundleVersion(host.bundleDir), registryUrl: D1_REGISTRY_URL, timeoutMs: DOCTOR_GIT_TIMEOUT_MS, env: buildChildEnv(env), cwd: process.cwd(), signal: ctx.signal, updateCommand: d1UpdateCommand(adapter.id, env, other) }),
53291
+ D2: () => checkNode({ nodeVersion: process.version, bunVersion: process.versions.bun }),
53292
+ D3: other !== void 0 ? () => unsupportedRow("D3", other) : wait("D3"),
53293
+ D4: () => checkV1Leftovers(adapter.id, requireHomeDir(env), { piAgentDir: piAgentDirOf(env, requireHomeDir(env)), claudeDir: claudeDirOf(env, requireHomeDir(env)), codexDir: codexDirOf(env, requireHomeDir(env)), geminiDir: geminiDirOf(env, requireHomeDir(env)), copilotDir: copilotDirOf(env, requireHomeDir(env)), kiroDir: kiroDirOf(env, requireHomeDir(env)), opencodeDir: opencodeDirOf(env, requireHomeDir(env)) }),
53294
+ D5: other !== void 0 ? () => unsupportedRow("D5", other) : wait("D5"),
53295
+ D5b: wait("D5b"),
53296
+ D6: () => checkMcp(ctx, adapter),
53297
+ D7: () => noProjectRow(missing2),
53298
+ D8: wait("D8"),
53299
+ D9: wait("D9"),
53300
+ D10: () => checkMode(adapter, ctx.hostPermission),
53301
+ D11: () => checkRuntimes(env, checkShell(env))
53302
+ };
53303
+ const rows = [];
53304
+ for (const id of DOCTOR_CHECK_ORDER) rows.push(await guard(id, checks[id]));
53305
+ return rows;
53306
+ }
53046
53307
  function reportEnv(env) {
53047
53308
  const out = {};
53048
53309
  for (const key of Object.keys(REPORT_ENV_ENUMS)) {
@@ -53052,7 +53313,7 @@ function reportEnv(env) {
53052
53313
  return out;
53053
53314
  }
53054
53315
  async function doctorReply(ctx, host) {
53055
- const adapter = getAdapter(ctx.project.agent);
53316
+ const adapter = getAdapter(ctx.agent ?? ctx.project.agent);
53056
53317
  const runtime = runtimeInfo(host.env, ctx.signal);
53057
53318
  const rows = await runDoctorChecks(ctx, adapter, host);
53058
53319
  const failed = rows.some((r) => r.status === "FAIL");
@@ -53071,12 +53332,16 @@ async function doctorReply(ctx, host) {
53071
53332
  const look = rows.find((r) => r.status === "FAIL") ?? rows.find((r) => r.status !== "PASS");
53072
53333
  const docs = look === void 0 ? [] : [DOCTOR_DOCS_LABEL + DOCTOR_DOCS_LINK(look.id)];
53073
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));
53074
53337
  const whole2 = [envLine2, table3, ...docs, ...info, ...notes].join("\n");
53075
53338
  const bytes5 = Buffer.byteLength(whole2, "utf8");
53076
53339
  if (bytes5 <= REPORT_CAP) return { text: whole2, isError: false, sandboxBytes: bytes5 };
53077
- const db = await openDb(ctx.project);
53340
+ const p = known;
53341
+ if ("missing" in p) return { text: whole2, isError: false, sandboxBytes: bytes5 };
53342
+ const db = await openDb(p.project);
53078
53343
  try {
53079
- indexText(db, ctx.project, ctx.sessionId, REPORT_SOURCE_LABEL, whole2, "text");
53344
+ indexText(db, p.project, ctx.sessionId, REPORT_SOURCE_LABEL, whole2, "text");
53080
53345
  } finally {
53081
53346
  closeDb(db);
53082
53347
  }
@@ -53223,11 +53488,11 @@ function schemaLine(issue4) {
53223
53488
  if (issue4.code === "unrecognized_keys") return new CtxError("UNKNOWN_FIELD", { f: issue4.keys[0] }).toLine();
53224
53489
  return issue4.message;
53225
53490
  }
53226
- function fileError(given, abs, root) {
53491
+ function fileError(given, abs, root, hostRoots) {
53227
53492
  let dir = abs;
53228
53493
  while (!existsSync19(dir) && dirname11(dir) !== dir) dir = dirname11(dir);
53229
- if (isInside(root, dir)) return null;
53230
- 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 };
53231
53496
  }
53232
53497
  function takesDashC(language, runtime) {
53233
53498
  if (language === "shell") return true;
@@ -53290,8 +53555,8 @@ async function handler3(raw, ctx) {
53290
53555
  const extra = { ...PLAIN_OUTPUT_ENV2 };
53291
53556
  if (input.file !== void 0) {
53292
53557
  const abs = resolve8(cwd, input.file);
53293
- const bad = fileError(input.file, abs, ctx.project.containmentRoot);
53294
- if (bad !== null) return fail4(bad);
53558
+ const bad = fileError(input.file, abs, ctx.project.containmentRoot, ctx.hostRoots);
53559
+ if (bad !== null) return bad;
53295
53560
  extra.CTX_FILE = abs;
53296
53561
  }
53297
53562
  let runtime;
@@ -53497,6 +53762,7 @@ function globSeg(pat, name) {
53497
53762
  }
53498
53763
 
53499
53764
  // src/core/sandbox/fetch.ts
53765
+ import { randomBytes } from "node:crypto";
53500
53766
  import { readFileSync as readFileSync16 } from "node:fs";
53501
53767
  import { lookup } from "node:dns/promises";
53502
53768
  import http from "node:http";
@@ -53531,6 +53797,26 @@ var PRIVATE_RANGES = [
53531
53797
  ];
53532
53798
  var BLOCKED = new BlockList();
53533
53799
  for (const [net, prefix, type] of PRIVATE_RANGES) BLOCKED.addSubnet(net, prefix, type);
53800
+ var FAKE_IP_POOL = new BlockList();
53801
+ FAKE_IP_POOL.addSubnet("198.18.0.0", 15, "ipv4");
53802
+ var FAKE_IP_PROBE_TLD = ".invalid";
53803
+ var FAKE_IP_PROBE_BYTES = 8;
53804
+ var FAKE_IP_PROBE_MS = 1500;
53805
+ var fakeIpProbe;
53806
+ function inFakeIpPool(address) {
53807
+ return isIP(address) === 4 && FAKE_IP_POOL.check(address, "ipv4");
53808
+ }
53809
+ function fakeIpResolver() {
53810
+ fakeIpProbe ??= new Promise((resolve10) => {
53811
+ const timer = setTimeout(() => resolve10(false), FAKE_IP_PROBE_MS);
53812
+ timer.unref();
53813
+ lookup(randomBytes(FAKE_IP_PROBE_BYTES).toString("hex") + FAKE_IP_PROBE_TLD, { all: true }).then(
53814
+ (addrs) => resolve10(addrs.length > 0 && addrs.every((a) => inFakeIpPool(a.address))),
53815
+ () => resolve10(false)
53816
+ ).finally(() => clearTimeout(timer));
53817
+ });
53818
+ return fakeIpProbe;
53819
+ }
53534
53820
  var STATUS_OK_FIRST = 200;
53535
53821
  var STATUS_OK_END = 300;
53536
53822
  var STATUS_REDIRECT = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
@@ -53633,8 +53919,15 @@ function checkAddress(hostname2, address) {
53633
53919
  throw new CtxError("SSRF", { host: hostname2 });
53634
53920
  }
53635
53921
  }
53636
- async function resolveTarget(u, signal) {
53637
- const host = bare(u.hostname);
53922
+ async function checkResolved(host, addrs, signal) {
53923
+ const pooled = isIP(host) === 0 ? addrs.filter((a) => inFakeIpPool(a.address)) : [];
53924
+ for (const a of addrs) if (!pooled.includes(a)) checkAddress(host, a.address);
53925
+ if (pooled.length === 0) return;
53926
+ const fakeIp = await fakeIpResolver();
53927
+ if (signal.aborted) throw fail5("ABORT_ERR");
53928
+ if (!fakeIp) checkAddress(host, pooled[0].address);
53929
+ }
53930
+ async function lookupAll(host, signal) {
53638
53931
  let addrs;
53639
53932
  try {
53640
53933
  addrs = await lookup(host, { all: true });
@@ -53643,9 +53936,26 @@ async function resolveTarget(u, signal) {
53643
53936
  }
53644
53937
  if (signal.aborted) throw fail5("ABORT_ERR");
53645
53938
  if (addrs.length === 0) throw fail5("ENOTFOUND");
53646
- for (const a of addrs) checkAddress(host, a.address);
53939
+ return addrs;
53940
+ }
53941
+ async function resolveTarget(u, signal, checked) {
53942
+ const host = bare(u.hostname);
53943
+ const addrs = await lookupAll(host, signal);
53944
+ if (checked) await checkResolved(host, addrs, signal);
53647
53945
  return { host, port: u.port === "" ? defaultPort(u.protocol) : Number(u.port), address: addrs[0].address };
53648
53946
  }
53947
+ async function checkProxiedTarget(u, signal) {
53948
+ const host = bare(u.hostname);
53949
+ if (isIP(host) !== 0) return checkAddress(host, host);
53950
+ let addrs;
53951
+ try {
53952
+ addrs = await lookupAll(host, signal);
53953
+ } catch (err) {
53954
+ if (signal.aborted) throw err;
53955
+ return;
53956
+ }
53957
+ await checkResolved(host, addrs, signal);
53958
+ }
53649
53959
  function tlsName(host) {
53650
53960
  return isIP(host) === 0 ? host : void 0;
53651
53961
  }
@@ -53703,9 +54013,8 @@ async function safeFetch(url4, signal) {
53703
54013
  for (let hop = 0; ; hop += 1) {
53704
54014
  if (signal.aborted) throw fail5("ABORT_ERR");
53705
54015
  const proxy = pickProxy(current);
53706
- const origin = bare(current.hostname);
53707
- if (proxy !== void 0 && isIP(origin) !== 0) checkAddress(origin, origin);
53708
- const conn = await resolveTarget(proxy === void 0 ? current : proxy.url, signal);
54016
+ if (proxy !== void 0) await checkProxiedTarget(current, signal);
54017
+ const conn = await resolveTarget(proxy === void 0 ? current : proxy.url, signal, proxy === void 0);
53709
54018
  const res = await request(current, conn, proxy, signal);
53710
54019
  const status = res.statusCode ?? 0;
53711
54020
  const location = res.headers.location;
@@ -57564,18 +57873,19 @@ function readUtf8(absPath) {
57564
57873
  return void 0;
57565
57874
  }
57566
57875
  }
57567
- function missingOrOutside(given, abs, root) {
57876
+ function missingOrOutside(given, abs, root, hostRoots) {
57568
57877
  let dir = abs;
57569
57878
  while (!existsSync20(dir) && dirname12(dir) !== dir) dir = dirname12(dir);
57570
- 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" });
57571
57880
  return new CtxError("OUTSIDE_ROOT", { p: given, root });
57572
57881
  }
57573
- function pathItems(input, project) {
57882
+ function pathItems(input, project, hostRoots) {
57574
57883
  const abs = resolve9(project.worktree, input.path);
57575
- 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);
57576
57886
  const base = relative3(project.worktree, abs);
57577
57887
  if (statSync8(abs).isDirectory()) {
57578
- return walkDir(abs, project.containmentRoot).map((f) => ({
57888
+ return walkDir(abs, allowed).map((f) => ({
57579
57889
  sourceKind: "path",
57580
57890
  label: pathLabel(join22(base, f.relPath)),
57581
57891
  kind: kindOfPath(f.relPath),
@@ -57592,7 +57902,7 @@ async function itemsOf(input, ctx) {
57592
57902
  return { items: [{ sourceKind: "content", label: label3, kind, read: () => text2 }], from: label3 };
57593
57903
  }
57594
57904
  if (input.path !== void 0) {
57595
- const items = pathItems({ ...input, path: input.path }, ctx.project);
57905
+ const items = pathItems({ ...input, path: input.path }, ctx.project, ctx.hostRoots);
57596
57906
  return { items, from: items.length === 1 ? items[0].label : pathLabel(input.path) };
57597
57907
  }
57598
57908
  const res = await safeFetch(input.url ?? "", AbortSignal.any([ctx.signal, AbortSignal.timeout(EXEC_TIMEOUT_MS)]));
@@ -57659,7 +57969,7 @@ async function handler4(input, ctx) {
57659
57969
  journal: { kind: "index", key: from, path: from, exit_code: null }
57660
57970
  };
57661
57971
  } catch (err) {
57662
- 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 } : {} };
57663
57973
  throw err;
57664
57974
  }
57665
57975
  }
@@ -57734,8 +58044,11 @@ var ctxPurge = Object.freeze({
57734
58044
 
57735
58045
  // src/core/compaction/candidates.ts
57736
58046
  function firstLine3(body) {
57737
- const nl = body.indexOf("\n");
57738
- return (nl < 0 ? body : body.slice(0, nl)).replaceAll("\r", " ");
58047
+ const i = body.length - body.trimStart().length;
58048
+ if (i === body.length) return "";
58049
+ const start = i === 0 ? 0 : body.lastIndexOf("\n", i) + 1;
58050
+ const nl = body.indexOf("\n", i);
58051
+ return (start === 0 && nl < 0 ? body : body.slice(start, nl < 0 ? body.length : nl)).replaceAll("\r", " ");
57739
58052
  }
57740
58053
  function make(section, row5, text, repeatCount, query) {
57741
58054
  const bytes5 = Buffer.byteLength(text, "utf8");
@@ -58549,7 +58862,7 @@ function ownEntries2(agent, env) {
58549
58862
  }
58550
58863
  if (agent === "omp") {
58551
58864
  return [{
58552
- file: ompImportFiles(home).mcp,
58865
+ file: ompImportFiles(env, home).mcp,
58553
58866
  key: OMP_DISABLED_SERVERS_KEY,
58554
58867
  shown: OMP_DISABLED_SERVERS_KEY,
58555
58868
  has: (v) => Array.isArray(v) && v.includes(SERVER_KEY),
@@ -58910,6 +59223,9 @@ function metaNumber(meta3, key) {
58910
59223
  function sessionIdOf(meta3, agent, env, serverId) {
58911
59224
  const fromMeta = metaString(meta3, "sessionId");
58912
59225
  if (fromMeta !== void 0) return fromMeta;
59226
+ const metaKey = agent === void 0 ? void 0 : HOST_SESSION_META[agent];
59227
+ const fromHostMeta = metaKey === void 0 ? void 0 : metaString(meta3, metaKey);
59228
+ if (fromHostMeta !== void 0) return fromHostMeta;
58913
59229
  const key = agent === void 0 ? void 0 : HOST_SESSION_ENV[agent];
58914
59230
  const fromHost = key === void 0 ? void 0 : env[key];
58915
59231
  if (typeof fromHost === "string" && fromHost !== "") return fromHost;
@@ -58928,6 +59244,38 @@ function workspaceFromMeta(meta3) {
58928
59244
  return void 0;
58929
59245
  }
58930
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
+ }
58931
59279
  function realOrSame(p) {
58932
59280
  try {
58933
59281
  return realpathSync12.native(p);
@@ -59015,6 +59363,8 @@ async function startServer(argv, env) {
59015
59363
  const agent = resolveAgent(argv, env);
59016
59364
  const fromRoots = agent === "vscode" && !hasWorkspaceFolder(argv) ? await workspaceFromRoots(server) : void 0;
59017
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 ?? []];
59018
59368
  let project;
59019
59369
  const projectOf = () => {
59020
59370
  if (agent === void 0) throw new CtxError("NO_PROJECT", { kind: "--agent" });
@@ -59025,6 +59375,10 @@ async function startServer(argv, env) {
59025
59375
  get project() {
59026
59376
  return projectOf();
59027
59377
  },
59378
+ ...agent === void 0 ? {} : { agent },
59379
+ // D-1410-DOCTOR-NO-PROJECT-1
59380
+ ...hostRoots.length === 0 ? {} : { hostRoots },
59381
+ // D-1398-HOST-ROOTS-1
59028
59382
  sessionId: sessionIdOf(meta3, agent, env, serverId),
59029
59383
  turn: metaNumber(meta3, "turn") ?? 0,
59030
59384
  signal: req.mcpReq.signal,
@@ -59042,6 +59396,9 @@ async function startServer(argv, env) {
59042
59396
  reply4 = errorReply(err);
59043
59397
  }
59044
59398
  }
59399
+ if (reply4.outsideRoot === true && fromInput === void 0 && listsRoots(req.mcpReq.envelope)) {
59400
+ return inputRequired({ inputRequests: { [HOST_ROOTS_INPUT_KEY]: inputRequired.listRoots() } });
59401
+ }
59045
59402
  if (stopRequested()) {
59046
59403
  setTimeout(stopSelf, UPGRADE_STOP_DELAY_MS);
59047
59404
  return { content: [{ type: "text", text: reply4.text }], isError: reply4.isError };