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/pi/index.js CHANGED
@@ -988,14 +988,14 @@ function prefixIssues(path8, issues) {
988
988
  return iss;
989
989
  });
990
990
  }
991
- function unwrapMessage(message3) {
992
- return typeof message3 === "string" ? message3 : message3?.message;
991
+ function unwrapMessage(message4) {
992
+ return typeof message4 === "string" ? message4 : message4?.message;
993
993
  }
994
994
  function finalizeIssue(iss, ctx, config4) {
995
995
  const full = { ...iss, path: iss.path ?? [] };
996
996
  if (!iss.message) {
997
- const message3 = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config4.customError?.(iss)) ?? unwrapMessage(config4.localeError?.(iss)) ?? "Invalid input";
998
- full.message = message3;
997
+ const message4 = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config4.customError?.(iss)) ?? unwrapMessage(config4.localeError?.(iss)) ?? "Invalid input";
998
+ full.message = message4;
999
999
  }
1000
1000
  delete full.inst;
1001
1001
  delete full.continue;
@@ -11162,16 +11162,11 @@ var POINTER_MIN = 640;
11162
11162
  var STATE_CLOSE_TAG = "</context_mode_state>";
11163
11163
  var INDEX_WRITE_CHUNK = 1048576;
11164
11164
  var SYNC_INDEX_MAX_BYTES = 65536;
11165
- var REPLACE_TRIGGER_BYTES_DEFAULT = 4096;
11165
+ var REPLACE_TRIGGER_BYTES = 4096;
11166
11166
  var REPLACE_TRIGGER_ENV = "CTX_REPLACE_TRIGGER_BYTES";
11167
- function readReplaceTrigger(raw) {
11168
- if (raw === void 0 || raw.trim() === "") return REPLACE_TRIGGER_BYTES_DEFAULT;
11169
- const n = Number(raw);
11170
- return Number.isSafeInteger(n) && n > 0 ? n : REPLACE_TRIGGER_BYTES_DEFAULT;
11171
- }
11172
- var REPLACE_TRIGGER_BYTES = readReplaceTrigger(process.env[REPLACE_TRIGGER_ENV]);
11173
11167
  var RANGE_READ_TOOLS = Object.freeze(["Read", "view"]);
11174
11168
  var READ_RANGE_KEYS = Object.freeze(["offset", "limit", "view_range"]);
11169
+ var SKILL_LOAD_TOOLS = Object.freeze(["Skill"]);
11175
11170
  var REPLACE_RETURN_BYTES = 96;
11176
11171
  var SHAPE_RETURN_BYTES = 256;
11177
11172
  var REPLACE_CHUNK_BYTES = 48;
@@ -11185,6 +11180,9 @@ function SUBAGENT_HANDLE_LINE(handle, bytes5, read3) {
11185
11180
  function SEARCH_TWIN_LINE(searchPath, handle, terms, projectDir) {
11186
11181
  return " Or run: node " + shellWord(searchPath) + " " + handle + " " + shellWord(terms) + " " + shellWord(projectDir);
11187
11182
  }
11183
+ function PERSISTED_FILE_LINE(file2) {
11184
+ return " The whole output is also in " + JSON.stringify(file2) + "; Read it with offset and limit.";
11185
+ }
11188
11186
  function shellWord(s) {
11189
11187
  return "'" + s.split("'").join("'\\''") + "'";
11190
11188
  }
@@ -11339,6 +11337,10 @@ var KILL_GRACE_MS = 1e3;
11339
11337
  var PIPE_EOF_GRACE_MS = 250;
11340
11338
  var PIPE_DRAIN_MAX_MS = 2e3;
11341
11339
  var DB_TIMEOUT_MS = 5e3;
11340
+ var HOOK_BUSY_MS = 250;
11341
+ var HOOK_SPOOL_DIR = "pending";
11342
+ var SPOOL_CLAIM_STALE_MS = 3e4;
11343
+ var SPOOL_DRAIN_MS = 1e3;
11342
11344
  var DB_WAL_SUFFIX = "-wal";
11343
11345
  var DB_SHM_SUFFIX = "-shm";
11344
11346
  var DB_TMP_SUFFIX = ".tmp";
@@ -11357,7 +11359,7 @@ var TOOLS_TTL_MS = 36e5;
11357
11359
  var IN_PROCESS_TIMEOUT_MS = 0;
11358
11360
  var MS_PER_DAY = 864e5;
11359
11361
  var PROJECT_KEY_HEX_LEN = 16;
11360
- var SCHEMA_VERSION = 6;
11362
+ var SCHEMA_VERSION = 7;
11361
11363
  var RETENTION_IDLE_DAYS = 30;
11362
11364
  var RETENTION_SIZE_CAP_BYTES = 524288e3;
11363
11365
  var PROJECT_DEAD_IDLE_DAYS = 14;
@@ -11385,6 +11387,7 @@ var SEARCH_WRAPPER_FILE = "search.mjs";
11385
11387
  var RUN_WRAPPER_AGENT = "claude-code";
11386
11388
  var RUN_SESSION_PREFIX = "mcp:";
11387
11389
  var HOST_SESSION_ENV = Object.freeze({ "claude-code": "CLAUDE_CODE_SESSION_ID" });
11390
+ var HOST_SESSION_META = Object.freeze({ zcode: "session_id" });
11388
11391
  var NODE_MIN = "24.15.0";
11389
11392
  var DATA_ROOT = "~/.context-mode";
11390
11393
  var DATA_DIR_ENV = "CONTEXT_MODE_DATA_DIR";
@@ -11409,6 +11412,7 @@ var FRONTMATTER_FENCE = "---";
11409
11412
  var FRONTMATTER_TOOLS_KEY = "tools";
11410
11413
  var FRONTMATTER_DISALLOWED_KEY = "disallowedTools";
11411
11414
  var MCP_SERVER_TOOL_PREFIX = "mcp__";
11415
+ var PLUGIN_CALL_ID_PREFIX = "toolu_plugin_";
11412
11416
  var MCP_NAME_JOIN = "__";
11413
11417
  var GEMINI_MCP_PREFIX = "mcp_";
11414
11418
  var GEMINI_NAME_EXTRA_CHARS = "_-.:";
@@ -11534,6 +11538,8 @@ var RECALL_BUDGET_BYTES = 2048;
11534
11538
  var RECALL_MIN_SCORE = 5;
11535
11539
  var RECALL_MAX_ROWS = 340;
11536
11540
  var COMPACTED_META_PREFIX = "compacted:";
11541
+ var BET_META_PREFIX = "bet:";
11542
+ var LOSTBET_META_PREFIX = "lostbet:";
11537
11543
  var RECALL_UNITS_SEEN_META_PREFIX = "recall_units_seen:";
11538
11544
  var UNITS_ANCESTOR_FACTOR = 8;
11539
11545
  var RECALL_QUERY_MAX_TERMS = 64;
@@ -11630,7 +11636,7 @@ var DECISION_ANSWERS_KEY = "answers";
11630
11636
  var DECISION_OPTION_KEY = "option";
11631
11637
  var DECISION_LABEL_JOIN = " | ";
11632
11638
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
11633
- var BUNDLE_SHA = true ? "1fce537096e8e2b7d1924c2b5ff2b83287f157ee" : void 0;
11639
+ var BUNDLE_SHA = true ? "f41c429ae530a3fec5bda3c12a8ecdc2a5f14ada" : void 0;
11634
11640
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
11635
11641
  var DOCTOR_LABEL = Object.freeze({
11636
11642
  D1: "version",
@@ -11741,6 +11747,10 @@ function D7_DETAIL(got) {
11741
11747
  return `resolved project source ${got} does not match the host's actual cwd`;
11742
11748
  }
11743
11749
  var D7_FIX = "restart the agent in the correct directory";
11750
+ function D7_NO_PROJECT_DETAIL(kind) {
11751
+ return `Project source ${kind} is missing`;
11752
+ }
11753
+ var DOCTOR_NEEDS_PROJECT_DETAIL = "runs once the project resolves; D7 names the project source";
11744
11754
  function D8_STALE_SCHEMA_DETAIL(got, want) {
11745
11755
  return `stale schema (v${got}, expected v${want})`;
11746
11756
  }
@@ -12066,6 +12076,7 @@ var OMP_CONTENT_INFO = "OMP keeps tool output in content; context-mode writes it
12066
12076
  var OMP_PRINT_MODE_INFO = "Print mode sends no prompt event. Use omp or omp --mode rpc to keep prompts.";
12067
12077
  var OMP_SCRIPTS_INFO = "Add < /dev/null in scripts.";
12068
12078
  var OMP_IMPORT_INFO = (claude, mcp) => `OMP also imports context-mode from ${claude}. To run it once, add "context-mode" to disabledServers in ${mcp}.`;
12079
+ 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}.`;
12069
12080
  var PI_CURRENT_MAJOR = 2;
12070
12081
  var V1_OPENCODE_PLUGIN_SPEC = "context-mode";
12071
12082
  var V1_TMP_PREFIX = "context-mode-";
@@ -12085,6 +12096,10 @@ var OPENCODE_CONFIG_DIR_ENV = "OPENCODE_CONFIG_DIR";
12085
12096
  var APPDATA_ENV = "APPDATA";
12086
12097
  var VSCODE_USER_DIR_SEGMENTS = Object.freeze(["Code", "User"]);
12087
12098
  var XDG_CONFIG_HOME_ENV = "XDG_CONFIG_HOME";
12099
+ var XDG_DATA_HOME_ENV = "XDG_DATA_HOME";
12100
+ var PI_CONFIG_DIR_ENV = "PI_CONFIG_DIR";
12101
+ var OMP_APP_DIR = "omp";
12102
+ var OMP_PLUGINS_DIR = "plugins";
12088
12103
  var CONFIG_TOML_FILE = "config.toml";
12089
12104
  var CONFIG_JSON_FILE = "config.json";
12090
12105
  var ZCODE_CLI_DIR = "cli";
@@ -12364,7 +12379,8 @@ var ERROR_TEXT = Object.freeze({
12364
12379
  NO_RUNTIME: "No <lang> runtime on PATH. Fix: install it or pick another language.",
12365
12380
  FETCH_FAILED: "Fetch failed: <code>. Fix: check the URL or proxy.",
12366
12381
  SSRF: "Blocked private address <host>. Fix: use a public URL.",
12367
- OUTSIDE_ROOT: "Path <p> is outside the project. Fix: use a path inside <root>.",
12382
+ 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).",
12383
+ // #1398 D-1398-HOST-ROOTS-1
12368
12384
  INVALID_ARGS: "Invalid argument <field>. Fix: <action>.",
12369
12385
  ONE_OF_INPUT: "Pass exactly one of <names>. Fix: drop the extra field.",
12370
12386
  SPAWN_FAILED: "Failed to start the process: <detail>. Fix: check the command and PATH.",
@@ -12422,7 +12438,7 @@ var CtxError = class extends Error {
12422
12438
  };
12423
12439
 
12424
12440
  // src/core/hooks/dispatch.ts
12425
- import { dirname as dirname4, join as join8, relative as relative3, resolve as resolve8, sep as sep3 } from "node:path";
12441
+ import { dirname as dirname4, join as join9, relative as relative3, resolve as resolve8, sep as sep3 } from "node:path";
12426
12442
 
12427
12443
  // src/core/contracts/agents.ts
12428
12444
  var AGENT_IDS = ["claude-code", "codex", "gemini", "qwen", "copilot-cli", "vscode", "kiro", "zcode", "pi", "opencode", "omp"];
@@ -12433,6 +12449,7 @@ var SHELL_TOOL_NAMES = Object.freeze(["Bash", "PowerShell"]);
12433
12449
  var POWERSHELL_TOOL = "PowerShell";
12434
12450
  var SHELL_CANONICAL = "Bash";
12435
12451
  var CLAUDE_SHAPE_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse"];
12452
+ var FAILURE_EVENT = "PostToolUseFailure";
12436
12453
  var MCP_PREFIX = "mcp__";
12437
12454
  var MCP_SEP = "__";
12438
12455
  var CLAUDE_SOURCES = { startup: "startup", resume: "resume", clear: "clear", compact: "compact" };
@@ -12606,7 +12623,14 @@ function requireFields(raw) {
12606
12623
  }
12607
12624
  function decode2(raw) {
12608
12625
  requireFields(raw);
12609
- const ev = decodeClaudeShape(raw, "claude-code", TOOL_NAME_PREFIX2, CLAUDE_SOURCES);
12626
+ const failure3 = typeof raw === "object" && raw !== null && !Array.isArray(raw) && raw.hook_event_name === FAILURE_EVENT;
12627
+ const payload = failure3 ? { ...raw, hook_event_name: "PostToolUse" } : raw;
12628
+ const ev = decodeClaudeShape(payload, "claude-code", TOOL_NAME_PREFIX2, CLAUDE_SOURCES);
12629
+ if (failure3) {
12630
+ const error42 = raw.error;
12631
+ const text = typeof error42 === "string" ? error42 : error42 === void 0 ? "" : JSON.stringify(error42);
12632
+ ev.result = { isError: true, bytes: Buffer.byteLength(text), text, keep: true };
12633
+ }
12610
12634
  if (ev.tool !== void 0 && ev.tool.name === POWERSHELL_TOOL) ev.tool.canonicalName = SHELL_CANONICAL;
12611
12635
  if (ev.cwd === "") ev.cwd = process.env.CLAUDE_PROJECT_DIR || process.cwd();
12612
12636
  if (ev.event === "PostToolUse" && ev.tool !== void 0 && ev.tool.callId === void 0) {
@@ -12785,9 +12809,9 @@ var NATIVE_TO_CANONICAL3 = {
12785
12809
  grep_search: "Grep",
12786
12810
  web_fetch: "WebFetch"
12787
12811
  };
12788
- var FAILURE_EVENT = "PostToolUseFailure";
12812
+ var FAILURE_EVENT2 = "PostToolUseFailure";
12789
12813
  function decode5(raw) {
12790
- const failure3 = typeof raw === "object" && raw !== null && !Array.isArray(raw) && raw.hook_event_name === FAILURE_EVENT;
12814
+ const failure3 = typeof raw === "object" && raw !== null && !Array.isArray(raw) && raw.hook_event_name === FAILURE_EVENT2;
12791
12815
  const payload = failure3 ? { ...raw, hook_event_name: "PostToolUse" } : raw;
12792
12816
  const ev = decodeClaudeShape(payload, "qwen", TOOL_NAME_PREFIX5, QWEN_SOURCES);
12793
12817
  if (ev.tool !== void 0 && Object.hasOwn(NATIVE_TO_CANONICAL3, ev.tool.name)) ev.tool.canonicalName = NATIVE_TO_CANONICAL3[ev.tool.name];
@@ -13107,12 +13131,12 @@ var TOOL_NAME_PREFIX9 = "mcp__context-mode__";
13107
13131
  var PLUGIN_TOOL_NAME_PREFIX = "mcp__plugin_context-mode_context-mode__";
13108
13132
  var ZCODE_SOURCES = { startup: "startup", resume: "resume", clear: "clear", compact: "compact" };
13109
13133
  var TWINS = { hook_event_name: "hookEventName", session_id: "sessionId" };
13110
- var FAILURE_EVENT2 = "PostToolUseFailure";
13134
+ var FAILURE_EVENT3 = "PostToolUseFailure";
13111
13135
  function decode9(raw) {
13112
13136
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("zcode: hook payload is not a JSON object");
13113
13137
  const p = { ...raw };
13114
13138
  for (const [snake, camel] of Object.entries(TWINS)) if (p[snake] === void 0) p[snake] = p[camel];
13115
- const failure3 = p.hook_event_name === FAILURE_EVENT2;
13139
+ const failure3 = p.hook_event_name === FAILURE_EVENT3;
13116
13140
  if (failure3) p.hook_event_name = "PostToolUse";
13117
13141
  const toolName2 = typeof p.tool_name === "string" ? p.tool_name : "";
13118
13142
  const prefix = toolName2.startsWith(PLUGIN_TOOL_NAME_PREFIX) ? PLUGIN_TOOL_NAME_PREFIX : TOOL_NAME_PREFIX9;
@@ -13141,7 +13165,8 @@ var OPENCODE_EVENTS = {
13141
13165
  var SHELL_TOOL_NAME = "bash";
13142
13166
  var READ_TOOL_NAME = "read";
13143
13167
  var SHELL_TOOL_NAMES5 = Object.freeze([SHELL_TOOL_NAME, "shell"]);
13144
- var NATIVE_TO_CANONICAL7 = { webfetch: "WebFetch", [READ_TOOL_NAME]: "Read", ...Object.fromEntries(SHELL_TOOL_NAMES5.map((n) => [n, "Bash"])) };
13168
+ var SKILL_TOOL_NAME = "skill";
13169
+ var NATIVE_TO_CANONICAL7 = { webfetch: "WebFetch", [READ_TOOL_NAME]: "Read", [SKILL_TOOL_NAME]: "Skill", ...Object.fromEntries(SHELL_TOOL_NAMES5.map((n) => [n, "Bash"])) };
13145
13170
  function toCanonicalTool(name) {
13146
13171
  if (name.startsWith(OWN_WIRE_PREFIX)) return name.slice(OWN_WIRE_PREFIX.length);
13147
13172
  return Object.prototype.hasOwnProperty.call(NATIVE_TO_CANONICAL7, name) ? NATIVE_TO_CANONICAL7[name] : name;
@@ -14857,6 +14882,24 @@ function piAgentDirOf(env, home) {
14857
14882
  const dir = env[PI_AGENT_DIR_ENV];
14858
14883
  return dir !== void 0 && dir !== "" ? dir : join(home, ...AGENT_HOME_DIR.pi, PI_AGENT_DIR);
14859
14884
  }
14885
+ function ompConfigRootOf(env, home) {
14886
+ const dir = env[PI_CONFIG_DIR_ENV];
14887
+ return dir !== void 0 && dir !== "" ? join(home, dir) : join(home, ...AGENT_HOME_DIR.omp);
14888
+ }
14889
+ function ompAgentDirOf(env, home) {
14890
+ return join(ompConfigRootOf(env, home), PI_AGENT_DIR);
14891
+ }
14892
+ function ompPluginsDirOf(env, home, platform = process.platform) {
14893
+ const root = ompConfigRootOf(env, home);
14894
+ const xdg = env[XDG_DATA_HOME_ENV];
14895
+ const agent = env[PI_AGENT_DIR_ENV];
14896
+ const defaultAgent = agent === void 0 || agent === "" || resolve2(agent) === join(root, PI_AGENT_DIR);
14897
+ if ((platform === "linux" || platform === "darwin") && defaultAgent && xdg !== void 0 && xdg !== "") {
14898
+ const app = join(xdg, OMP_APP_DIR);
14899
+ if (existsSync(app)) return join(app, OMP_PLUGINS_DIR);
14900
+ }
14901
+ return join(root, OMP_PLUGINS_DIR);
14902
+ }
14860
14903
  function vscodeUserDirOf(env, home, platform = process.platform) {
14861
14904
  const set3 = (v) => v !== void 0 && v !== "";
14862
14905
  const p = platform === "win32" ? win32 : posix;
@@ -15408,7 +15451,7 @@ var TOOL_DESCRIPTIONS = Object.freeze({
15408
15451
  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.',
15409
15452
  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.',
15410
15453
  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.',
15411
- 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.',
15454
+ 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.',
15412
15455
  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.",
15413
15456
  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.",
15414
15457
  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",
@@ -15456,6 +15499,10 @@ function isInside(root, p) {
15456
15499
  }
15457
15500
  return true;
15458
15501
  }
15502
+ function allowedRootOf(containmentRoot, hostRoots, p) {
15503
+ if (isInside(containmentRoot, p)) return containmentRoot;
15504
+ return hostRoots?.find((r) => isInside(r, p));
15505
+ }
15459
15506
  var rootReal = /* @__PURE__ */ new Map();
15460
15507
  function realRoot(root) {
15461
15508
  const hit = rootReal.get(root);
@@ -15884,7 +15931,7 @@ function dumpTarget(name, args) {
15884
15931
  }
15885
15932
 
15886
15933
  // src/core/project/resolve.ts
15887
- import { basename as basename2, dirname as dirname3, join as join6, resolve as resolve6 } from "node:path";
15934
+ import { basename as basename2, dirname as dirname3, isAbsolute as isAbsolute3, join as join6, resolve as resolve6 } from "node:path";
15888
15935
 
15889
15936
  // src/core/project/sha256.ts
15890
15937
  var K = new Uint32Array([
@@ -16039,12 +16086,7 @@ function dirOf(kind, src) {
16039
16086
  }
16040
16087
  }
16041
16088
  function gitDirs(dir) {
16042
- let cur;
16043
- try {
16044
- cur = realpathSync3.native(dir);
16045
- } catch {
16046
- throw new CtxError("NO_GIT_DIR", { path: dir });
16047
- }
16089
+ let cur = nearestRealDir(dir);
16048
16090
  const start = cur;
16049
16091
  for (; ; ) {
16050
16092
  const gitDir = gitDirAt(join6(cur, GIT_DIR_NAME));
@@ -16057,6 +16099,18 @@ function gitDirs(dir) {
16057
16099
  cur = up;
16058
16100
  }
16059
16101
  }
16102
+ function nearestRealDir(dir) {
16103
+ const walk3 = isAbsolute3(dir);
16104
+ for (let d = walk3 ? resolve6(dir) : dir; ; ) {
16105
+ try {
16106
+ return realpathSync3.native(d);
16107
+ } catch {
16108
+ const up = dirname3(d);
16109
+ if (!walk3 || up === d) throw new CtxError("NO_GIT_DIR", { path: dir });
16110
+ d = up;
16111
+ }
16112
+ }
16113
+ }
16060
16114
  function gitDirAt(dotGit) {
16061
16115
  let gitDir;
16062
16116
  try {
@@ -16119,7 +16173,7 @@ function resolveProject(agent, src) {
16119
16173
  },
16120
16174
  worktree,
16121
16175
  get containmentRoot() {
16122
- root ??= plain ?? containmentRootOf(dir, commonDir);
16176
+ root ??= plain ?? containmentRootOf(worktree, commonDir);
16123
16177
  return root;
16124
16178
  },
16125
16179
  agent,
@@ -16229,13 +16283,22 @@ CREATE VIRTUAL TABLE line_units USING fts5(
16229
16283
  var DDL_V6 = `
16230
16284
  UPDATE sources SET label = replace(label, char(92), '/') WHERE kind = 'path' AND instr(label, char(92)) > 0;
16231
16285
  `;
16286
+ var DDL_V7 = `
16287
+ ALTER TABLE sources ADD COLUMN unit_lo INTEGER;
16288
+ ALTER TABLE sources ADD COLUMN unit_hi INTEGER;
16289
+ CREATE INDEX IF NOT EXISTS idx_sources_session ON sources(session_id, id);
16290
+ UPDATE sources SET unit_lo = g.lo, unit_hi = g.hi
16291
+ FROM (SELECT source_id, MIN(rowid) AS lo, MAX(rowid) AS hi FROM line_units GROUP BY source_id) AS g
16292
+ WHERE g.source_id = sources.id;
16293
+ `;
16232
16294
  var MIGRATIONS = [
16233
16295
  { version: 1, sql: DDL },
16234
16296
  { version: 2, sql: DDL_V2 },
16235
16297
  { version: 3, sql: DDL_V3 },
16236
16298
  { version: 4, sql: DDL_V4 },
16237
16299
  { version: 5, sql: DDL_V5 },
16238
- { version: 6, sql: DDL_V6 }
16300
+ { version: 6, sql: DDL_V6 },
16301
+ { version: 7, sql: DDL_V7 }
16239
16302
  ];
16240
16303
  function applyMigrations(db, fromVersion) {
16241
16304
  if (fromVersion === SCHEMA_VERSION2) return;
@@ -16302,26 +16365,26 @@ function errCode(err) {
16302
16365
  return err.code ?? "";
16303
16366
  }
16304
16367
  function publishWithoutLink(tmp, path8) {
16305
- const claim3 = path8 + DB_PUBLISH_CLAIM_SUFFIX;
16368
+ const claim4 = path8 + DB_PUBLISH_CLAIM_SUFFIX;
16306
16369
  const start = Date.now();
16307
16370
  for (; ; ) {
16308
16371
  if (existsSync3(path8)) return;
16309
16372
  try {
16310
- mkdirSync2(claim3);
16373
+ mkdirSync2(claim4);
16311
16374
  } catch (err) {
16312
16375
  if (!DB_CLAIM_BUSY_CODES.includes(errCode(err))) throw err;
16313
16376
  if (Date.now() - start < DB_TIMEOUT_MS) {
16314
16377
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, DB_PUBLISH_POLL_MS);
16315
16378
  continue;
16316
16379
  }
16317
- const held = statSync3(claim3, { throwIfNoEntry: false });
16318
- if (held !== void 0 && held.mtimeMs < start) rmSync(claim3, { recursive: true, force: true });
16319
- throw new Error(`context.db was not published within ${DB_TIMEOUT_MS} ms: ${claim3} was held; open again`);
16380
+ const held = statSync3(claim4, { throwIfNoEntry: false });
16381
+ if (held !== void 0 && held.mtimeMs < start) rmSync(claim4, { recursive: true, force: true });
16382
+ throw new Error(`context.db was not published within ${DB_TIMEOUT_MS} ms: ${claim4} was held; open again`);
16320
16383
  }
16321
16384
  try {
16322
16385
  if (!existsSync3(path8)) renameSync(tmp, path8);
16323
16386
  } finally {
16324
- rmSync(claim3, { recursive: true, force: true });
16387
+ rmSync(claim4, { recursive: true, force: true });
16325
16388
  }
16326
16389
  return;
16327
16390
  }
@@ -16435,14 +16498,59 @@ function metaTake(db, key) {
16435
16498
  });
16436
16499
  }
16437
16500
 
16501
+ // src/core/store/lost-bet.ts
16502
+ function lostKey(sessionId, key) {
16503
+ return LOSTBET_META_PREFIX + sessionId + ":" + key;
16504
+ }
16505
+ function isLostBet(db, sessionId, key) {
16506
+ return sessionId !== "" && metaGet(db, lostKey(sessionId, key)) !== null;
16507
+ }
16508
+ function markLostBet(db, sessionId, key, reason, source) {
16509
+ if (sessionId === "" || key === "") return;
16510
+ try {
16511
+ metaSet(db, lostKey(sessionId, key), JSON.stringify({ at: Date.now(), reason, source }));
16512
+ } catch {
16513
+ }
16514
+ }
16515
+ function hasBet(db, sessionId, key) {
16516
+ return sessionId !== "" && metaGet(db, BET_META_PREFIX + sessionId + ":" + key) !== null;
16517
+ }
16518
+ function noteBet(db, sessionId, key, source) {
16519
+ if (sessionId === "" || key === "") return;
16520
+ try {
16521
+ metaSet(db, BET_META_PREFIX + sessionId + ":" + key, source);
16522
+ } catch {
16523
+ }
16524
+ }
16525
+ function clearLostBets(db, sessionId) {
16526
+ if (sessionId === "") return;
16527
+ const lo = LOSTBET_META_PREFIX + sessionId + ":";
16528
+ const hi = LOSTBET_META_PREFIX + sessionId + ";";
16529
+ const run = (h) => {
16530
+ h.raw.prepare("DELETE FROM meta WHERE key >= ? AND key < ?").run(lo, hi);
16531
+ };
16532
+ if (db.raw.isTransaction) run(db);
16533
+ else withWrite(db, run);
16534
+ }
16535
+ function betKeyOfLabel(label2) {
16536
+ if (label2.startsWith(SUBAGENT_SOURCE_PREFIX)) return null;
16537
+ const hash = label2.lastIndexOf("#");
16538
+ if (hash <= 0) return null;
16539
+ const stem = label2.slice(0, hash);
16540
+ const colon = stem.indexOf(":");
16541
+ if (colon <= 0) return null;
16542
+ if (colon + 1 < stem.length || stem.startsWith(MCP_SERVER_TOOL_PREFIX)) return stem;
16543
+ return null;
16544
+ }
16545
+
16438
16546
  // src/core/journal/append.ts
16439
16547
  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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
16440
16548
  var INSERT_SQL = "INSERT INTO " + COLUMNS;
16441
16549
  var INSERT_COST_SQL = "INSERT OR IGNORE INTO " + COLUMNS;
16442
16550
  var COST_SEQ_SQL = "SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";
16443
- function appendEvent(db, row5) {
16551
+ function appendEvent(db, row5, at2) {
16444
16552
  return withWrite(db, (h) => {
16445
- const now = Date.now();
16553
+ const now = at2 ?? Date.now();
16446
16554
  const isCost = row5.kind === "cost";
16447
16555
  const res = h.raw.prepare(isCost ? INSERT_COST_SQL : INSERT_SQL).run(
16448
16556
  row5.session_id,
@@ -18548,18 +18656,6 @@ function reserveSource(db, src, chunks) {
18548
18656
  return Number(row5.id);
18549
18657
  });
18550
18658
  }
18551
- function finishReserved(db, id, src, chunks, units) {
18552
- try {
18553
- insertChunks(db, id, src, chunks);
18554
- insertUnits(db, id, src.sessionId, units);
18555
- } catch (err) {
18556
- withWrite(db, (h) => {
18557
- deleteChunkRows(h.raw, { sourceId: id });
18558
- h.raw.prepare("DELETE FROM sources WHERE id = ?").run(id);
18559
- });
18560
- throw err;
18561
- }
18562
- }
18563
18659
  function insertChunks(db, id, src, chunks) {
18564
18660
  const batches = [];
18565
18661
  let batch = [];
@@ -18590,11 +18686,13 @@ function deleteChunkRows(raw, scope) {
18590
18686
  if (scope === "all") {
18591
18687
  raw.exec("INSERT INTO chunks_tri(chunks_tri) VALUES ('delete-all')");
18592
18688
  raw.exec("DELETE FROM line_units");
18689
+ raw.exec("UPDATE sources SET unit_lo = NULL, unit_hi = NULL WHERE unit_lo IS NOT NULL");
18593
18690
  return Number(raw.prepare("DELETE FROM chunks").run().changes);
18594
18691
  }
18595
- const [where, arg] = "sourceId" in scope ? ["source_id = ?", scope.sourceId] : ["source_id IN (SELECT id FROM sources WHERE label = ?)", scope.label];
18692
+ const [where, arg, own4] = "sourceId" in scope ? ["source_id = ?", scope.sourceId, "id = ?"] : ["source_id IN (SELECT id FROM sources WHERE label = ?)", scope.label, "label = ?"];
18596
18693
  raw.prepare(TRI_DELETE + " WHERE " + where).run(arg);
18597
18694
  raw.prepare("DELETE FROM line_units WHERE " + where).run(arg);
18695
+ raw.prepare("UPDATE sources SET unit_lo = NULL, unit_hi = NULL WHERE " + own4).run(arg);
18598
18696
  return Number(raw.prepare("DELETE FROM chunks WHERE " + where).run(arg).changes);
18599
18697
  }
18600
18698
  function toMatch(q) {
@@ -18998,43 +19096,53 @@ function parseSourceHandle(s) {
18998
19096
  function pathLabel(p) {
18999
19097
  return p.includes("\\") ? p.split("\\").join("/") : p;
19000
19098
  }
19001
- function labelStored(db, label2) {
19002
- return stmt(db.raw, "SELECT 1 AS x FROM sources WHERE label = ? LIMIT 1").get(label2) !== void 0;
19099
+ var EVERY_ROW = { scope: "project", sessionId: "", worktree: "" };
19100
+ var IN_SCOPE = "(:scope <> 'session' OR session_id = :session_id) AND (:scope <> 'worktree' OR worktree = :worktree)";
19101
+ var scopeArgs = (w) => ({ scope: w.scope, session_id: w.sessionId, worktree: w.worktree });
19102
+ function labelStored(db, label2, w) {
19103
+ 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;
19003
19104
  }
19004
- function storedLabel(db, source) {
19005
- if (labelStored(db, source)) return source;
19105
+ function storedLabel(db, source, w = EVERY_ROW) {
19106
+ if (labelStored(db, source, w)) return source;
19006
19107
  const canon = pathLabel(source);
19007
- return canon !== source && labelStored(db, canon) ? canon : source;
19108
+ return canon !== source && labelStored(db, canon, w) ? canon : source;
19008
19109
  }
19009
- function newestId(db, label2) {
19010
- const row5 = stmt(db.raw, "SELECT id FROM sources WHERE label = ? ORDER BY id DESC LIMIT 1").get(label2);
19110
+ function newestId(db, label2, w) {
19111
+ 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) });
19011
19112
  return row5 === void 0 ? null : Number(row5.id);
19012
19113
  }
19013
- function labelOfId(db, id) {
19014
- const row5 = stmt(db.raw, "SELECT label FROM sources WHERE id = ?").get(id);
19114
+ function labelOfId(db, id, w) {
19115
+ const row5 = stmt(db.raw, "SELECT label FROM sources WHERE id = :id AND " + IN_SCOPE).get({ id, ...scopeArgs(w) });
19015
19116
  return row5 === void 0 ? null : row5.label;
19016
19117
  }
19017
- function pickSource(db, source, suffix = true) {
19018
- const named2 = storedLabel(db, source);
19118
+ function pickIn(db, source, suffix, w) {
19119
+ const named2 = storedLabel(db, source, w);
19019
19120
  const id = parseSourceHandle(source);
19020
- const own4 = newestId(db, named2);
19121
+ const own4 = newestId(db, named2, w);
19021
19122
  if (own4 !== null) {
19022
- const otherLabel = id === null || id === own4 ? null : labelOfId(db, id);
19123
+ const otherLabel = id === null || id === own4 ? null : labelOfId(db, id, EVERY_ROW);
19023
19124
  return { label: named2, id: own4, via: "label", other: otherLabel === null || otherLabel === named2 ? null : { id, label: otherLabel } };
19024
19125
  }
19025
19126
  if (id !== null) {
19026
- const label2 = labelOfId(db, id);
19127
+ const label2 = labelOfId(db, id, w);
19027
19128
  if (label2 !== null) return { label: label2, id, via: "handle", other: null };
19028
19129
  }
19029
19130
  if (suffix) {
19030
19131
  const prefix = named2 + LABEL_SUFFIX_SEP;
19031
- const rows = stmt(db.raw, "SELECT id, label FROM sources WHERE substr(label, 1, ?) = ? ORDER BY id DESC").all(prefix.length, prefix);
19132
+ 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) });
19032
19133
  for (const r of rows) {
19033
19134
  if (r.label.lastIndexOf(LABEL_SUFFIX_SEP) === named2.length) return { label: r.label, id: Number(r.id), via: "suffix", other: null };
19034
19135
  }
19035
19136
  }
19036
19137
  return { label: source, id: null, via: "none", other: null };
19037
19138
  }
19139
+ function pickSource(db, source, suffix = true, w = EVERY_ROW) {
19140
+ if (w.scope !== "project") {
19141
+ const here = pickIn(db, source, suffix, w);
19142
+ if (here.via !== "none") return here;
19143
+ }
19144
+ return pickIn(db, source, suffix, EVERY_ROW);
19145
+ }
19038
19146
  function collisionLine(value, pick4) {
19039
19147
  if (pick4.other === null || pick4.id === null) return null;
19040
19148
  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) + ".");
@@ -19101,10 +19209,15 @@ function insertUnits(db, sourceId, sessionId, units) {
19101
19209
  const from = start;
19102
19210
  withWrite(db, (h) => {
19103
19211
  const ins = h.raw.prepare("INSERT INTO line_units(body, source_id, session_id, ord) VALUES (?, ?, ?, ?)");
19212
+ let lo = Number.MAX_SAFE_INTEGER;
19213
+ let hi = 0;
19104
19214
  for (let i = from; i < end; i++) {
19105
19215
  const u = units[i];
19106
- ins.run(u.body, sourceId, sessionId, u.ord);
19216
+ const rid = Number(ins.run(u.body, sourceId, sessionId, u.ord).lastInsertRowid);
19217
+ if (rid < lo) lo = rid;
19218
+ if (rid > hi) hi = rid;
19107
19219
  }
19220
+ h.raw.prepare("UPDATE sources SET unit_lo = min(coalesce(unit_lo, ?), ?), unit_hi = max(coalesce(unit_hi, ?), ?) WHERE id = ?").run(lo, lo, hi, hi, sourceId);
19108
19221
  });
19109
19222
  start = end;
19110
19223
  }
@@ -19136,48 +19249,25 @@ function readMaxSourceId(db) {
19136
19249
  function queryUnits(db, sessionId, q, limit, maxSourceId = Number.MAX_SAFE_INTEGER) {
19137
19250
  const match = searchTerms(q).join(" OR ");
19138
19251
  if (match === "" || sessionId === "") return [];
19139
- const rows = db.raw.prepare(
19140
- "SELECT u.source_id AS source_id, u.ord AS ord, u.body AS body, -bm25(line_units) AS score, s.label AS label FROM line_units u JOIN sources s ON s.id = u.source_id WHERE line_units MATCH ? AND u.session_id = ? AND s.id <= ? ORDER BY bm25(line_units) LIMIT ?"
19141
- ).all(match, sessionId, maxSourceId, limit);
19252
+ const span2 = stmt(
19253
+ db.raw,
19254
+ "SELECT MIN(unit_lo) AS lo, MAX(unit_hi) AS hi FROM sources WHERE session_id = ? AND id <= ? AND unit_lo IS NOT NULL"
19255
+ ).get(sessionId, maxSourceId);
19256
+ if (span2 === void 0 || span2.lo === null || span2.hi === null) return [];
19257
+ const rows = stmt(
19258
+ db.raw,
19259
+ "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 ?"
19260
+ ).all(match, span2.lo, span2.hi, sessionId, maxSourceId, limit);
19142
19261
  return rows.map((r) => ({ sourceId: Number(r.source_id), ord: Number(r.ord), label: r.label, body: r.body, score: r.score }));
19143
19262
  }
19144
19263
 
19145
- // src/core/index/units.ts
19146
- function indentOf(line) {
19147
- let n = 0;
19148
- while (n < line.length && (line[n] === " " || line[n] === " ")) n++;
19149
- return n;
19150
- }
19151
- function buildUnits(text) {
19152
- const lines = text.split("\n");
19153
- const stack2 = [];
19154
- const out = [];
19155
- let left = UNITS_ANCESTOR_FACTOR * Buffer.byteLength(text, "utf8");
19156
- for (let i = 0; i < lines.length; i++) {
19157
- const line = lines[i].endsWith("\r") ? lines[i].slice(0, -1) : lines[i];
19158
- const indent = indentOf(line);
19159
- if (indent === line.length) continue;
19160
- while (stack2.length > 0 && stack2[stack2.length - 1].indent >= indent) stack2.pop();
19161
- const bytes5 = Buffer.byteLength(line, "utf8");
19162
- let size = bytes5;
19163
- let from = stack2.length;
19164
- while (from > 0) {
19165
- const add = stack2[from - 1].bytes + 1;
19166
- if (size + add > RECALL_BUDGET_BYTES || size - bytes5 + add > left) break;
19167
- size += add;
19168
- from--;
19169
- }
19170
- left -= size - bytes5;
19171
- out.push({ ord: i, body: [...stack2.slice(from).map((s) => s.line), line].join("\n") });
19172
- stack2.push({ indent, line, bytes: bytes5 });
19173
- }
19174
- return out;
19175
- }
19176
-
19177
19264
  // src/core/compaction/candidates.ts
19178
19265
  function firstLine2(body) {
19179
- const nl = body.indexOf("\n");
19180
- return (nl < 0 ? body : body.slice(0, nl)).replaceAll("\r", " ");
19266
+ const i = body.length - body.trimStart().length;
19267
+ if (i === body.length) return "";
19268
+ const start = i === 0 ? 0 : body.lastIndexOf("\n", i) + 1;
19269
+ const nl = body.indexOf("\n", i);
19270
+ return (start === 0 && nl < 0 ? body : body.slice(start, nl < 0 ? body.length : nl)).replaceAll("\r", " ");
19181
19271
  }
19182
19272
  function make(section, row5, text, repeatCount, query) {
19183
19273
  const bytes5 = Buffer.byteLength(text, "utf8");
@@ -19720,7 +19810,7 @@ function cutPoint(src, start, end, scratch) {
19720
19810
  const r = encoder.encodeInto(src.slice(start, limit), scratch);
19721
19811
  return { end: start + r.read, written: r.written };
19722
19812
  }
19723
- function merge2(src, blocks, join29, cap, lineCut) {
19813
+ function merge2(src, blocks, join30, cap, lineCut) {
19724
19814
  const out = [];
19725
19815
  const scratch = new Uint8Array(cap);
19726
19816
  let wide;
@@ -19730,7 +19820,7 @@ function merge2(src, blocks, join29, cap, lineCut) {
19730
19820
  out.push({ ord: out.length, text: src.slice(start, end), bytes: bytes5 });
19731
19821
  };
19732
19822
  for (const b of blocks) {
19733
- if (cur !== void 0 && !join29) {
19823
+ if (cur !== void 0 && !join30) {
19734
19824
  emit(cur.start, cur.end, curBytes);
19735
19825
  cur = void 0;
19736
19826
  }
@@ -20051,37 +20141,255 @@ function lineShape(text) {
20051
20141
  return { header, units };
20052
20142
  }
20053
20143
 
20054
- // src/core/index/text.ts
20055
- function storeText(db, project, sessionId, sourceKind, label2, text, kind, chunks = chunkText(text, kind)) {
20056
- const sourceId = ftsInsert(db, {
20057
- projectKey: project.projectKey,
20058
- sessionId,
20059
- worktree: project.worktree,
20060
- agent: project.agent,
20061
- kind: sourceKind,
20062
- label: label2,
20063
- bytes: Buffer.byteLength(text, "utf8"),
20064
- chunkCount: chunks.length,
20065
- createdAt: Date.now()
20066
- }, chunks);
20067
- return { sourceId, chunks: chunks.length };
20144
+ // src/core/hooks/spool.ts
20145
+ import { join as join7 } from "node:path";
20146
+
20147
+ // src/core/index/units.ts
20148
+ function indentOf(line) {
20149
+ let n = 0;
20150
+ while (n < line.length && (line[n] === " " || line[n] === " ")) n++;
20151
+ return n;
20068
20152
  }
20069
- function indexText(db, ctx, sessionId, source, text, kind, chunks) {
20070
- return storeText(db, ctx, sessionId, "content", source, text, kind, chunks);
20153
+ function buildUnits(text) {
20154
+ const lines = text.split("\n");
20155
+ const stack2 = [];
20156
+ const out = [];
20157
+ let left = UNITS_ANCESTOR_FACTOR * Buffer.byteLength(text, "utf8");
20158
+ for (let i = 0; i < lines.length; i++) {
20159
+ const line = lines[i].endsWith("\r") ? lines[i].slice(0, -1) : lines[i];
20160
+ const indent = indentOf(line);
20161
+ if (indent === line.length) continue;
20162
+ while (stack2.length > 0 && stack2[stack2.length - 1].indent >= indent) stack2.pop();
20163
+ const bytes5 = Buffer.byteLength(line, "utf8");
20164
+ let size = bytes5;
20165
+ let from = stack2.length;
20166
+ while (from > 0) {
20167
+ const add = stack2[from - 1].bytes + 1;
20168
+ if (size + add > RECALL_BUDGET_BYTES || size - bytes5 + add > left) break;
20169
+ size += add;
20170
+ from--;
20171
+ }
20172
+ left -= size - bytes5;
20173
+ out.push({ ord: i, body: [...stack2.slice(from).map((s) => s.line), line].join("\n") });
20174
+ stack2.push({ indent, line, bytes: bytes5 });
20175
+ }
20176
+ return out;
20071
20177
  }
20072
20178
 
20073
- // src/core/hooks/detached.ts
20074
- async function write(project, row5) {
20179
+ // src/core/hooks/spool.ts
20180
+ var { mkdirSync: mkdirSync3, readdirSync: readdirSync3, readFileSync: readFileSync5, renameSync: renameSync2, statSync: statSync4, unlinkSync, utimesSync, writeFileSync } = process.getBuiltinModule("node:fs");
20181
+ var SEEN_TAG = ".seen";
20182
+ var OP_SUFFIX = ".json";
20183
+ var CLAIM_SUFFIX = ".claim";
20184
+ var TMP_SUFFIX = ".tmp";
20185
+ var BAD_SUFFIX = ".bad";
20186
+ var NAME_TIME_DIGITS = 15;
20187
+ var NAME_SEQ_DIGITS = 6;
20188
+ var nameSeq = 0;
20189
+ function isBusy(err) {
20190
+ const code = err?.errcode;
20191
+ return typeof code === "number" && (code & SQLITE_PRIMARY_CODE_MASK) === SQLITE_BUSY_CODE;
20192
+ }
20193
+ function message(err) {
20194
+ return err instanceof Error ? err.message : String(err);
20195
+ }
20196
+ async function hookDb(project) {
20197
+ const db = await openDb(project);
20198
+ db.raw.exec("PRAGMA busy_timeout = " + String(HOOK_BUSY_MS));
20199
+ return db;
20200
+ }
20201
+ function spoolDir(project) {
20202
+ return join7(project.projectDir, HOOK_SPOOL_DIR);
20203
+ }
20204
+ function spool(project, op) {
20205
+ const dir = spoolDir(project);
20206
+ mkdirSync3(dir, { recursive: true });
20207
+ const name = String(Date.now()).padStart(NAME_TIME_DIGITS, "0") + "-" + String(process.pid) + "-" + String(nameSeq++).padStart(NAME_SEQ_DIGITS, "0");
20208
+ const tmp = join7(dir, name + TMP_SUFFIX);
20209
+ writeFileSync(tmp, JSON.stringify(op));
20210
+ renameSync2(tmp, join7(dir, name + (op.t === "seen" ? SEEN_TAG : "") + OP_SUFFIX));
20211
+ }
20212
+ function runOp(db, op, chunks, cur) {
20213
+ if (op.t === "row") {
20214
+ appendEvent(db, op.row, op.at);
20215
+ return null;
20216
+ }
20217
+ if (op.t === "seen") {
20218
+ withWrite(db, (h) => {
20219
+ const have = parseList(metaGet(h, op.key));
20220
+ const add = op.add.filter((v) => !have.includes(v));
20221
+ if (add.length > 0) metaSet(h, op.key, JSON.stringify([...have, ...add]));
20222
+ });
20223
+ return null;
20224
+ }
20225
+ const c = chunks ?? chunkText(op.text, "text", op.max);
20226
+ let id = op.id;
20227
+ if (id === null) {
20228
+ id = reserveSource(db, op.src, c);
20229
+ cur.op = { ...op, id };
20230
+ } else if (chunks === void 0) {
20231
+ const sid = id;
20232
+ const gone = withWrite(db, (h) => {
20233
+ if (h.raw.prepare("SELECT 1 AS x FROM sources WHERE id = ?").get(sid) === void 0) return true;
20234
+ deleteChunkRows(h.raw, { sourceId: sid });
20235
+ return false;
20236
+ });
20237
+ if (gone) return null;
20238
+ }
20075
20239
  try {
20076
- const db = await openDb(project);
20077
- appendEvent(db, row5);
20240
+ insertChunks(db, id, op.src, c);
20241
+ if (op.units) insertUnits(db, id, op.src.sessionId, buildUnits(op.text));
20242
+ } catch (err) {
20243
+ if (isBusy(err)) throw err;
20244
+ const sid = id;
20245
+ withWrite(db, (h) => {
20246
+ deleteChunkRows(h.raw, { sourceId: sid });
20247
+ h.raw.prepare("DELETE FROM sources WHERE id = ?").run(sid);
20248
+ });
20249
+ throw err;
20250
+ }
20251
+ return id;
20252
+ }
20253
+ function parseList(value) {
20254
+ if (value === null) return [];
20255
+ try {
20256
+ const v = JSON.parse(value);
20257
+ return Array.isArray(v) ? v.filter((x) => typeof x === "number" || typeof x === "string") : [];
20258
+ } catch {
20259
+ return [];
20260
+ }
20261
+ }
20262
+ function readSeen(project, db, key) {
20263
+ const out = [];
20264
+ const dir = spoolDir(project);
20265
+ let names = [];
20266
+ try {
20267
+ names = readdirSync3(dir);
20268
+ } catch {
20269
+ }
20270
+ for (const name of names) {
20271
+ const base = name.endsWith(CLAIM_SUFFIX) ? name.slice(0, -CLAIM_SUFFIX.length) : name;
20272
+ if (!base.endsWith(SEEN_TAG + OP_SUFFIX)) continue;
20273
+ let op = null;
20274
+ for (const n of [name, base + CLAIM_SUFFIX, base]) {
20275
+ try {
20276
+ op = JSON.parse(readFileSync5(join7(dir, n), "utf8"));
20277
+ break;
20278
+ } catch {
20279
+ }
20280
+ }
20281
+ if (op !== null && op.t === "seen" && op.key === key) out.push(...op.add);
20282
+ }
20283
+ for (const v of parseList(metaGet(db, key))) if (!out.includes(v)) out.push(v);
20284
+ return out;
20285
+ }
20286
+ var busyUntil = 0;
20287
+ function writeOrSpool(project, db, op, chunks) {
20288
+ const cur = { op };
20289
+ try {
20290
+ return runOp(db, op, chunks, cur);
20078
20291
  } catch (err) {
20079
- const message3 = err instanceof Error ? err.message : String(err);
20080
- process.stderr.write("hooks: journal write failed: " + message3 + "\n");
20292
+ if (!isBusy(err)) throw err;
20293
+ busyUntil = Date.now() + HOOK_BUSY_MS;
20294
+ spool(project, cur.op);
20295
+ return cur.op.t === "src" ? cur.op.id : null;
20081
20296
  }
20082
20297
  }
20298
+ function writeDetached(project, op, what, chunks) {
20299
+ void (async () => {
20300
+ try {
20301
+ const db = await hookDb(project);
20302
+ if (Date.now() < busyUntil) {
20303
+ spool(project, op);
20304
+ } else if (drain(project, db)) {
20305
+ busyUntil = Date.now() + HOOK_BUSY_MS;
20306
+ spool(project, op);
20307
+ } else {
20308
+ writeOrSpool(project, db, op, chunks);
20309
+ }
20310
+ } catch (err) {
20311
+ try {
20312
+ if (!isBusy(err)) throw err;
20313
+ busyUntil = Date.now() + HOOK_BUSY_MS;
20314
+ spool(project, op);
20315
+ } catch (e) {
20316
+ process.stderr.write("hooks: " + what + " write failed: " + message(e) + "\n");
20317
+ }
20318
+ }
20319
+ })();
20320
+ }
20321
+ function claim(dir, name) {
20322
+ let base = name;
20323
+ if (name.endsWith(OP_SUFFIX + CLAIM_SUFFIX)) {
20324
+ const path8 = join7(dir, name);
20325
+ try {
20326
+ if (Date.now() - statSync4(path8).mtimeMs < SPOOL_CLAIM_STALE_MS) return null;
20327
+ base = name.slice(0, -CLAIM_SUFFIX.length);
20328
+ renameSync2(path8, join7(dir, base));
20329
+ } catch {
20330
+ return null;
20331
+ }
20332
+ } else if (!name.endsWith(OP_SUFFIX)) {
20333
+ return null;
20334
+ }
20335
+ const claimed = join7(dir, base + CLAIM_SUFFIX);
20336
+ try {
20337
+ renameSync2(join7(dir, base), claimed);
20338
+ const now = /* @__PURE__ */ new Date();
20339
+ utimesSync(claimed, now, now);
20340
+ return claimed;
20341
+ } catch {
20342
+ return null;
20343
+ }
20344
+ }
20345
+ function drain(project, db) {
20346
+ const dir = spoolDir(project);
20347
+ let names;
20348
+ try {
20349
+ names = readdirSync3(dir);
20350
+ } catch {
20351
+ return false;
20352
+ }
20353
+ const start = Date.now();
20354
+ for (const name of names.sort()) {
20355
+ if (Date.now() - start > SPOOL_DRAIN_MS) return false;
20356
+ const claimed = claim(dir, name);
20357
+ if (claimed === null) continue;
20358
+ const base = claimed.slice(0, -CLAIM_SUFFIX.length);
20359
+ let op;
20360
+ try {
20361
+ op = JSON.parse(readFileSync5(claimed, "utf8"));
20362
+ } catch (err) {
20363
+ process.stderr.write("hooks: pending write unreadable: " + message(err) + "\n");
20364
+ renameSync2(claimed, base + BAD_SUFFIX);
20365
+ continue;
20366
+ }
20367
+ const cur = { op };
20368
+ try {
20369
+ runOp(db, op, void 0, cur);
20370
+ } catch (err) {
20371
+ if (isBusy(err)) {
20372
+ if (cur.op === op) {
20373
+ renameSync2(claimed, base);
20374
+ } else {
20375
+ writeFileSync(base + TMP_SUFFIX, JSON.stringify(cur.op));
20376
+ renameSync2(base + TMP_SUFFIX, base);
20377
+ unlinkSync(claimed);
20378
+ }
20379
+ return true;
20380
+ }
20381
+ process.stderr.write("hooks: pending write failed: " + message(err) + "\n");
20382
+ renameSync2(claimed, base + BAD_SUFFIX);
20383
+ continue;
20384
+ }
20385
+ unlinkSync(claimed);
20386
+ }
20387
+ return false;
20388
+ }
20389
+
20390
+ // src/core/hooks/detached.ts
20083
20391
  function appendDetached(project, sessionId, row5) {
20084
- void write(project, row5);
20392
+ writeDetached(project, { t: "row", row: row5, at: Date.now() }, "journal");
20085
20393
  }
20086
20394
 
20087
20395
  // src/core/hooks/handle-query.ts
@@ -20172,7 +20480,7 @@ function shouldHint(db, sessionId, onceKey, everyN) {
20172
20480
  }
20173
20481
 
20174
20482
  // src/core/hooks/fallback.ts
20175
- import { join as join7, resolve as resolve7 } from "node:path";
20483
+ import { join as join8, resolve as resolve7 } from "node:path";
20176
20484
  var fs = process.getBuiltinModule("node:fs");
20177
20485
  function isRec(v) {
20178
20486
  return typeof v === "object" && v !== null && !Array.isArray(v);
@@ -20200,9 +20508,9 @@ function homeOf(env) {
20200
20508
  }
20201
20509
  function hookLogPath(env) {
20202
20510
  const dir = env[DATA_DIR_ENV];
20203
- if (dir !== void 0 && dir !== "") return join7(dataRootOf(env, ""), HOOK_ERROR_LOG_FILE);
20511
+ if (dir !== void 0 && dir !== "") return join8(dataRootOf(env, ""), HOOK_ERROR_LOG_FILE);
20204
20512
  const home = homeOf(env);
20205
- return home === "" ? "" : join7(dataRootOf(env, home), HOOK_ERROR_LOG_FILE);
20513
+ return home === "" ? "" : join8(dataRootOf(env, home), HOOK_ERROR_LOG_FILE);
20206
20514
  }
20207
20515
  function errorLabel(err) {
20208
20516
  const code = isRec(err) ? err.code : void 0;
@@ -20213,7 +20521,7 @@ function logHookError(env, agent, stage, err) {
20213
20521
  try {
20214
20522
  const file2 = hookLogPath(env);
20215
20523
  if (file2 === "") return;
20216
- fs.mkdirSync(join7(file2, ".."), { recursive: true });
20524
+ fs.mkdirSync(join8(file2, ".."), { recursive: true });
20217
20525
  const line = JSON.stringify({
20218
20526
  ts: (/* @__PURE__ */ new Date()).toISOString(),
20219
20527
  agent,
@@ -20327,14 +20635,14 @@ function failureOutput(agent, raw, err, cwdFallback = "") {
20327
20635
  var { read: read2, writeSync } = process.getBuiltinModule("node:fs");
20328
20636
 
20329
20637
  // src/core/hooks/dispatch.ts
20330
- var { lstatSync: lstatSync2, readFileSync: readFileSync5 } = process.getBuiltinModule("node:fs");
20638
+ var { lstatSync: lstatSync2, readFileSync: readFileSync6 } = process.getBuiltinModule("node:fs");
20331
20639
  var ALLOW2 = { kind: "allow" };
20332
20640
  var EMPTY5 = { stdout: "", exitCode: 0 };
20333
20641
  var DIGIT_0 = 48;
20334
20642
  function isAgentId(s) {
20335
20643
  return AGENT_IDS.includes(s);
20336
20644
  }
20337
- function message(err) {
20645
+ function message2(err) {
20338
20646
  return err instanceof Error ? err.message : String(err);
20339
20647
  }
20340
20648
  function str2(v) {
@@ -20348,7 +20656,7 @@ async function handleHook(agent, raw, env) {
20348
20656
  const row5 = getAdapter(agent);
20349
20657
  const report2 = (stage, err, line) => {
20350
20658
  logHookError(env, agent, stage, err);
20351
- process.stderr.write(line ?? "hooks: " + stage + " failed: " + message(err) + "\n");
20659
+ process.stderr.write(line ?? "hooks: " + stage + " failed: " + message2(err) + "\n");
20352
20660
  };
20353
20661
  const fail7 = (stage, err, line) => {
20354
20662
  report2(stage, err, line);
@@ -20374,7 +20682,7 @@ async function handleHook(agent, raw, env) {
20374
20682
  const argv = agent === "vscode" ? [WORKSPACE_FOLDER_FLAG, ev.cwd] : process.argv;
20375
20683
  project = resolveProject(agent, { env, argv, cwd: ev.cwd, piCwd: getAdapter(agent).projectSource === "pi:ctx.cwd" ? ev.cwd : void 0 });
20376
20684
  } catch (err) {
20377
- return fail7("project", err, "hooks: no project: " + String(err.code ?? "ERROR") + " " + message(err) + "\n");
20685
+ return fail7("project", err, "hooks: no project: " + String(err.code ?? "ERROR") + " " + message2(err) + "\n");
20378
20686
  }
20379
20687
  let decision;
20380
20688
  const settle3 = {};
@@ -20419,14 +20727,15 @@ function compactText(db, ev, row5) {
20419
20727
  return renderState(readSessionEvents(db, ev.sessionId), ev.turn ?? 0, void 0, row5.toolNamePrefix);
20420
20728
  }
20421
20729
  async function sessionStart(ev, row5, project) {
20422
- if (ev.source === "compact" && hasRecall(row5)) markCompacted(await openDb(project), ev.sessionId);
20730
+ if (ev.source === "compact" && hasRecall(row5)) markCompacted(await hookDb(project), ev.sessionId);
20731
+ if (ev.source === "compact") endLostBets(await hookDb(project), ev.sessionId);
20423
20732
  if (ev.source === "compact" && row5.compactDelivery === "sessionstart") {
20424
- const db2 = await openDb(project);
20733
+ const db2 = await hookDb(project);
20425
20734
  const onceKey = COMPACT_STATE_KEY + ":" + lastSessionSeq(db2, ev.sessionId);
20426
20735
  if (!shouldHint(db2, ev.sessionId, onceKey)) return ALLOW2;
20427
20736
  return { kind: "hint", text: compactText(db2, ev, row5), onceKey };
20428
20737
  }
20429
- const db = await openDb(project);
20738
+ const db = await hookDb(project);
20430
20739
  if (row5.compactDelivery === "opencode-cache" && metaTake(db, PENDING_COMPACT_META_PREFIX + ev.sessionId) !== null) {
20431
20740
  return { kind: "hint", text: compactText(db, ev, row5), onceKey: PENDING_COMPACT_KEY };
20432
20741
  }
@@ -20454,7 +20763,7 @@ async function userPromptSubmit(ev, row5, project) {
20454
20763
  });
20455
20764
  echoDetached(ev, project, body);
20456
20765
  if (row5.compactDelivery === "pending-flag") {
20457
- const db = await openDb(project);
20766
+ const db = await hookDb(project);
20458
20767
  if (metaTake(db, PENDING_COMPACT_META_PREFIX + ev.sessionId) !== null) {
20459
20768
  return { kind: "hint", text: compactText(db, ev, row5), onceKey: PENDING_COMPACT_KEY };
20460
20769
  }
@@ -20464,7 +20773,7 @@ async function userPromptSubmit(ev, row5, project) {
20464
20773
  }
20465
20774
  async function firstTurnResume(ev, row5, project) {
20466
20775
  if (row5.eventMap.SessionStart !== void 0 || ev.sessionId === "") return null;
20467
- const db = await openDb(project);
20776
+ const db = await hookDb(project);
20468
20777
  if (hasSessionRows(db, ev.sessionId)) return null;
20469
20778
  if (!shouldHint(db, ev.sessionId, RESUME_HINT_KEY)) return null;
20470
20779
  if (!hasAgentRows(db, project.worktree, ev.agent)) return null;
@@ -20488,40 +20797,22 @@ function compactBoundary(value) {
20488
20797
  return all;
20489
20798
  }
20490
20799
  }
20491
- function seenSeqs(value) {
20492
- if (value === null) return [];
20493
- try {
20494
- const v = JSON.parse(value);
20495
- return Array.isArray(v) ? v.filter((n) => typeof n === "number") : [];
20496
- } catch {
20497
- return [];
20498
- }
20499
- }
20500
- function seenUnitKeys(value) {
20501
- if (value === null) return [];
20502
- try {
20503
- const v = JSON.parse(value);
20504
- return Array.isArray(v) ? v.filter((k) => typeof k === "string") : [];
20505
- } catch {
20506
- return [];
20507
- }
20508
- }
20509
20800
  async function recall(ev, row5, project, prompt) {
20510
20801
  if (!hasRecall(row5) || ev.sessionId === "") return ALLOW2;
20511
- const db = await openDb(project);
20802
+ const db = await hookDb(project);
20512
20803
  const compacted = metaGet(db, COMPACTED_META_PREFIX + ev.sessionId);
20513
20804
  if (compacted === null) return ALLOW2;
20514
20805
  const boundary = compactBoundary(compacted);
20515
20806
  const seenKey = RECALL_SEEN_META_PREFIX + ev.sessionId;
20516
- const seen = seenSeqs(metaGet(db, seenKey));
20807
+ const seen = readSeen(project, db, seenKey).filter((n) => typeof n === "number");
20517
20808
  const unitsKey = RECALL_UNITS_SEEN_META_PREFIX + ev.sessionId;
20518
- const seenUnits = seenUnitKeys(metaGet(db, unitsKey));
20809
+ const seenUnits = readSeen(project, db, unitsKey).filter((k) => typeof k === "string");
20519
20810
  const units = queryUnits(db, ev.sessionId, recallQueryText(prompt), RECALL_UNIT_CANDIDATES, boundary.source);
20520
20811
  const rows = readRecallRows(db, ev.sessionId, project.worktree, RECALL_MAX_ROWS, boundary.seq);
20521
20812
  const picked = pickRecall(rows, prompt, new Set(seen), units, new Set(seenUnits));
20522
20813
  if (picked.text === "") return ALLOW2;
20523
- if (picked.seqs.length > 0) metaSet(db, seenKey, JSON.stringify([...seen, ...picked.seqs]));
20524
- if (picked.units !== void 0) metaSet(db, unitsKey, JSON.stringify([...seenUnits, ...picked.units]));
20814
+ if (picked.seqs.length > 0) writeDetached(project, { t: "seen", key: seenKey, add: picked.seqs }, "recall");
20815
+ if (picked.units !== void 0) writeDetached(project, { t: "seen", key: unitsKey, add: picked.units }, "recall");
20525
20816
  return { kind: "hint", text: picked.text, onceKey: RECALL_KEY };
20526
20817
  }
20527
20818
  function optionsKey(sessionId) {
@@ -20541,7 +20832,7 @@ function readOptions(value) {
20541
20832
  function echoDetached(ev, project, prompt) {
20542
20833
  if (ev.sessionId === "") return;
20543
20834
  const key = optionsKey(ev.sessionId);
20544
- void openDb(project).then((db) => {
20835
+ void hookDb(project).then((db) => {
20545
20836
  if (metaGet(db, key) === null) return;
20546
20837
  const taken = metaTake(db, key);
20547
20838
  const offered = taken === null ? null : readOptions(taken);
@@ -20549,12 +20840,12 @@ function echoDetached(ev, project, prompt) {
20549
20840
  const part = optionEchoDecision(prompt, offered.labels, offered.seq);
20550
20841
  if (part !== null) writeDecisions(db, ev, project, [part]);
20551
20842
  }).catch((err) => {
20552
- process.stderr.write("hooks: decision write failed: " + message(err) + "\n");
20843
+ process.stderr.write("hooks: decision write failed: " + message2(err) + "\n");
20553
20844
  });
20554
20845
  }
20555
20846
  function writeDecisions(db, ev, project, parts) {
20556
20847
  for (const part of parts) {
20557
- appendEvent(db, {
20848
+ writeOrSpool(project, db, { t: "row", at: Date.now(), row: {
20558
20849
  session_id: ev.sessionId,
20559
20850
  worktree: project.worktree,
20560
20851
  agent: ev.agent,
@@ -20569,22 +20860,22 @@ function writeDecisions(db, ev, project, parts) {
20569
20860
  turn: ev.turn ?? 0,
20570
20861
  sandbox_bytes: 0,
20571
20862
  returned_bytes: 0
20572
- });
20573
- indexText(db, project, ev.sessionId, DECISION_SOURCE, part.body, "text");
20863
+ } });
20864
+ writeOrSpool(project, db, { t: "src", id: null, src: sourceRowOf(project, ev.sessionId, DECISION_SOURCE), text: part.body, max: MAX_CHUNK_BYTES, units: false });
20574
20865
  }
20575
20866
  }
20576
20867
  function askDetached(ev, project, tool, text) {
20577
20868
  const parts = answerDecisions(text);
20578
20869
  const labels = parts.length === 0 ? askOptionLabels(tool.input) : [];
20579
20870
  if (parts.length === 0 && labels.length === 0) return;
20580
- void openDb(project).then((db) => {
20871
+ void hookDb(project).then((db) => {
20581
20872
  if (parts.length > 0) return writeDecisions(db, ev, project, parts);
20582
20873
  const prompts = readSessionEvents(db, ev.sessionId, "prompt");
20583
20874
  const last2 = prompts[prompts.length - 1];
20584
20875
  if (last2 === void 0 || ev.sessionId === "") return;
20585
20876
  metaSet(db, optionsKey(ev.sessionId), JSON.stringify({ seq: last2.seq, labels }));
20586
20877
  }).catch((err) => {
20587
- process.stderr.write("hooks: decision write failed: " + message(err) + "\n");
20878
+ process.stderr.write("hooks: decision write failed: " + message2(err) + "\n");
20588
20879
  });
20589
20880
  }
20590
20881
  function toolSetSources(ev, project, env) {
@@ -20620,7 +20911,7 @@ function caseB(ev, row5, d0, userDeny) {
20620
20911
  if (tool === void 0 || !isShell(tool, row5) || isUserPolicyDeny(d0.reason, row5)) return d0;
20621
20912
  const command = tool.input.command;
20622
20913
  if (typeof command !== "string") return d0;
20623
- const wrapper = '"' + join8(dirname4(process.argv[1] ?? ""), RUN_WRAPPER_FILE) + '"';
20914
+ const wrapper = '"' + join9(dirname4(process.argv[1] ?? ""), RUN_WRAPPER_FILE) + '"';
20624
20915
  const rewritten = [RUN_WRAPPER_NODE, wrapper, b64(command), b64(JSON.stringify(userDeny ?? [])), b64(str2(tool.input.description))].join(" ");
20625
20916
  return { kind: "deny", reason: SUBAGENT_RUN_DENY, rewritten };
20626
20917
  }
@@ -20661,7 +20952,8 @@ async function postToolUse(ev, row5, project, env, settle3) {
20661
20952
  const tool = ev.tool;
20662
20953
  if (tool === void 0 || tool.canonicalName.startsWith(OWN_TOOL_PREFIX)) return ALLOW2;
20663
20954
  const result = ev.result ?? { isError: false, bytes: 0 };
20664
- const text = wholeOutput(result, ev.sessionId, env);
20955
+ const whole2 = wholeOutput(result, ev.sessionId, env);
20956
+ const text = whole2.text;
20665
20957
  if (result.persistedPath !== void 0) result.bytes = Buffer.byteLength(text);
20666
20958
  if (tool.canonicalName === DECISION_TOOL) askDetached(ev, project, tool, text);
20667
20959
  const kind = journalKind(tool, row5, result.isError);
@@ -20688,7 +20980,7 @@ async function postToolUse(ev, row5, project, env, settle3) {
20688
20980
  };
20689
20981
  let decision;
20690
20982
  try {
20691
- decision = await postReplace(ev, row5, project, env, tool, result, text);
20983
+ decision = await postReplace(ev, row5, project, env, tool, result, text, whole2.file);
20692
20984
  } catch (err) {
20693
20985
  journal(result.bytes);
20694
20986
  throw err;
@@ -20702,19 +20994,25 @@ function ownRead(ev, tool, env) {
20702
20994
  const p = READ_PATH_KEYS.map((k) => tool.input[k]).find((v) => typeof v === "string" && v !== "");
20703
20995
  return p !== void 0 && isOwnFile(ev.agent, ev.cwd, p, env);
20704
20996
  }
20705
- async function postReplace(ev, row5, project, env, tool, result, text) {
20997
+ async function postReplace(ev, row5, project, env, tool, result, text, persistedFile) {
20998
+ if (boundedRead(tool)) {
20999
+ await rangedAfterBet(ev, row5, project, tool);
21000
+ return ALLOW2;
21001
+ }
20706
21002
  if (result.bytes <= REPLACE_TRIGGER_BYTES) return ALLOW2;
20707
- if (boundedRead(tool)) return ALLOW2;
20708
21003
  if (ompRangedRead(ev, tool)) return ALLOW2;
20709
21004
  if (ownRead(ev, tool, env)) return ALLOW2;
21005
+ if (SKILL_LOAD_TOOLS.includes(tool.canonicalName)) return ALLOW2;
20710
21006
  if (result.keep === true) return ALLOW2;
20711
21007
  if (!hasReplace(row5)) return ALLOW2;
20712
21008
  let label2;
20713
21009
  let caller = { ctx: true, shell: true, read: false };
21010
+ let canRead = true;
20714
21011
  if (isSubagentCall(ev)) {
20715
21012
  const set3 = toolSetForAgentType(ev, toolSetSources(ev, project, env));
20716
21013
  const subCase = pickSubagentCase(ev, set3);
20717
21014
  const has3 = (names) => set3 !== null && names.some((n) => set3.includes(n));
21015
+ canRead = has3(row5.nativeTools.read ?? []);
20718
21016
  caller = {
20719
21017
  ctx: subCase === "A",
20720
21018
  shell: has3(row5.nativeTools.shell),
@@ -20727,29 +21025,53 @@ async function postReplace(ev, row5, project, env, tool, result, text) {
20727
21025
  }
20728
21026
  const intent = [tool.input.description, tool.input.command, tool.input.file_path, tool.input.pattern, tool.input.url, tool.name].map(str2).find((v) => v.trim() !== "") ?? tool.canonicalName;
20729
21027
  const chunks = chunkText(text, "text", REPLACE_CHUNK_BYTES);
20730
- const db = await openDb(project);
21028
+ const db = await hookDb(project);
21029
+ const betOn = betKey(ev, tool);
21030
+ if (result.bytes <= OUTPUT_CAP && betOn !== "" && isLostBet(db, ev.sessionId, betOn)) return ALLOW2;
21031
+ const op = { t: "src", id: null, src: sourceRowOf(project, ev.sessionId, label2), text, max: REPLACE_CHUNK_BYTES, units: true };
20731
21032
  let sourceId;
20732
21033
  if (result.bytes <= SYNC_INDEX_MAX_BYTES) {
20733
- sourceId = indexText(db, project, ev.sessionId, label2, text, "text", chunks).sourceId;
20734
- insertUnits(db, sourceId, ev.sessionId, buildUnits(text));
21034
+ sourceId = writeOrSpool(project, db, op, chunks);
20735
21035
  } else {
20736
- sourceId = reserveSource(db, sourceRowOf(project, ev.sessionId, label2), chunks);
20737
- indexDetached(project, ev.sessionId, sourceId, label2, text, chunks);
21036
+ sourceId = reserveOrSpool(project, db, op, chunks);
21037
+ if (sourceId !== null) indexDetached(project, { ...op, id: sourceId }, chunks);
20738
21038
  }
20739
- const handle = sourceHandle(sourceId);
21039
+ if (pluginMcpCall(tool)) return ALLOW2;
21040
+ const handle = sourceId === null ? label2 : sourceHandle(sourceId);
21041
+ if (RANGE_READ_TOOLS.includes(tool.canonicalName) && betOn !== "" && !hasBet(db, ev.sessionId, betOn)) noteBet(db, ev.sessionId, betOn, handle);
20740
21042
  const prompt = await lastPrompt(project, ev.sessionId);
20741
21043
  const rankQuery = prompt.trim() === "" ? void 0 : intent + " " + prompt;
20742
21044
  const handleLine = caller.ctx ? REPLACE_HANDLE_LINE(intent, handle, result.bytes, row5.toolNamePrefix, askedWords(intent, prompt, text)) : SUBAGENT_HANDLE_LINE(handle, result.bytes, caller.read);
20743
21045
  const budget = replaceBudget(handleLine, moreLine2(intent, label2));
20744
- const pointer = handleLine + (caller.shell && ev.agent === RUN_WRAPPER_AGENT ? searchTwin(handle, intent, project) : "");
21046
+ const pointer = handleLine + (caller.shell && ev.agent === RUN_WRAPPER_AGENT && sourceId !== null ? searchTwin(handle, intent, project) : "") + (persistedFile !== void 0 && canRead ? PERSISTED_FILE_LINE(persistedFile) : "");
20745
21047
  const digest = shapeDigest(text, rankQuery ?? intent, SHAPE_RETURN_BYTES);
20746
21048
  if (digest !== null) return { kind: "replace", output: replaceOutput(digest, pointer) };
20747
21049
  const selected = selectChunksInMemory(chunks, intent, budget, label2, rankQuery);
20748
21050
  return { kind: "replace", output: selected.more !== null ? replaceOutput(selected.text, pointer) : selected.text };
20749
21051
  }
21052
+ function betKey(ev, tool) {
21053
+ if (RANGE_READ_TOOLS.includes(tool.canonicalName)) {
21054
+ const p = READ_PATH_KEYS.map((k) => tool.input[k]).find((v) => typeof v === "string" && v !== "");
21055
+ return p === void 0 ? "" : tool.canonicalName + ":" + resolve8(ev.cwd, p);
21056
+ }
21057
+ return betKeyOfLabel(mainLabel(tool, ev)) ?? "";
21058
+ }
21059
+ async function rangedAfterBet(ev, row5, project, tool) {
21060
+ if (ev.sessionId === "" || !hasReplace(row5)) return;
21061
+ const key = betKey(ev, tool);
21062
+ if (key === "") return;
21063
+ try {
21064
+ const db = await hookDb(project);
21065
+ if (hasBet(db, ev.sessionId, key) && !isLostBet(db, ev.sessionId, key)) markLostBet(db, ev.sessionId, key, "ranged-read", tool.callId ?? "");
21066
+ } catch {
21067
+ }
21068
+ }
21069
+ function pluginMcpCall(tool) {
21070
+ return tool.callId !== void 0 && tool.callId.startsWith(PLUGIN_CALL_ID_PREFIX) && tool.name.startsWith(MCP_SERVER_TOOL_PREFIX);
21071
+ }
20750
21072
  function searchTwin(handle, intent, project) {
20751
21073
  const terms = Buffer.byteLength(intent, "utf8") > ECHO_MAX_BYTES ? "" : intent;
20752
- return SEARCH_TWIN_LINE(join8(dirname4(process.argv[1] ?? ""), SEARCH_WRAPPER_FILE), handle, terms, project.worktree);
21074
+ return SEARCH_TWIN_LINE(join9(dirname4(process.argv[1] ?? ""), SEARCH_WRAPPER_FILE), handle, terms, project.worktree);
20753
21075
  }
20754
21076
  function boundedRead(tool) {
20755
21077
  return RANGE_READ_TOOLS.includes(tool.canonicalName) && READ_RANGE_KEYS.some((k) => tool.input[k] !== void 0 && tool.input[k] !== null);
@@ -20809,7 +21131,7 @@ function replaceBudget(handleLine, more) {
20809
21131
  }
20810
21132
  function hostToolResult(file2, sessionId, env) {
20811
21133
  if (sessionId === "" || sessionId.includes(sep3) || sessionId.includes("/")) return false;
20812
- const projects = join8(claudeDirOf(env, homeDirOf(env) ?? ""), PROJECTS_DIR_NAME);
21134
+ const projects = join9(claudeDirOf(env, homeDirOf(env) ?? ""), PROJECTS_DIR_NAME);
20813
21135
  const steps = relative3(projects, resolve8(file2)).split(sep3);
20814
21136
  if (steps.length !== 4 || steps.includes("..") || steps.includes("")) return false;
20815
21137
  if (steps[1] !== sessionId || steps[2] !== CLAUDE_TOOL_RESULTS_DIR_NAME) return false;
@@ -20818,20 +21140,20 @@ function hostToolResult(file2, sessionId, env) {
20818
21140
  }
20819
21141
  function wholeOutput(result, sessionId, env) {
20820
21142
  const head2 = result.text ?? "";
20821
- if (result.persistedPath === void 0) return head2;
21143
+ if (result.persistedPath === void 0) return { text: head2 };
20822
21144
  try {
20823
21145
  if (!hostToolResult(result.persistedPath, sessionId, env)) {
20824
21146
  logHookError(env, "claude-code", "persisted-output", new Error("persisted output path is outside this session's tool-results dir or too large; kept the head"));
20825
- return head2;
21147
+ return { text: head2 };
20826
21148
  }
20827
- return readFileSync5(result.persistedPath, "utf8");
21149
+ return { text: readFileSync6(result.persistedPath, "utf8"), file: result.persistedPath };
20828
21150
  } catch {
20829
- return head2;
21151
+ return { text: head2 };
20830
21152
  }
20831
21153
  }
20832
21154
  async function lastPrompt(project, sessionId) {
20833
21155
  try {
20834
- return readLastPrompt(await openDb(project), sessionId);
21156
+ return readLastPrompt(await hookDb(project), sessionId);
20835
21157
  } catch {
20836
21158
  return "";
20837
21159
  }
@@ -20842,22 +21164,34 @@ function mainLabel(tool, ev) {
20842
21164
  const head2 = (tool.canonicalName + ":" + (nl < 0 ? cmd : cmd.slice(0, nl))).slice(0, SOURCE_LABEL_MAX_CHARS);
20843
21165
  return head2 + "#" + (tool.callId ?? String(ev.turn ?? 0));
20844
21166
  }
20845
- function indexDetached(project, sessionId, sourceId, label2, text, chunks) {
20846
- void openDb(project).then((db) => {
20847
- finishReserved(db, sourceId, sourceRowOf(project, sessionId, label2), chunks, buildUnits(text));
20848
- }).catch((err) => {
20849
- process.stderr.write("hooks: index write failed: " + message(err) + "\n");
20850
- });
21167
+ function indexDetached(project, op, chunks) {
21168
+ writeDetached(project, op, "index", chunks);
21169
+ }
21170
+ function reserveOrSpool(project, db, op, chunks) {
21171
+ try {
21172
+ return reserveSource(db, op.src, chunks);
21173
+ } catch (err) {
21174
+ if (!isBusy(err)) throw err;
21175
+ spool(project, op);
21176
+ return null;
21177
+ }
20851
21178
  }
20852
21179
  function sourceRowOf(project, sessionId, label2) {
20853
21180
  return { sessionId, worktree: project.worktree, agent: project.agent, kind: "content", label: label2, createdAt: Date.now() };
20854
21181
  }
20855
21182
  async function preCompact(ev, row5, project) {
20856
- const db = await openDb(project);
21183
+ const db = await hookDb(project);
20857
21184
  metaSet(db, PENDING_COMPACT_META_PREFIX + ev.sessionId, PENDING_COMPACT_FLAG);
20858
21185
  if (hasRecall(row5)) markCompacted(db, ev.sessionId);
21186
+ endLostBets(db, ev.sessionId);
20859
21187
  return ALLOW2;
20860
21188
  }
21189
+ function endLostBets(db, sessionId) {
21190
+ try {
21191
+ clearLostBets(db, sessionId);
21192
+ } catch {
21193
+ }
21194
+ }
20861
21195
  function usage(ev, project) {
20862
21196
  appendDetached(project, ev.sessionId, {
20863
21197
  session_id: ev.sessionId,
@@ -20935,7 +21269,7 @@ function buildChildEnv(parent, extra) {
20935
21269
  }
20936
21270
 
20937
21271
  // src/core/sandbox/runtimes.ts
20938
- import { accessSync, constants as fsConstants, statSync as statSync4 } from "node:fs";
21272
+ import { accessSync, constants as fsConstants, statSync as statSync5 } from "node:fs";
20939
21273
  import path from "node:path";
20940
21274
 
20941
21275
  // src/core/sandbox/path-entries.ts
@@ -20980,7 +21314,7 @@ function fileNames(name, pathExt) {
20980
21314
  function probe(full) {
20981
21315
  let st;
20982
21316
  try {
20983
- st = statSync4(full, { throwIfNoEntry: false });
21317
+ st = statSync5(full, { throwIfNoEntry: false });
20984
21318
  } catch {
20985
21319
  return "unreadable";
20986
21320
  }
@@ -21175,8 +21509,8 @@ function runProcess(argv, o) {
21175
21509
  }
21176
21510
 
21177
21511
  // src/core/index/auto-memory.ts
21178
- import { readdirSync as readdirSync3, readFileSync as readFileSync6, statSync as statSync5 } from "node:fs";
21179
- import { join as join9 } from "node:path";
21512
+ import { readdirSync as readdirSync4, readFileSync as readFileSync7, statSync as statSync6 } from "node:fs";
21513
+ import { join as join10 } from "node:path";
21180
21514
  var MEMORY_FILES = Object.freeze([
21181
21515
  Object.freeze(["CLAUDE.md"]),
21182
21516
  Object.freeze(["CLAUDE.local.md"]),
@@ -21190,7 +21524,7 @@ var KIRO_STEERING = Object.freeze([".kiro", "steering"]);
21190
21524
  var MD = ".md";
21191
21525
  function steeringFiles(worktree) {
21192
21526
  try {
21193
- return readdirSync3(join9(worktree, ...KIRO_STEERING)).filter((n) => n.endsWith(MD)).sort().map((n) => [...KIRO_STEERING, n]);
21527
+ return readdirSync4(join10(worktree, ...KIRO_STEERING)).filter((n) => n.endsWith(MD)).sort().map((n) => [...KIRO_STEERING, n]);
21194
21528
  } catch {
21195
21529
  return [];
21196
21530
  }
@@ -21198,10 +21532,10 @@ function steeringFiles(worktree) {
21198
21532
  function readAutoMemory(project) {
21199
21533
  const rows = [];
21200
21534
  for (const segs of [...MEMORY_FILES, ...steeringFiles(project.worktree)]) {
21201
- const path8 = join9(project.worktree, ...segs);
21535
+ const path8 = join10(project.worktree, ...segs);
21202
21536
  if (!isInside(project.worktree, path8)) continue;
21203
21537
  try {
21204
- const st = statSync5(path8);
21538
+ const st = statSync6(path8);
21205
21539
  if (!st.isFile()) continue;
21206
21540
  rows.push({
21207
21541
  origin: "memory",
@@ -21210,7 +21544,7 @@ function readAutoMemory(project) {
21210
21544
  sourceId: null,
21211
21545
  path: path8,
21212
21546
  label: segs.join("/"),
21213
- text: readFileSync6(path8, "utf8")
21547
+ text: readFileSync7(path8, "utf8")
21214
21548
  });
21215
21549
  } catch {
21216
21550
  }
@@ -21274,10 +21608,11 @@ function sourceCount(db, scope, ctx, source) {
21274
21608
  function zeroHits(db, scope, ctx, source, mem, nm, queries, offset = 0) {
21275
21609
  const inScope = sourceCount(db, scope, ctx, source);
21276
21610
  const n = inScope + mem.rows.length;
21277
- if (offset > 0) return reply("No more hits past offset " + offset + ' in scope "' + scope + '" across ' + n + " source(s).", false);
21278
21611
  const head2 = 'No hits in scope "' + scope + '" across ' + n + " source(s).";
21279
21612
  const pick4 = nm.pick;
21280
- if (pick4 === null || mem.named || inScope > 0) return reply(head2, false);
21613
+ if (pick4 === null || mem.named || inScope > 0) {
21614
+ return reply(offset > 0 ? "No more hits past offset " + offset + ' in scope "' + scope + '" across ' + n + " source(s)." : head2, false);
21615
+ }
21281
21616
  if (pick4.id !== null) {
21282
21617
  const wider = scope === "session" && sourceCount(db, "worktree", ctx, source) > 0 ? "worktree" : "project";
21283
21618
  return reply(head2 + "\nSource " + JSON.stringify(nm.arg) + ' is stored in scope "' + wider + '": ' + callText(queries, wider, nm.arg, "") + " searches it.", false);
@@ -21304,9 +21639,9 @@ function unknownSource(db, scope, ctx, given) {
21304
21639
  return line + "\nStored sources, newest first: " + names.join(", ") + more + ". " + callText([], scope, void 0, 'sort:"timeline"') + " lists them all.";
21305
21640
  }
21306
21641
  function named(given, pick4) {
21307
- if (given === void 0 || pick4 === null) return { arg: given, note: null, pick: null };
21642
+ if (given === void 0 || pick4 === null) return { arg: given, note: null, pick: null, lost: null };
21308
21643
  const arg = pick4.id !== null && isLongLabel(given) ? sourceHandle(pick4.id) : given;
21309
- return { arg, note: collisionLine(given, pick4), pick: pick4 };
21644
+ return { arg, note: collisionLine(given, pick4), pick: pick4, lost: null };
21310
21645
  }
21311
21646
  function sourceCard(db, id, input, scope, arg) {
21312
21647
  const row5 = sourceCardRow(db, id);
@@ -21330,7 +21665,7 @@ function decisionQueries(input) {
21330
21665
  function pageSize(input) {
21331
21666
  return input.source === DECISION_SOURCE ? SEARCH_PAGE_SIZE : SEARCH_REPLY_HITS;
21332
21667
  }
21333
- function page(db, q, input, scope, ctx, offset, extra = 0) {
21668
+ function page(db, q, input, scope, ctx, offset, extra = 0, h9 = { n: 0, list: true }) {
21334
21669
  const size = pageSize(input) + extra;
21335
21670
  if (input.source === DECISION_SOURCE && q.trim() === "") {
21336
21671
  return ftsListSource(db, DECISION_SOURCE, scope, ctx.project, ctx.sessionId, size, offset);
@@ -21339,6 +21674,8 @@ function page(db, q, input, scope, ctx, offset, extra = 0) {
21339
21674
  if (hits.length > 0 || input.source === void 0) return hits;
21340
21675
  const any3 = offset === 0 ? hits : ftsQuery(db, q, scope, ctx.project, ctx.sessionId, 1, 0, input.source);
21341
21676
  if (any3.length > 0) return hits;
21677
+ h9.n++;
21678
+ if (!h9.list) return [];
21342
21679
  return ftsListSource(db, input.source, scope, ctx.project, ctx.sessionId, size, offset);
21343
21680
  }
21344
21681
  var JSON_ROWS_PAGE = 5;
@@ -21427,15 +21764,27 @@ function relevance(db, given, scope, ctx, nm, ms, indexed) {
21427
21764
  const size = pageSize(input);
21428
21765
  const mem = ms.named || offset === 0 ? memoryChunks(ms.rows) : [];
21429
21766
  const count2 = (hits, n) => ms.named ? Math.min(n, hits.length) : contentIn(hits, n);
21430
- const fetched = input.queries.map((q) => {
21767
+ const h9 = { n: 0, list: false };
21768
+ const listed = [];
21769
+ const fetched = input.queries.map((q, qi) => {
21431
21770
  if (ms.named) {
21432
21771
  const want = offset + size + 1;
21433
21772
  const content2 = indexed ? ftsQuery(db, q, scope, ctx.project, ctx.sessionId, want, 0, input.source) : [];
21434
21773
  return mergeMemory(content2, memoryHits(mem, q, want)).slice(offset, want);
21435
21774
  }
21436
- const content = page(db, q, input, scope, ctx, offset, 1);
21775
+ const before = h9.n;
21776
+ const content = page(db, q, input, scope, ctx, offset, 1, h9);
21777
+ if (h9.n > before) listed.push(qi);
21437
21778
  return mem.length === 0 ? content : mergeMemory(content, memoryHits(mem, q, MEMORY_HITS));
21438
21779
  });
21780
+ if (listed.length > 0 && listed.length === input.queries.length) {
21781
+ const ordered = orderedRead(db, input, scope, ctx, nm);
21782
+ if (ordered !== null) return ordered;
21783
+ }
21784
+ for (const qi of listed) {
21785
+ const content = ftsListSource(db, input.source, scope, ctx.project, ctx.sessionId, size + 1, offset);
21786
+ fetched[qi] = mem.length === 0 ? content : mergeMemory(content, memoryHits(mem, input.queries[qi], MEMORY_HITS));
21787
+ }
21439
21788
  const take = fetched.map((h) => replyHits(h, size));
21440
21789
  const pages = fetched.map((h, i) => h.slice(0, take[i]));
21441
21790
  if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source, ms, nm, input.queries, offset);
@@ -21500,6 +21849,49 @@ function relevance(db, given, scope, ctx, nm, ms, indexed) {
21500
21849
  for (const [pos, qs] of byPos) moreLines.push("More: " + callText(qs, scope, nm.arg, "offset:" + pos));
21501
21850
  return reply(lines.concat(moreLines).join("\n"), false);
21502
21851
  }
21852
+ var ORDERED_LINE_BACK = 512;
21853
+ var SOURCE_IN_SCOPE = `
21854
+ SELECT session_id FROM sources WHERE id = :id
21855
+ AND (:scope <> 'session' OR session_id = :session_id)
21856
+ AND (:scope <> 'worktree' OR worktree = :worktree)`;
21857
+ function sourceText(db, id) {
21858
+ const rows = db.raw.prepare("SELECT body FROM chunks WHERE source_id = ? ORDER BY CAST(ord AS INTEGER)").all(id);
21859
+ const parts = [];
21860
+ for (let i = 0; i < rows.length; i++) {
21861
+ const body = rows[i].body;
21862
+ parts.push(body);
21863
+ if (i + 1 < rows.length && !body.endsWith("\n") && bytes2(body) < MAX_CHUNK_BYTES - 3) parts.push("\n\n");
21864
+ }
21865
+ return parts.join("");
21866
+ }
21867
+ function orderedRead(db, input, scope, ctx, nm) {
21868
+ const pick4 = nm.pick;
21869
+ if (pick4 === null || pick4.id === null || input.source === void 0 || input.source === DECISION_SOURCE) return null;
21870
+ const where = { id: pick4.id, scope, session_id: ctx.sessionId, worktree: ctx.project.worktree };
21871
+ const row5 = db.raw.prepare(SOURCE_IN_SCOPE).get(where);
21872
+ if (row5 === void 0) return null;
21873
+ const buf = Buffer.from(sourceText(db, pick4.id), "utf8");
21874
+ const total = buf.length;
21875
+ if (total === 0) return null;
21876
+ const name = isLongLabel(pick4.label) ? shownLabel(pick4.label, pick4.id) : JSON.stringify(pick4.label);
21877
+ let start = Math.min(input.offset ?? 0, total);
21878
+ while (start < total && (buf[start] & 192) === 128) start++;
21879
+ if (start >= total) return reply("No more text past offset " + start + " in source " + name + " (" + total + " B).", false);
21880
+ const note = nm.note === null ? "" : " " + nm.note;
21881
+ const headOf2 = (end2) => "Source " + name + " in order, bytes " + start + "-" + end2 + " of " + total + ":" + note;
21882
+ const moreOf = (end2) => "More: " + callText([""], scope, nm.arg, "offset:" + end2);
21883
+ let end = total;
21884
+ if (bytes2(headOf2(total)) + 1 + (total - start) > OUTPUT_CAP) {
21885
+ end = start + OUTPUT_CAP - bytes2(headOf2(total)) - 1 - bytes2(moreOf(total)) - 1;
21886
+ while (end > start && (buf[end] & 192) === 128) end--;
21887
+ const nl = buf.lastIndexOf(10, end - 1);
21888
+ if (nl >= start && nl + 1 > end - ORDERED_LINE_BACK) end = nl + 1;
21889
+ }
21890
+ const text = buf.subarray(start, end).toString("utf8");
21891
+ const key = end * 2 >= total ? betKeyOfLabel(pick4.label) : null;
21892
+ if (key !== null && !isLostBet(db, row5.session_id, key)) nm.lost = { sessionId: row5.session_id, key, source: sourceHandle(pick4.id) };
21893
+ return reply(headOf2(end) + "\n" + text + (end < total ? "\n" + moreOf(end) : ""), false);
21894
+ }
21503
21895
  function timelineLine(r) {
21504
21896
  const nl = r.text.indexOf("\n");
21505
21897
  const first = nl < 0 ? r.text : r.text.slice(0, nl);
@@ -21560,9 +21952,11 @@ async function handler(input, ctx) {
21560
21952
  }
21561
21953
  const scope = input.scope ?? "worktree";
21562
21954
  const db = await openDb(ctx.project, { readOnly: true });
21955
+ let lost = null;
21563
21956
  try {
21564
21957
  const given = input.source;
21565
- const pick4 = given !== void 0 && given !== DECISION_SOURCE ? pickSource(db, given) : null;
21958
+ const within = { scope, sessionId: ctx.sessionId, worktree: ctx.project.worktree };
21959
+ const pick4 = given !== void 0 && given !== DECISION_SOURCE ? pickSource(db, given, true, within) : null;
21566
21960
  if (pick4 !== null) input = { ...input, source: pick4.label };
21567
21961
  const nm = named(given, pick4);
21568
21962
  const indexed = pick4 !== null && pick4.id !== null;
@@ -21574,11 +21968,24 @@ async function handler(input, ctx) {
21574
21968
  nm.note = nm.note === null ? both : nm.note + "\n" + both;
21575
21969
  }
21576
21970
  const out = answer(db, input, scope, ctx, nm, ms, indexed, sort, pick4);
21971
+ lost = nm.lost;
21577
21972
  if (file2 === null || scope !== "session") return out;
21578
21973
  const call = callText(input.queries, "worktree", nm.arg, sort === "timeline" ? 'sort:"timeline"' : "");
21579
21974
  return reply(out.text + "\nMemory file " + file2.label + ' is in scope "worktree": ' + call + " searches it.", out.isError);
21580
21975
  } finally {
21581
21976
  closeDb(db);
21977
+ if (lost !== null) await recordLostBet(ctx, lost);
21978
+ }
21979
+ }
21980
+ async function recordLostBet(ctx, lost) {
21981
+ try {
21982
+ const w = await openDb(ctx.project);
21983
+ try {
21984
+ markLostBet(w, lost.sessionId, lost.key, "ordered-read", lost.source);
21985
+ } finally {
21986
+ closeDb(w);
21987
+ }
21988
+ } catch {
21582
21989
  }
21583
21990
  }
21584
21991
  var ctxSearch = Object.freeze({
@@ -21811,19 +22218,19 @@ var ctxBatch = Object.freeze({
21811
22218
  });
21812
22219
 
21813
22220
  // src/core/tools/doctor.ts
21814
- import { readdirSync as readdirSync8, readFileSync as readFileSync17, existsSync as existsSync17 } from "node:fs";
21815
- import { basename as basename5, join as join20 } from "node:path";
22221
+ import { readdirSync as readdirSync9, readFileSync as readFileSync18, existsSync as existsSync17 } from "node:fs";
22222
+ import { basename as basename5, join as join21 } from "node:path";
21816
22223
 
21817
22224
  // src/core/ops/bundle-dir.ts
21818
22225
  import { existsSync as existsSync4 } from "node:fs";
21819
- import { dirname as dirname5, join as join10 } from "node:path";
22226
+ import { dirname as dirname5, join as join11 } from "node:path";
21820
22227
  import { fileURLToPath } from "node:url";
21821
22228
  function bundleDirOf(argv1, moduleFile) {
21822
22229
  const own4 = dirname5(argv1);
21823
- if (existsSync4(join10(own4, SERVER_ENTRY_FILE))) return own4;
22230
+ if (existsSync4(join11(own4, SERVER_ENTRY_FILE))) return own4;
21824
22231
  let dir = dirname5(moduleFile);
21825
22232
  for (; ; ) {
21826
- if (existsSync4(join10(dir, SERVER_ENTRY_FILE))) return dir;
22233
+ if (existsSync4(join11(dir, SERVER_ENTRY_FILE))) return dir;
21827
22234
  const up = dirname5(dir);
21828
22235
  if (up === dir) return own4;
21829
22236
  dir = up;
@@ -21837,17 +22244,17 @@ function ownBundleDir() {
21837
22244
  }
21838
22245
 
21839
22246
  // src/core/ops/doctor-config.ts
21840
- import { existsSync as existsSync11, readdirSync as readdirSync6, readFileSync as readFileSync13 } from "node:fs";
21841
- import { dirname as dirname8, isAbsolute as isAbsolute5, join as join16, resolve as resolve9 } from "node:path";
22247
+ import { existsSync as existsSync11, readdirSync as readdirSync7, readFileSync as readFileSync14 } from "node:fs";
22248
+ import { dirname as dirname8, isAbsolute as isAbsolute6, join as join17, resolve as resolve9 } from "node:path";
21842
22249
 
21843
22250
  // src/core/ops/detect-v1.ts
21844
- import { existsSync as existsSync6, opendirSync, readdirSync as readdirSync4, readFileSync as readFileSync8 } from "node:fs";
22251
+ import { existsSync as existsSync6, opendirSync, readdirSync as readdirSync5, readFileSync as readFileSync9 } from "node:fs";
21845
22252
  import { tmpdir } from "node:os";
21846
- import { join as join12 } from "node:path";
22253
+ import { join as join13 } from "node:path";
21847
22254
 
21848
22255
  // src/core/ops/host-config.ts
21849
- import { existsSync as existsSync5, readFileSync as readFileSync7 } from "node:fs";
21850
- import { dirname as dirname6, join as join11 } from "node:path";
22256
+ import { existsSync as existsSync5, readFileSync as readFileSync8 } from "node:fs";
22257
+ import { dirname as dirname6, join as join12 } from "node:path";
21851
22258
 
21852
22259
  // node_modules/eslint-visitor-keys/lib/visitor-keys.js
21853
22260
  var KEYS2 = {
@@ -23893,7 +24300,7 @@ function parseTOML(code, options) {
23893
24300
  }
23894
24301
 
23895
24302
  // src/core/ops/atomic-file.ts
23896
- import { mkdirSync as mkdirSync3, renameSync as renameSync2, unlinkSync, writeFileSync } from "node:fs";
24303
+ import { mkdirSync as mkdirSync4, renameSync as renameSync3, unlinkSync as unlinkSync2, writeFileSync as writeFileSync2 } from "node:fs";
23897
24304
  import path3 from "node:path";
23898
24305
  function sleepSync(ms) {
23899
24306
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
@@ -23902,7 +24309,7 @@ function errCode2(e) {
23902
24309
  return e.code;
23903
24310
  }
23904
24311
  function renameWithRetry(from, to, opts = {}) {
23905
- const rename = opts.rename ?? renameSync2;
24312
+ const rename = opts.rename ?? renameSync3;
23906
24313
  const sleep2 = opts.sleep ?? sleepSync;
23907
24314
  const win = (opts.platform ?? process.platform) === "win32";
23908
24315
  for (let attempt = 0; ; attempt += 1) {
@@ -23917,7 +24324,7 @@ function renameWithRetry(from, to, opts = {}) {
23917
24324
  }
23918
24325
  }
23919
24326
  function unlinkWithRetry(file2, opts = {}) {
23920
- const unlink = opts.unlink ?? unlinkSync;
24327
+ const unlink = opts.unlink ?? unlinkSync2;
23921
24328
  const sleep2 = opts.sleep ?? sleepSync;
23922
24329
  const win = (opts.platform ?? process.platform) === "win32";
23923
24330
  for (let attempt = 0; ; attempt += 1) {
@@ -23944,10 +24351,10 @@ function removeTmpFile(tmp, opts = {}) {
23944
24351
  }
23945
24352
  }
23946
24353
  function atomicWriteFile(file2, text, opts = {}) {
23947
- mkdirSync3(path3.dirname(file2), { recursive: true });
24354
+ mkdirSync4(path3.dirname(file2), { recursive: true });
23948
24355
  const tmp = path3.join(path3.dirname(file2), `${ATOMIC_TMP_PREFIX}${path3.basename(file2)}${ATOMIC_TMP_MARK}${process.pid}`);
23949
24356
  try {
23950
- writeFileSync(tmp, text);
24357
+ writeFileSync2(tmp, text);
23951
24358
  renameWithRetry(tmp, file2, opts);
23952
24359
  } catch (e) {
23953
24360
  removeTmpFile(tmp, opts);
@@ -23964,10 +24371,10 @@ function formatOf(path8) {
23964
24371
  function readHostConfig(agent, path8) {
23965
24372
  let file2 = path8;
23966
24373
  if (agent === "opencode") {
23967
- const jsonc = join11(dirname6(path8), OPENCODE_CONFIG_FILES[0]);
24374
+ const jsonc = join12(dirname6(path8), OPENCODE_CONFIG_FILES[0]);
23968
24375
  if (existsSync5(jsonc)) file2 = jsonc;
23969
24376
  }
23970
- const raw = existsSync5(file2) ? readFileSync7(file2, "utf8") : "";
24377
+ const raw = existsSync5(file2) ? readFileSync8(file2, "utf8") : "";
23971
24378
  return { agent, text: hostText(raw), format: agent === "opencode" && !file2.endsWith(TOML_EXT) ? "jsonc" : formatOf(file2), path: file2, layout: hostLayout(raw) };
23972
24379
  }
23973
24380
  function stripJsonComments(text) {
@@ -24312,7 +24719,7 @@ function setText(agent, path8, text, format, key, value) {
24312
24719
  }
24313
24720
  }
24314
24721
  function serverScript() {
24315
- return join11(dirname6(process.argv[1] ?? ""), SERVER_ENTRY_FILE);
24722
+ return join12(dirname6(process.argv[1] ?? ""), SERVER_ENTRY_FILE);
24316
24723
  }
24317
24724
  function isNodeCommand(command) {
24318
24725
  if (typeof command !== "string") return false;
@@ -24439,14 +24846,14 @@ function stripJsonc(text) {
24439
24846
  }
24440
24847
  function readJson(file2) {
24441
24848
  try {
24442
- return JSON.parse(stripJsonc(hostText(readFileSync8(file2, "utf8"))));
24849
+ return JSON.parse(stripJsonc(hostText(readFileSync9(file2, "utf8"))));
24443
24850
  } catch {
24444
24851
  return void 0;
24445
24852
  }
24446
24853
  }
24447
24854
  function readText(file2) {
24448
24855
  try {
24449
- return hostText(readFileSync8(file2, "utf8"));
24856
+ return hostText(readFileSync9(file2, "utf8"));
24450
24857
  } catch {
24451
24858
  return "";
24452
24859
  }
@@ -24511,7 +24918,7 @@ function mcpEntry(file2, doc, out) {
24511
24918
  }
24512
24919
  }
24513
24920
  function claudeShapeSettings(agentHome, out) {
24514
- const file2 = join12(agentHome, SETTINGS_FILE);
24921
+ const file2 = join13(agentHome, SETTINGS_FILE);
24515
24922
  const doc = readJson(file2);
24516
24923
  for (const c of nestedCommands(doc)) {
24517
24924
  if (c.command.includes(V1_CACHE_HEAL_NAME)) out.push(finding(file2, c.path, V1_REASON.cacheHealHook));
@@ -24531,63 +24938,63 @@ function v1HookFile(file2, out) {
24531
24938
  function scanClaudeCode(home, agentHome, out) {
24532
24939
  claudeShapeSettings(agentHome, out);
24533
24940
  for (const ext of V1_CACHE_HEAL_EXTS) {
24534
- const file2 = join12(agentHome, V1_HOOKS_DIR_NAME, V1_CACHE_HEAL_NAME + ext);
24941
+ const file2 = join13(agentHome, V1_HOOKS_DIR_NAME, V1_CACHE_HEAL_NAME + ext);
24535
24942
  if (existsSync6(file2)) out.push(finding(file2, "", V1_REASON.cacheHealFile));
24536
24943
  }
24537
- const userFile = join12(home, CLAUDE_USER_CONFIG_FILE);
24944
+ const userFile = join13(home, CLAUDE_USER_CONFIG_FILE);
24538
24945
  mcpEntry(userFile, readJson(userFile), out);
24539
- dataDir(join12(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
24946
+ dataDir(join13(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
24540
24947
  }
24541
24948
  function scanCodex(agentHome, out) {
24542
- const hooksFile = join12(agentHome, HOOKS_JSON_FILE);
24949
+ const hooksFile = join13(agentHome, HOOKS_JSON_FILE);
24543
24950
  for (const c of nestedCommands(readJson(hooksFile))) {
24544
24951
  if (c.command.includes(V1_CODEX_HOOK_COMMAND) || isCodexScript(c.command)) {
24545
24952
  out.push(finding(hooksFile, c.path, V1_REASON.codexHook));
24546
24953
  }
24547
24954
  }
24548
- const tomlFile = join12(agentHome, CONFIG_TOML_FILE);
24955
+ const tomlFile = join13(agentHome, CONFIG_TOML_FILE);
24549
24956
  const config4 = readTomlValue(tomlFile);
24550
24957
  for (const span2 of readTomlTables(tomlFile)) {
24551
24958
  if (span2.path[0] !== V1_TOML_SECTION_ROOT || span2.path[1] !== SERVER_KEY) continue;
24552
24959
  if (isV2McpTable(hostConfigValueAt(config4, span2.path.slice(0, 2)))) continue;
24553
24960
  out.push(finding(tomlFile, span2.header.trim(), V1_REASON.codexToml));
24554
24961
  }
24555
- dataDir(join12(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
24962
+ dataDir(join13(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
24556
24963
  }
24557
24964
  function scanGemini(agentHome, out) {
24558
- const file2 = join12(agentHome, SETTINGS_FILE);
24965
+ const file2 = join13(agentHome, SETTINGS_FILE);
24559
24966
  for (const c of nestedCommands(readJson(file2))) {
24560
24967
  if (c.command.includes(SERVER_KEY)) out.push(finding(file2, c.path, V1_REASON.hook));
24561
24968
  }
24562
- dataDir(join12(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDirShared, out);
24969
+ dataDir(join13(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDirShared, out);
24563
24970
  }
24564
24971
  function scanVscode(agentHome, project, out) {
24565
24972
  if (project !== void 0) {
24566
- v1HookFile(join12(project, GITHUB_DIR_NAME, V1_HOOKS_DIR_NAME, OWN_HOOK_FILE), out);
24567
- const mcpFile2 = join12(project, VSCODE_DIR_NAME, VSCODE_MCP_FILE);
24973
+ v1HookFile(join13(project, GITHUB_DIR_NAME, V1_HOOKS_DIR_NAME, OWN_HOOK_FILE), out);
24974
+ const mcpFile2 = join13(project, VSCODE_DIR_NAME, VSCODE_MCP_FILE);
24568
24975
  const doc = readJson(mcpFile2);
24569
24976
  const servers = isObj(doc) && isObj(doc[VSCODE_MCP_SERVERS_KEY]) ? doc[VSCODE_MCP_SERVERS_KEY] : {};
24570
24977
  const entry = Object.hasOwn(servers, SERVER_KEY) ? servers[SERVER_KEY] : void 0;
24571
24978
  if (isObj(entry) && (entry.command === V1_BIN_COMMAND || listOf(entry.args).some((a) => a === V1_BIN_COMMAND))) {
24572
24979
  out.push(finding(mcpFile2, keyPath(VSCODE_MCP_SERVERS_KEY, SERVER_KEY), V1_REASON.vscodeMcp));
24573
24980
  }
24574
- const sessions = join12(project, GITHUB_DIR_NAME, V1_DATA_DIR_NAME, V1_SESSIONS_DIR_NAME);
24981
+ const sessions = join13(project, GITHUB_DIR_NAME, V1_DATA_DIR_NAME, V1_SESSIONS_DIR_NAME);
24575
24982
  dataDir(sessions, reachedThroughLink(project, sessions) ? V1_REASON.projectLink : V1_REASON.dataDir, out);
24576
24983
  }
24577
- dataDir(join12(agentHome, V1_DATA_DIR_NAME, V1_SESSIONS_DIR_NAME), V1_REASON.dataDir, out);
24984
+ dataDir(join13(agentHome, V1_DATA_DIR_NAME, V1_SESSIONS_DIR_NAME), V1_REASON.dataDir, out);
24578
24985
  }
24579
24986
  function jsonFiles(dir) {
24580
24987
  try {
24581
- return readdirSync4(dir).filter((name) => name.endsWith(KIRO_AGENT_FILE_EXT)).sort();
24988
+ return readdirSync5(dir).filter((name) => name.endsWith(KIRO_AGENT_FILE_EXT)).sort();
24582
24989
  } catch {
24583
24990
  return [];
24584
24991
  }
24585
24992
  }
24586
24993
  function scanKiro(agentHome, project, out) {
24587
- const agentsDir = join12(agentHome, KIRO_AGENTS_DIR);
24588
- const defaultFile = join12(agentHome, ...KIRO_AGENT_FILE);
24994
+ const agentsDir = join13(agentHome, KIRO_AGENTS_DIR);
24995
+ const defaultFile = join13(agentHome, ...KIRO_AGENT_FILE);
24589
24996
  for (const name of jsonFiles(agentsDir)) {
24590
- const file2 = join12(agentsDir, name);
24997
+ const file2 = join13(agentsDir, name);
24591
24998
  const doc = readJson(file2);
24592
24999
  if (isObj(doc) && doc[KIRO_AGENT_NAME_KEY] === SERVER_KEY) {
24593
25000
  out.push(finding(file2, "", V1_REASON.kiroAgentFile));
@@ -24598,31 +25005,31 @@ function scanKiro(agentHome, project, out) {
24598
25005
  if (isV1Hook(c.command)) out.push(finding(file2, c.path, V1_REASON.kiroHook));
24599
25006
  }
24600
25007
  }
24601
- const steeringDocs = [join12(agentHome, ...KIRO_STEERING_FILE)];
24602
- if (project !== void 0) steeringDocs.push(join12(project, ...AGENT_HOME_DIR.kiro, ...KIRO_STEERING_FILE));
25008
+ const steeringDocs = [join13(agentHome, ...KIRO_STEERING_FILE)];
25009
+ if (project !== void 0) steeringDocs.push(join13(project, ...AGENT_HOME_DIR.kiro, ...KIRO_STEERING_FILE));
24603
25010
  for (const file2 of steeringDocs) {
24604
25011
  if (existsSync6(file2)) out.push(finding(file2, "", V1_REASON.kiroSteering));
24605
25012
  }
24606
- dataDir(join12(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
25013
+ dataDir(join13(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
24607
25014
  }
24608
25015
  function piNpmIsCurrent(piAgentDir) {
24609
- const doc = readJson(join12(piAgentDir, PI_NPM_DIR, PI_NODE_MODULES_DIR, SERVER_KEY, PI_PACKAGE_JSON_FILE));
25016
+ const doc = readJson(join13(piAgentDir, PI_NPM_DIR, PI_NODE_MODULES_DIR, SERVER_KEY, PI_PACKAGE_JSON_FILE));
24610
25017
  const version4 = isObj(doc) && typeof doc.version === "string" ? doc.version : "";
24611
25018
  return Number.parseInt(version4, 10) >= PI_CURRENT_MAJOR;
24612
25019
  }
24613
25020
  function scanPi(piAgentDir, agentHome, out) {
24614
- const file2 = join12(piAgentDir, SETTINGS_FILE);
25021
+ const file2 = join13(piAgentDir, SETTINGS_FILE);
24615
25022
  const doc = readJson(file2);
24616
25023
  listOf(isObj(doc) ? doc[PI_PACKAGES_KEY] : void 0).forEach((pkg, i) => {
24617
25024
  const spec = isObj(pkg) ? pkg[PI_PACKAGE_SOURCE_KEY] : pkg;
24618
25025
  if (spec === V1_PI_PACKAGE && !piNpmIsCurrent(piAgentDir)) out.push(finding(file2, keyPath(PI_PACKAGES_KEY, i), V1_REASON.piNpm));
24619
25026
  if (spec === PI_GIT_PACKAGE) out.push(finding(file2, keyPath(PI_PACKAGES_KEY, i), V1_REASON.piGit));
24620
25027
  });
24621
- dataDir(join12(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
25028
+ dataDir(join13(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
24622
25029
  }
24623
25030
  function scanOpencode(agentHome, out) {
24624
25031
  for (const name of OPENCODE_CONFIG_FILES) {
24625
- const file2 = join12(agentHome, name);
25032
+ const file2 = join13(agentHome, name);
24626
25033
  const doc = readJson(file2);
24627
25034
  if (!isObj(doc) || !Array.isArray(doc[OPENCODE_PLUGIN_KEY])) continue;
24628
25035
  doc[OPENCODE_PLUGIN_KEY].forEach((spec, i) => {
@@ -24633,13 +25040,13 @@ function scanOpencode(agentHome, out) {
24633
25040
  }
24634
25041
  }
24635
25042
  function scanZcode(agentHome, out) {
24636
- const configFile = join12(agentHome, ZCODE_CLI_DIR, CONFIG_JSON_FILE);
25043
+ const configFile = join13(agentHome, ZCODE_CLI_DIR, CONFIG_JSON_FILE);
24637
25044
  const config4 = readJson(configFile);
24638
25045
  const events = isObj(config4) && isObj(config4[HOOKS_KEY]) ? config4[HOOKS_KEY][ZCODE_EVENTS_KEY] : void 0;
24639
25046
  for (const c of flatCommands(events, [HOOKS_KEY, ZCODE_EVENTS_KEY])) {
24640
25047
  if (c.command.includes(V1_HOOK_COMMAND)) out.push(finding(configFile, c.path, V1_REASON.zcodeHook));
24641
25048
  }
24642
- const hooksFile = join12(agentHome, ZCODE_CLI_DIR, HOOKS_JSON_FILE);
25049
+ const hooksFile = join13(agentHome, ZCODE_CLI_DIR, HOOKS_JSON_FILE);
24643
25050
  for (const c of nestedCommands(readJson(hooksFile))) {
24644
25051
  if (c.command.includes(V1_HOOK_COMMAND)) out.push(finding(hooksFile, c.path, V1_REASON.zcodeHook));
24645
25052
  }
@@ -24663,14 +25070,14 @@ function firstTmpMatch(dir) {
24663
25070
  }
24664
25071
  }
24665
25072
  function scanAll(home, tmp, out) {
24666
- const root = join12(home, DATA_ROOT.slice(1));
24667
- for (const name of V1_DATA_ROOT_ENTRIES) dataDir(join12(root, name), V1_REASON.dataRoot, out);
25073
+ const root = join13(home, DATA_ROOT.slice(1));
25074
+ for (const name of V1_DATA_ROOT_ENTRIES) dataDir(join13(root, name), V1_REASON.dataRoot, out);
24668
25075
  if (firstTmpMatch(tmp) !== null) out.push(finding(tmp, V1_TMP_PREFIX + "*", V1_REASON.tmpFile));
24669
25076
  }
24670
25077
  function detectV1(agent, home, scope = {}) {
24671
25078
  const out = [];
24672
25079
  const project = scope.project;
24673
- const agentHome = agent === "claude-code" && scope.claudeDir !== void 0 ? scope.claudeDir : agent === "codex" && scope.codexDir !== void 0 ? scope.codexDir : agent === "gemini" && scope.geminiDir !== void 0 ? scope.geminiDir : agent === "copilot-cli" && scope.copilotDir !== void 0 ? scope.copilotDir : agent === "kiro" && scope.kiroDir !== void 0 ? scope.kiroDir : agent === "opencode" && scope.opencodeDir !== void 0 ? scope.opencodeDir : join12(home, ...AGENT_HOME_DIR[agent]);
25080
+ const agentHome = agent === "claude-code" && scope.claudeDir !== void 0 ? scope.claudeDir : agent === "codex" && scope.codexDir !== void 0 ? scope.codexDir : agent === "gemini" && scope.geminiDir !== void 0 ? scope.geminiDir : agent === "copilot-cli" && scope.copilotDir !== void 0 ? scope.copilotDir : agent === "kiro" && scope.kiroDir !== void 0 ? scope.kiroDir : agent === "opencode" && scope.opencodeDir !== void 0 ? scope.opencodeDir : join13(home, ...AGENT_HOME_DIR[agent]);
24674
25081
  switch (agent) {
24675
25082
  case "claude-code":
24676
25083
  scanClaudeCode(home, agentHome, out);
@@ -24683,11 +25090,11 @@ function detectV1(agent, home, scope = {}) {
24683
25090
  break;
24684
25091
  case "qwen":
24685
25092
  claudeShapeSettings(agentHome, out);
24686
- dataDir(join12(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
25093
+ dataDir(join13(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
24687
25094
  break;
24688
25095
  case "copilot-cli":
24689
- v1HookFile(join12(agentHome, V1_HOOKS_DIR_NAME, OWN_HOOK_FILE), out);
24690
- dataDir(join12(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
25096
+ v1HookFile(join13(agentHome, V1_HOOKS_DIR_NAME, OWN_HOOK_FILE), out);
25097
+ dataDir(join13(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
24691
25098
  break;
24692
25099
  case "vscode":
24693
25100
  scanVscode(agentHome, project, out);
@@ -24696,7 +25103,7 @@ function detectV1(agent, home, scope = {}) {
24696
25103
  scanKiro(agentHome, project, out);
24697
25104
  break;
24698
25105
  case "pi":
24699
- scanPi(scope.piAgentDir !== void 0 && scope.piAgentDir !== "" ? scope.piAgentDir : join12(agentHome, PI_AGENT_DIR), agentHome, out);
25106
+ scanPi(scope.piAgentDir !== void 0 && scope.piAgentDir !== "" ? scope.piAgentDir : join13(agentHome, PI_AGENT_DIR), agentHome, out);
24700
25107
  break;
24701
25108
  // D-WIN-PIDIR-1: empty is unset
24702
25109
  case "opencode":
@@ -24711,8 +25118,8 @@ function detectV1(agent, home, scope = {}) {
24711
25118
  }
24712
25119
 
24713
25120
  // src/core/ops/plugin-root.ts
24714
- import { existsSync as existsSync7, readdirSync as readdirSync5, readFileSync as readFileSync9, realpathSync as realpathSync4 } from "node:fs";
24715
- import { dirname as dirname7, isAbsolute as isAbsolute3, join as join13, sep as sep4 } from "node:path";
25121
+ import { existsSync as existsSync7, readdirSync as readdirSync6, readFileSync as readFileSync10, realpathSync as realpathSync4 } from "node:fs";
25122
+ import { dirname as dirname7, isAbsolute as isAbsolute4, join as join14, sep as sep4 } from "node:path";
24716
25123
  import { fileURLToPath as fileURLToPath2 } from "node:url";
24717
25124
  function missing(agent, path8) {
24718
25125
  return new CtxError("PLUGIN_ROOT_MISSING", { agent, path: path8 });
@@ -24753,15 +25160,15 @@ var realOrNull = (path8) => {
24753
25160
  };
24754
25161
  var readOrNull = (file2) => {
24755
25162
  try {
24756
- return readFileSync9(file2, "utf8");
25163
+ return readFileSync10(file2, "utf8");
24757
25164
  } catch {
24758
25165
  return null;
24759
25166
  }
24760
25167
  };
24761
25168
  var samePath = (a, b) => a === b || (realOrNull(a) ?? a) === (realOrNull(b) ?? b);
24762
25169
  function enabledPlugins(claudeDir, project) {
24763
- const files = [join13(claudeDir, SETTINGS_FILE)];
24764
- if (project !== void 0) files.push(join13(project, HOST_CONFIG_DIR_NAME, SETTINGS_FILE), join13(project, HOST_CONFIG_DIR_NAME, SETTINGS_LOCAL_FILE));
25170
+ const files = [join14(claudeDir, SETTINGS_FILE)];
25171
+ if (project !== void 0) files.push(join14(project, HOST_CONFIG_DIR_NAME, SETTINGS_FILE), join14(project, HOST_CONFIG_DIR_NAME, SETTINGS_LOCAL_FILE));
24765
25172
  const out = {};
24766
25173
  for (const file2 of files) {
24767
25174
  const text = readOrNull(file2);
@@ -24777,7 +25184,7 @@ function marketplaceChoice(env, worktree) {
24777
25184
  const ownReal = script === void 0 || script === "" ? null : realOrNull(dirname7(script));
24778
25185
  const hostRoot = env[CLAUDE_PLUGIN_ROOT_ENV];
24779
25186
  if (ownReal !== null && hostRoot !== void 0 && hostRoot !== "" && realOrNull(hostRoot) === ownReal) return { root: ownReal };
24780
- const record6 = readOrNull(join13(claudeDir, HOST_PLUGINS_DIR_NAME, INSTALLED_PLUGINS_FILE));
25187
+ const record6 = readOrNull(join14(claudeDir, HOST_PLUGINS_DIR_NAME, INSTALLED_PLUGINS_FILE));
24781
25188
  const recorded = record6 === null ? [] : recordedInstalls(record6);
24782
25189
  if (recorded.length === 0) return { record: false };
24783
25190
  const live = recorded.filter((r) => existsSync7(r.installPath));
@@ -24800,18 +25207,18 @@ function marketplaceChoice(env, worktree) {
24800
25207
  }
24801
25208
  function marketplaceRoot(adapter, env, worktree) {
24802
25209
  const claudeDir = claudeDirOf(env, requireHomeDir(env));
24803
- const plugins = join13(claudeDir, HOST_PLUGINS_DIR_NAME);
24804
- const cache = join13(plugins, PLUGIN_CACHE_DIR_NAME);
25210
+ const plugins = join14(claudeDir, HOST_PLUGINS_DIR_NAME);
25211
+ const cache = join14(plugins, PLUGIN_CACHE_DIR_NAME);
24805
25212
  const script = process.argv[1];
24806
25213
  const ownReal = script === void 0 || script === "" ? null : realOrNull(dirname7(script));
24807
25214
  const choice = marketplaceChoice(env, worktree);
24808
25215
  if ("root" in choice) return choice.root;
24809
25216
  if ("installs" in choice) throw missing(adapter.id, choice.installs.map((r) => r.installPath).join(", "));
24810
25217
  const cacheReal = realOrNull(cache);
24811
- if (ownReal !== null && cacheReal !== null && ownReal.startsWith(cacheReal + sep4) && existsSync7(join13(ownReal, SERVER_ENTRY_FILE))) return ownReal;
24812
- const pattern = join13(cache, "*", PLUGIN_NAME);
25218
+ if (ownReal !== null && cacheReal !== null && ownReal.startsWith(cacheReal + sep4) && existsSync7(join14(ownReal, SERVER_ENTRY_FILE))) return ownReal;
25219
+ const pattern = join14(cache, "*", PLUGIN_NAME);
24813
25220
  if (!existsSync7(cache)) throw missing(adapter.id, pattern);
24814
- const found = readdirSync5(cache).sort().map((marketplace) => join13(cache, marketplace, PLUGIN_NAME)).filter((dir) => existsSync7(dir));
25221
+ const found = readdirSync6(cache).sort().map((marketplace) => join14(cache, marketplace, PLUGIN_NAME)).filter((dir) => existsSync7(dir));
24815
25222
  if (found.length !== 1) throw missing(adapter.id, found.length === 0 ? pattern : found.join(", "));
24816
25223
  return found[0];
24817
25224
  }
@@ -24824,12 +25231,12 @@ function configEntryRoot(adapter, env) {
24824
25231
  const value = parseHostConfig(adapter.id, file2, current.text, current.format);
24825
25232
  const args = hostConfigValueAt(value, [...spec.key, MCP_ARGS_FIELD]);
24826
25233
  const script = Array.isArray(args) ? args[0] : void 0;
24827
- if (typeof script !== "string" || !isAbsolute3(script)) throw missing(adapter.id, file2);
25234
+ if (typeof script !== "string" || !isAbsolute4(script)) throw missing(adapter.id, file2);
24828
25235
  return dirname7(script);
24829
25236
  }
24830
25237
  function packageDirOf(dir) {
24831
25238
  for (let cur = dir; ; ) {
24832
- if (existsSync7(join13(cur, D1_PACKAGE_FILE))) return cur;
25239
+ if (existsSync7(join14(cur, D1_PACKAGE_FILE))) return cur;
24833
25240
  const up = dirname7(cur);
24834
25241
  if (up === cur) return dir;
24835
25242
  cur = up;
@@ -24844,9 +25251,9 @@ function candidate(adapter, env, worktree) {
24844
25251
  case "hooks+mcp":
24845
25252
  return configEntryRoot(adapter, env);
24846
25253
  case "extension":
24847
- return join13(adapter.id === "gemini" ? geminiDirOf(env, requireHomeDir(env)) : join13(requireHomeDir(env), ...AGENT_HOME_DIR[adapter.id]), EXTENSIONS_DIR_NAME, PLUGIN_NAME);
25254
+ return join14(adapter.id === "gemini" ? geminiDirOf(env, requireHomeDir(env)) : join14(requireHomeDir(env), ...AGENT_HOME_DIR[adapter.id]), EXTENSIONS_DIR_NAME, PLUGIN_NAME);
24848
25255
  case "plugin":
24849
- return join13(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, adapter.id, PLUGIN_CURRENT_LINK);
25256
+ return join14(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, adapter.id, PLUGIN_CURRENT_LINK);
24850
25257
  case "in-process":
24851
25258
  return packageDirOf(dirname7(fileURLToPath2(import.meta.url)));
24852
25259
  }
@@ -24861,7 +25268,7 @@ function resolvePluginRoot(adapter, env, worktree) {
24861
25268
  }
24862
25269
 
24863
25270
  // src/setup/pi-gate.ts
24864
- import { existsSync as existsSync8, readFileSync as readFileSync10, realpathSync as realpathSync5 } from "node:fs";
25271
+ import { existsSync as existsSync8, readFileSync as readFileSync11, realpathSync as realpathSync5 } from "node:fs";
24865
25272
  import path4 from "node:path";
24866
25273
  var EXTENSIONS_KEY = "extensions";
24867
25274
  var PROJECT_DIR = ".pi";
@@ -24871,7 +25278,7 @@ var SOURCE_PREFIXES = ["npm:", "git:"];
24871
25278
  function load(file2) {
24872
25279
  if (!existsSync8(file2)) return void 0;
24873
25280
  try {
24874
- return { file: file2, doc: parseHostConfig("pi", file2, hostText(readFileSync10(file2, "utf8")), "json") };
25281
+ return { file: file2, doc: parseHostConfig("pi", file2, hostText(readFileSync11(file2, "utf8")), "json") };
24875
25282
  } catch {
24876
25283
  return void 0;
24877
25284
  }
@@ -24930,8 +25337,8 @@ function piInstalledIn(env, home, pkgDir, cwd) {
24930
25337
  }
24931
25338
 
24932
25339
  // src/core/ops/doctor-env.ts
24933
- import { existsSync as existsSync9, readFileSync as readFileSync11, realpathSync as realpathSync6 } from "node:fs";
24934
- import { isAbsolute as isAbsolute4, join as join14, relative as relative4 } from "node:path";
25340
+ import { existsSync as existsSync9, readFileSync as readFileSync12, realpathSync as realpathSync6 } from "node:fs";
25341
+ import { isAbsolute as isAbsolute5, join as join15, relative as relative4 } from "node:path";
24935
25342
  function pass(id, detail = DOCTOR_PASS_DETAIL) {
24936
25343
  return { id, label: DOCTOR_LABEL[id], status: "PASS", detail };
24937
25344
  }
@@ -24946,7 +25353,7 @@ function warn(id, detail, fixCommand) {
24946
25353
  }
24947
25354
  function bundleVersion(bundleDir2) {
24948
25355
  try {
24949
- const v = JSON.parse(readFileSync11(join14(bundleDir2, D1_PACKAGE_FILE), "utf8")).version;
25356
+ const v = JSON.parse(readFileSync12(join15(bundleDir2, D1_PACKAGE_FILE), "utf8")).version;
24950
25357
  return typeof v === "string" && v !== "" ? v : void 0;
24951
25358
  } catch {
24952
25359
  return void 0;
@@ -25100,7 +25507,7 @@ function checkMcp(ctx, adapter) {
25100
25507
  function piCwdInside(worktree, piCwd) {
25101
25508
  if (piCwd === void 0 || !existsSync9(piCwd)) return false;
25102
25509
  const rel = relative4(worktree, realpathSync6.native(piCwd));
25103
- return rel === "" || !rel.startsWith("..") && !isAbsolute4(rel);
25510
+ return rel === "" || !rel.startsWith("..") && !isAbsolute5(rel);
25104
25511
  }
25105
25512
  function checkProject(i) {
25106
25513
  const bad = fail2("D7", D7_DETAIL(i.project.source), D7_FIX);
@@ -25108,6 +25515,20 @@ function checkProject(i) {
25108
25515
  if (i.adapter.projectSource === "pi:ctx.cwd" && !piCwdInside(i.project.worktree, i.piCwd)) return bad;
25109
25516
  return pass("D7");
25110
25517
  }
25518
+ function projectOrMissing(ctx) {
25519
+ try {
25520
+ return { project: ctx.project };
25521
+ } catch (err) {
25522
+ if (err instanceof CtxError && err.code === "NO_PROJECT") return { missing: String(err.vars.kind) };
25523
+ throw err;
25524
+ }
25525
+ }
25526
+ function noProjectRow(kind) {
25527
+ return fail2("D7", D7_NO_PROJECT_DETAIL(kind), D7_FIX);
25528
+ }
25529
+ function needsProjectRow(id) {
25530
+ return unknown2(id, DOCTOR_NEEDS_PROJECT_DETAIL);
25531
+ }
25111
25532
  function checkMode(adapter, hostPermission) {
25112
25533
  if (hostPermission === "missing") return fail2("D10", D10_PERMISSION_MISSING_DETAIL, D10_PERMISSION_FIX);
25113
25534
  if (hostPermission === "wired") return pass("D10", D10_PERMISSION_DETAIL(adapter.denyChannel));
@@ -25130,8 +25551,8 @@ function checkRuntimes(env, shellRow) {
25130
25551
  }
25131
25552
 
25132
25553
  // src/core/ops/omp-import.ts
25133
- import { join as join15 } from "node:path";
25134
- var { existsSync: existsSync10, readFileSync: readFileSync12 } = process.getBuiltinModule("node:fs");
25554
+ import { join as join16 } from "node:path";
25555
+ var { existsSync: existsSync10, readFileSync: readFileSync13 } = process.getBuiltinModule("node:fs");
25135
25556
  var OMP_DISABLED_SERVERS_KEY = "disabledServers";
25136
25557
  var OMP_MCP_FILE = "mcp.json";
25137
25558
  var OMP_CONFIG_FILE = "config.yml";
@@ -25139,13 +25560,13 @@ var ENABLED_PROVIDERS = "enabledProviders";
25139
25560
  var DISABLED_PROVIDERS = "disabledProviders";
25140
25561
  var CLAUDE_PROVIDER = "claude";
25141
25562
  var ALL_PROVIDERS = ["*", "all"];
25142
- function ompImportFiles(home) {
25143
- const agentDir = join15(home, ...AGENT_HOME_DIR.omp, PI_AGENT_DIR);
25144
- return { config: join15(agentDir, OMP_CONFIG_FILE), mcp: join15(agentDir, OMP_MCP_FILE), claude: join15(home, CLAUDE_USER_CONFIG_FILE) };
25563
+ function ompImportFiles(env, home) {
25564
+ const agentDir = ompAgentDirOf(env, home);
25565
+ return { config: join16(agentDir, OMP_CONFIG_FILE), mcp: join16(agentDir, OMP_MCP_FILE), claude: join16(home, CLAUDE_USER_CONFIG_FILE) };
25145
25566
  }
25146
25567
  function readText2(file2) {
25147
25568
  try {
25148
- return existsSync10(file2) ? hostText(readFileSync12(file2, "utf8")) : void 0;
25569
+ return existsSync10(file2) ? hostText(readFileSync13(file2, "utf8")) : void 0;
25149
25570
  } catch {
25150
25571
  return void 0;
25151
25572
  }
@@ -25273,11 +25694,11 @@ function ownHooks(block, shape, timeoutKey, native, agent) {
25273
25694
  var validTimeout = (v) => typeof v === "number" && Number.isFinite(v) && v > 0;
25274
25695
  function mcpFile(row5, home, env) {
25275
25696
  const spec = OWN_MCP_ENTRY[row5.id];
25276
- if (row5.id === "codex") return join16(codexDirOf(env, home), CONFIG_TOML_FILE);
25697
+ if (row5.id === "codex") return join17(codexDirOf(env, home), CONFIG_TOML_FILE);
25277
25698
  if (spec !== void 0) return ownMcpFileOf(row5.id, spec.file, env, home);
25278
- if (row5.id === "opencode") return join16(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
25699
+ if (row5.id === "opencode") return join17(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
25279
25700
  if (row5.id === "pi") {
25280
- return join16(piAgentDirOf(env, home), SETTINGS_FILE);
25701
+ return join17(piAgentDirOf(env, home), SETTINGS_FILE);
25281
25702
  }
25282
25703
  return null;
25283
25704
  }
@@ -25290,27 +25711,27 @@ function codexNativeDir(env, home) {
25290
25711
  const codexDir = codexDirOf(env, home);
25291
25712
  let enabled;
25292
25713
  try {
25293
- enabled = hostConfigValueAt(readParsed("codex", join16(codexDir, CONFIG_TOML_FILE)).value, ["plugins", CODEX_PLUGIN_KEY, "enabled"]);
25714
+ enabled = hostConfigValueAt(readParsed("codex", join17(codexDir, CONFIG_TOML_FILE)).value, ["plugins", CODEX_PLUGIN_KEY, "enabled"]);
25294
25715
  } catch {
25295
25716
  return null;
25296
25717
  }
25297
25718
  if (enabled !== true) return null;
25298
- const cache = join16(codexDir, "plugins", PLUGIN_CACHE_DIR_NAME);
25719
+ const cache = join17(codexDir, "plugins", PLUGIN_CACHE_DIR_NAME);
25299
25720
  if (!existsSync11(cache)) return null;
25300
25721
  const found = [];
25301
- for (const market of readdirSync6(cache)) {
25302
- const plugin = join16(cache, market, SERVER_KEY);
25722
+ for (const market of readdirSync7(cache)) {
25723
+ const plugin = join17(cache, market, SERVER_KEY);
25303
25724
  if (!existsSync11(plugin)) continue;
25304
- for (const version4 of readdirSync6(plugin).sort()) {
25305
- const dir = join16(plugin, version4, CODEX_PLUGIN_SUBDIR);
25306
- if (existsSync11(join16(dir, CODEX_PLUGIN_MCP_FILE))) found.push(dir);
25725
+ for (const version4 of readdirSync7(plugin).sort()) {
25726
+ const dir = join17(plugin, version4, CODEX_PLUGIN_SUBDIR);
25727
+ if (existsSync11(join17(dir, CODEX_PLUGIN_MCP_FILE))) found.push(dir);
25307
25728
  }
25308
25729
  }
25309
25730
  return found.length === 0 ? null : found[found.length - 1];
25310
25731
  }
25311
25732
  function nativeMcpWrong(dir, row5) {
25312
25733
  try {
25313
- const entry = hostConfigValueAt(readParsed(row5.id, join16(dir, CODEX_PLUGIN_MCP_FILE)).value, [MCP_SERVERS_FIELD, SERVER_KEY]);
25734
+ const entry = hostConfigValueAt(readParsed(row5.id, join17(dir, CODEX_PLUGIN_MCP_FILE)).value, [MCP_SERVERS_FIELD, SERVER_KEY]);
25314
25735
  if (!isObject4(entry)) return true;
25315
25736
  const args = list2(entry[MCP_ARGS_FIELD]);
25316
25737
  const script = args[0];
@@ -25381,17 +25802,17 @@ function opencodePluginDirs(configDir, worktree) {
25381
25802
  return [configDir, opencodeProjectDir(worktree)];
25382
25803
  }
25383
25804
  function opencodeProjectDir(worktree) {
25384
- return join16(worktree, OPENCODE_PROJECT_DIR);
25805
+ return join17(worktree, OPENCODE_PROJECT_DIR);
25385
25806
  }
25386
25807
  function packageResolves(fromDir) {
25387
25808
  for (let d = fromDir; ; d = dirname8(d)) {
25388
- if (existsSync11(join16(d, NODE_MODULES_DIR, SERVER_KEY, PACKAGE_JSON_FILE))) return true;
25809
+ if (existsSync11(join17(d, NODE_MODULES_DIR, SERVER_KEY, PACKAGE_JSON_FILE))) return true;
25389
25810
  if (dirname8(d) === d) return false;
25390
25811
  }
25391
25812
  }
25392
25813
  function opencodeDirPlugins(dirs) {
25393
25814
  const bundle = opencodePluginFile();
25394
- const ownFile = join16(bundle, ...OPENCODE_PLUGIN_PATH).split("\\").join("/");
25815
+ const ownFile = join17(bundle, ...OPENCODE_PLUGIN_PATH).split("\\").join("/");
25395
25816
  const isModule = (p) => OWN_PLUGIN_MODULES.includes(p);
25396
25817
  const isPath = (p) => {
25397
25818
  if (p === ownFile || p === `${FILE_URL_PREFIX}${ownFile}`) return true;
@@ -25401,20 +25822,20 @@ function opencodeDirPlugins(dirs) {
25401
25822
  };
25402
25823
  const out = [];
25403
25824
  for (const dir of dirs) {
25404
- const pdir = join16(dir, OPENCODE_PLUGINS_DIR);
25825
+ const pdir = join17(dir, OPENCODE_PLUGINS_DIR);
25405
25826
  let names;
25406
25827
  try {
25407
- names = readdirSync6(pdir);
25828
+ names = readdirSync7(pdir);
25408
25829
  } catch {
25409
25830
  continue;
25410
25831
  }
25411
25832
  for (const name of names) {
25412
- const loose = OPENCODE_PLUGIN_EXTS.some((x) => name.endsWith(x)) ? [join16(pdir, name)] : [];
25413
- const files = [...loose, ...OPENCODE_PLUGIN_EXTS.map((x) => join16(pdir, name, `${OPENCODE_PLUGIN_INDEX}${x}`))];
25833
+ const loose = OPENCODE_PLUGIN_EXTS.some((x) => name.endsWith(x)) ? [join17(pdir, name)] : [];
25834
+ const files = [...loose, ...OPENCODE_PLUGIN_EXTS.map((x) => join17(pdir, name, `${OPENCODE_PLUGIN_INDEX}${x}`))];
25414
25835
  for (const f of files) {
25415
25836
  let text;
25416
25837
  try {
25417
- const b = readFileSync13(f);
25838
+ const b = readFileSync14(f);
25418
25839
  if (b.length > OPENCODE_DIR_FILE_MAX) continue;
25419
25840
  text = b.toString("utf8");
25420
25841
  } catch {
@@ -25425,7 +25846,7 @@ function opencodeDirPlugins(dirs) {
25425
25846
  const loads = lits.some((p) => {
25426
25847
  if (isModule(p)) return packageResolves(dirname8(f));
25427
25848
  const bare2 = p.startsWith(FILE_URL_PREFIX) ? p.slice(FILE_URL_PREFIX.length) : p;
25428
- return existsSync11(isAbsolute5(bare2) ? bare2 : resolve9(dirname8(f), bare2));
25849
+ return existsSync11(isAbsolute6(bare2) ? bare2 : resolve9(dirname8(f), bare2));
25429
25850
  });
25430
25851
  out.push({ file: f, loads });
25431
25852
  }
@@ -25444,18 +25865,18 @@ function opencodeMcpOwn(entry) {
25444
25865
  }
25445
25866
  function opencodeFileValue(file2) {
25446
25867
  if (!existsSync11(file2)) return {};
25447
- return parseHostConfig("opencode", file2, hostText(readFileSync13(file2, "utf8")), "jsonc");
25868
+ return parseHostConfig("opencode", file2, hostText(readFileSync14(file2, "utf8")), "jsonc");
25448
25869
  }
25449
25870
  function opencodeValueListed(value) {
25450
25871
  const bundle = opencodePluginFile();
25451
- const own4 = [bundle, join16(bundle, ...OPENCODE_PLUGIN_PATH)];
25872
+ const own4 = [bundle, join17(bundle, ...OPENCODE_PLUGIN_PATH)];
25452
25873
  if ([OPENCODE_PLUGIN_KEY, OPENCODE_PLUGINS_KEY].some((key) => list2(isObject4(value) ? value[key] : void 0).some((e) => isOwnOpencodeEntry(e, key, own4)))) return true;
25453
25874
  const mcp = isObject4(value) && isObject4(value.mcp) ? value.mcp : {};
25454
25875
  return opencodeMcpOwn(mcp[SERVER_KEY]) || isObject4(mcp.servers) && opencodeMcpOwn(mcp.servers[SERVER_KEY]);
25455
25876
  }
25456
25877
  function opencodeListed(file2, worktree) {
25457
25878
  const dirs = [dirname8(file2), worktree];
25458
- if (dirs.some((dir) => OPENCODE_CONFIG_FILES.some((name) => opencodeValueListed(opencodeFileValue(join16(dir, name)))))) return true;
25879
+ if (dirs.some((dir) => OPENCODE_CONFIG_FILES.some((name) => opencodeValueListed(opencodeFileValue(join17(dir, name)))))) return true;
25459
25880
  return opencodeDirPlugin(opencodePluginDirs(dirname8(file2), worktree)) !== void 0;
25460
25881
  }
25461
25882
  function mcpWrong(row5, home, env, worktree) {
@@ -25477,7 +25898,7 @@ function mcpWrong(row5, home, env, worktree) {
25477
25898
  function hookFile(row5, spec, home, env, worktree) {
25478
25899
  const root = spec.root === "plugin" ? resolvePluginRoot(row5, env, worktree) : spec.root === "home" ? home : worktree;
25479
25900
  const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
25480
- const file2 = native !== null ? join16(native, CODEX_PLUGIN_HOOKS_FILE) : row5.id === "codex" ? join16(codexDirOf(env, home), HOOKS_JSON_FILE) : row5.id === "copilot-cli" ? join16(copilotDirOf(env, home), ...spec.file.slice(1)) : row5.id === "kiro" ? join16(kiroDirOf(env, home), ...spec.file.slice(1)) : join16(root, ...spec.file);
25901
+ const file2 = native !== null ? join17(native, CODEX_PLUGIN_HOOKS_FILE) : row5.id === "codex" ? join17(codexDirOf(env, home), HOOKS_JSON_FILE) : row5.id === "copilot-cli" ? join17(copilotDirOf(env, home), ...spec.file.slice(1)) : row5.id === "kiro" ? join17(kiroDirOf(env, home), ...spec.file.slice(1)) : join17(root, ...spec.file);
25481
25902
  return file2;
25482
25903
  }
25483
25904
  function hookParts(row5, home, env, worktree) {
@@ -25488,7 +25909,7 @@ function hookParts(row5, home, env, worktree) {
25488
25909
  const file2 = hookFile(row5, spec, home, env, worktree);
25489
25910
  block = hostConfigValueAt(readParsed(row5.id, file2).value, spec.key);
25490
25911
  if (row5.id === "codex") {
25491
- const config4 = readParsed(row5.id, join16(codexDirOf(env, home), CONFIG_TOML_FILE)).value;
25912
+ const config4 = readParsed(row5.id, join17(codexDirOf(env, home), CONFIG_TOML_FILE)).value;
25492
25913
  if (hostConfigValueAt(config4, CODEX_FEATURES_HOOKS_KEY) === false) return [PART_HOOKS];
25493
25914
  }
25494
25915
  } catch {
@@ -25523,7 +25944,7 @@ function checkHostConfig(row5, env, worktree) {
25523
25944
  if ("installs" in choice) return fail3("D3", D3_ROOT_DETAIL(choice.installs.map((r) => r.installPath)), D3_ROOT_FIX(choice.installs));
25524
25945
  }
25525
25946
  if (row5.id === "pi") return checkPiInstall(env, home, worktree);
25526
- if (row5.id === "omp") return checkOmpInstall(home);
25947
+ if (row5.id === "omp") return checkOmpInstall(env, home);
25527
25948
  const parts = [...mcpWrong(row5, home, env, worktree) ? [PART_MCP] : [], ...hookParts(row5, home, env, worktree)];
25528
25949
  if (parts.length === 0) return pass2("D3");
25529
25950
  const detail = D3_DETAIL(parts);
@@ -25533,13 +25954,12 @@ function checkHostConfig(row5, env, worktree) {
25533
25954
  function checkPiInstall(env, home, worktree) {
25534
25955
  const found = piInstalledIn(env, home, ownBundleDir(), worktree);
25535
25956
  if (found !== void 0) return { ...pass2("D3"), detail: found };
25536
- return fail3("D3", D3_DETAIL([PART_MCP]) + D4_REASON_JOIN + join16(piAgentDirOf(env, home), SETTINGS_FILE), NATIVE_INSTALL.pi[0]);
25957
+ return fail3("D3", D3_DETAIL([PART_MCP]) + D4_REASON_JOIN + join17(piAgentDirOf(env, home), SETTINGS_FILE), NATIVE_INSTALL.pi[0]);
25537
25958
  }
25538
- var OMP_PLUGINS_DIR = "plugins";
25539
25959
  var OMP_LOCK_FILE = "omp-plugins.lock.json";
25540
25960
  function readJson2(file2) {
25541
25961
  try {
25542
- const doc = JSON.parse(readFileSync13(file2, "utf8"));
25962
+ const doc = JSON.parse(readFileSync14(file2, "utf8"));
25543
25963
  return typeof doc === "object" && doc !== null ? doc : void 0;
25544
25964
  } catch {
25545
25965
  return void 0;
@@ -25549,10 +25969,10 @@ function ownEntry(doc, key) {
25549
25969
  const map2 = doc?.[key];
25550
25970
  return typeof map2 === "object" && map2 !== null ? map2[SERVER_KEY] : void 0;
25551
25971
  }
25552
- function checkOmpInstall(home) {
25553
- const dir = join16(home, ...AGENT_HOME_DIR.omp, OMP_PLUGINS_DIR);
25554
- const lock = join16(dir, OMP_LOCK_FILE);
25555
- const pkg = join16(dir, PI_PACKAGE_JSON_FILE);
25972
+ function checkOmpInstall(env, home) {
25973
+ const dir = ompPluginsDirOf(env, home);
25974
+ const lock = join17(dir, OMP_LOCK_FILE);
25975
+ const pkg = join17(dir, PI_PACKAGE_JSON_FILE);
25556
25976
  const entry = ownEntry(readJson2(lock), "plugins");
25557
25977
  const missing2 = (file2) => fail3("D3", D3_DETAIL([PART_MCP]) + D4_REASON_JOIN + file2, NATIVE_INSTALL.omp[0]);
25558
25978
  if (typeof entry !== "object" || entry === null) return missing2(lock);
@@ -25566,12 +25986,26 @@ function ompInfoLines(env, version4) {
25566
25986
  out.push(OMP_CONTENT_INFO, OMP_PRINT_MODE_INFO, OMP_SCRIPTS_INFO);
25567
25987
  const home = homeDirOf(env);
25568
25988
  if (home === null) return out;
25569
- const files = ompImportFiles(home);
25989
+ const files = ompImportFiles(env, home);
25570
25990
  if (!ompImportsUs(files, env)) return out;
25571
25991
  const listed = readJson2(files.mcp)?.[OMP_DISABLED_SERVERS_KEY];
25572
25992
  if (!(Array.isArray(listed) && listed.includes(SERVER_KEY))) out.push(OMP_IMPORT_INFO(files.claude, files.mcp));
25573
25993
  return out;
25574
25994
  }
25995
+ function replaceTriggerInfoLines(agent, env, project) {
25996
+ const files = [];
25997
+ const home = homeDirOf(env);
25998
+ if (agent === "claude-code") {
25999
+ if (home !== null) files.push(join17(claudeDirOf(env, home), SETTINGS_FILE));
26000
+ if (project !== void 0 && project !== "") files.push(join17(project, HOST_CONFIG_DIR_NAME, SETTINGS_FILE));
26001
+ }
26002
+ const where = [...new Set(files)].filter((f) => {
26003
+ const block = readJson2(f)?.env;
26004
+ return typeof block === "object" && block !== null && REPLACE_TRIGGER_ENV in block;
26005
+ });
26006
+ if (where.length > 0) return [REPLACE_TRIGGER_RETIRED_INFO(where.join(" and "))];
26007
+ return env[REPLACE_TRIGGER_ENV] === void 0 ? [] : [REPLACE_TRIGGER_RETIRED_INFO("the process env")];
26008
+ }
25575
26009
  function checkV1Leftovers(agent, home, scope = {}) {
25576
26010
  const findings = detectV1(agent, home, scope);
25577
26011
  if (findings.length === 0) return pass2("D4");
@@ -25589,10 +26023,10 @@ function parsedOrNull(agent, file2, jsonc) {
25589
26023
  }
25590
26024
  function checkDoubleFire(agent, worktree) {
25591
26025
  if (agent !== "claude-code" && agent !== "vscode") return pass2("D5b");
25592
- const claude = parsedOrNull(agent, join16(worktree, HOST_CONFIG_DIR_NAME, SETTINGS_FILE), false);
26026
+ const claude = parsedOrNull(agent, join17(worktree, HOST_CONFIG_DIR_NAME, SETTINGS_FILE), false);
25593
26027
  const hooks = isObject4(claude) ? claude[HOOKS_KEY] : void 0;
25594
26028
  const hooksOn = isObject4(hooks) && Object.keys(hooks).length > 0;
25595
- const vscode = parsedOrNull(agent, join16(worktree, VSCODE_DIR_NAME, VSCODE_SETTINGS_FILE), true);
26029
+ const vscode = parsedOrNull(agent, join17(worktree, VSCODE_DIR_NAME, VSCODE_SETTINGS_FILE), true);
25596
26030
  const useClaudeHooks = isObject4(vscode) && vscode[VSCODE_CLAUDE_HOOKS_SETTING] === true;
25597
26031
  return hooksOn && useClaudeHooks ? fail3("D5b", D5B_DETAIL, D5B_FIX) : pass2("D5b");
25598
26032
  }
@@ -25603,7 +26037,7 @@ function configPaths(row5, env, worktree) {
25603
26037
  const mcp = mcpFile(row5, home, env);
25604
26038
  if (mcp !== null) out.push({ label: "MCP entry", path: mcp });
25605
26039
  const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
25606
- if (native !== null) out.push({ label: "Codex plugin MCP", path: join16(native, CODEX_PLUGIN_MCP_FILE) });
26040
+ if (native !== null) out.push({ label: "Codex plugin MCP", path: join17(native, CODEX_PLUGIN_MCP_FILE) });
25607
26041
  const spec = HOOK_HOST_FILE[row5.id];
25608
26042
  if (spec !== null) {
25609
26043
  try {
@@ -25623,7 +26057,7 @@ function configPaths(row5, env, worktree) {
25623
26057
  }
25624
26058
 
25625
26059
  // src/core/ops/doctor-db.ts
25626
- import { existsSync as existsSync12, statSync as statSync6 } from "node:fs";
26060
+ import { existsSync as existsSync12, statSync as statSync7 } from "node:fs";
25627
26061
  var unknown3 = (id, detail) => ({ id, label: DOCTOR_LABEL[id], status: "UNKNOWN", detail });
25628
26062
  var pass3 = (id, detail) => ({ id, label: DOCTOR_LABEL[id], status: "PASS", detail });
25629
26063
  var fail4 = (detail, fixCommand) => ({ id: "D8", label: DOCTOR_LABEL.D8, status: "FAIL", detail, fixCommand });
@@ -25634,7 +26068,7 @@ function isCorrupt2(err) {
25634
26068
  const primary = code & SQLITE_PRIMARY_CODE_MASK;
25635
26069
  return primary === SQLITE_CORRUPT_CODE || primary === SQLITE_NOTADB_CODE;
25636
26070
  }
25637
- var message2 = (err) => err instanceof Error ? err.message : String(err);
26071
+ var message3 = (err) => err instanceof Error ? err.message : String(err);
25638
26072
  async function loadSqlite2() {
25639
26073
  try {
25640
26074
  return await import(SQLITE_MODULE);
@@ -25665,7 +26099,7 @@ function orphanFiles(dbPath) {
25665
26099
  const files = [];
25666
26100
  for (const suffix of [DB_WAL_SUFFIX, DB_SHM_SUFFIX]) {
25667
26101
  const path8 = dbPath + suffix;
25668
- if (existsSync12(path8)) files.push({ path: path8, bytes: statSync6(path8).size });
26102
+ if (existsSync12(path8)) files.push({ path: path8, bytes: statSync7(path8).size });
25669
26103
  }
25670
26104
  return files.length > 0 && !existsSync12(dbPath) ? files : [];
25671
26105
  }
@@ -25693,7 +26127,7 @@ async function checkDb(project) {
25693
26127
  return { row: pass3("D8", DOCTOR_PASS_DETAIL), ...clean };
25694
26128
  } catch (err) {
25695
26129
  if (isCorrupt2(err)) return { row: fail4(D8_INTEGRITY_DETAIL, D8_INTEGRITY_FIX), schemaStale: false, integrityFailed: true, orphan: [] };
25696
- return { row: unknown3("D8", message2(err)), ...clean };
26130
+ return { row: unknown3("D8", message3(err)), ...clean };
25697
26131
  } finally {
25698
26132
  raw?.close();
25699
26133
  }
@@ -25709,14 +26143,14 @@ async function checkIndex(project) {
25709
26143
  const chunks = Number(cell(raw.prepare("SELECT count(*) FROM chunks").get()));
25710
26144
  return pass3("D9", D9_INDEX_DETAIL(sources, chunks));
25711
26145
  } catch (err) {
25712
- return unknown3("D9", message2(err));
26146
+ return unknown3("D9", message3(err));
25713
26147
  } finally {
25714
26148
  raw?.close();
25715
26149
  }
25716
26150
  }
25717
26151
 
25718
26152
  // src/core/ops/doctor-hook.ts
25719
- import { existsSync as existsSync14, mkdirSync as mkdirSync4, mkdtempSync, readFileSync as readFileSync14, realpathSync as realpathSync8, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
26153
+ import { existsSync as existsSync14, mkdirSync as mkdirSync5, mkdtempSync, readFileSync as readFileSync15, realpathSync as realpathSync8, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
25720
26154
  import { tmpdir as tmpdir2 } from "node:os";
25721
26155
  import path7 from "node:path";
25722
26156
 
@@ -27550,7 +27984,7 @@ import { spawn as spawn3, spawnSync as spawnSync2 } from "node:child_process";
27550
27984
 
27551
27985
  // src/setup/spawn-bin.ts
27552
27986
  import { spawnSync } from "node:child_process";
27553
- import { accessSync as accessSync2, constants as fsc, statSync as statSync7 } from "node:fs";
27987
+ import { accessSync as accessSync2, constants as fsc, statSync as statSync8 } from "node:fs";
27554
27988
  import path5 from "node:path";
27555
27989
  var WIN_EXT = ".COM;.EXE;.BAT;.CMD";
27556
27990
  var WIN_SHIM_EXTS = Object.freeze([".cmd", ".bat"]);
@@ -27568,7 +28002,7 @@ function whichBin(bin, env, platform = process.platform) {
27568
28002
  const f = path5.join(dir, n);
27569
28003
  try {
27570
28004
  accessSync2(f, fsc.X_OK);
27571
- if (statSync7(f).isFile()) return f;
28005
+ if (statSync8(f).isFile()) return f;
27572
28006
  } catch {
27573
28007
  }
27574
28008
  }
@@ -27770,7 +28204,7 @@ function loadFixture(bundleDir2, agent) {
27770
28204
  if (!existsSync14(file2)) return { cause: D5_FIXTURE_FILE_ABSENT(file2) };
27771
28205
  let all;
27772
28206
  try {
27773
- all = JSON.parse(hostText(readFileSync14(file2, "utf8")));
28207
+ all = JSON.parse(hostText(readFileSync15(file2, "utf8")));
27774
28208
  } catch (err) {
27775
28209
  return { cause: D5_FIXTURE_PARSE(file2, err instanceof Error ? err.message : String(err)) };
27776
28210
  }
@@ -27862,7 +28296,7 @@ async function mediaProbe(i, timeoutMs) {
27862
28296
  const home = mkdtempSync(path7.join(tmpdir2(), "cm-d5-media-"));
27863
28297
  try {
27864
28298
  const filePath = path7.join(home, "d5-media-probe.png");
27865
- writeFileSync2(filePath, Buffer.concat([PNG_SIGNATURE, Buffer.alloc(OUTPUT_CAP + 1)]));
28299
+ writeFileSync3(filePath, Buffer.concat([PNG_SIGNATURE, Buffer.alloc(OUTPUT_CAP + 1)]));
27866
28300
  const node3 = nodeLaunch({ ...i.env, HOME: home, USERPROFILE: home });
27867
28301
  const r = await runProcess([node3.file, path7.join(i.bundleDir, HOOK_ENTRY_FILE), AGENT_ARG, i.agent], {
27868
28302
  cwd: i.bundleDir,
@@ -27889,9 +28323,9 @@ async function ownProbe(i, timeoutMs) {
27889
28323
  try {
27890
28324
  const cfg = path7.join(home, ".claude");
27891
28325
  const refs = path7.join(cfg, "skills", "d5-probe", "references");
27892
- mkdirSync4(refs, { recursive: true });
28326
+ mkdirSync5(refs, { recursive: true });
27893
28327
  const filePath = path7.join(refs, "d5-own-probe.md");
27894
- writeFileSync2(filePath, "# d5 own probe\n".repeat(Math.ceil((OUTPUT_CAP + 1) / 15)));
28328
+ writeFileSync3(filePath, "# d5 own probe\n".repeat(Math.ceil((OUTPUT_CAP + 1) / 15)));
27895
28329
  const node3 = nodeLaunch({ ...i.env, HOME: home, USERPROFILE: home, CLAUDE_CONFIG_DIR: cfg });
27896
28330
  const r = await runProcess([node3.file, path7.join(i.bundleDir, HOOK_ENTRY_FILE), AGENT_ARG, i.agent], {
27897
28331
  cwd: i.bundleDir,
@@ -28045,24 +28479,24 @@ async function checkHookRoundTrip(i) {
28045
28479
  }
28046
28480
 
28047
28481
  // src/core/ops/db-heal.ts
28048
- import { existsSync as existsSync15, mkdirSync as mkdirSync6, rmSync as rmSync4 } from "node:fs";
28049
- import { basename as basename4, dirname as dirname9, join as join18 } from "node:path";
28482
+ import { existsSync as existsSync15, mkdirSync as mkdirSync7, rmSync as rmSync4 } from "node:fs";
28483
+ import { basename as basename4, dirname as dirname9, join as join19 } from "node:path";
28050
28484
 
28051
28485
  // src/core/store/owners.ts
28052
- import { mkdirSync as mkdirSync5, readdirSync as readdirSync7, readFileSync as readFileSync15, rmSync as rmSync3, writeFileSync as writeFileSync3 } from "node:fs";
28053
- import { basename as basename3, join as join17 } from "node:path";
28486
+ import { mkdirSync as mkdirSync6, readdirSync as readdirSync8, readFileSync as readFileSync16, rmSync as rmSync3, writeFileSync as writeFileSync4 } from "node:fs";
28487
+ import { basename as basename3, join as join18 } from "node:path";
28054
28488
  function ownersDir(configDir, projectKey) {
28055
- return join17(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
28489
+ return join18(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
28056
28490
  }
28057
28491
  function ownerFile(configDir, projectKey, serverId) {
28058
- return join17(ownersDir(configDir, projectKey), serverId + OWNER_PID_EXT);
28492
+ return join18(ownersDir(configDir, projectKey), serverId + OWNER_PID_EXT);
28059
28493
  }
28060
28494
  function errCode3(err) {
28061
28495
  return err.code;
28062
28496
  }
28063
28497
  function writeOwnerPid(configDir, projectKey, serverId) {
28064
- mkdirSync5(ownersDir(configDir, projectKey), { recursive: true });
28065
- writeFileSync3(ownerFile(configDir, projectKey, serverId), String(process.pid), "utf8");
28498
+ mkdirSync6(ownersDir(configDir, projectKey), { recursive: true });
28499
+ writeFileSync4(ownerFile(configDir, projectKey, serverId), String(process.pid), "utf8");
28066
28500
  }
28067
28501
  function removeOwnerPid(configDir, projectKey, serverId) {
28068
28502
  rmSync3(ownerFile(configDir, projectKey, serverId), { force: true });
@@ -28082,7 +28516,7 @@ function listLiveOwners(configDir, projectKey) {
28082
28516
  const dir = ownersDir(configDir, projectKey);
28083
28517
  let names;
28084
28518
  try {
28085
- names = readdirSync7(dir);
28519
+ names = readdirSync8(dir);
28086
28520
  } catch (err) {
28087
28521
  if (errCode3(err) === "ENOENT") return [];
28088
28522
  throw err;
@@ -28090,10 +28524,10 @@ function listLiveOwners(configDir, projectKey) {
28090
28524
  const live = [];
28091
28525
  for (const name of names) {
28092
28526
  if (!name.endsWith(OWNER_PID_EXT)) continue;
28093
- const file2 = join17(dir, name);
28527
+ const file2 = join18(dir, name);
28094
28528
  let text;
28095
28529
  try {
28096
- text = readFileSync15(file2, "utf8");
28530
+ text = readFileSync16(file2, "utf8");
28097
28531
  } catch (err) {
28098
28532
  if (errCode3(err) === "ENOENT") continue;
28099
28533
  throw err;
@@ -28162,11 +28596,11 @@ function utcStamp(now) {
28162
28596
  return now.toISOString().slice(0, 19).replaceAll("-", "").replaceAll(":", "") + "Z";
28163
28597
  }
28164
28598
  function makeOrphanDir(projectDir) {
28165
- const base = join18(projectDir, ORPHAN_DIR_PREFIX + utcStamp(/* @__PURE__ */ new Date()));
28599
+ const base = join19(projectDir, ORPHAN_DIR_PREFIX + utcStamp(/* @__PURE__ */ new Date()));
28166
28600
  for (let n = 1; ; n += 1) {
28167
28601
  const dir = n === 1 ? base : base + "-" + String(n);
28168
28602
  try {
28169
- mkdirSync6(dir);
28603
+ mkdirSync7(dir);
28170
28604
  return dir;
28171
28605
  } catch (err) {
28172
28606
  if (err.code !== "EEXIST") throw err;
@@ -28179,7 +28613,7 @@ async function healOrphan(project, files, row5) {
28179
28613
  try {
28180
28614
  dir = makeOrphanDir(dirname9(project.dbPath));
28181
28615
  for (const f of files) {
28182
- const to = join18(dir, basename4(f.path));
28616
+ const to = join19(dir, basename4(f.path));
28183
28617
  renameWithRetry(f.path, to);
28184
28618
  moved.push({ path: to, bytes: f.bytes });
28185
28619
  }
@@ -28277,8 +28711,8 @@ function unsupportedHostOf(sig) {
28277
28711
 
28278
28712
  // src/core/ops/doctor-issue.ts
28279
28713
  import { spawnSync as spawnSync3 } from "node:child_process";
28280
- import { closeSync as closeSync2, existsSync as existsSync16, fstatSync, mkdirSync as mkdirSync7, openSync as openSync2, readFileSync as readFileSync16, readSync as readSync2, realpathSync as realpathSync9, writeFileSync as writeFileSync4 } from "node:fs";
28281
- import { delimiter, dirname as dirname10, join as join19 } from "node:path";
28714
+ import { closeSync as closeSync2, existsSync as existsSync16, fstatSync, mkdirSync as mkdirSync8, openSync as openSync2, readFileSync as readFileSync17, readSync as readSync2, realpathSync as realpathSync9, writeFileSync as writeFileSync5 } from "node:fs";
28715
+ import { delimiter, dirname as dirname10, join as join20 } from "node:path";
28282
28716
  var TOKEN_PREFIXES = ["ghp_", "gho_", "github_pat_", "sk-", "xoxb-", "AKIA"];
28283
28717
  function tildeOf(env) {
28284
28718
  const home = homeDirOf(env);
@@ -28334,8 +28768,8 @@ function onPath(env, tool) {
28334
28768
  const out = [];
28335
28769
  for (const dir of (envValue(env, "PATH") ?? "").split(delimiter)) {
28336
28770
  if (dir === "") continue;
28337
- for (const n of names) if (existsSync16(join19(dir, n))) {
28338
- out.push(join19(dir, n));
28771
+ for (const n of names) if (existsSync16(join20(dir, n))) {
28772
+ out.push(join20(dir, n));
28339
28773
  break;
28340
28774
  }
28341
28775
  }
@@ -28363,9 +28797,11 @@ function hookLogTail(env) {
28363
28797
  }
28364
28798
  async function journalRows(ctx) {
28365
28799
  const head2 = ["| kind | tool | bytes | ok | exit_code | created_at |", "|---|---|---|---|---|---|"];
28366
- if (!existsSync16(ctx.project.dbPath)) return [`(context.db is absent at ${ctx.project.dbPath})`];
28800
+ const p = projectOrMissing(ctx);
28801
+ if ("missing" in p) return [`(no project: ${D7_NO_PROJECT_DETAIL(p.missing)})`];
28802
+ if (!existsSync16(p.project.dbPath)) return [`(context.db is absent at ${p.project.dbPath})`];
28367
28803
  try {
28368
- const db = await openDb(ctx.project, { readOnly: true });
28804
+ const db = await openDb(p.project, { readOnly: true });
28369
28805
  try {
28370
28806
  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();
28371
28807
  const cell5 = (v) => v === null || v === void 0 ? "" : String(v);
@@ -28381,8 +28817,8 @@ function agentConfig(adapter, env, worktree) {
28381
28817
  const home = homeDirOf(env);
28382
28818
  const files = configPaths(adapter, env, worktree);
28383
28819
  if (home !== null) {
28384
- if (adapter.id === "claude-code") files.push({ label: "agent settings (enabledPlugins)", path: join19(claudeDirOf(env, home), SETTINGS_FILE) });
28385
- if (adapter.id === "codex") files.push({ label: "agent config (plugins, trust)", path: join19(codexDirOf(env, home), CONFIG_TOML_FILE) });
28820
+ if (adapter.id === "claude-code") files.push({ label: "agent settings (enabledPlugins)", path: join20(claudeDirOf(env, home), SETTINGS_FILE) });
28821
+ if (adapter.id === "codex") files.push({ label: "agent config (plugins, trust)", path: join20(codexDirOf(env, home), CONFIG_TOML_FILE) });
28386
28822
  }
28387
28823
  const out = [];
28388
28824
  const seen = /* @__PURE__ */ new Set();
@@ -28395,7 +28831,7 @@ function agentConfig(adapter, env, worktree) {
28395
28831
  }
28396
28832
  let text = "";
28397
28833
  try {
28398
- text = readFileSync16(f.path, "utf8");
28834
+ text = readFileSync17(f.path, "utf8");
28399
28835
  } catch (err) {
28400
28836
  out.push(`${f.label}: ${f.path} (read: ${err instanceof Error ? err.message : String(err)})`);
28401
28837
  continue;
@@ -28424,6 +28860,7 @@ async function buildIssueBody(i) {
28424
28860
  const failRows = i.rows.filter((r) => r.status !== "PASS");
28425
28861
  const envNames = DOCTOR_ENV_NAMES.map((n) => i.env[n] === void 0 ? `${n} (unset)` : `${n}=${i.env[n]}`);
28426
28862
  const pathTools = DOCTOR_PATH_TOOLS.map((t) => `PATH holds ${t}: ${onPath(i.env, t).join(", ") || "(absent)"}`);
28863
+ const p = projectOrMissing(i.ctx);
28427
28864
  const sections = {
28428
28865
  "Summary": [summaryOf(agent, i.rows, i.unsupported)],
28429
28866
  "ctx-report": [i.table],
@@ -28434,7 +28871,7 @@ async function buildIssueBody(i) {
28434
28871
  ],
28435
28872
  "Hook errors": ["hook-errors.log, last " + DOCTOR_HOOK_LOG_LINES + " lines (UTC):", "```", ...hookLogTail(i.env), "```"],
28436
28873
  "Journal rows": ["events, newest first, last " + DOCTOR_JOURNAL_ROWS + " (bodies stay local):", ...await journalRows(i.ctx)],
28437
- "Agent config": agentConfig(i.adapter, i.env, i.ctx.project.worktree),
28874
+ "Agent config": agentConfig(i.adapter, i.env, "project" in p ? p.project.worktree : process.cwd()),
28438
28875
  "Expected": ["Expected: <the agent fills this in: what should happen, with the byte count>"],
28439
28876
  "Steps": [
28440
28877
  "Reproduced: <yes (2 of 2) or 1 of 2>",
@@ -28455,7 +28892,7 @@ async function buildIssueBody(i) {
28455
28892
  `git: ${gitVersion(i.env)}`,
28456
28893
  ...pathTools,
28457
28894
  ...envNames,
28458
- `Project: ${i.ctx.project.worktree} (key ${i.ctx.project.projectKey})`,
28895
+ "project" in p ? `Project: ${p.project.worktree} (key ${p.project.projectKey})` : `Project: ${D7_NO_PROJECT_DETAIL(p.missing)}`,
28459
28896
  "Filed by: <your agent name, version, model id>"
28460
28897
  ]
28461
28898
  };
@@ -28466,10 +28903,10 @@ async function buildIssueBody(i) {
28466
28903
  async function writeIssueReport(i) {
28467
28904
  const tilde = tildeOf(i.env);
28468
28905
  const body = await buildIssueBody(i);
28469
- const dir = join19(resolveConfigDir(i.env), DOCTOR_REPORTS_DIR);
28470
- mkdirSync7(dir, { recursive: true });
28471
- const file2 = join19(dir, `${DOCTOR_REPORT_FILE_PREFIX}${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
28472
- writeFileSync4(file2, body);
28906
+ const dir = join20(resolveConfigDir(i.env), DOCTOR_REPORTS_DIR);
28907
+ mkdirSync8(dir, { recursive: true });
28908
+ const file2 = join20(dir, `${DOCTOR_REPORT_FILE_PREFIX}${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
28909
+ writeFileSync5(file2, body);
28473
28910
  const shown2 = tilde(file2);
28474
28911
  const title = issueTitle(i.adapter.id, i.rows, i.unsupported);
28475
28912
  const gh = [`gh issue create --repo ${ISSUE_REPO_SLUG} --label bug \\`, `${DOCTOR_GH_NEXT}title ${JSON.stringify(title)} \\`, `${DOCTOR_GH_NEXT}body-file ${shown2}`];
@@ -28481,6 +28918,25 @@ function formUrl(title, summary) {
28481
28918
  return full.length < ISSUE_URL_MAX ? full : base;
28482
28919
  }
28483
28920
 
28921
+ // src/core/index/text.ts
28922
+ function storeText(db, project, sessionId, sourceKind, label2, text, kind, chunks = chunkText(text, kind)) {
28923
+ const sourceId = ftsInsert(db, {
28924
+ projectKey: project.projectKey,
28925
+ sessionId,
28926
+ worktree: project.worktree,
28927
+ agent: project.agent,
28928
+ kind: sourceKind,
28929
+ label: label2,
28930
+ bytes: Buffer.byteLength(text, "utf8"),
28931
+ chunkCount: chunks.length,
28932
+ createdAt: Date.now()
28933
+ }, chunks);
28934
+ return { sourceId, chunks: chunks.length };
28935
+ }
28936
+ function indexText(db, ctx, sessionId, source, text, kind, chunks) {
28937
+ return storeText(db, ctx, sessionId, "content", source, text, kind, chunks);
28938
+ }
28939
+
28484
28940
  // src/core/tools/doctor.ts
28485
28941
  var ctxDoctorSchema = external_exports.object({}).strict();
28486
28942
  function lineOf2(err) {
@@ -28494,10 +28950,10 @@ async function guard(id, run) {
28494
28950
  return { id, label: DOCTOR_LABEL[id], status: "UNKNOWN", detail: lineOf2(err) };
28495
28951
  }
28496
28952
  }
28497
- async function codexDb(ctx, adapter) {
28498
- if (adapter.id !== "codex" || !existsSync17(ctx.project.dbPath)) return null;
28953
+ async function codexDb(project, adapter) {
28954
+ if (adapter.id !== "codex" || !existsSync17(project.dbPath)) return null;
28499
28955
  try {
28500
- return await openDb(ctx.project, { readOnly: true });
28956
+ return await openDb(project, { readOnly: true });
28501
28957
  } catch {
28502
28958
  return null;
28503
28959
  }
@@ -28508,12 +28964,12 @@ function d1UpdateCommand(agent, env, other) {
28508
28964
  function unsupportedRow(id, h) {
28509
28965
  return { id, label: DOCTOR_LABEL[id], status: "WARN", detail: UNSUPPORTED_HOST_LINE(h.name) };
28510
28966
  }
28511
- async function hookRow(ctx, adapter, host) {
28512
- const db = await codexDb(ctx, adapter);
28967
+ async function hookRow(ctx, project, adapter, host) {
28968
+ const db = await codexDb(project, adapter);
28513
28969
  const runStart = Date.now();
28514
28970
  try {
28515
28971
  const row5 = await checkHookRoundTrip({
28516
- worktree: ctx.project.worktree,
28972
+ worktree: project.worktree,
28517
28973
  agent: adapter.id,
28518
28974
  bundleDir: host.bundleDir,
28519
28975
  env: buildChildEnv(host.env),
@@ -28531,18 +28987,20 @@ async function hookRow(ctx, adapter, host) {
28531
28987
  }
28532
28988
  }
28533
28989
  function ownServerId(configDir, projectKey) {
28534
- const dir = join20(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
28990
+ const dir = join21(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
28535
28991
  if (!existsSync17(dir)) return "";
28536
- for (const name of readdirSync8(dir)) {
28992
+ for (const name of readdirSync9(dir)) {
28537
28993
  if (!name.endsWith(OWNER_PID_EXT)) continue;
28538
- if (readFileSync17(join20(dir, name), "utf8").trim() === String(process.pid)) return basename5(name, OWNER_PID_EXT);
28994
+ if (readFileSync18(join21(dir, name), "utf8").trim() === String(process.pid)) return basename5(name, OWNER_PID_EXT);
28539
28995
  }
28540
28996
  return "";
28541
28997
  }
28542
28998
  async function runDoctorChecks(ctx, adapter, host0) {
28543
28999
  const host = adapter.id === "codex" ? { ...host0, env: { ...host0.env, CODEX_HOME: codexRunDirOf(host0.env, homeDirOf(host0.env) ?? "", host0.bundleDir) } } : host0;
28544
29000
  const env = host.env;
28545
- const project = ctx.project;
29001
+ const p = projectOrMissing(ctx);
29002
+ if ("missing" in p) return noProjectRows(ctx, adapter, host, p.missing);
29003
+ const project = p.project;
28546
29004
  const other = adapter.installMode === "in-process" ? void 0 : unsupportedHostOf({ clientName: ctx.clientInfo?.name, bundleDir: host.bundleDir, env });
28547
29005
  let integrityFailed = false;
28548
29006
  let orphan = [];
@@ -28552,7 +29010,7 @@ async function runDoctorChecks(ctx, adapter, host0) {
28552
29010
  D3: () => other !== void 0 ? unsupportedRow("D3", other) : checkHostConfig(adapter, env, project.worktree),
28553
29011
  // D-UNSUPPORTED-HOSTS-1
28554
29012
  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)) }),
28555
- D5: () => other !== void 0 ? unsupportedRow("D5", other) : hookRow(ctx, adapter, host),
29013
+ D5: () => other !== void 0 ? unsupportedRow("D5", other) : hookRow(ctx, project, adapter, host),
28556
29014
  D5b: () => checkDoubleFire(adapter.id, project.worktree),
28557
29015
  D6: () => checkMcp(ctx, adapter),
28558
29016
  D7: () => checkProject({ project, adapter, piCwd: host.piCwd }),
@@ -28582,6 +29040,28 @@ async function runDoctorChecks(ctx, adapter, host0) {
28582
29040
  });
28583
29041
  return rows;
28584
29042
  }
29043
+ async function noProjectRows(ctx, adapter, host, missing2) {
29044
+ const env = host.env;
29045
+ const other = adapter.installMode === "in-process" ? void 0 : unsupportedHostOf({ clientName: ctx.clientInfo?.name, bundleDir: host.bundleDir, env });
29046
+ const wait = (id) => () => needsProjectRow(id);
29047
+ const checks = {
29048
+ 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) }),
29049
+ D2: () => checkNode({ nodeVersion: process.version, bunVersion: process.versions.bun }),
29050
+ D3: other !== void 0 ? () => unsupportedRow("D3", other) : wait("D3"),
29051
+ 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)) }),
29052
+ D5: other !== void 0 ? () => unsupportedRow("D5", other) : wait("D5"),
29053
+ D5b: wait("D5b"),
29054
+ D6: () => checkMcp(ctx, adapter),
29055
+ D7: () => noProjectRow(missing2),
29056
+ D8: wait("D8"),
29057
+ D9: wait("D9"),
29058
+ D10: () => checkMode(adapter, ctx.hostPermission),
29059
+ D11: () => checkRuntimes(env, checkShell(env))
29060
+ };
29061
+ const rows = [];
29062
+ for (const id of DOCTOR_CHECK_ORDER) rows.push(await guard(id, checks[id]));
29063
+ return rows;
29064
+ }
28585
29065
  function reportEnv(env) {
28586
29066
  const out = {};
28587
29067
  for (const key of Object.keys(REPORT_ENV_ENUMS)) {
@@ -28591,7 +29071,7 @@ function reportEnv(env) {
28591
29071
  return out;
28592
29072
  }
28593
29073
  async function doctorReply(ctx, host) {
28594
- const adapter = getAdapter(ctx.project.agent);
29074
+ const adapter = getAdapter(ctx.agent ?? ctx.project.agent);
28595
29075
  const runtime = runtimeInfo(host.env, ctx.signal);
28596
29076
  const rows = await runDoctorChecks(ctx, adapter, host);
28597
29077
  const failed = rows.some((r) => r.status === "FAIL");
@@ -28610,12 +29090,16 @@ async function doctorReply(ctx, host) {
28610
29090
  const look = rows.find((r) => r.status === "FAIL") ?? rows.find((r) => r.status !== "PASS");
28611
29091
  const docs = look === void 0 ? [] : [DOCTOR_DOCS_LABEL + DOCTOR_DOCS_LINK(look.id)];
28612
29092
  const info = adapter.id === "omp" ? ompInfoLines(host.env, ctx.clientInfo?.version) : [];
29093
+ const known = projectOrMissing(ctx);
29094
+ info.push(...replaceTriggerInfoLines(adapter.id, host.env, "missing" in known ? host.env.CLAUDE_PROJECT_DIR : known.project.worktree));
28613
29095
  const whole2 = [envLine2, table3, ...docs, ...info, ...notes].join("\n");
28614
29096
  const bytes5 = Buffer.byteLength(whole2, "utf8");
28615
29097
  if (bytes5 <= REPORT_CAP) return { text: whole2, isError: false, sandboxBytes: bytes5 };
28616
- const db = await openDb(ctx.project);
29098
+ const p = known;
29099
+ if ("missing" in p) return { text: whole2, isError: false, sandboxBytes: bytes5 };
29100
+ const db = await openDb(p.project);
28617
29101
  try {
28618
- indexText(db, ctx.project, ctx.sessionId, REPORT_SOURCE_LABEL, whole2, "text");
29102
+ indexText(db, p.project, ctx.sessionId, REPORT_SOURCE_LABEL, whole2, "text");
28619
29103
  } finally {
28620
29104
  closeDb(db);
28621
29105
  }
@@ -28640,9 +29124,9 @@ var ctxDoctor = Object.freeze({
28640
29124
  });
28641
29125
 
28642
29126
  // src/core/tools/execute.ts
28643
- import { existsSync as existsSync18, mkdtempSync as mkdtempSync2, rmSync as rmSync5, writeFileSync as writeFileSync5 } from "node:fs";
29127
+ import { existsSync as existsSync18, mkdtempSync as mkdtempSync2, rmSync as rmSync5, writeFileSync as writeFileSync6 } from "node:fs";
28644
29128
  import { tmpdir as tmpdir3 } from "node:os";
28645
- import { dirname as dirname12, join as join21, parse as parse3, resolve as resolve11 } from "node:path";
29129
+ import { dirname as dirname12, join as join22, parse as parse3, resolve as resolve11 } from "node:path";
28646
29130
 
28647
29131
  // src/core/sandbox/win-build.ts
28648
29132
  var SEPARATORS2 = ";&|(\n";
@@ -28723,11 +29207,11 @@ function schemaLine(issue4) {
28723
29207
  if (issue4.code === "unrecognized_keys") return new CtxError("UNKNOWN_FIELD", { f: issue4.keys[0] }).toLine();
28724
29208
  return issue4.message;
28725
29209
  }
28726
- function fileError(given, abs, root) {
29210
+ function fileError(given, abs, root, hostRoots) {
28727
29211
  let dir = abs;
28728
29212
  while (!existsSync18(dir) && dirname12(dir) !== dir) dir = dirname12(dir);
28729
- if (isInside(root, dir)) return null;
28730
- return new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine();
29213
+ if (allowedRootOf(root, hostRoots, dir) !== void 0) return null;
29214
+ return { ...fail5(new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine()), outsideRoot: true };
28731
29215
  }
28732
29216
  function takesDashC(language, runtime) {
28733
29217
  if (language === "shell") return true;
@@ -28790,8 +29274,8 @@ async function handler3(raw, ctx) {
28790
29274
  const extra = { ...PLAIN_OUTPUT_ENV2 };
28791
29275
  if (input.file !== void 0) {
28792
29276
  const abs = resolve11(cwd, input.file);
28793
- const bad = fileError(input.file, abs, ctx.project.containmentRoot);
28794
- if (bad !== null) return fail5(bad);
29277
+ const bad = fileError(input.file, abs, ctx.project.containmentRoot, ctx.hostRoots);
29278
+ if (bad !== null) return bad;
28795
29279
  extra.CTX_FILE = abs;
28796
29280
  }
28797
29281
  let runtime;
@@ -28811,9 +29295,9 @@ async function handler3(raw, ctx) {
28811
29295
  if (takesDashC(input.language, runtime)) {
28812
29296
  argv = [runtime, "-c", input.language === "shell" ? rewriteWindowsBuildTools(input.code, process.platform) : input.code];
28813
29297
  } else {
28814
- tmpDir = mkdtempSync2(join21(tmpdir3(), TMP_PREFIX));
28815
- const file2 = join21(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
28816
- writeFileSync5(file2, scriptText(input.language, input.code), "utf8");
29298
+ tmpDir = mkdtempSync2(join22(tmpdir3(), TMP_PREFIX));
29299
+ const file2 = join22(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
29300
+ writeFileSync6(file2, scriptText(input.language, input.code), "utf8");
28817
29301
  argv = scriptArgv(input.language, runtime, file2);
28818
29302
  }
28819
29303
  if (input.background === true) {
@@ -28848,12 +29332,12 @@ var ctxExecute = {
28848
29332
  };
28849
29333
 
28850
29334
  // src/core/tools/index.ts
28851
- import { existsSync as existsSync19, readFileSync as readFileSync20, statSync as statSync9 } from "node:fs";
28852
- import { dirname as dirname13, extname as extname3, join as join24, relative as relative5, resolve as resolve12 } from "node:path";
29335
+ import { existsSync as existsSync19, readFileSync as readFileSync21, statSync as statSync10 } from "node:fs";
29336
+ import { dirname as dirname13, extname as extname3, join as join25, relative as relative5, resolve as resolve12 } from "node:path";
28853
29337
 
28854
29338
  // src/core/index/walk.ts
28855
- import { readdirSync as readdirSync9, readFileSync as readFileSync18, realpathSync as realpathSync10, statSync as statSync8 } from "node:fs";
28856
- import { join as join22 } from "node:path";
29339
+ import { readdirSync as readdirSync10, readFileSync as readFileSync19, realpathSync as realpathSync10, statSync as statSync9 } from "node:fs";
29340
+ import { join as join23 } from "node:path";
28857
29341
  var GITIGNORE = ".gitignore";
28858
29342
  var GIT_DIR = ".git";
28859
29343
  function walkDir(root, containmentRoot) {
@@ -28862,19 +29346,19 @@ function walkDir(root, containmentRoot) {
28862
29346
  const found = [];
28863
29347
  visit(real3, [], [], containmentRoot, /* @__PURE__ */ new Set([real3]), found);
28864
29348
  found.sort(compareFound);
28865
- return found.map((f) => ({ absPath: f.absPath, relPath: join22(...f.dir, f.name) }));
29349
+ return found.map((f) => ({ absPath: f.absPath, relPath: join23(...f.dir, f.name) }));
28866
29350
  }
28867
29351
  function visit(abs, rel, parent, contain, seen, found) {
28868
29352
  let entries;
28869
29353
  try {
28870
- entries = readdirSync9(abs, { withFileTypes: true });
29354
+ entries = readdirSync10(abs, { withFileTypes: true });
28871
29355
  } catch {
28872
29356
  return;
28873
29357
  }
28874
- const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join22(abs, GITIGNORE), rel)) : parent;
29358
+ const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join23(abs, GITIGNORE), rel)) : parent;
28875
29359
  for (const e of entries) {
28876
29360
  if (e.name === GIT_DIR) continue;
28877
- const path8 = join22(abs, e.name);
29361
+ const path8 = join23(abs, e.name);
28878
29362
  let isDir = e.isDirectory();
28879
29363
  let isFile = e.isFile();
28880
29364
  let target = path8;
@@ -28886,7 +29370,7 @@ function visit(abs, rel, parent, contain, seen, found) {
28886
29370
  continue;
28887
29371
  }
28888
29372
  if (!isInside(contain, resolved)) continue;
28889
- const st = statSync8(resolved);
29373
+ const st = statSync9(resolved);
28890
29374
  isDir = st.isDirectory();
28891
29375
  isFile = st.isFile();
28892
29376
  target = resolved;
@@ -28914,7 +29398,7 @@ function compareFound(a, b) {
28914
29398
  function readRules(file2, base) {
28915
29399
  let body;
28916
29400
  try {
28917
- body = readFileSync18(file2, "utf8");
29401
+ body = readFileSync19(file2, "utf8");
28918
29402
  } catch {
28919
29403
  return [];
28920
29404
  }
@@ -28997,12 +29481,13 @@ function globSeg(pat, name) {
28997
29481
  }
28998
29482
 
28999
29483
  // src/core/sandbox/fetch.ts
29000
- import { readFileSync as readFileSync19 } from "node:fs";
29484
+ import { randomBytes } from "node:crypto";
29485
+ import { readFileSync as readFileSync20 } from "node:fs";
29001
29486
  import { lookup } from "node:dns/promises";
29002
29487
  import http from "node:http";
29003
29488
  import https from "node:https";
29004
29489
  import { BlockList, isIP } from "node:net";
29005
- import { join as join23 } from "node:path";
29490
+ import { join as join24 } from "node:path";
29006
29491
  import { connect as tlsConnect } from "node:tls";
29007
29492
  var PRIVATE_RANGES = [
29008
29493
  ["127.0.0.0", 8, "ipv4"],
@@ -29031,6 +29516,26 @@ var PRIVATE_RANGES = [
29031
29516
  ];
29032
29517
  var BLOCKED = new BlockList();
29033
29518
  for (const [net, prefix, type] of PRIVATE_RANGES) BLOCKED.addSubnet(net, prefix, type);
29519
+ var FAKE_IP_POOL = new BlockList();
29520
+ FAKE_IP_POOL.addSubnet("198.18.0.0", 15, "ipv4");
29521
+ var FAKE_IP_PROBE_TLD = ".invalid";
29522
+ var FAKE_IP_PROBE_BYTES = 8;
29523
+ var FAKE_IP_PROBE_MS = 1500;
29524
+ var fakeIpProbe;
29525
+ function inFakeIpPool(address) {
29526
+ return isIP(address) === 4 && FAKE_IP_POOL.check(address, "ipv4");
29527
+ }
29528
+ function fakeIpResolver() {
29529
+ fakeIpProbe ??= new Promise((resolve13) => {
29530
+ const timer = setTimeout(() => resolve13(false), FAKE_IP_PROBE_MS);
29531
+ timer.unref();
29532
+ lookup(randomBytes(FAKE_IP_PROBE_BYTES).toString("hex") + FAKE_IP_PROBE_TLD, { all: true }).then(
29533
+ (addrs) => resolve13(addrs.length > 0 && addrs.every((a) => inFakeIpPool(a.address))),
29534
+ () => resolve13(false)
29535
+ ).finally(() => clearTimeout(timer));
29536
+ });
29537
+ return fakeIpProbe;
29538
+ }
29034
29539
  var STATUS_OK_FIRST = 200;
29035
29540
  var STATUS_OK_END = 300;
29036
29541
  var STATUS_REDIRECT = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
@@ -29041,7 +29546,7 @@ function baseHeaders() {
29041
29546
  if (namedHeaders === void 0) {
29042
29547
  let version4 = UA_DEV_VERSION;
29043
29548
  try {
29044
- const v = JSON.parse(readFileSync19(join23(ownBundleDir(), D1_PACKAGE_FILE), "utf8")).version;
29549
+ const v = JSON.parse(readFileSync20(join24(ownBundleDir(), D1_PACKAGE_FILE), "utf8")).version;
29045
29550
  if (typeof v === "string" && v !== "") version4 = v;
29046
29551
  } catch {
29047
29552
  }
@@ -29133,8 +29638,15 @@ function checkAddress(hostname2, address) {
29133
29638
  throw new CtxError("SSRF", { host: hostname2 });
29134
29639
  }
29135
29640
  }
29136
- async function resolveTarget(u, signal) {
29137
- const host = bare(u.hostname);
29641
+ async function checkResolved(host, addrs, signal) {
29642
+ const pooled = isIP(host) === 0 ? addrs.filter((a) => inFakeIpPool(a.address)) : [];
29643
+ for (const a of addrs) if (!pooled.includes(a)) checkAddress(host, a.address);
29644
+ if (pooled.length === 0) return;
29645
+ const fakeIp = await fakeIpResolver();
29646
+ if (signal.aborted) throw fail6("ABORT_ERR");
29647
+ if (!fakeIp) checkAddress(host, pooled[0].address);
29648
+ }
29649
+ async function lookupAll(host, signal) {
29138
29650
  let addrs;
29139
29651
  try {
29140
29652
  addrs = await lookup(host, { all: true });
@@ -29143,9 +29655,26 @@ async function resolveTarget(u, signal) {
29143
29655
  }
29144
29656
  if (signal.aborted) throw fail6("ABORT_ERR");
29145
29657
  if (addrs.length === 0) throw fail6("ENOTFOUND");
29146
- for (const a of addrs) checkAddress(host, a.address);
29658
+ return addrs;
29659
+ }
29660
+ async function resolveTarget(u, signal, checked) {
29661
+ const host = bare(u.hostname);
29662
+ const addrs = await lookupAll(host, signal);
29663
+ if (checked) await checkResolved(host, addrs, signal);
29147
29664
  return { host, port: u.port === "" ? defaultPort(u.protocol) : Number(u.port), address: addrs[0].address };
29148
29665
  }
29666
+ async function checkProxiedTarget(u, signal) {
29667
+ const host = bare(u.hostname);
29668
+ if (isIP(host) !== 0) return checkAddress(host, host);
29669
+ let addrs;
29670
+ try {
29671
+ addrs = await lookupAll(host, signal);
29672
+ } catch (err) {
29673
+ if (signal.aborted) throw err;
29674
+ return;
29675
+ }
29676
+ await checkResolved(host, addrs, signal);
29677
+ }
29149
29678
  function tlsName(host) {
29150
29679
  return isIP(host) === 0 ? host : void 0;
29151
29680
  }
@@ -29203,9 +29732,8 @@ async function safeFetch(url4, signal) {
29203
29732
  for (let hop = 0; ; hop += 1) {
29204
29733
  if (signal.aborted) throw fail6("ABORT_ERR");
29205
29734
  const proxy = pickProxy(current);
29206
- const origin = bare(current.hostname);
29207
- if (proxy !== void 0 && isIP(origin) !== 0) checkAddress(origin, origin);
29208
- const conn = await resolveTarget(proxy === void 0 ? current : proxy.url, signal);
29735
+ if (proxy !== void 0) await checkProxiedTarget(current, signal);
29736
+ const conn = await resolveTarget(proxy === void 0 ? current : proxy.url, signal, proxy === void 0);
29209
29737
  const res = await request(current, conn, proxy, signal);
29210
29738
  const status = res.statusCode ?? 0;
29211
29739
  const location = res.headers.location;
@@ -29354,7 +29882,7 @@ function decodeTrieDict(input, resultLength, atomCount, dict1AtomCount, ngramCou
29354
29882
  readNgramReferences(ngramCount - dictSize + dict1AtomCount, dictSize + dict2AtomCount);
29355
29883
  readNgramReferences(dictSize - dict1AtomCount, dict1AtomCount);
29356
29884
  const pool = new Uint16Array(poolSize);
29357
- let write2 = 0;
29885
+ let write = 0;
29358
29886
  for (let index = 0; index < ngramIndex; index++) {
29359
29887
  for (let half = 0; half < 2; half++) {
29360
29888
  const source = references[index * 2 + half];
@@ -29363,9 +29891,9 @@ function decodeTrieDict(input, resultLength, atomCount, dict1AtomCount, ngramCou
29363
29891
  let read3 = start[source];
29364
29892
  const readEnd = read3 + length[source];
29365
29893
  while (read3 < readEnd)
29366
- pool[write2++] = pool[read3++];
29894
+ pool[write++] = pool[read3++];
29367
29895
  } else {
29368
- pool[write2++] = value;
29896
+ pool[write++] = value;
29369
29897
  }
29370
29898
  }
29371
29899
  }
@@ -33059,25 +33587,26 @@ function kindOfType(contentType) {
33059
33587
  }
33060
33588
  function readUtf8(absPath) {
33061
33589
  try {
33062
- return utf8.decode(readFileSync20(absPath));
33590
+ return utf8.decode(readFileSync21(absPath));
33063
33591
  } catch {
33064
33592
  return void 0;
33065
33593
  }
33066
33594
  }
33067
- function missingOrOutside(given, abs, root) {
33595
+ function missingOrOutside(given, abs, root, hostRoots) {
33068
33596
  let dir = abs;
33069
33597
  while (!existsSync19(dir) && dirname13(dir) !== dir) dir = dirname13(dir);
33070
- if (dir !== abs && isInside(root, dir)) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
33598
+ if (dir !== abs && allowedRootOf(root, hostRoots, dir) !== void 0) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
33071
33599
  return new CtxError("OUTSIDE_ROOT", { p: given, root });
33072
33600
  }
33073
- function pathItems(input, project) {
33601
+ function pathItems(input, project, hostRoots) {
33074
33602
  const abs = resolve12(project.worktree, input.path);
33075
- if (!isInside(project.containmentRoot, abs)) throw missingOrOutside(input.path, abs, project.containmentRoot);
33603
+ const allowed = allowedRootOf(project.containmentRoot, hostRoots, abs);
33604
+ if (allowed === void 0) throw missingOrOutside(input.path, abs, project.containmentRoot, hostRoots);
33076
33605
  const base = relative5(project.worktree, abs);
33077
- if (statSync9(abs).isDirectory()) {
33078
- return walkDir(abs, project.containmentRoot).map((f) => ({
33606
+ if (statSync10(abs).isDirectory()) {
33607
+ return walkDir(abs, allowed).map((f) => ({
33079
33608
  sourceKind: "path",
33080
- label: pathLabel(join24(base, f.relPath)),
33609
+ label: pathLabel(join25(base, f.relPath)),
33081
33610
  kind: kindOfPath(f.relPath),
33082
33611
  read: () => readUtf8(f.absPath)
33083
33612
  }));
@@ -33092,7 +33621,7 @@ async function itemsOf(input, ctx) {
33092
33621
  return { items: [{ sourceKind: "content", label: label3, kind, read: () => text2 }], from: label3 };
33093
33622
  }
33094
33623
  if (input.path !== void 0) {
33095
- const items = pathItems({ ...input, path: input.path }, ctx.project);
33624
+ const items = pathItems({ ...input, path: input.path }, ctx.project, ctx.hostRoots);
33096
33625
  return { items, from: items.length === 1 ? items[0].label : pathLabel(input.path) };
33097
33626
  }
33098
33627
  const res = await safeFetch(input.url ?? "", AbortSignal.any([ctx.signal, AbortSignal.timeout(EXEC_TIMEOUT_MS)]));
@@ -33159,7 +33688,7 @@ async function handler4(input, ctx) {
33159
33688
  journal: { kind: "index", key: from, path: from, exit_code: null }
33160
33689
  };
33161
33690
  } catch (err) {
33162
- if (err instanceof CtxError) return { text: err.toLine(), isError: true, sandboxBytes: 0 };
33691
+ if (err instanceof CtxError) return { text: err.toLine(), isError: true, sandboxBytes: 0, ...err.code === "OUTSIDE_ROOT" ? { outsideRoot: true } : {} };
33163
33692
  throw err;
33164
33693
  }
33165
33694
  }
@@ -33201,7 +33730,7 @@ function purgeScope(db, scope, input) {
33201
33730
  const chunks = deleteChunkRows(raw, "all");
33202
33731
  return changes(raw, "DELETE FROM events") + chunks + changes(raw, "DELETE FROM sources");
33203
33732
  }
33204
- function isBusy(err) {
33733
+ function isBusy2(err) {
33205
33734
  const code = err?.errcode;
33206
33735
  return typeof code === "number" && (code & SQLITE_PRIMARY_CODE_MASK) === SQLITE_BUSY_CODE;
33207
33736
  }
@@ -33219,7 +33748,7 @@ async function handler5(input, ctx) {
33219
33748
  closeDb(db);
33220
33749
  }
33221
33750
  } catch (err) {
33222
- if (isBusy(err)) return reply2(PURGE_BUSY_LINE, true);
33751
+ if (isBusy2(err)) return reply2(PURGE_BUSY_LINE, true);
33223
33752
  throw err;
33224
33753
  }
33225
33754
  }
@@ -33617,22 +34146,22 @@ var ctxStats = Object.freeze({
33617
34146
  });
33618
34147
 
33619
34148
  // src/core/ops/host-write.ts
33620
- import { copyFileSync, existsSync as existsSync20, mkdirSync as mkdirSync8, writeFileSync as writeFileSync6 } from "node:fs";
33621
- import { dirname as dirname14, join as join25 } from "node:path";
34149
+ import { copyFileSync, existsSync as existsSync20, mkdirSync as mkdirSync9, writeFileSync as writeFileSync7 } from "node:fs";
34150
+ import { dirname as dirname14, join as join26 } from "node:path";
33622
34151
  function defaultWrite(file2, text) {
33623
- writeFileSync6(file2, text, "utf8");
34152
+ writeFileSync7(file2, text, "utf8");
33624
34153
  }
33625
34154
  function hostConfigPath(agent, home, env) {
33626
34155
  const own4 = OWN_MCP_ENTRY[agent];
33627
34156
  if (own4 !== void 0) return ownMcpFileOf(agent, own4.file, env, home);
33628
34157
  switch (agent) {
33629
34158
  case "opencode":
33630
- return join25(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
34159
+ return join26(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
33631
34160
  // D-WIN-OPENCODE-DIR-1
33632
34161
  case "pi":
33633
- return join25(piAgentDirOf(env, home), SETTINGS_FILE);
34162
+ return join26(piAgentDirOf(env, home), SETTINGS_FILE);
33634
34163
  case "gemini":
33635
- return join25(geminiDirOf(env, home), SETTINGS_FILE);
34164
+ return join26(geminiDirOf(env, home), SETTINGS_FILE);
33636
34165
  // D-R38-GEMINI-HOME-1
33637
34166
  case "copilot-cli":
33638
34167
  return null;
@@ -33640,7 +34169,7 @@ function hostConfigPath(agent, home, env) {
33640
34169
  return null;
33641
34170
  // ADR-0026 decision 8 (D-OMP-UPGRADE-1): OMP loads the plugin from its own store; no MCP entry, nothing under ~/.pi
33642
34171
  default:
33643
- return join25(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
34172
+ return join26(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
33644
34173
  }
33645
34174
  }
33646
34175
  function cell3(value) {
@@ -33649,14 +34178,14 @@ function cell3(value) {
33649
34178
  function toRow(file2, edit) {
33650
34179
  return { area: file2 + UPGRADE_AREA_KEY_SEP + edit.path, before: cell3(edit.before), after: cell3(edit.after) };
33651
34180
  }
33652
- function writeWithRollback(file2, text, write2, atomic) {
34181
+ function writeWithRollback(file2, text, write, atomic) {
33653
34182
  const trash = file2 + UPGRADE_TRASH_SUFFIX;
33654
34183
  const tmp = `${file2}${HOST_CONFIG_TMP_SUFFIX}.${process.pid}`;
33655
34184
  const had = existsSync20(file2);
33656
- mkdirSync8(dirname14(file2), { recursive: true });
34185
+ mkdirSync9(dirname14(file2), { recursive: true });
33657
34186
  if (had) copyFileSync(file2, trash);
33658
34187
  try {
33659
- write2(tmp, text);
34188
+ write(tmp, text);
33660
34189
  renameWithRetry(tmp, file2, atomic);
33661
34190
  } catch (err) {
33662
34191
  removeTmpFile(tmp, atomic);
@@ -33690,15 +34219,15 @@ function regenerateHostConfig(row5, home, opts = {}) {
33690
34219
  }
33691
34220
 
33692
34221
  // src/core/ops/uninstall.ts
33693
- import { existsSync as existsSync21, readdirSync as readdirSync10, rmSync as rmSync6, writeFileSync as writeFileSync7 } from "node:fs";
33694
- import { join as join26 } from "node:path";
34222
+ import { existsSync as existsSync21, readdirSync as readdirSync11, rmSync as rmSync6, writeFileSync as writeFileSync8 } from "node:fs";
34223
+ import { join as join27 } from "node:path";
33695
34224
  function row2(area, before, after) {
33696
34225
  return { area, before, after };
33697
34226
  }
33698
34227
  function stopServers(configDir, projectKey) {
33699
34228
  const stopped = listLiveOwners(configDir, projectKey);
33700
- const dir = join26(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
33701
- for (const serverId of stopped) writeFileSync7(join26(dir, serverId + OWNER_STOP_EXT), "", "utf8");
34229
+ const dir = join27(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
34230
+ for (const serverId of stopped) writeFileSync8(join27(dir, serverId + OWNER_STOP_EXT), "", "utf8");
33702
34231
  return stopped.length === 0 ? { row: row2(UPGRADE_SERVER_AREA, "", UPGRADE_NOT_FOUND), stopped } : { row: row2(UPGRADE_SERVER_AREA, UPGRADE_SERVER_RUNNING, UPGRADE_SERVER_STOPPED), stopped };
33703
34232
  }
33704
34233
  function rootOrNull(adapter, env) {
@@ -33716,14 +34245,14 @@ function removeCache(adapter, env, configDir) {
33716
34245
  const root = rootOrNull(adapter, env);
33717
34246
  if (root === null) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
33718
34247
  if (adapter.installMode === "marketplace") {
33719
- const cache = join26(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
34248
+ const cache = join27(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
33720
34249
  if (!isInside(cache, root) || isInside(root, cache)) return row2(UPGRADE_CACHE_AREA, root, UPGRADE_CACHE_BY_HAND);
33721
34250
  }
33722
34251
  rmSync6(root, { recursive: true, force: true });
33723
34252
  return row2(UPGRADE_CACHE_AREA, root, UPGRADE_REMOVED);
33724
34253
  }
33725
34254
  case "plugin": {
33726
- const agentDir = join26(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
34255
+ const agentDir = join27(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
33727
34256
  if (!existsSync21(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
33728
34257
  rmSync6(agentDir, { recursive: true, force: true });
33729
34258
  return row2(UPGRADE_CACHE_AREA, agentDir, UPGRADE_REMOVED);
@@ -33769,7 +34298,7 @@ function ownEntries2(agent, env) {
33769
34298
  }
33770
34299
  if (agent === "opencode") {
33771
34300
  return [{
33772
- file: join26(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
34301
+ file: join27(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
33773
34302
  // D-WIN-OPENCODE-DIR-1
33774
34303
  key: OPENCODE_PLUGIN_KEY,
33775
34304
  shown: OPENCODE_PLUGIN_KEY,
@@ -33780,7 +34309,7 @@ function ownEntries2(agent, env) {
33780
34309
  if (agent === "pi") {
33781
34310
  const agentDir = piAgentDirOf(env, home);
33782
34311
  return [{
33783
- file: join26(agentDir, SETTINGS_FILE),
34312
+ file: join27(agentDir, SETTINGS_FILE),
33784
34313
  key: PI_PACKAGES_KEY,
33785
34314
  shown: PI_PACKAGES_KEY,
33786
34315
  has: (v) => Array.isArray(v) && v.some((x) => piSource2(x) === PI_GIT_PACKAGE),
@@ -33789,7 +34318,7 @@ function ownEntries2(agent, env) {
33789
34318
  }
33790
34319
  if (agent === "omp") {
33791
34320
  return [{
33792
- file: ompImportFiles(home).mcp,
34321
+ file: ompImportFiles(env, home).mcp,
33793
34322
  key: OMP_DISABLED_SERVERS_KEY,
33794
34323
  shown: OMP_DISABLED_SERVERS_KEY,
33795
34324
  has: (v) => Array.isArray(v) && v.includes(SERVER_KEY),
@@ -33811,12 +34340,12 @@ function removeOwnEntries(agent, env) {
33811
34340
  return rows.length === 0 ? [row2(UPGRADE_CONFIG_AREA, "", UPGRADE_NOT_FOUND)] : rows;
33812
34341
  }
33813
34342
  function removeProjectData(configDir, projectKey) {
33814
- const projects = join26(configDir, PROJECTS_DIR_NAME);
33815
- const dir = join26(projects, projectKey);
34343
+ const projects = join27(configDir, PROJECTS_DIR_NAME);
34344
+ const dir = join27(projects, projectKey);
33816
34345
  if (!existsSync21(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
33817
34346
  if (dir === projects || !isInside(projects, dir)) throw new CtxError("OUTSIDE_ROOT", { p: dir, root: projects });
33818
- for (const name of readdirSync10(dir)) {
33819
- if (name !== OWNERS_DIR_NAME) rmSync6(join26(dir, name), { recursive: true, force: true });
34347
+ for (const name of readdirSync11(dir)) {
34348
+ if (name !== OWNERS_DIR_NAME) rmSync6(join27(dir, name), { recursive: true, force: true });
33820
34349
  }
33821
34350
  return row2(UPGRADE_DATA_AREA, dir, UPGRADE_DATA_DELETED);
33822
34351
  }
@@ -33824,12 +34353,12 @@ function runUninstall(input) {
33824
34353
  const configDir = resolveConfigDir(input.env);
33825
34354
  const stop = stopServers(configDir, input.project.projectKey);
33826
34355
  const rows = [stop.row, removeCache(input.adapter, input.env, configDir), ...removeOwnEntries(input.adapter.id, input.env)];
33827
- rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join26(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
34356
+ rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join27(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
33828
34357
  return { rows, stopped: stop.stopped };
33829
34358
  }
33830
34359
 
33831
34360
  // src/core/ops/v1-remove.ts
33832
- import { copyFileSync as copyFileSync2, existsSync as existsSync22, readFileSync as readFileSync21, rmSync as rmSync7 } from "node:fs";
34361
+ import { copyFileSync as copyFileSync2, existsSync as existsSync22, readFileSync as readFileSync22, rmSync as rmSync7 } from "node:fs";
33833
34362
  var isObj4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
33834
34363
  var areaOf = (f) => f.path === "" ? f.file : f.file + UPGRADE_AREA_KEY_SEP + f.path;
33835
34364
  var row3 = (f, after) => ({ area: areaOf(f), before: f.reason, after });
@@ -33880,8 +34409,8 @@ function locate(doc, path8) {
33880
34409
  return null;
33881
34410
  }
33882
34411
  function stripJsonEntries(agent, file2, findings, kept, undo) {
33883
- const layout = hostLayout(readFileSync21(file2, "utf8"));
33884
- const text = hostText(readFileSync21(file2, "utf8"));
34412
+ const layout = hostLayout(readFileSync22(file2, "utf8"));
34413
+ const text = hostText(readFileSync22(file2, "utf8"));
33885
34414
  const doc = parseHostConfig(agent, file2, text, "jsonc");
33886
34415
  const hit = /* @__PURE__ */ new Set();
33887
34416
  const byContainer = /* @__PURE__ */ new Map();
@@ -33931,7 +34460,7 @@ function removeV1(agent, findings, project) {
33931
34460
  continue;
33932
34461
  }
33933
34462
  if (file2.endsWith(TOML_EXT)) {
33934
- const rawToml = readFileSync21(file2, "utf8");
34463
+ const rawToml = readFileSync22(file2, "utf8");
33935
34464
  const tomlLayout = hostLayout(rawToml);
33936
34465
  let text = hostText(rawToml);
33937
34466
  for (const f of list4) {
@@ -34091,7 +34620,7 @@ function checkCall(tool, input) {
34091
34620
  // src/entries/server.ts
34092
34621
  import { randomUUID } from "node:crypto";
34093
34622
  import { existsSync as existsSync24, realpathSync as realpathSync12, rmSync as rmSync9 } from "node:fs";
34094
- import { dirname as dirname15, join as join28 } from "node:path";
34623
+ import { dirname as dirname15, join as join29 } from "node:path";
34095
34624
  import { fileURLToPath as fileURLToPath3 } from "node:url";
34096
34625
 
34097
34626
  // node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
@@ -34739,8 +35268,8 @@ function prefixIssues2(path8, issues) {
34739
35268
  return iss;
34740
35269
  });
34741
35270
  }
34742
- function unwrapMessage2(message3) {
34743
- return typeof message3 === "string" ? message3 : message3?.message;
35271
+ function unwrapMessage2(message4) {
35272
+ return typeof message4 === "string" ? message4 : message4?.message;
34744
35273
  }
34745
35274
  function sizeCaps(defChecks) {
34746
35275
  const caps = [];
@@ -34770,7 +35299,7 @@ function finalizeIssue2(iss, ctx, config4) {
34770
35299
  iss.schema = iss.inst;
34771
35300
  }
34772
35301
  const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0;
34773
- const message3 = iss.message ? iss.message : unwrapMessage2(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage2(schemaError?.(iss)) ?? unwrapMessage2(ctx?.error?.(iss)) ?? unwrapMessage2(config4.customError?.(iss)) ?? unwrapMessage2(config4.localeError?.(iss)) ?? "Invalid input";
35302
+ const message4 = iss.message ? iss.message : unwrapMessage2(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage2(schemaError?.(iss)) ?? unwrapMessage2(ctx?.error?.(iss)) ?? unwrapMessage2(config4.customError?.(iss)) ?? unwrapMessage2(config4.localeError?.(iss)) ?? "Invalid input";
34774
35303
  const full = {};
34775
35304
  for (const k of Object.keys(iss)) {
34776
35305
  if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__")
@@ -34778,7 +35307,7 @@ function finalizeIssue2(iss, ctx, config4) {
34778
35307
  full[k] = iss[k];
34779
35308
  }
34780
35309
  full.path ?? (full.path = []);
34781
- full.message = message3;
35310
+ full.message = message4;
34782
35311
  if (ctx?.reportInput) {
34783
35312
  full.input = iss.input;
34784
35313
  }
@@ -34937,7 +35466,7 @@ function defineBound(proto, key, fn) {
34937
35466
  }
34938
35467
  });
34939
35468
  }
34940
- function claim(inst, sentinel) {
35469
+ function claim2(inst, sentinel) {
34941
35470
  const proto = Object.getPrototypeOf(inst);
34942
35471
  return sentinel in proto ? void 0 : proto;
34943
35472
  }
@@ -34983,7 +35512,7 @@ function defineLazyInternal(inst, key, compute) {
34983
35512
  });
34984
35513
  }
34985
35514
  function installLazyProp(inst, key, make2, enumerable) {
34986
- const proto = claim(inst, key);
35515
+ const proto = claim2(inst, key);
34987
35516
  if (!proto)
34988
35517
  return;
34989
35518
  Object.defineProperty(proto, key, {
@@ -38587,12 +39116,12 @@ function initializeContext(params) {
38587
39116
  external: params?.external ?? void 0
38588
39117
  };
38589
39118
  }
38590
- function handleUnrepresentable(schema, ctx, json2, params, message3) {
38591
- const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message: message3 }) : ctx.unrepresentable;
39119
+ function handleUnrepresentable(schema, ctx, json2, params, message4) {
39120
+ const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message: message4 }) : ctx.unrepresentable;
38592
39121
  if (result === "any")
38593
39122
  return false;
38594
39123
  if (result === void 0 || result === "throw")
38595
- throw new Error(message3);
39124
+ throw new Error(message4);
38596
39125
  Object.assign(json2, result);
38597
39126
  return true;
38598
39127
  }
@@ -42320,8 +42849,8 @@ function prefixIssues3(path8, issues) {
42320
42849
  return iss;
42321
42850
  });
42322
42851
  }
42323
- function unwrapMessage3(message3) {
42324
- return typeof message3 === "string" ? message3 : message3?.message;
42852
+ function unwrapMessage3(message4) {
42853
+ return typeof message4 === "string" ? message4 : message4?.message;
42325
42854
  }
42326
42855
  function sizeCaps2(defChecks) {
42327
42856
  const caps = [];
@@ -42351,7 +42880,7 @@ function finalizeIssue3(iss, ctx, config4) {
42351
42880
  iss.schema = iss.inst;
42352
42881
  }
42353
42882
  const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : void 0;
42354
- const message3 = iss.message ? iss.message : unwrapMessage3(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage3(schemaError?.(iss)) ?? unwrapMessage3(ctx?.error?.(iss)) ?? unwrapMessage3(config4.customError?.(iss)) ?? unwrapMessage3(config4.localeError?.(iss)) ?? "Invalid input";
42883
+ const message4 = iss.message ? iss.message : unwrapMessage3(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage3(schemaError?.(iss)) ?? unwrapMessage3(ctx?.error?.(iss)) ?? unwrapMessage3(config4.customError?.(iss)) ?? unwrapMessage3(config4.localeError?.(iss)) ?? "Invalid input";
42355
42884
  const full = {};
42356
42885
  for (const k of Object.keys(iss)) {
42357
42886
  if (k === "inst" || k === "schema" || k === "continue" || k === "input" || k === "__proto__")
@@ -42359,7 +42888,7 @@ function finalizeIssue3(iss, ctx, config4) {
42359
42888
  full[k] = iss[k];
42360
42889
  }
42361
42890
  full.path ?? (full.path = []);
42362
- full.message = message3;
42891
+ full.message = message4;
42363
42892
  if (ctx?.reportInput) {
42364
42893
  full.input = iss.input;
42365
42894
  }
@@ -42518,7 +43047,7 @@ function defineBound2(proto, key, fn) {
42518
43047
  }
42519
43048
  });
42520
43049
  }
42521
- function claim2(inst, sentinel) {
43050
+ function claim3(inst, sentinel) {
42522
43051
  const proto = Object.getPrototypeOf(inst);
42523
43052
  return sentinel in proto ? void 0 : proto;
42524
43053
  }
@@ -42564,7 +43093,7 @@ function defineLazyInternal2(inst, key, compute) {
42564
43093
  });
42565
43094
  }
42566
43095
  function installLazyProp2(inst, key, make2, enumerable) {
42567
- const proto = claim2(inst, key);
43096
+ const proto = claim3(inst, key);
42568
43097
  if (!proto)
42569
43098
  return;
42570
43099
  Object.defineProperty(proto, key, {
@@ -46078,12 +46607,12 @@ function initializeContext2(params) {
46078
46607
  external: params?.external ?? void 0
46079
46608
  };
46080
46609
  }
46081
- function handleUnrepresentable2(schema, ctx, json2, params, message3) {
46082
- const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message: message3 }) : ctx.unrepresentable;
46610
+ function handleUnrepresentable2(schema, ctx, json2, params, message4) {
46611
+ const result = typeof ctx.unrepresentable === "function" ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message: message4 }) : ctx.unrepresentable;
46083
46612
  if (result === "any")
46084
46613
  return false;
46085
46614
  if (result === void 0 || result === "throw")
46086
- throw new Error(message3);
46615
+ throw new Error(message4);
46087
46616
  Object.assign(json2, result);
46088
46617
  return true;
46089
46618
  }
@@ -48410,8 +48939,8 @@ var OAuthError = class OAuthError2 extends Error {
48410
48939
  if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");
48411
48940
  return brandedHasInstance(this, value);
48412
48941
  }
48413
- constructor(code, message3, errorUri) {
48414
- super(message3);
48942
+ constructor(code, message4, errorUri) {
48943
+ super(message4);
48415
48944
  this.code = code;
48416
48945
  this.errorUri = errorUri;
48417
48946
  this.name = "OAuthError";
@@ -48487,8 +49016,8 @@ var SdkError = class extends Error {
48487
49016
  * failure as `{ cause }` so it is reachable through the `Error.cause` chain that
48488
49017
  * loggers and error trackers walk.
48489
49018
  */
48490
- constructor(code, message3, data, options) {
48491
- super(message3, options);
49019
+ constructor(code, message4, data, options) {
49020
+ super(message4, options);
48492
49021
  this.code = code;
48493
49022
  this.data = data;
48494
49023
  this.name = "SdkError";
@@ -48502,8 +49031,8 @@ var SdkHttpError = class extends SdkError {
48502
49031
  /**
48503
49032
  * @param options - Standard `ErrorOptions`, forwarded to `Error` (see {@linkcode SdkError}).
48504
49033
  */
48505
- constructor(code, message3, data, options) {
48506
- super(code, message3, data, options);
49034
+ constructor(code, message4, data, options) {
49035
+ super(code, message4, data, options);
48507
49036
  this.name = "SdkHttpError";
48508
49037
  }
48509
49038
  get status() {
@@ -50688,8 +51217,8 @@ var ProtocolError = class ProtocolError2 extends Error {
50688
51217
  if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`");
50689
51218
  return brandedHasInstance(this, value);
50690
51219
  }
50691
- constructor(code, message3, data) {
50692
- super(message3);
51220
+ constructor(code, message4, data) {
51221
+ super(message4);
50693
51222
  this.code = code;
50694
51223
  this.data = data;
50695
51224
  this.name = "ProtocolError";
@@ -50698,35 +51227,35 @@ var ProtocolError = class ProtocolError2 extends Error {
50698
51227
  /**
50699
51228
  * Factory method to create the appropriate error type based on the error code and data
50700
51229
  */
50701
- static fromError(code, message3, data) {
51230
+ static fromError(code, message4, data) {
50702
51231
  if (code === ProtocolErrorCode.UrlElicitationRequired && data) {
50703
51232
  const errorData = data;
50704
- if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message3);
51233
+ if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message4);
50705
51234
  }
50706
51235
  if (code === ProtocolErrorCode.UnsupportedProtocolVersion && data) {
50707
51236
  const errorData = data;
50708
51237
  if (Array.isArray(errorData.supported) && typeof errorData.requested === "string") return new UnsupportedProtocolVersionError({
50709
51238
  supported: errorData.supported,
50710
51239
  requested: errorData.requested
50711
- }, message3);
51240
+ }, message4);
50712
51241
  }
50713
51242
  if (code === ProtocolErrorCode.InvalidParams || code === ProtocolErrorCode.ResourceNotFound) {
50714
51243
  const errorData = data;
50715
- if (typeof errorData?.uri === "string" && (code === ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)) return new ResourceNotFoundError(errorData.uri, message3);
51244
+ if (typeof errorData?.uri === "string" && (code === ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)) return new ResourceNotFoundError(errorData.uri, message4);
50716
51245
  }
50717
51246
  if (code === ProtocolErrorCode.MissingRequiredClientCapability && data) {
50718
51247
  const errorData = data;
50719
- if (errorData.requiredCapabilities !== null && typeof errorData.requiredCapabilities === "object" && !Array.isArray(errorData.requiredCapabilities)) return new MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message3);
51248
+ if (errorData.requiredCapabilities !== null && typeof errorData.requiredCapabilities === "object" && !Array.isArray(errorData.requiredCapabilities)) return new MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message4);
50720
51249
  }
50721
- return new ProtocolError2(code, message3, data);
51250
+ return new ProtocolError2(code, message4, data);
50722
51251
  }
50723
51252
  };
50724
51253
  var ResourceNotFoundError = class extends ProtocolError {
50725
51254
  static {
50726
51255
  Object.defineProperty(this, "mcpBrand", { value: "mcp.ResourceNotFoundError" });
50727
51256
  }
50728
- constructor(uri, message3 = `Resource not found: ${uri}`) {
50729
- super(ProtocolErrorCode.InvalidParams, message3, { uri });
51257
+ constructor(uri, message4 = `Resource not found: ${uri}`) {
51258
+ super(ProtocolErrorCode.InvalidParams, message4, { uri });
50730
51259
  }
50731
51260
  /** The URI that was requested and not found. */
50732
51261
  get uri() {
@@ -50737,8 +51266,8 @@ var UrlElicitationRequiredError = class extends ProtocolError {
50737
51266
  static {
50738
51267
  Object.defineProperty(this, "mcpBrand", { value: "mcp.UrlElicitationRequiredError" });
50739
51268
  }
50740
- constructor(elicitations, message3 = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {
50741
- super(ProtocolErrorCode.UrlElicitationRequired, message3, { elicitations });
51269
+ constructor(elicitations, message4 = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {
51270
+ super(ProtocolErrorCode.UrlElicitationRequired, message4, { elicitations });
50742
51271
  }
50743
51272
  get elicitations() {
50744
51273
  return this.data?.elicitations ?? [];
@@ -50748,8 +51277,8 @@ var UnsupportedProtocolVersionError = class extends ProtocolError {
50748
51277
  static {
50749
51278
  Object.defineProperty(this, "mcpBrand", { value: "mcp.UnsupportedProtocolVersionError" });
50750
51279
  }
50751
- constructor(data, message3 = `Unsupported protocol version: ${data.requested}`) {
50752
- super(ProtocolErrorCode.UnsupportedProtocolVersion, message3, data);
51280
+ constructor(data, message4 = `Unsupported protocol version: ${data.requested}`) {
51281
+ super(ProtocolErrorCode.UnsupportedProtocolVersion, message4, data);
50753
51282
  }
50754
51283
  /**
50755
51284
  * Protocol versions the receiver supports.
@@ -50768,8 +51297,8 @@ var MissingRequiredClientCapabilityError = class extends ProtocolError {
50768
51297
  static {
50769
51298
  Object.defineProperty(this, "mcpBrand", { value: "mcp.MissingRequiredClientCapabilityError" });
50770
51299
  }
50771
- constructor(data, message3 = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`) {
50772
- super(ProtocolErrorCode.MissingRequiredClientCapability, message3, data);
51300
+ constructor(data, message4 = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`) {
51301
+ super(ProtocolErrorCode.MissingRequiredClientCapability, message4, data);
50773
51302
  }
50774
51303
  /**
50775
51304
  * The capabilities the server requires from the client to process the
@@ -51783,6 +52312,29 @@ var inputRequired = Object.assign(buildInputRequired, {
51783
52312
  return { method: "roots/list" };
51784
52313
  }
51785
52314
  });
52315
+ function inputResponse(responses, key) {
52316
+ if (responses === void 0 || typeof responses !== "object" || responses === null) return { kind: "missing" };
52317
+ const entry = responses[key];
52318
+ if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return { kind: "missing" };
52319
+ const candidate2 = entry;
52320
+ if (candidate2["action"] === "accept" || candidate2["action"] === "decline" || candidate2["action"] === "cancel") {
52321
+ const content = candidate2["content"];
52322
+ return {
52323
+ kind: "elicit",
52324
+ action: candidate2["action"],
52325
+ ...content !== null && typeof content === "object" && !Array.isArray(content) && { content }
52326
+ };
52327
+ }
52328
+ if (Array.isArray(candidate2["roots"])) return {
52329
+ kind: "roots",
52330
+ roots: candidate2["roots"]
52331
+ };
52332
+ if (typeof candidate2["role"] === "string" && candidate2["content"] !== void 0) return {
52333
+ kind: "sampling",
52334
+ result: candidate2
52335
+ };
52336
+ return { kind: "missing" };
52337
+ }
51786
52338
  var REQUEST_STATE_ONLY_LEG_PACING_MS = 250;
51787
52339
  function inputRequiredRoundsExceededMessage(method, maxRounds) {
51788
52340
  return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`;
@@ -52022,17 +52574,17 @@ var RESERVED_ENVELOPE_META_KEYS = [
52022
52574
  LOG_LEVEL_META_KEY
52023
52575
  ];
52024
52576
  var RETRY_PARAMS_KEYS = ["inputResponses", "requestState"];
52025
- function liftWireOnlyMaterial(message3, kind) {
52026
- const params = message3.params;
52577
+ function liftWireOnlyMaterial(message4, kind) {
52578
+ const params = message4.params;
52027
52579
  if (!isPlainObject$1(params)) return {
52028
- message: message3,
52580
+ message: message4,
52029
52581
  lifted: {}
52030
52582
  };
52031
52583
  const meta3 = params._meta;
52032
52584
  const envelopeKeys = isPlainObject$1(meta3) ? RESERVED_ENVELOPE_META_KEYS.filter((key) => key in meta3) : [];
52033
52585
  const retryKeys = kind === "request" ? RETRY_PARAMS_KEYS.filter((key) => key in params) : [];
52034
52586
  if (envelopeKeys.length === 0 && retryKeys.length === 0) return {
52035
- message: message3,
52587
+ message: message4,
52036
52588
  lifted: {}
52037
52589
  };
52038
52590
  const lifted = {};
@@ -52055,7 +52607,7 @@ function liftWireOnlyMaterial(message3, kind) {
52055
52607
  }
52056
52608
  return {
52057
52609
  message: {
52058
- ...message3,
52610
+ ...message4,
52059
52611
  params: nextParams
52060
52612
  },
52061
52613
  lifted
@@ -52185,12 +52737,12 @@ var Protocol = class {
52185
52737
  * byte-identical. User-supplied `_meta` keys are spread last so they win
52186
52738
  * over the auto-attached envelope keys.
52187
52739
  */
52188
- _envelopeOutbound(message3) {
52740
+ _envelopeOutbound(message4) {
52189
52741
  const envelope = this._outboundMetaEnvelope();
52190
- if (envelope === void 0) return message3;
52191
- const params = message3.params ?? {};
52742
+ if (envelope === void 0) return message4;
52743
+ const params = message4.params ?? {};
52192
52744
  return {
52193
- ...message3,
52745
+ ...message4,
52194
52746
  params: {
52195
52747
  ...params,
52196
52748
  _meta: {
@@ -52289,12 +52841,12 @@ var Protocol = class {
52289
52841
  this._onerror(error42);
52290
52842
  };
52291
52843
  const _onmessage = this._transport?.onmessage;
52292
- this._transport.onmessage = (message3, extra) => {
52293
- _onmessage?.(message3, extra);
52294
- if (isJSONRPCResultResponse(message3) || isJSONRPCErrorResponse(message3)) this._onresponse(message3);
52295
- else if (isJSONRPCRequest(message3)) this._onrequest(message3, extra);
52296
- else if (isJSONRPCNotification(message3)) this._onnotification(message3, extra);
52297
- else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message3)}`));
52844
+ this._transport.onmessage = (message4, extra) => {
52845
+ _onmessage?.(message4, extra);
52846
+ if (isJSONRPCResultResponse(message4) || isJSONRPCErrorResponse(message4)) this._onresponse(message4);
52847
+ else if (isJSONRPCRequest(message4)) this._onrequest(message4, extra);
52848
+ else if (isJSONRPCNotification(message4)) this._onnotification(message4, extra);
52849
+ else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message4)}`));
52298
52850
  };
52299
52851
  transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions);
52300
52852
  await this._transport.start();
@@ -52356,13 +52908,13 @@ var Protocol = class {
52356
52908
  return;
52357
52909
  }
52358
52910
  const capturedTransport = this._transport;
52359
- const sendErrorResponse = (code, message3, data) => {
52911
+ const sendErrorResponse = (code, message4, data) => {
52360
52912
  const errorResponse = {
52361
52913
  jsonrpc: "2.0",
52362
52914
  id: request2.id,
52363
52915
  error: {
52364
52916
  code,
52365
- message: message3,
52917
+ message: message4,
52366
52918
  ...data !== void 0 && { data }
52367
52919
  }
52368
52920
  };
@@ -52956,8 +53508,8 @@ var ReadBuffer = class {
52956
53508
  function deserializeMessage(line) {
52957
53509
  return JSONRPCMessageSchema.parse(JSON.parse(line));
52958
53510
  }
52959
- function serializeMessage(message3) {
52960
- return JSON.stringify(message3) + "\n";
53511
+ function serializeMessage(message4) {
53512
+ return JSON.stringify(message4) + "\n";
52961
53513
  }
52962
53514
  var TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/;
52963
53515
  function validateToolName(name) {
@@ -54208,11 +54760,11 @@ var require_errors = /* @__PURE__ */ __commonJSMin((exports) => {
54208
54760
  if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
54209
54761
  return [E.schemaPath, schPath];
54210
54762
  }
54211
- function extraErrorProps(cxt, { params, message: message3 }, keyValues) {
54763
+ function extraErrorProps(cxt, { params, message: message4 }, keyValues) {
54212
54764
  const { keyword, data, schemaValue, it } = cxt;
54213
54765
  const { opts, propertyName, topSchemaRef, schemaPath } = it;
54214
54766
  keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]);
54215
- if (opts.messages) keyValues.push([E.message, typeof message3 == "function" ? message3(cxt) : message3]);
54767
+ if (opts.messages) keyValues.push([E.message, typeof message4 == "function" ? message4(cxt) : message4]);
54216
54768
  if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
54217
54769
  if (propertyName) keyValues.push([E.propertyName, propertyName]);
54218
54770
  }
@@ -56536,9 +57088,9 @@ var require_core$3 = /* @__PURE__ */ __commonJSMin((exports) => {
56536
57088
  }
56537
57089
  const valid = this.validate($schema, schema);
56538
57090
  if (!valid && throwOrLogError) {
56539
- const message3 = "schema is invalid: " + this.errorsText();
56540
- if (this.opts.validateSchema === "log") this.logger.error(message3);
56541
- else throw new Error(message3);
57091
+ const message4 = "schema is invalid: " + this.errorsText();
57092
+ if (this.opts.validateSchema === "log") this.logger.error(message4);
57093
+ else throw new Error(message4);
56542
57094
  }
56543
57095
  return valid;
56544
57096
  }
@@ -60078,8 +60630,8 @@ function stampSubscriptionId(notification, subscriptionId) {
60078
60630
  }
60079
60631
  };
60080
60632
  }
60081
- function parseListenFilter(message3) {
60082
- const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message3);
60633
+ function parseListenFilter(message4) {
60634
+ const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message4);
60083
60635
  return outcome.ok ? outcome.value.params?.notifications : void 0;
60084
60636
  }
60085
60637
  var CHANGE_NOTIFICATION_METHODS = /* @__PURE__ */ new Set([
@@ -60134,31 +60686,31 @@ var StdioListenRouter = class {
60134
60686
  * open (deliver unadvertised types); the entry guarantees capabilities are
60135
60687
  * set before any listen request is routed here.
60136
60688
  */
60137
- serve(message3) {
60689
+ serve(message4) {
60138
60690
  if (this._serverCapabilities === void 0) throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities");
60139
60691
  if (this._subs.size >= this._maxSubscriptions) return {
60140
60692
  jsonrpc: "2.0",
60141
- id: message3.id,
60693
+ id: message4.id,
60142
60694
  error: {
60143
60695
  code: -32603,
60144
60696
  message: "Subscription limit reached"
60145
60697
  }
60146
60698
  };
60147
- const filter2 = parseListenFilter(message3);
60699
+ const filter2 = parseListenFilter(message4);
60148
60700
  if (filter2 === void 0) return {
60149
60701
  jsonrpc: "2.0",
60150
- id: message3.id,
60702
+ id: message4.id,
60151
60703
  error: {
60152
60704
  code: -32602,
60153
60705
  message: "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"
60154
60706
  }
60155
60707
  };
60156
60708
  const honored = honoredSubset(filter2, this._serverCapabilities);
60157
- this._subs.set(message3.id, honored);
60709
+ this._subs.set(message4.id, honored);
60158
60710
  return stampSubscriptionId({
60159
60711
  method: "notifications/subscriptions/acknowledged",
60160
60712
  params: { notifications: honored }
60161
- }, message3.id);
60713
+ }, message4.id);
60162
60714
  }
60163
60715
  /**
60164
60716
  * Tear down one subscription (inbound `notifications/cancelled`). Returns
@@ -60177,15 +60729,15 @@ var StdioListenRouter = class {
60177
60729
  * - For any other outbound message, returns `'passthrough'` (the entry
60178
60730
  * forwards it as-is).
60179
60731
  */
60180
- routeOutbound(message3) {
60181
- if (!CHANGE_NOTIFICATION_METHODS.has(message3.method)) return "passthrough";
60182
- const uriParam = message3.params?.["uri"];
60732
+ routeOutbound(message4) {
60733
+ if (!CHANGE_NOTIFICATION_METHODS.has(message4.method)) return "passthrough";
60734
+ const uriParam = message4.params?.["uri"];
60183
60735
  const uri = typeof uriParam === "string" ? uriParam : void 0;
60184
- const event = notificationToServerEvent(message3.method, uri);
60736
+ const event = notificationToServerEvent(message4.method, uri);
60185
60737
  const out = [];
60186
60738
  for (const [subscriptionId, filter2] of this._subs) if (listenFilterAccepts(filter2, event)) out.push(stampSubscriptionId({
60187
- method: message3.method,
60188
- params: message3.params ?? {}
60739
+ method: message4.method,
60740
+ params: message4.params ?? {}
60189
60741
  }, subscriptionId));
60190
60742
  return out;
60191
60743
  }
@@ -60262,15 +60814,15 @@ function syntheticElicitationId() {
60262
60814
  const hex = [...bytes5].map((byte) => byte.toString(16).padStart(2, "0")).join("");
60263
60815
  return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
60264
60816
  }
60265
- function legacyShimFailure(method, message3) {
60817
+ function legacyShimFailure(method, message4) {
60266
60818
  if (method === "tools/call") return {
60267
60819
  content: [{
60268
60820
  type: "text",
60269
- text: message3
60821
+ text: message4
60270
60822
  }],
60271
60823
  isError: true
60272
60824
  };
60273
- throw new ProtocolError(ProtocolErrorCode.InternalError, message3);
60825
+ throw new ProtocolError(ProtocolErrorCode.InternalError, message4);
60274
60826
  }
60275
60827
  var LegacyInputRequiredShim = class {
60276
60828
  constructor(_host) {
@@ -61689,9 +62241,9 @@ var StdioServerTransport = class {
61689
62241
  }
61690
62242
  processReadBuffer() {
61691
62243
  while (true) try {
61692
- const message3 = this._readBuffer.readMessage();
61693
- if (message3 === null) break;
61694
- this.onmessage?.(message3);
62244
+ const message4 = this._readBuffer.readMessage();
62245
+ if (message4 === null) break;
62246
+ this.onmessage?.(message4);
61695
62247
  } catch (error42) {
61696
62248
  this.onerror?.(error42);
61697
62249
  }
@@ -61708,10 +62260,10 @@ var StdioServerTransport = class {
61708
62260
  this._readBuffer.clear();
61709
62261
  this.onclose?.();
61710
62262
  }
61711
- send(message3) {
62263
+ send(message4) {
61712
62264
  if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed"));
61713
62265
  return new Promise((resolve13, reject) => {
61714
- const json2 = serializeMessage(message3);
62266
+ const json2 = serializeMessage(message4);
61715
62267
  let settled = false;
61716
62268
  const onError = (error42) => {
61717
62269
  if (settled) return;
@@ -61753,27 +62305,27 @@ var StdioConnectionChannel = class {
61753
62305
  }
61754
62306
  async start() {
61755
62307
  }
61756
- async send(message3, options) {
61757
- if (isJSONRPCResultResponse(message3) || isJSONRPCErrorResponse(message3)) {
61758
- const { id } = message3;
62308
+ async send(message4, options) {
62309
+ if (isJSONRPCResultResponse(message4) || isJSONRPCErrorResponse(message4)) {
62310
+ const { id } = message4;
61759
62311
  if (id !== void 0) this._settle(id);
61760
62312
  }
61761
62313
  if (this._closed) return;
61762
- if (this._outboundIntercept?.(message3) === "handled") return;
61763
- return this._wire.send(message3, options);
62314
+ if (this._outboundIntercept?.(message4) === "handled") return;
62315
+ return this._wire.send(message4, options);
61764
62316
  }
61765
62317
  setProtocolVersion = (version4) => {
61766
62318
  this._wire.setProtocolVersion?.(version4);
61767
62319
  };
61768
62320
  /** Forwards one inbound message to the connected instance. */
61769
- deliver(message3, extra) {
62321
+ deliver(message4, extra) {
61770
62322
  if (this._closed) return;
61771
- if (isJSONRPCRequest(message3)) this._pendingRequests.add(message3.id);
61772
- else if (isJSONRPCNotification(message3) && message3.method === "notifications/cancelled") {
61773
- const cancelledId = message3.params?.requestId;
62323
+ if (isJSONRPCRequest(message4)) this._pendingRequests.add(message4.id);
62324
+ else if (isJSONRPCNotification(message4) && message4.method === "notifications/cancelled") {
62325
+ const cancelledId = message4.params?.requestId;
61774
62326
  if (cancelledId !== void 0) this._settle(cancelledId);
61775
62327
  }
61776
- this.onmessage?.(message3, extra);
62328
+ this.onmessage?.(message4, extra);
61777
62329
  }
61778
62330
  /**
61779
62331
  * Resolves once every request delivered to the instance has been answered
@@ -61819,9 +62371,9 @@ var StdioConnectionChannel = class {
61819
62371
  for (const waiter of waiters) waiter();
61820
62372
  }
61821
62373
  };
61822
- function classifyOpeningMessage(message3) {
61823
- const params = message3.params;
61824
- if (message3.method === "initialize" && !carriesValidModernEnvelopeClaim(params)) {
62374
+ function classifyOpeningMessage(message4) {
62375
+ const params = message4.params;
62376
+ if (message4.method === "initialize" && !carriesValidModernEnvelopeClaim(params)) {
61825
62377
  const requestedVersion = params !== null && typeof params === "object" && typeof params.protocolVersion === "string" ? params.protocolVersion : void 0;
61826
62378
  return {
61827
62379
  kind: "legacy",
@@ -61866,19 +62418,19 @@ function serveStdio(factory, options = {}) {
61866
62418
  } catch {
61867
62419
  }
61868
62420
  };
61869
- const writeErrorResponse = (id, code, message3, data) => wire.send({
62421
+ const writeErrorResponse = (id, code, message4, data) => wire.send({
61870
62422
  jsonrpc: "2.0",
61871
62423
  id,
61872
62424
  error: {
61873
62425
  code,
61874
- message: message3,
62426
+ message: message4,
61875
62427
  ...data !== void 0 && { data }
61876
62428
  }
61877
62429
  }).catch((error42) => reportError(toError(error42)));
61878
62430
  const listenRouter = new StdioListenRouter(options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS);
61879
- const modernOutboundIntercept = (message3) => {
61880
- if (!isJSONRPCNotification(message3)) return void 0;
61881
- const routed = listenRouter.routeOutbound(message3);
62431
+ const modernOutboundIntercept = (message4) => {
62432
+ if (!isJSONRPCNotification(message4)) return void 0;
62433
+ const routed = listenRouter.routeOutbound(message4);
61882
62434
  if (routed === "passthrough") return void 0;
61883
62435
  for (const stamped of routed) wire.send({
61884
62436
  jsonrpc: "2.0",
@@ -61886,18 +62438,18 @@ function serveStdio(factory, options = {}) {
61886
62438
  }).catch((error42) => reportError(toError(error42)));
61887
62439
  return "handled";
61888
62440
  };
61889
- const tryServeListen = async (message3) => {
61890
- if (isJSONRPCRequest(message3) && message3.method === "subscriptions/listen") {
61891
- const meta3 = requestMetaOf(message3.params);
61892
- const issue4 = hasEnvelopeClaim(message3.params) ? (meta3 === void 0 ? [] : validateEnvelopeMeta(meta3))[0] : {
62441
+ const tryServeListen = async (message4) => {
62442
+ if (isJSONRPCRequest(message4) && message4.method === "subscriptions/listen") {
62443
+ const meta3 = requestMetaOf(message4.params);
62444
+ const issue4 = hasEnvelopeClaim(message4.params) ? (meta3 === void 0 ? [] : validateEnvelopeMeta(meta3))[0] : {
61893
62445
  key: "_meta",
61894
62446
  problem: "the per-request envelope is required on protocol revision 2026-07-28"
61895
62447
  };
61896
- const claimedVersion = envelopeClaimVersion(message3.params);
62448
+ const claimedVersion = envelopeClaimVersion(message4.params);
61897
62449
  let reply4;
61898
62450
  if (issue4 !== void 0) reply4 = {
61899
62451
  jsonrpc: "2.0",
61900
- id: message3.id,
62452
+ id: message4.id,
61901
62453
  error: {
61902
62454
  code: -32602,
61903
62455
  message: `Invalid _meta envelope: ${issue4.key}: ${issue4.problem}`
@@ -61910,14 +62462,14 @@ function serveStdio(factory, options = {}) {
61910
62462
  });
61911
62463
  reply4 = {
61912
62464
  jsonrpc: "2.0",
61913
- id: message3.id,
62465
+ id: message4.id,
61914
62466
  error: {
61915
62467
  code: error42.code,
61916
62468
  message: error42.message,
61917
62469
  data: error42.data
61918
62470
  }
61919
62471
  };
61920
- } else reply4 = listenRouter.serve(message3);
62472
+ } else reply4 = listenRouter.serve(message4);
61921
62473
  await wire.send("error" in reply4 ? reply4 : {
61922
62474
  jsonrpc: "2.0",
61923
62475
  method: reply4.method,
@@ -61925,8 +62477,8 @@ function serveStdio(factory, options = {}) {
61925
62477
  }).catch((error42) => reportError(toError(error42)));
61926
62478
  return true;
61927
62479
  }
61928
- if (isJSONRPCNotification(message3) && message3.method === "notifications/cancelled") {
61929
- const cancelledId = message3.params?.requestId;
62480
+ if (isJSONRPCNotification(message4) && message4.method === "notifications/cancelled") {
62481
+ const cancelledId = message4.params?.requestId;
61930
62482
  if (cancelledId !== void 0 && listenRouter.cancel(cancelledId)) return true;
61931
62483
  }
61932
62484
  return false;
@@ -61972,44 +62524,44 @@ function serveStdio(factory, options = {}) {
61972
62524
  discarding = void 0;
61973
62525
  }
61974
62526
  };
61975
- const processMessage = async (message3) => {
62527
+ const processMessage = async (message4) => {
61976
62528
  if (state.phase === "closed") return;
61977
62529
  if (state.phase === "pinned") {
61978
- if (state.era === "modern" && isJSONRPCRequest(message3) && message3.method === "initialize" && !carriesValidModernEnvelopeClaim(message3.params)) {
61979
- await answerLegacyRejection(message3, "initialize", message3.params !== null && typeof message3.params === "object" && typeof message3.params.protocolVersion === "string" ? message3.params.protocolVersion : void 0);
62530
+ if (state.era === "modern" && isJSONRPCRequest(message4) && message4.method === "initialize" && !carriesValidModernEnvelopeClaim(message4.params)) {
62531
+ await answerLegacyRejection(message4, "initialize", message4.params !== null && typeof message4.params === "object" && typeof message4.params.protocolVersion === "string" ? message4.params.protocolVersion : void 0);
61980
62532
  return;
61981
62533
  }
61982
- if (state.era === "modern" && await tryServeListen(message3)) return;
62534
+ if (state.era === "modern" && await tryServeListen(message4)) return;
61983
62535
  if (isTornDown()) return;
61984
- state.instance.channel.deliver(message3);
62536
+ state.instance.channel.deliver(message4);
61985
62537
  return;
61986
62538
  }
61987
- if (!isJSONRPCRequest(message3) && !isJSONRPCNotification(message3)) {
62539
+ if (!isJSONRPCRequest(message4) && !isJSONRPCNotification(message4)) {
61988
62540
  reportError(/* @__PURE__ */ new Error("Discarded a JSON-RPC response received before the connection negotiated an era"));
61989
62541
  return;
61990
62542
  }
61991
- const opening = classifyOpeningMessage(message3);
62543
+ const opening = classifyOpeningMessage(message4);
61992
62544
  switch (opening.kind) {
61993
62545
  case "invalid-envelope": {
61994
62546
  const detail = `Invalid _meta envelope for protocol revision 2026-07-28: ${opening.issue.key}: ${opening.issue.problem}`;
61995
- if (isJSONRPCRequest(message3)) await writeErrorResponse(message3.id, ProtocolErrorCode.InvalidParams, detail, { envelope: opening.issue });
62547
+ if (isJSONRPCRequest(message4)) await writeErrorResponse(message4.id, ProtocolErrorCode.InvalidParams, detail, { envelope: opening.issue });
61996
62548
  else reportError(/* @__PURE__ */ new Error(`Discarded a notification with a malformed envelope: ${detail}`));
61997
62549
  return;
61998
62550
  }
61999
62551
  case "unsupported-revision":
62000
- if (isJSONRPCRequest(message3)) {
62552
+ if (isJSONRPCRequest(message4)) {
62001
62553
  const error42 = new UnsupportedProtocolVersionError({
62002
62554
  supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS],
62003
62555
  requested: opening.requested
62004
62556
  });
62005
62557
  reportError(error42);
62006
- await writeErrorResponse(message3.id, error42.code, error42.message, error42.data);
62558
+ await writeErrorResponse(message4.id, error42.code, error42.message, error42.data);
62007
62559
  } else reportError(/* @__PURE__ */ new Error(`Discarded a notification claiming unsupported protocol revision ${opening.requested}`));
62008
62560
  return;
62009
62561
  case "modern":
62010
- if (isJSONRPCRequest(message3) && message3.method === "server/discover") {
62562
+ if (isJSONRPCRequest(message4) && message4.method === "server/discover") {
62011
62563
  if (state.phase === "probe") {
62012
- state.instance.channel.deliver(message3, { classification: opening.classification });
62564
+ state.instance.channel.deliver(message4, { classification: opening.classification });
62013
62565
  return;
62014
62566
  }
62015
62567
  const instance = await connectInstance("modern", opening.revision);
@@ -62021,12 +62573,12 @@ function serveStdio(factory, options = {}) {
62021
62573
  phase: "probe",
62022
62574
  instance
62023
62575
  };
62024
- instance.channel.deliver(message3, { classification: opening.classification });
62576
+ instance.channel.deliver(message4, { classification: opening.classification });
62025
62577
  return;
62026
62578
  }
62027
62579
  if (state.phase === "probe") {
62028
- if (isJSONRPCNotification(message3)) {
62029
- state.instance.channel.deliver(message3, { classification: opening.classification });
62580
+ if (isJSONRPCNotification(message4)) {
62581
+ state.instance.channel.deliver(message4, { classification: opening.classification });
62030
62582
  return;
62031
62583
  }
62032
62584
  state = {
@@ -62046,13 +62598,13 @@ function serveStdio(factory, options = {}) {
62046
62598
  instance
62047
62599
  };
62048
62600
  }
62049
- if (await tryServeListen(message3)) return;
62601
+ if (await tryServeListen(message4)) return;
62050
62602
  if (isTornDown()) return;
62051
- state.instance.channel.deliver(message3, { classification: opening.classification });
62603
+ state.instance.channel.deliver(message4, { classification: opening.classification });
62052
62604
  return;
62053
62605
  case "legacy": {
62054
62606
  if (legacyMode === "reject") {
62055
- if (isJSONRPCRequest(message3)) await answerLegacyRejection(message3, opening.reason, opening.requestedVersion);
62607
+ if (isJSONRPCRequest(message4)) await answerLegacyRejection(message4, opening.reason, opening.requestedVersion);
62056
62608
  return;
62057
62609
  }
62058
62610
  if (state.phase === "probe") {
@@ -62070,7 +62622,7 @@ function serveStdio(factory, options = {}) {
62070
62622
  era: "legacy",
62071
62623
  instance
62072
62624
  };
62073
- state.instance.channel.deliver(message3);
62625
+ state.instance.channel.deliver(message4);
62074
62626
  return;
62075
62627
  }
62076
62628
  }
@@ -62082,11 +62634,11 @@ function serveStdio(factory, options = {}) {
62082
62634
  pumping = true;
62083
62635
  try {
62084
62636
  while (queue.length > 0) {
62085
- const message3 = queue.shift();
62637
+ const message4 = queue.shift();
62086
62638
  try {
62087
- await processMessage(message3);
62639
+ await processMessage(message4);
62088
62640
  } catch (error42) {
62089
- if (isJSONRPCRequest(message3)) await writeErrorResponse(message3.id, ProtocolErrorCode.InternalError, "Internal server error");
62641
+ if (isJSONRPCRequest(message4)) await writeErrorResponse(message4.id, ProtocolErrorCode.InternalError, "Internal server error");
62090
62642
  reportError(toError(error42));
62091
62643
  }
62092
62644
  }
@@ -62103,8 +62655,8 @@ function serveStdio(factory, options = {}) {
62103
62655
  if (current.phase === "probe" || current.phase === "pinned") await current.instance.product.close().catch((error42) => reportError(toError(error42)));
62104
62656
  await wire.close().catch((error42) => reportError(toError(error42)));
62105
62657
  };
62106
- wire.onmessage = (message3) => {
62107
- queue.push(message3);
62658
+ wire.onmessage = (message4) => {
62659
+ queue.push(message4);
62108
62660
  pump();
62109
62661
  };
62110
62662
  wire.onerror = (error42) => {
@@ -62156,8 +62708,8 @@ function installExitGuard(opts) {
62156
62708
  }
62157
62709
 
62158
62710
  // src/core/store/cleanup.ts
62159
- import { existsSync as existsSync23, readdirSync as readdirSync11, rmSync as rmSync8 } from "node:fs";
62160
- import { join as join27 } from "node:path";
62711
+ import { existsSync as existsSync23, readdirSync as readdirSync12, rmSync as rmSync8 } from "node:fs";
62712
+ import { join as join28 } from "node:path";
62161
62713
  function deleteSource(raw, id) {
62162
62714
  raw.prepare("DELETE FROM sources WHERE id = ?").run(id);
62163
62715
  deleteChunkRows(raw, { sourceId: id });
@@ -62213,8 +62765,8 @@ function lastAccess(raw) {
62213
62765
  return row5.t;
62214
62766
  }
62215
62767
  function sweepOne(configDir, projectKey, cutoff) {
62216
- const dir = join27(configDir, PROJECTS_DIR_NAME, projectKey);
62217
- const db = openForSweep(join27(dir, DB_FILE_NAME), projectKey);
62768
+ const dir = join28(configDir, PROJECTS_DIR_NAME, projectKey);
62769
+ const db = openForSweep(join28(dir, DB_FILE_NAME), projectKey);
62218
62770
  let dead;
62219
62771
  try {
62220
62772
  dead = withWrite(db, (h) => listLiveOwners(configDir, projectKey).length === 0 && lastAccess(h.raw) < cutoff);
@@ -62227,7 +62779,7 @@ function sweepOne(configDir, projectKey, cutoff) {
62227
62779
  function sweepDeadProjects(configDir) {
62228
62780
  let entries;
62229
62781
  try {
62230
- entries = readdirSync11(join27(configDir, PROJECTS_DIR_NAME), { withFileTypes: true });
62782
+ entries = readdirSync12(join28(configDir, PROJECTS_DIR_NAME), { withFileTypes: true });
62231
62783
  } catch (err) {
62232
62784
  if (err.code === "ENOENT") return [];
62233
62785
  throw err;
@@ -62307,6 +62859,9 @@ function metaNumber(meta3, key) {
62307
62859
  function sessionIdOf(meta3, agent, env, serverId) {
62308
62860
  const fromMeta = metaString(meta3, "sessionId");
62309
62861
  if (fromMeta !== void 0) return fromMeta;
62862
+ const metaKey = agent === void 0 ? void 0 : HOST_SESSION_META[agent];
62863
+ const fromHostMeta = metaKey === void 0 ? void 0 : metaString(meta3, metaKey);
62864
+ if (fromHostMeta !== void 0) return fromHostMeta;
62310
62865
  const key = agent === void 0 ? void 0 : HOST_SESSION_ENV[agent];
62311
62866
  const fromHost = key === void 0 ? void 0 : env[key];
62312
62867
  if (typeof fromHost === "string" && fromHost !== "") return fromHost;
@@ -62325,6 +62880,38 @@ function workspaceFromMeta(meta3) {
62325
62880
  return void 0;
62326
62881
  }
62327
62882
  }
62883
+ var HOST_ROOTS_INPUT_KEY = "roots";
62884
+ var WRITE_ACCESS = "write";
62885
+ function grantedFromMeta(meta3) {
62886
+ const state = meta3?.[CODEX_SANDBOX_STATE_META];
62887
+ const profile = typeof state === "object" && state !== null ? state.permissionProfile : void 0;
62888
+ const fs2 = typeof profile === "object" && profile !== null ? profile.file_system : void 0;
62889
+ const entries = typeof fs2 === "object" && fs2 !== null ? fs2.entries : void 0;
62890
+ if (!Array.isArray(entries)) return [];
62891
+ const out = [];
62892
+ for (const e of entries) {
62893
+ const path8 = e?.path;
62894
+ if (e?.access === WRITE_ACCESS && path8?.type === "path" && typeof path8.path === "string" && path8.path !== "") out.push(path8.path);
62895
+ }
62896
+ return out;
62897
+ }
62898
+ function grantedFromInput(responses) {
62899
+ const view = inputResponse(responses, HOST_ROOTS_INPUT_KEY);
62900
+ if (view.kind !== "roots") return void 0;
62901
+ const out = [];
62902
+ for (const root of view.roots) {
62903
+ if (!root.uri.startsWith(FILE_URL_PREFIX2)) continue;
62904
+ try {
62905
+ out.push(fileURLToPath3(root.uri));
62906
+ } catch {
62907
+ }
62908
+ }
62909
+ return out;
62910
+ }
62911
+ function listsRoots(envelope) {
62912
+ const caps = envelope?.[CLIENT_CAPABILITIES_META_KEY];
62913
+ return typeof caps === "object" && caps !== null && caps.roots !== void 0;
62914
+ }
62328
62915
  function realOrSame(p) {
62329
62916
  try {
62330
62917
  return realpathSync12.native(p);
@@ -62396,7 +62983,7 @@ async function startServer(argv, env) {
62396
62983
  return db;
62397
62984
  }
62398
62985
  function stopMarker(configDir, projectKey) {
62399
- return join28(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME, serverId + OWNER_STOP_EXT);
62986
+ return join29(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME, serverId + OWNER_STOP_EXT);
62400
62987
  }
62401
62988
  function stopRequested() {
62402
62989
  const configDir = resolveConfigDir(process.env);
@@ -62412,6 +62999,8 @@ async function startServer(argv, env) {
62412
62999
  const agent = resolveAgent(argv, env);
62413
63000
  const fromRoots = agent === "vscode" && !hasWorkspaceFolder(argv) ? await workspaceFromRoots(server) : void 0;
62414
63001
  const callArgv = fromRoots === void 0 ? argv : [...argv, WORKSPACE_FOLDER_FLAG, fromRoots];
63002
+ const fromInput = grantedFromInput(req.mcpReq.inputResponses);
63003
+ const hostRoots = [...grantedFromMeta(meta3), ...fromInput ?? []];
62415
63004
  let project;
62416
63005
  const projectOf = () => {
62417
63006
  if (agent === void 0) throw new CtxError("NO_PROJECT", { kind: "--agent" });
@@ -62422,6 +63011,10 @@ async function startServer(argv, env) {
62422
63011
  get project() {
62423
63012
  return projectOf();
62424
63013
  },
63014
+ ...agent === void 0 ? {} : { agent },
63015
+ // D-1410-DOCTOR-NO-PROJECT-1
63016
+ ...hostRoots.length === 0 ? {} : { hostRoots },
63017
+ // D-1398-HOST-ROOTS-1
62425
63018
  sessionId: sessionIdOf(meta3, agent, env, serverId),
62426
63019
  turn: metaNumber(meta3, "turn") ?? 0,
62427
63020
  signal: req.mcpReq.signal,
@@ -62439,6 +63032,9 @@ async function startServer(argv, env) {
62439
63032
  reply4 = errorReply(err);
62440
63033
  }
62441
63034
  }
63035
+ if (reply4.outsideRoot === true && fromInput === void 0 && listsRoots(req.mcpReq.envelope)) {
63036
+ return inputRequired({ inputRequests: { [HOST_ROOTS_INPUT_KEY]: inputRequired.listRoots() } });
63037
+ }
62442
63038
  if (stopRequested()) {
62443
63039
  setTimeout(stopSelf, UPGRADE_STOP_DELAY_MS);
62444
63040
  return { content: [{ type: "text", text: reply4.text }], isError: reply4.isError };