context-mode 2.2.0 → 2.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/server.mjs CHANGED
@@ -28075,6 +28075,7 @@ function readReplaceTrigger(raw) {
28075
28075
  var REPLACE_TRIGGER_BYTES = readReplaceTrigger(process.env[REPLACE_TRIGGER_ENV]);
28076
28076
  var RANGE_READ_TOOLS = Object.freeze(["Read", "view"]);
28077
28077
  var READ_RANGE_KEYS = Object.freeze(["offset", "limit", "view_range"]);
28078
+ var SKILL_LOAD_TOOLS = Object.freeze(["Skill"]);
28078
28079
  var MAX_CHUNK_BYTES = 4096;
28079
28080
  var SEARCH_PAGE_SIZE = 20;
28080
28081
  var MEMORY_LABEL_PREFIX = "memory ";
@@ -28227,6 +28228,10 @@ var DB_TIMEOUT_MS = 5e3;
28227
28228
  var DB_WAL_SUFFIX = "-wal";
28228
28229
  var DB_SHM_SUFFIX = "-shm";
28229
28230
  var DB_TMP_SUFFIX = ".tmp";
28231
+ var DB_LINK_DENIED_CODES = ["EACCES", "EPERM", "ENOSYS", "ENOTSUP", "EOPNOTSUPP"];
28232
+ var DB_PUBLISH_CLAIM_SUFFIX = ".publish";
28233
+ var DB_CLAIM_BUSY_CODES = ["EEXIST", "EPERM"];
28234
+ var DB_PUBLISH_POLL_MS = 5;
28230
28235
  var SQLITE_PRIMARY_CODE_MASK = 255;
28231
28236
  var SQLITE_CORRUPT_CODE = 11;
28232
28237
  var SQLITE_NOTADB_CODE = 26;
@@ -28264,6 +28269,7 @@ var PLAIN_OUTPUT_ENV = Object.freeze({ NO_COLOR: "1", FORCE_COLOR: "0" });
28264
28269
  var RUN_LABEL_PREFIX = "run.mjs:";
28265
28270
  var RUN_SESSION_PREFIX = "mcp:";
28266
28271
  var HOST_SESSION_ENV = Object.freeze({ "claude-code": "CLAUDE_CODE_SESSION_ID" });
28272
+ var HOST_SESSION_META = Object.freeze({ zcode: "session_id" });
28267
28273
  var NODE_MIN = "24.15.0";
28268
28274
  var DATA_ROOT = "~/.context-mode";
28269
28275
  var DATA_DIR_ENV = "CONTEXT_MODE_DATA_DIR";
@@ -28447,7 +28453,7 @@ function PURGE_SUMMARY(rows, scope) {
28447
28453
  var DECISION_SOURCE = "decision";
28448
28454
  var DECISION_USER_LABEL = "decision (user)";
28449
28455
  var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
28450
- var BUNDLE_SHA = true ? "9cb2aaa5ebb63491960b3f3e9655a5821383eae4" : void 0;
28456
+ var BUNDLE_SHA = true ? "ae2e1bb106e462a19ab3c042e371cd8a7f691074" : void 0;
28451
28457
  var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
28452
28458
  var DOCTOR_LABEL = Object.freeze({
28453
28459
  D1: "version",
@@ -28558,6 +28564,10 @@ function D7_DETAIL(got) {
28558
28564
  return `resolved project source ${got} does not match the host's actual cwd`;
28559
28565
  }
28560
28566
  var D7_FIX = "restart the agent in the correct directory";
28567
+ function D7_NO_PROJECT_DETAIL(kind) {
28568
+ return `Project source ${kind} is missing`;
28569
+ }
28570
+ var DOCTOR_NEEDS_PROJECT_DETAIL = "runs once the project resolves; D7 names the project source";
28561
28571
  function D8_STALE_SCHEMA_DETAIL(got, want) {
28562
28572
  return `stale schema (v${got}, expected v${want})`;
28563
28573
  }
@@ -29314,7 +29324,7 @@ function openReadOnlyHandle(sqlite, path8, opts = {}) {
29314
29324
  }
29315
29325
 
29316
29326
  // src/core/store/db.ts
29317
- var { existsSync, linkSync, mkdirSync, rmSync } = process.getBuiltinModule("node:fs");
29327
+ var { existsSync, linkSync, mkdirSync, renameSync, rmSync, statSync } = process.getBuiltinModule("node:fs");
29318
29328
  function versionParts(v) {
29319
29329
  const bare2 = v.startsWith("v") ? v.slice(1) : v;
29320
29330
  return bare2.split(".").map((p) => Number.parseInt(p, 10));
@@ -29346,6 +29356,34 @@ function readUserVersion(raw) {
29346
29356
  const row5 = raw.prepare("PRAGMA user_version").get();
29347
29357
  return row5.user_version;
29348
29358
  }
29359
+ function errCode(err) {
29360
+ return err.code ?? "";
29361
+ }
29362
+ function publishWithoutLink(tmp, path8) {
29363
+ const claim3 = path8 + DB_PUBLISH_CLAIM_SUFFIX;
29364
+ const start = Date.now();
29365
+ for (; ; ) {
29366
+ if (existsSync(path8)) return;
29367
+ try {
29368
+ mkdirSync(claim3);
29369
+ } catch (err) {
29370
+ if (!DB_CLAIM_BUSY_CODES.includes(errCode(err))) throw err;
29371
+ if (Date.now() - start < DB_TIMEOUT_MS) {
29372
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, DB_PUBLISH_POLL_MS);
29373
+ continue;
29374
+ }
29375
+ const held = statSync(claim3, { throwIfNoEntry: false });
29376
+ if (held !== void 0 && held.mtimeMs < start) rmSync(claim3, { recursive: true, force: true });
29377
+ throw new Error(`context.db was not published within ${DB_TIMEOUT_MS} ms: ${claim3} was held; open again`);
29378
+ }
29379
+ try {
29380
+ if (!existsSync(path8)) renameSync(tmp, path8);
29381
+ } finally {
29382
+ rmSync(claim3, { recursive: true, force: true });
29383
+ }
29384
+ return;
29385
+ }
29386
+ }
29349
29387
  function createAtomically(sqlite, path8) {
29350
29388
  const { randomUUID: randomUUID2 } = process.getBuiltinModule("node:crypto");
29351
29389
  const tmp = path8 + "." + randomUUID2() + DB_TMP_SUFFIX;
@@ -29359,7 +29397,9 @@ function createAtomically(sqlite, path8) {
29359
29397
  try {
29360
29398
  linkSync(tmp, path8);
29361
29399
  } catch (err) {
29362
- if (err.code !== "EEXIST") throw err;
29400
+ const code = errCode(err);
29401
+ if (DB_LINK_DENIED_CODES.includes(code)) publishWithoutLink(tmp, path8);
29402
+ else if (code !== "EEXIST") throw err;
29363
29403
  }
29364
29404
  } finally {
29365
29405
  for (const suffix of ["", DB_WAL_SUFFIX, DB_SHM_SUFFIX]) rmSync(tmp + suffix, { force: true });
@@ -29440,9 +29480,9 @@ var COLUMNS = "events(session_id, worktree, agent, kind, tool, key, path, ok, ex
29440
29480
  var INSERT_SQL = "INSERT INTO " + COLUMNS;
29441
29481
  var INSERT_COST_SQL = "INSERT OR IGNORE INTO " + COLUMNS;
29442
29482
  var COST_SEQ_SQL = "SELECT seq FROM events WHERE kind = 'cost' AND session_id = ? AND turn = ?";
29443
- function appendEvent(db, row5) {
29483
+ function appendEvent(db, row5, at) {
29444
29484
  return withWrite(db, (h) => {
29445
- const now = Date.now();
29485
+ const now = at ?? Date.now();
29446
29486
  const isCost = row5.kind === "cost";
29447
29487
  const res = h.raw.prepare(isCost ? INSERT_COST_SQL : INSERT_SQL).run(
29448
29488
  row5.session_id,
@@ -29683,7 +29723,7 @@ function resolveConfigDir(env) {
29683
29723
  }
29684
29724
 
29685
29725
  // src/core/project/resolve.ts
29686
- import { basename as basename2, dirname as dirname3, join as join3, resolve as resolve3 } from "node:path";
29726
+ import { basename as basename2, dirname as dirname3, isAbsolute as isAbsolute2, join as join3, resolve as resolve3 } from "node:path";
29687
29727
 
29688
29728
  // src/core/project/contain.ts
29689
29729
  import { dirname as dirname2, isAbsolute, join as join2, relative, resolve as resolve2, sep } from "node:path";
@@ -29855,7 +29895,7 @@ function sha256Hex(text) {
29855
29895
  }
29856
29896
 
29857
29897
  // src/core/project/resolve.ts
29858
- var { existsSync: existsSync3, readFileSync: readFileSync2, realpathSync: realpathSync3, statSync } = process.getBuiltinModule("node:fs");
29898
+ var { existsSync: existsSync3, readFileSync: readFileSync2, realpathSync: realpathSync3, statSync: statSync2 } = process.getBuiltinModule("node:fs");
29859
29899
  function sourceOf(agent) {
29860
29900
  switch (agent) {
29861
29901
  case "claude-code":
@@ -29895,12 +29935,7 @@ function dirOf(kind, src) {
29895
29935
  }
29896
29936
  }
29897
29937
  function gitDirs(dir) {
29898
- let cur;
29899
- try {
29900
- cur = realpathSync3.native(dir);
29901
- } catch {
29902
- throw new CtxError("NO_GIT_DIR", { path: dir });
29903
- }
29938
+ let cur = nearestRealDir(dir);
29904
29939
  const start = cur;
29905
29940
  for (; ; ) {
29906
29941
  const gitDir = gitDirAt(join3(cur, GIT_DIR_NAME));
@@ -29913,10 +29948,22 @@ function gitDirs(dir) {
29913
29948
  cur = up;
29914
29949
  }
29915
29950
  }
29951
+ function nearestRealDir(dir) {
29952
+ const walk2 = isAbsolute2(dir);
29953
+ for (let d = walk2 ? resolve3(dir) : dir; ; ) {
29954
+ try {
29955
+ return realpathSync3.native(d);
29956
+ } catch {
29957
+ const up = dirname3(d);
29958
+ if (!walk2 || up === d) throw new CtxError("NO_GIT_DIR", { path: dir });
29959
+ d = up;
29960
+ }
29961
+ }
29962
+ }
29916
29963
  function gitDirAt(dotGit) {
29917
29964
  let gitDir;
29918
29965
  try {
29919
- if (statSync(dotGit).isDirectory()) {
29966
+ if (statSync2(dotGit).isDirectory()) {
29920
29967
  gitDir = dotGit;
29921
29968
  } else {
29922
29969
  const line = firstLine(dotGit);
@@ -29975,7 +30022,7 @@ function resolveProject(agent, src) {
29975
30022
  },
29976
30023
  worktree,
29977
30024
  get containmentRoot() {
29978
- root ??= plain ?? containmentRootOf(dir, commonDir);
30025
+ root ??= plain ?? containmentRootOf(worktree, commonDir);
29979
30026
  return root;
29980
30027
  },
29981
30028
  agent,
@@ -32420,43 +32467,53 @@ function parseSourceHandle(s) {
32420
32467
  function pathLabel(p) {
32421
32468
  return p.includes("\\") ? p.split("\\").join("/") : p;
32422
32469
  }
32423
- function labelStored(db, label2) {
32424
- return stmt(db.raw, "SELECT 1 AS x FROM sources WHERE label = ? LIMIT 1").get(label2) !== void 0;
32470
+ var EVERY_ROW = { scope: "project", sessionId: "", worktree: "" };
32471
+ var IN_SCOPE = "(:scope <> 'session' OR session_id = :session_id) AND (:scope <> 'worktree' OR worktree = :worktree)";
32472
+ var scopeArgs = (w) => ({ scope: w.scope, session_id: w.sessionId, worktree: w.worktree });
32473
+ function labelStored(db, label2, w) {
32474
+ 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;
32425
32475
  }
32426
- function storedLabel(db, source) {
32427
- if (labelStored(db, source)) return source;
32476
+ function storedLabel(db, source, w = EVERY_ROW) {
32477
+ if (labelStored(db, source, w)) return source;
32428
32478
  const canon = pathLabel(source);
32429
- return canon !== source && labelStored(db, canon) ? canon : source;
32479
+ return canon !== source && labelStored(db, canon, w) ? canon : source;
32430
32480
  }
32431
- function newestId(db, label2) {
32432
- const row5 = stmt(db.raw, "SELECT id FROM sources WHERE label = ? ORDER BY id DESC LIMIT 1").get(label2);
32481
+ function newestId(db, label2, w) {
32482
+ 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) });
32433
32483
  return row5 === void 0 ? null : Number(row5.id);
32434
32484
  }
32435
- function labelOfId(db, id) {
32436
- const row5 = stmt(db.raw, "SELECT label FROM sources WHERE id = ?").get(id);
32485
+ function labelOfId(db, id, w) {
32486
+ const row5 = stmt(db.raw, "SELECT label FROM sources WHERE id = :id AND " + IN_SCOPE).get({ id, ...scopeArgs(w) });
32437
32487
  return row5 === void 0 ? null : row5.label;
32438
32488
  }
32439
- function pickSource(db, source, suffix = true) {
32440
- const named2 = storedLabel(db, source);
32489
+ function pickIn(db, source, suffix, w) {
32490
+ const named2 = storedLabel(db, source, w);
32441
32491
  const id = parseSourceHandle(source);
32442
- const own4 = newestId(db, named2);
32492
+ const own4 = newestId(db, named2, w);
32443
32493
  if (own4 !== null) {
32444
- const otherLabel = id === null || id === own4 ? null : labelOfId(db, id);
32494
+ const otherLabel = id === null || id === own4 ? null : labelOfId(db, id, EVERY_ROW);
32445
32495
  return { label: named2, id: own4, via: "label", other: otherLabel === null || otherLabel === named2 ? null : { id, label: otherLabel } };
32446
32496
  }
32447
32497
  if (id !== null) {
32448
- const label2 = labelOfId(db, id);
32498
+ const label2 = labelOfId(db, id, w);
32449
32499
  if (label2 !== null) return { label: label2, id, via: "handle", other: null };
32450
32500
  }
32451
32501
  if (suffix) {
32452
32502
  const prefix = named2 + LABEL_SUFFIX_SEP;
32453
- const rows = stmt(db.raw, "SELECT id, label FROM sources WHERE substr(label, 1, ?) = ? ORDER BY id DESC").all(prefix.length, prefix);
32503
+ 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) });
32454
32504
  for (const r of rows) {
32455
32505
  if (r.label.lastIndexOf(LABEL_SUFFIX_SEP) === named2.length) return { label: r.label, id: Number(r.id), via: "suffix", other: null };
32456
32506
  }
32457
32507
  }
32458
32508
  return { label: source, id: null, via: "none", other: null };
32459
32509
  }
32510
+ function pickSource(db, source, suffix = true, w = EVERY_ROW) {
32511
+ if (w.scope !== "project") {
32512
+ const here = pickIn(db, source, suffix, w);
32513
+ if (here.via !== "none") return here;
32514
+ }
32515
+ return pickIn(db, source, suffix, EVERY_ROW);
32516
+ }
32460
32517
  function collisionLine(value, pick4) {
32461
32518
  if (pick4.other === null || pick4.id === null) return null;
32462
32519
  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) + ".");
@@ -32531,12 +32588,12 @@ function recallQueryText(prompt) {
32531
32588
  if (cur !== "" && kept.size < RECALL_QUERY_MAX_TERMS) add(cur);
32532
32589
  return [...kept.size > 0 ? kept : all].join(" ");
32533
32590
  }
32534
- function queryUnits(db, sessionId, q, limit) {
32591
+ function queryUnits(db, sessionId, q, limit, maxSourceId = Number.MAX_SAFE_INTEGER) {
32535
32592
  const match = searchTerms(q).join(" OR ");
32536
32593
  if (match === "" || sessionId === "") return [];
32537
32594
  const rows = db.raw.prepare(
32538
- "SELECT u.source_id AS source_id, u.ord AS ord, u.body AS body, -bm25(line_units) AS score, s.label AS label FROM line_units u JOIN sources s ON s.id = u.source_id WHERE line_units MATCH ? AND u.session_id = ? ORDER BY bm25(line_units) LIMIT ?"
32539
- ).all(match, sessionId, limit);
32595
+ "SELECT u.source_id AS source_id, u.ord AS ord, u.body AS body, -bm25(line_units) AS score, s.label AS label FROM line_units u JOIN sources s ON s.id = u.source_id WHERE line_units MATCH ? AND u.session_id = ? AND s.id <= ? ORDER BY bm25(line_units) LIMIT ?"
32596
+ ).all(match, sessionId, maxSourceId, limit);
32540
32597
  return rows.map((r) => ({ sourceId: Number(r.source_id), ord: Number(r.ord), label: r.label, body: r.body, score: r.score }));
32541
32598
  }
32542
32599
 
@@ -32549,7 +32606,7 @@ function ownersDir(configDir, projectKey) {
32549
32606
  function ownerFile(configDir, projectKey, serverId) {
32550
32607
  return join4(ownersDir(configDir, projectKey), serverId + OWNER_PID_EXT);
32551
32608
  }
32552
- function errCode(err) {
32609
+ function errCode2(err) {
32553
32610
  return err.code;
32554
32611
  }
32555
32612
  function writeOwnerPid(configDir, projectKey, serverId) {
@@ -32565,8 +32622,8 @@ function isLive(pid) {
32565
32622
  process.kill(pid, 0);
32566
32623
  return true;
32567
32624
  } catch (err) {
32568
- if (errCode(err) === "ESRCH") return false;
32569
- if (errCode(err) === "EPERM") return true;
32625
+ if (errCode2(err) === "ESRCH") return false;
32626
+ if (errCode2(err) === "EPERM") return true;
32570
32627
  throw err;
32571
32628
  }
32572
32629
  }
@@ -32576,7 +32633,7 @@ function listLiveOwners(configDir, projectKey) {
32576
32633
  try {
32577
32634
  names = readdirSync2(dir);
32578
32635
  } catch (err) {
32579
- if (errCode(err) === "ENOENT") return [];
32636
+ if (errCode2(err) === "ENOENT") return [];
32580
32637
  throw err;
32581
32638
  }
32582
32639
  const live = [];
@@ -32587,7 +32644,7 @@ function listLiveOwners(configDir, projectKey) {
32587
32644
  try {
32588
32645
  text = readFileSync3(file2, "utf8");
32589
32646
  } catch (err) {
32590
- if (errCode(err) === "ENOENT") continue;
32647
+ if (errCode2(err) === "ENOENT") continue;
32591
32648
  throw err;
32592
32649
  }
32593
32650
  const serverId = basename3(name, OWNER_PID_EXT);
@@ -44220,7 +44277,7 @@ function buildChildEnv(parent, extra) {
44220
44277
  }
44221
44278
 
44222
44279
  // src/core/sandbox/runtimes.ts
44223
- import { accessSync, constants as fsConstants, statSync as statSync2 } from "node:fs";
44280
+ import { accessSync, constants as fsConstants, statSync as statSync3 } from "node:fs";
44224
44281
  import path from "node:path";
44225
44282
 
44226
44283
  // src/core/sandbox/path-entries.ts
@@ -44265,7 +44322,7 @@ function fileNames(name, pathExt) {
44265
44322
  function probe(full) {
44266
44323
  let st;
44267
44324
  try {
44268
- st = statSync2(full, { throwIfNoEntry: false });
44325
+ st = statSync3(full, { throwIfNoEntry: false });
44269
44326
  } catch {
44270
44327
  return "unreadable";
44271
44328
  }
@@ -44460,7 +44517,7 @@ function runProcess(argv, o) {
44460
44517
  }
44461
44518
 
44462
44519
  // src/core/index/auto-memory.ts
44463
- import { readdirSync as readdirSync4, readFileSync as readFileSync4, statSync as statSync3 } from "node:fs";
44520
+ import { readdirSync as readdirSync4, readFileSync as readFileSync4, statSync as statSync4 } from "node:fs";
44464
44521
  import { join as join6 } from "node:path";
44465
44522
  var MEMORY_FILES = Object.freeze([
44466
44523
  Object.freeze(["CLAUDE.md"]),
@@ -44486,7 +44543,7 @@ function readAutoMemory(project) {
44486
44543
  const path8 = join6(project.worktree, ...segs);
44487
44544
  if (!isInside(project.worktree, path8)) continue;
44488
44545
  try {
44489
- const st = statSync3(path8);
44546
+ const st = statSync4(path8);
44490
44547
  if (!st.isFile()) continue;
44491
44548
  rows.push({
44492
44549
  origin: "memory",
@@ -44610,15 +44667,43 @@ function sourceCount(db, scope, ctx, source) {
44610
44667
  });
44611
44668
  return Number(row5.n);
44612
44669
  }
44613
- function zeroHits(db, scope, ctx, source, mem, offset = 0) {
44614
- const n = sourceCount(db, scope, ctx, source) + mem.rows.length;
44615
- if (offset > 0) return reply("No more hits past offset " + offset + ' in scope "' + scope + '" across ' + n + " source(s).", false);
44616
- return reply('No hits in scope "' + scope + '" across ' + n + " source(s).", false);
44670
+ function zeroHits(db, scope, ctx, source, mem, nm, queries, offset = 0) {
44671
+ const inScope = sourceCount(db, scope, ctx, source);
44672
+ const n = inScope + mem.rows.length;
44673
+ const head = 'No hits in scope "' + scope + '" across ' + n + " source(s).";
44674
+ const pick4 = nm.pick;
44675
+ if (pick4 === null || mem.named || inScope > 0) {
44676
+ return reply(offset > 0 ? "No more hits past offset " + offset + ' in scope "' + scope + '" across ' + n + " source(s)." : head, false);
44677
+ }
44678
+ if (pick4.id !== null) {
44679
+ const wider = scope === "session" && sourceCount(db, "worktree", ctx, source) > 0 ? "worktree" : "project";
44680
+ return reply(head + "\nSource " + JSON.stringify(nm.arg) + ' is stored in scope "' + wider + '": ' + callText(queries, wider, nm.arg, "") + " searches it.", false);
44681
+ }
44682
+ return reply(head + "\n" + unknownSource(db, scope, ctx, nm.arg), true);
44683
+ }
44684
+ var STORED_SOURCES = `
44685
+ SELECT MAX(id) AS id, label FROM sources
44686
+ WHERE (:scope <> 'session' OR session_id = :session_id)
44687
+ AND (:scope <> 'worktree' OR worktree = :worktree)
44688
+ GROUP BY label ORDER BY MAX(id) DESC LIMIT :limit`;
44689
+ var STORED_SOURCES_SHOWN = 5;
44690
+ function unknownSource(db, scope, ctx, given) {
44691
+ const line = "Source " + JSON.stringify(given) + ' is not a stored source in scope "' + scope + '".';
44692
+ const rows = db.raw.prepare(STORED_SOURCES).all({
44693
+ scope,
44694
+ session_id: ctx.sessionId,
44695
+ worktree: ctx.project.worktree,
44696
+ limit: STORED_SOURCES_SHOWN + 1
44697
+ });
44698
+ if (rows.length === 0) return line + '\nctx_index stores one: ctx_index({content:"...", source:' + JSON.stringify(given) + "}).";
44699
+ const names = rows.slice(0, STORED_SOURCES_SHOWN).map((r) => isLongLabel(r.label) ? sourceHandle(Number(r.id)) : JSON.stringify(r.label));
44700
+ const more = rows.length > STORED_SOURCES_SHOWN ? ", ..." : "";
44701
+ return line + "\nStored sources, newest first: " + names.join(", ") + more + ". " + callText([], scope, void 0, 'sort:"timeline"') + " lists them all.";
44617
44702
  }
44618
44703
  function named(given, pick4) {
44619
- if (given === void 0 || pick4 === null) return { arg: given, note: null };
44704
+ if (given === void 0 || pick4 === null) return { arg: given, note: null, pick: null };
44620
44705
  const arg = pick4.id !== null && isLongLabel(given) ? sourceHandle(pick4.id) : given;
44621
- return { arg, note: collisionLine(given, pick4) };
44706
+ return { arg, note: collisionLine(given, pick4), pick: pick4 };
44622
44707
  }
44623
44708
  function sourceCard(db, id, input, scope, arg) {
44624
44709
  const row5 = sourceCardRow(db, id);
@@ -44750,7 +44835,7 @@ function relevance(db, given, scope, ctx, nm, ms, indexed) {
44750
44835
  });
44751
44836
  const take = fetched.map((h) => replyHits(h, size));
44752
44837
  const pages = fetched.map((h, i) => h.slice(0, take[i]));
44753
- if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source, ms, offset);
44838
+ if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source, ms, nm, input.queries, offset);
44754
44839
  const moreLine3 = (q, pos) => "More: " + callText([q], scope, nm.arg, "offset:" + pos);
44755
44840
  let reserve = 0;
44756
44841
  for (const q of input.queries) reserve += bytes2(moreLine3(q, offset + size)) + 1;
@@ -44820,7 +44905,7 @@ function timelineLine(r) {
44820
44905
  }
44821
44906
  function timeline(db, input, scope, ctx, nm, ms) {
44822
44907
  const page2 = ftsQueryTimeline(db, scope, ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, input.after ?? null, input.source, ms.rows);
44823
- if (page2.rows.length === 0) return zeroHits(db, scope, ctx, input.source, ms);
44908
+ if (page2.rows.length === 0) return zeroHits(db, scope, ctx, input.source, ms, nm, input.queries);
44824
44909
  const moreLine3 = (ts) => "more: " + callText(input.queries, scope, nm.arg, 'sort:"timeline", after:' + ts);
44825
44910
  const reserve = bytes2(moreLine3(page2.rows[page2.rows.length - 1].ts)) + 1;
44826
44911
  const lines = nm.note === null ? [] : [nm.note];
@@ -44874,7 +44959,8 @@ async function handler(input, ctx) {
44874
44959
  const db = await openDb(ctx.project, { readOnly: true });
44875
44960
  try {
44876
44961
  const given = input.source;
44877
- const pick4 = given !== void 0 && given !== DECISION_SOURCE ? pickSource(db, given) : null;
44962
+ const within = { scope, sessionId: ctx.sessionId, worktree: ctx.project.worktree };
44963
+ const pick4 = given !== void 0 && given !== DECISION_SOURCE ? pickSource(db, given, true, within) : null;
44878
44964
  if (pick4 !== null) input = { ...input, source: pick4.label };
44879
44965
  const nm = named(given, pick4);
44880
44966
  const indexed = pick4 !== null && pick4.id !== null;
@@ -45132,6 +45218,7 @@ var SHELL_TOOL_NAMES = Object.freeze(["Bash", "PowerShell"]);
45132
45218
  var POWERSHELL_TOOL = "PowerShell";
45133
45219
  var SHELL_CANONICAL = "Bash";
45134
45220
  var CLAUDE_SHAPE_EVENTS = ["SessionStart", "UserPromptSubmit", "PreToolUse", "PostToolUse"];
45221
+ var FAILURE_EVENT = "PostToolUseFailure";
45135
45222
  var MCP_PREFIX = "mcp__";
45136
45223
  var MCP_SEP = "__";
45137
45224
  var CLAUDE_SOURCES = { startup: "startup", resume: "resume", clear: "clear", compact: "compact" };
@@ -45305,7 +45392,14 @@ function requireFields(raw) {
45305
45392
  }
45306
45393
  function decode3(raw) {
45307
45394
  requireFields(raw);
45308
- const ev = decodeClaudeShape(raw, "claude-code", TOOL_NAME_PREFIX, CLAUDE_SOURCES);
45395
+ const failure3 = typeof raw === "object" && raw !== null && !Array.isArray(raw) && raw.hook_event_name === FAILURE_EVENT;
45396
+ const payload = failure3 ? { ...raw, hook_event_name: "PostToolUse" } : raw;
45397
+ const ev = decodeClaudeShape(payload, "claude-code", TOOL_NAME_PREFIX, CLAUDE_SOURCES);
45398
+ if (failure3) {
45399
+ const error42 = raw.error;
45400
+ const text = typeof error42 === "string" ? error42 : error42 === void 0 ? "" : JSON.stringify(error42);
45401
+ ev.result = { isError: true, bytes: Buffer.byteLength(text), text, keep: true };
45402
+ }
45309
45403
  if (ev.tool !== void 0 && ev.tool.name === POWERSHELL_TOOL) ev.tool.canonicalName = SHELL_CANONICAL;
45310
45404
  if (ev.cwd === "") ev.cwd = process.env.CLAUDE_PROJECT_DIR || process.cwd();
45311
45405
  if (ev.event === "PostToolUse" && ev.tool !== void 0 && ev.tool.callId === void 0) {
@@ -45484,9 +45578,9 @@ var NATIVE_TO_CANONICAL2 = {
45484
45578
  grep_search: "Grep",
45485
45579
  web_fetch: "WebFetch"
45486
45580
  };
45487
- var FAILURE_EVENT = "PostToolUseFailure";
45581
+ var FAILURE_EVENT2 = "PostToolUseFailure";
45488
45582
  function decode6(raw) {
45489
- const failure3 = typeof raw === "object" && raw !== null && !Array.isArray(raw) && raw.hook_event_name === FAILURE_EVENT;
45583
+ const failure3 = typeof raw === "object" && raw !== null && !Array.isArray(raw) && raw.hook_event_name === FAILURE_EVENT2;
45490
45584
  const payload = failure3 ? { ...raw, hook_event_name: "PostToolUse" } : raw;
45491
45585
  const ev = decodeClaudeShape(payload, "qwen", TOOL_NAME_PREFIX4, QWEN_SOURCES);
45492
45586
  if (ev.tool !== void 0 && Object.hasOwn(NATIVE_TO_CANONICAL2, ev.tool.name)) ev.tool.canonicalName = NATIVE_TO_CANONICAL2[ev.tool.name];
@@ -45806,12 +45900,12 @@ var TOOL_NAME_PREFIX8 = "mcp__context-mode__";
45806
45900
  var PLUGIN_TOOL_NAME_PREFIX = "mcp__plugin_context-mode_context-mode__";
45807
45901
  var ZCODE_SOURCES = { startup: "startup", resume: "resume", clear: "clear", compact: "compact" };
45808
45902
  var TWINS = { hook_event_name: "hookEventName", session_id: "sessionId" };
45809
- var FAILURE_EVENT2 = "PostToolUseFailure";
45903
+ var FAILURE_EVENT3 = "PostToolUseFailure";
45810
45904
  function decode10(raw) {
45811
45905
  if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new Error("zcode: hook payload is not a JSON object");
45812
45906
  const p = { ...raw };
45813
45907
  for (const [snake, camel] of Object.entries(TWINS)) if (p[snake] === void 0) p[snake] = p[camel];
45814
- const failure3 = p.hook_event_name === FAILURE_EVENT2;
45908
+ const failure3 = p.hook_event_name === FAILURE_EVENT3;
45815
45909
  if (failure3) p.hook_event_name = "PostToolUse";
45816
45910
  const toolName2 = typeof p.tool_name === "string" ? p.tool_name : "";
45817
45911
  const prefix = toolName2.startsWith(PLUGIN_TOOL_NAME_PREFIX) ? PLUGIN_TOOL_NAME_PREFIX : TOOL_NAME_PREFIX8;
@@ -45902,7 +45996,8 @@ var OPENCODE_EVENTS = {
45902
45996
  var SHELL_TOOL_NAME = "bash";
45903
45997
  var READ_TOOL_NAME = "read";
45904
45998
  var SHELL_TOOL_NAMES5 = Object.freeze([SHELL_TOOL_NAME, "shell"]);
45905
- var NATIVE_TO_CANONICAL7 = { webfetch: "WebFetch", [READ_TOOL_NAME]: "Read", ...Object.fromEntries(SHELL_TOOL_NAMES5.map((n) => [n, "Bash"])) };
45999
+ var SKILL_TOOL_NAME = "skill";
46000
+ var NATIVE_TO_CANONICAL7 = { webfetch: "WebFetch", [READ_TOOL_NAME]: "Read", [SKILL_TOOL_NAME]: "Skill", ...Object.fromEntries(SHELL_TOOL_NAMES5.map((n) => [n, "Bash"])) };
45906
46001
  function toCanonicalTool(name) {
45907
46002
  if (name.startsWith(OWN_WIRE_PREFIX)) return name.slice(OWN_WIRE_PREFIX.length);
45908
46003
  return Object.prototype.hasOwnProperty.call(NATIVE_TO_CANONICAL7, name) ? NATIVE_TO_CANONICAL7[name] : name;
@@ -46207,7 +46302,7 @@ function ownBundleDir() {
46207
46302
 
46208
46303
  // src/core/ops/doctor-config.ts
46209
46304
  import { existsSync as existsSync12, readdirSync as readdirSync7, readFileSync as readFileSync11 } from "node:fs";
46210
- import { dirname as dirname7, isAbsolute as isAbsolute4, join as join13, resolve as resolve4 } from "node:path";
46305
+ import { dirname as dirname7, isAbsolute as isAbsolute5, join as join13, resolve as resolve4 } from "node:path";
46211
46306
 
46212
46307
  // src/core/ops/host-text.ts
46213
46308
  var BOM_CODE = 65279;
@@ -48285,16 +48380,16 @@ function parseTOML(code, options) {
48285
48380
  }
48286
48381
 
48287
48382
  // src/core/ops/atomic-file.ts
48288
- import { mkdirSync as mkdirSync4, renameSync, unlinkSync, writeFileSync as writeFileSync2 } from "node:fs";
48383
+ import { mkdirSync as mkdirSync4, renameSync as renameSync2, unlinkSync, writeFileSync as writeFileSync2 } from "node:fs";
48289
48384
  import path3 from "node:path";
48290
48385
  function sleepSync(ms) {
48291
48386
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
48292
48387
  }
48293
- function errCode2(e) {
48388
+ function errCode3(e) {
48294
48389
  return e.code;
48295
48390
  }
48296
48391
  function renameWithRetry(from, to, opts = {}) {
48297
- const rename = opts.rename ?? renameSync;
48392
+ const rename = opts.rename ?? renameSync2;
48298
48393
  const sleep2 = opts.sleep ?? sleepSync;
48299
48394
  const win = (opts.platform ?? process.platform) === "win32";
48300
48395
  for (let attempt = 0; ; attempt += 1) {
@@ -48302,7 +48397,7 @@ function renameWithRetry(from, to, opts = {}) {
48302
48397
  rename(from, to);
48303
48398
  return;
48304
48399
  } catch (e) {
48305
- const busy = win && ATOMIC_RENAME_BUSY_CODES.includes(errCode2(e) ?? "");
48400
+ const busy = win && ATOMIC_RENAME_BUSY_CODES.includes(errCode3(e) ?? "");
48306
48401
  if (!busy || attempt >= ATOMIC_RENAME_RETRIES) throw e;
48307
48402
  sleep2(ATOMIC_RENAME_DELAY_MS);
48308
48403
  }
@@ -48317,15 +48412,15 @@ function unlinkWithRetry(file2, opts = {}) {
48317
48412
  unlink(file2);
48318
48413
  return;
48319
48414
  } catch (e) {
48320
- if (errCode2(e) === "ENOENT") return;
48321
- const busy = win && ATOMIC_RENAME_BUSY_CODES.includes(errCode2(e) ?? "");
48415
+ if (errCode3(e) === "ENOENT") return;
48416
+ const busy = win && ATOMIC_RENAME_BUSY_CODES.includes(errCode3(e) ?? "");
48322
48417
  if (!busy || attempt >= ATOMIC_RENAME_RETRIES) throw replaceFailure(file2, e);
48323
48418
  sleep2(ATOMIC_RENAME_DELAY_MS);
48324
48419
  }
48325
48420
  }
48326
48421
  }
48327
48422
  function replaceFailure(file2, e) {
48328
- const busy = ATOMIC_RENAME_BUSY_CODES.includes(errCode2(e) ?? "");
48423
+ const busy = ATOMIC_RENAME_BUSY_CODES.includes(errCode3(e) ?? "");
48329
48424
  const cause = e.message;
48330
48425
  return new Error(busy ? `Could not replace ${file2}: ${cause}. Fix: close the program using ${file2}, then re-run` : `Could not write ${file2}: ${cause}. Fix: check the path and its permissions, then re-run`, { cause: e });
48331
48426
  }
@@ -49104,7 +49199,7 @@ function detectV1(agent, home, scope = {}) {
49104
49199
 
49105
49200
  // src/core/ops/plugin-root.ts
49106
49201
  import { existsSync as existsSync8, readdirSync as readdirSync6, readFileSync as readFileSync7, realpathSync as realpathSync4 } from "node:fs";
49107
- import { dirname as dirname6, isAbsolute as isAbsolute2, join as join10, sep as sep2 } from "node:path";
49202
+ import { dirname as dirname6, isAbsolute as isAbsolute3, join as join10, sep as sep2 } from "node:path";
49108
49203
  import { fileURLToPath as fileURLToPath2 } from "node:url";
49109
49204
  function missing(agent, path8) {
49110
49205
  return new CtxError("PLUGIN_ROOT_MISSING", { agent, path: path8 });
@@ -49216,7 +49311,7 @@ function configEntryRoot(adapter, env) {
49216
49311
  const value = parseHostConfig(adapter.id, file2, current.text, current.format);
49217
49312
  const args = hostConfigValueAt(value, [...spec.key, MCP_ARGS_FIELD]);
49218
49313
  const script = Array.isArray(args) ? args[0] : void 0;
49219
- if (typeof script !== "string" || !isAbsolute2(script)) throw missing(adapter.id, file2);
49314
+ if (typeof script !== "string" || !isAbsolute3(script)) throw missing(adapter.id, file2);
49220
49315
  return dirname6(script);
49221
49316
  }
49222
49317
  function packageDirOf(dir) {
@@ -49323,7 +49418,7 @@ function piInstalledIn(env, home, pkgDir, cwd) {
49323
49418
 
49324
49419
  // src/core/ops/doctor-env.ts
49325
49420
  import { existsSync as existsSync10, readFileSync as readFileSync9, realpathSync as realpathSync6 } from "node:fs";
49326
- import { isAbsolute as isAbsolute3, join as join11, relative as relative2 } from "node:path";
49421
+ import { isAbsolute as isAbsolute4, join as join11, relative as relative2 } from "node:path";
49327
49422
  function pass(id, detail = DOCTOR_PASS_DETAIL) {
49328
49423
  return { id, label: DOCTOR_LABEL[id], status: "PASS", detail };
49329
49424
  }
@@ -49492,7 +49587,7 @@ function checkMcp(ctx, adapter) {
49492
49587
  function piCwdInside(worktree, piCwd) {
49493
49588
  if (piCwd === void 0 || !existsSync10(piCwd)) return false;
49494
49589
  const rel = relative2(worktree, realpathSync6.native(piCwd));
49495
- return rel === "" || !rel.startsWith("..") && !isAbsolute3(rel);
49590
+ return rel === "" || !rel.startsWith("..") && !isAbsolute4(rel);
49496
49591
  }
49497
49592
  function checkProject(i) {
49498
49593
  const bad = fail("D7", D7_DETAIL(i.project.source), D7_FIX);
@@ -49500,6 +49595,20 @@ function checkProject(i) {
49500
49595
  if (i.adapter.projectSource === "pi:ctx.cwd" && !piCwdInside(i.project.worktree, i.piCwd)) return bad;
49501
49596
  return pass("D7");
49502
49597
  }
49598
+ function projectOrMissing(ctx) {
49599
+ try {
49600
+ return { project: ctx.project };
49601
+ } catch (err) {
49602
+ if (err instanceof CtxError && err.code === "NO_PROJECT") return { missing: String(err.vars.kind) };
49603
+ throw err;
49604
+ }
49605
+ }
49606
+ function noProjectRow(kind) {
49607
+ return fail("D7", D7_NO_PROJECT_DETAIL(kind), D7_FIX);
49608
+ }
49609
+ function needsProjectRow(id) {
49610
+ return unknown4(id, DOCTOR_NEEDS_PROJECT_DETAIL);
49611
+ }
49503
49612
  function checkMode(adapter, hostPermission) {
49504
49613
  if (hostPermission === "missing") return fail("D10", D10_PERMISSION_MISSING_DETAIL, D10_PERMISSION_FIX);
49505
49614
  if (hostPermission === "wired") return pass("D10", D10_PERMISSION_DETAIL(adapter.denyChannel));
@@ -49817,7 +49926,7 @@ function opencodeDirPlugins(dirs) {
49817
49926
  const loads = lits.some((p) => {
49818
49927
  if (isModule(p)) return packageResolves(dirname7(f));
49819
49928
  const bare2 = p.startsWith(FILE_URL_PREFIX) ? p.slice(FILE_URL_PREFIX.length) : p;
49820
- return existsSync12(isAbsolute4(bare2) ? bare2 : resolve4(dirname7(f), bare2));
49929
+ return existsSync12(isAbsolute5(bare2) ? bare2 : resolve4(dirname7(f), bare2));
49821
49930
  });
49822
49931
  out.push({ file: f, loads });
49823
49932
  }
@@ -50015,7 +50124,7 @@ function configPaths(row5, env, worktree) {
50015
50124
  }
50016
50125
 
50017
50126
  // src/core/ops/doctor-db.ts
50018
- import { existsSync as existsSync13, statSync as statSync4 } from "node:fs";
50127
+ import { existsSync as existsSync13, statSync as statSync5 } from "node:fs";
50019
50128
  var unknown5 = (id, detail) => ({ id, label: DOCTOR_LABEL[id], status: "UNKNOWN", detail });
50020
50129
  var pass3 = (id, detail) => ({ id, label: DOCTOR_LABEL[id], status: "PASS", detail });
50021
50130
  var fail3 = (detail, fixCommand) => ({ id: "D8", label: DOCTOR_LABEL.D8, status: "FAIL", detail, fixCommand });
@@ -50057,7 +50166,7 @@ function orphanFiles(dbPath) {
50057
50166
  const files = [];
50058
50167
  for (const suffix of [DB_WAL_SUFFIX, DB_SHM_SUFFIX]) {
50059
50168
  const path8 = dbPath + suffix;
50060
- if (existsSync13(path8)) files.push({ path: path8, bytes: statSync4(path8).size });
50169
+ if (existsSync13(path8)) files.push({ path: path8, bytes: statSync5(path8).size });
50061
50170
  }
50062
50171
  return files.length > 0 && !existsSync13(dbPath) ? files : [];
50063
50172
  }
@@ -51942,7 +52051,7 @@ import { spawn as spawn3, spawnSync as spawnSync2 } from "node:child_process";
51942
52051
 
51943
52052
  // src/setup/spawn-bin.ts
51944
52053
  import { spawnSync } from "node:child_process";
51945
- import { accessSync as accessSync2, constants as fsc, statSync as statSync5 } from "node:fs";
52054
+ import { accessSync as accessSync2, constants as fsc, statSync as statSync6 } from "node:fs";
51946
52055
  import path5 from "node:path";
51947
52056
  var WIN_EXT = ".COM;.EXE;.BAT;.CMD";
51948
52057
  var WIN_SHIM_EXTS = Object.freeze([".cmd", ".bat"]);
@@ -51960,7 +52069,7 @@ function whichBin(bin, env, platform = process.platform) {
51960
52069
  const f = path5.join(dir, n);
51961
52070
  try {
51962
52071
  accessSync2(f, fsc.X_OK);
51963
- if (statSync5(f).isFile()) return f;
52072
+ if (statSync6(f).isFile()) return f;
51964
52073
  } catch {
51965
52074
  }
51966
52075
  }
@@ -52744,9 +52853,11 @@ function hookLogTail(env) {
52744
52853
  }
52745
52854
  async function journalRows(ctx) {
52746
52855
  const head = ["| kind | tool | bytes | ok | exit_code | created_at |", "|---|---|---|---|---|---|"];
52747
- if (!existsSync17(ctx.project.dbPath)) return [`(context.db is absent at ${ctx.project.dbPath})`];
52856
+ const p = projectOrMissing(ctx);
52857
+ if ("missing" in p) return [`(no project: ${D7_NO_PROJECT_DETAIL(p.missing)})`];
52858
+ if (!existsSync17(p.project.dbPath)) return [`(context.db is absent at ${p.project.dbPath})`];
52748
52859
  try {
52749
- const db = await openDb(ctx.project, { readOnly: true });
52860
+ const db = await openDb(p.project, { readOnly: true });
52750
52861
  try {
52751
52862
  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();
52752
52863
  const cell5 = (v) => v === null || v === void 0 ? "" : String(v);
@@ -52805,6 +52916,7 @@ async function buildIssueBody(i) {
52805
52916
  const failRows = i.rows.filter((r) => r.status !== "PASS");
52806
52917
  const envNames = DOCTOR_ENV_NAMES.map((n) => i.env[n] === void 0 ? `${n} (unset)` : `${n}=${i.env[n]}`);
52807
52918
  const pathTools = DOCTOR_PATH_TOOLS.map((t) => `PATH holds ${t}: ${onPath(i.env, t).join(", ") || "(absent)"}`);
52919
+ const p = projectOrMissing(i.ctx);
52808
52920
  const sections = {
52809
52921
  "Summary": [summaryOf(agent, i.rows, i.unsupported)],
52810
52922
  "ctx-report": [i.table],
@@ -52815,7 +52927,7 @@ async function buildIssueBody(i) {
52815
52927
  ],
52816
52928
  "Hook errors": ["hook-errors.log, last " + DOCTOR_HOOK_LOG_LINES + " lines (UTC):", "```", ...hookLogTail(i.env), "```"],
52817
52929
  "Journal rows": ["events, newest first, last " + DOCTOR_JOURNAL_ROWS + " (bodies stay local):", ...await journalRows(i.ctx)],
52818
- "Agent config": agentConfig(i.adapter, i.env, i.ctx.project.worktree),
52930
+ "Agent config": agentConfig(i.adapter, i.env, "project" in p ? p.project.worktree : process.cwd()),
52819
52931
  "Expected": ["Expected: <the agent fills this in: what should happen, with the byte count>"],
52820
52932
  "Steps": [
52821
52933
  "Reproduced: <yes (2 of 2) or 1 of 2>",
@@ -52836,7 +52948,7 @@ async function buildIssueBody(i) {
52836
52948
  `git: ${gitVersion(i.env)}`,
52837
52949
  ...pathTools,
52838
52950
  ...envNames,
52839
- `Project: ${i.ctx.project.worktree} (key ${i.ctx.project.projectKey})`,
52951
+ "project" in p ? `Project: ${p.project.worktree} (key ${p.project.projectKey})` : `Project: ${D7_NO_PROJECT_DETAIL(p.missing)}`,
52840
52952
  "Filed by: <your agent name, version, model id>"
52841
52953
  ]
52842
52954
  };
@@ -52894,10 +53006,10 @@ async function guard(id, run) {
52894
53006
  return { id, label: DOCTOR_LABEL[id], status: "UNKNOWN", detail: lineOf(err) };
52895
53007
  }
52896
53008
  }
52897
- async function codexDb(ctx, adapter) {
52898
- if (adapter.id !== "codex" || !existsSync18(ctx.project.dbPath)) return null;
53009
+ async function codexDb(project, adapter) {
53010
+ if (adapter.id !== "codex" || !existsSync18(project.dbPath)) return null;
52899
53011
  try {
52900
- return await openDb(ctx.project, { readOnly: true });
53012
+ return await openDb(project, { readOnly: true });
52901
53013
  } catch {
52902
53014
  return null;
52903
53015
  }
@@ -52908,12 +53020,12 @@ function d1UpdateCommand(agent, env, other) {
52908
53020
  function unsupportedRow(id, h) {
52909
53021
  return { id, label: DOCTOR_LABEL[id], status: "WARN", detail: UNSUPPORTED_HOST_LINE(h.name) };
52910
53022
  }
52911
- async function hookRow(ctx, adapter, host) {
52912
- const db = await codexDb(ctx, adapter);
53023
+ async function hookRow(ctx, project, adapter, host) {
53024
+ const db = await codexDb(project, adapter);
52913
53025
  const runStart = Date.now();
52914
53026
  try {
52915
53027
  const row5 = await checkHookRoundTrip({
52916
- worktree: ctx.project.worktree,
53028
+ worktree: project.worktree,
52917
53029
  agent: adapter.id,
52918
53030
  bundleDir: host.bundleDir,
52919
53031
  env: buildChildEnv(host.env),
@@ -52942,7 +53054,9 @@ function ownServerId(configDir, projectKey) {
52942
53054
  async function runDoctorChecks(ctx, adapter, host0) {
52943
53055
  const host = adapter.id === "codex" ? { ...host0, env: { ...host0.env, CODEX_HOME: codexRunDirOf(host0.env, homeDirOf(host0.env) ?? "", host0.bundleDir) } } : host0;
52944
53056
  const env = host.env;
52945
- const project = ctx.project;
53057
+ const p = projectOrMissing(ctx);
53058
+ if ("missing" in p) return noProjectRows(ctx, adapter, host, p.missing);
53059
+ const project = p.project;
52946
53060
  const other = adapter.installMode === "in-process" ? void 0 : unsupportedHostOf({ clientName: ctx.clientInfo?.name, bundleDir: host.bundleDir, env });
52947
53061
  let integrityFailed = false;
52948
53062
  let orphan = [];
@@ -52952,7 +53066,7 @@ async function runDoctorChecks(ctx, adapter, host0) {
52952
53066
  D3: () => other !== void 0 ? unsupportedRow("D3", other) : checkHostConfig(adapter, env, project.worktree),
52953
53067
  // D-UNSUPPORTED-HOSTS-1
52954
53068
  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)) }),
52955
- D5: () => other !== void 0 ? unsupportedRow("D5", other) : hookRow(ctx, adapter, host),
53069
+ D5: () => other !== void 0 ? unsupportedRow("D5", other) : hookRow(ctx, project, adapter, host),
52956
53070
  D5b: () => checkDoubleFire(adapter.id, project.worktree),
52957
53071
  D6: () => checkMcp(ctx, adapter),
52958
53072
  D7: () => checkProject({ project, adapter, piCwd: host.piCwd }),
@@ -52982,6 +53096,28 @@ async function runDoctorChecks(ctx, adapter, host0) {
52982
53096
  });
52983
53097
  return rows;
52984
53098
  }
53099
+ async function noProjectRows(ctx, adapter, host, missing2) {
53100
+ const env = host.env;
53101
+ const other = adapter.installMode === "in-process" ? void 0 : unsupportedHostOf({ clientName: ctx.clientInfo?.name, bundleDir: host.bundleDir, env });
53102
+ const wait = (id) => () => needsProjectRow(id);
53103
+ const checks = {
53104
+ 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) }),
53105
+ D2: () => checkNode({ nodeVersion: process.version, bunVersion: process.versions.bun }),
53106
+ D3: other !== void 0 ? () => unsupportedRow("D3", other) : wait("D3"),
53107
+ 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)) }),
53108
+ D5: other !== void 0 ? () => unsupportedRow("D5", other) : wait("D5"),
53109
+ D5b: wait("D5b"),
53110
+ D6: () => checkMcp(ctx, adapter),
53111
+ D7: () => noProjectRow(missing2),
53112
+ D8: wait("D8"),
53113
+ D9: wait("D9"),
53114
+ D10: () => checkMode(adapter, ctx.hostPermission),
53115
+ D11: () => checkRuntimes(env, checkShell(env))
53116
+ };
53117
+ const rows = [];
53118
+ for (const id of DOCTOR_CHECK_ORDER) rows.push(await guard(id, checks[id]));
53119
+ return rows;
53120
+ }
52985
53121
  function reportEnv(env) {
52986
53122
  const out = {};
52987
53123
  for (const key of Object.keys(REPORT_ENV_ENUMS)) {
@@ -52991,7 +53127,7 @@ function reportEnv(env) {
52991
53127
  return out;
52992
53128
  }
52993
53129
  async function doctorReply(ctx, host) {
52994
- const adapter = getAdapter(ctx.project.agent);
53130
+ const adapter = getAdapter(ctx.agent ?? ctx.project.agent);
52995
53131
  const runtime = runtimeInfo(host.env, ctx.signal);
52996
53132
  const rows = await runDoctorChecks(ctx, adapter, host);
52997
53133
  const failed = rows.some((r) => r.status === "FAIL");
@@ -53013,9 +53149,11 @@ async function doctorReply(ctx, host) {
53013
53149
  const whole2 = [envLine2, table3, ...docs, ...info, ...notes].join("\n");
53014
53150
  const bytes5 = Buffer.byteLength(whole2, "utf8");
53015
53151
  if (bytes5 <= REPORT_CAP) return { text: whole2, isError: false, sandboxBytes: bytes5 };
53016
- const db = await openDb(ctx.project);
53152
+ const p = projectOrMissing(ctx);
53153
+ if ("missing" in p) return { text: whole2, isError: false, sandboxBytes: bytes5 };
53154
+ const db = await openDb(p.project);
53017
53155
  try {
53018
- indexText(db, ctx.project, ctx.sessionId, REPORT_SOURCE_LABEL, whole2, "text");
53156
+ indexText(db, p.project, ctx.sessionId, REPORT_SOURCE_LABEL, whole2, "text");
53019
53157
  } finally {
53020
53158
  closeDb(db);
53021
53159
  }
@@ -53287,11 +53425,11 @@ var ctxExecute = {
53287
53425
  };
53288
53426
 
53289
53427
  // src/core/tools/index.ts
53290
- import { existsSync as existsSync20, readFileSync as readFileSync17, statSync as statSync7 } from "node:fs";
53428
+ import { existsSync as existsSync20, readFileSync as readFileSync17, statSync as statSync8 } from "node:fs";
53291
53429
  import { dirname as dirname12, extname as extname3, join as join22, relative as relative3, resolve as resolve9 } from "node:path";
53292
53430
 
53293
53431
  // src/core/index/walk.ts
53294
- import { readdirSync as readdirSync9, readFileSync as readFileSync15, realpathSync as realpathSync10, statSync as statSync6 } from "node:fs";
53432
+ import { readdirSync as readdirSync9, readFileSync as readFileSync15, realpathSync as realpathSync10, statSync as statSync7 } from "node:fs";
53295
53433
  import { join as join20 } from "node:path";
53296
53434
  var GITIGNORE = ".gitignore";
53297
53435
  var GIT_DIR = ".git";
@@ -53325,7 +53463,7 @@ function visit(abs, rel, parent, contain, seen, found) {
53325
53463
  continue;
53326
53464
  }
53327
53465
  if (!isInside(contain, resolved)) continue;
53328
- const st = statSync6(resolved);
53466
+ const st = statSync7(resolved);
53329
53467
  isDir = st.isDirectory();
53330
53468
  isFile = st.isFile();
53331
53469
  target = resolved;
@@ -53436,6 +53574,7 @@ function globSeg(pat, name) {
53436
53574
  }
53437
53575
 
53438
53576
  // src/core/sandbox/fetch.ts
53577
+ import { randomBytes } from "node:crypto";
53439
53578
  import { readFileSync as readFileSync16 } from "node:fs";
53440
53579
  import { lookup } from "node:dns/promises";
53441
53580
  import http from "node:http";
@@ -53470,6 +53609,26 @@ var PRIVATE_RANGES = [
53470
53609
  ];
53471
53610
  var BLOCKED = new BlockList();
53472
53611
  for (const [net, prefix, type] of PRIVATE_RANGES) BLOCKED.addSubnet(net, prefix, type);
53612
+ var FAKE_IP_POOL = new BlockList();
53613
+ FAKE_IP_POOL.addSubnet("198.18.0.0", 15, "ipv4");
53614
+ var FAKE_IP_PROBE_TLD = ".invalid";
53615
+ var FAKE_IP_PROBE_BYTES = 8;
53616
+ var FAKE_IP_PROBE_MS = 1500;
53617
+ var fakeIpProbe;
53618
+ function inFakeIpPool(address) {
53619
+ return isIP(address) === 4 && FAKE_IP_POOL.check(address, "ipv4");
53620
+ }
53621
+ function fakeIpResolver() {
53622
+ fakeIpProbe ??= new Promise((resolve10) => {
53623
+ const timer = setTimeout(() => resolve10(false), FAKE_IP_PROBE_MS);
53624
+ timer.unref();
53625
+ lookup(randomBytes(FAKE_IP_PROBE_BYTES).toString("hex") + FAKE_IP_PROBE_TLD, { all: true }).then(
53626
+ (addrs) => resolve10(addrs.length > 0 && addrs.every((a) => inFakeIpPool(a.address))),
53627
+ () => resolve10(false)
53628
+ ).finally(() => clearTimeout(timer));
53629
+ });
53630
+ return fakeIpProbe;
53631
+ }
53473
53632
  var STATUS_OK_FIRST = 200;
53474
53633
  var STATUS_OK_END = 300;
53475
53634
  var STATUS_REDIRECT = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
@@ -53572,8 +53731,15 @@ function checkAddress(hostname2, address) {
53572
53731
  throw new CtxError("SSRF", { host: hostname2 });
53573
53732
  }
53574
53733
  }
53575
- async function resolveTarget(u, signal) {
53576
- const host = bare(u.hostname);
53734
+ async function checkResolved(host, addrs, signal) {
53735
+ const pooled = isIP(host) === 0 ? addrs.filter((a) => inFakeIpPool(a.address)) : [];
53736
+ for (const a of addrs) if (!pooled.includes(a)) checkAddress(host, a.address);
53737
+ if (pooled.length === 0) return;
53738
+ const fakeIp = await fakeIpResolver();
53739
+ if (signal.aborted) throw fail5("ABORT_ERR");
53740
+ if (!fakeIp) checkAddress(host, pooled[0].address);
53741
+ }
53742
+ async function lookupAll(host, signal) {
53577
53743
  let addrs;
53578
53744
  try {
53579
53745
  addrs = await lookup(host, { all: true });
@@ -53582,9 +53748,26 @@ async function resolveTarget(u, signal) {
53582
53748
  }
53583
53749
  if (signal.aborted) throw fail5("ABORT_ERR");
53584
53750
  if (addrs.length === 0) throw fail5("ENOTFOUND");
53585
- for (const a of addrs) checkAddress(host, a.address);
53751
+ return addrs;
53752
+ }
53753
+ async function resolveTarget(u, signal, checked) {
53754
+ const host = bare(u.hostname);
53755
+ const addrs = await lookupAll(host, signal);
53756
+ if (checked) await checkResolved(host, addrs, signal);
53586
53757
  return { host, port: u.port === "" ? defaultPort(u.protocol) : Number(u.port), address: addrs[0].address };
53587
53758
  }
53759
+ async function checkProxiedTarget(u, signal) {
53760
+ const host = bare(u.hostname);
53761
+ if (isIP(host) !== 0) return checkAddress(host, host);
53762
+ let addrs;
53763
+ try {
53764
+ addrs = await lookupAll(host, signal);
53765
+ } catch (err) {
53766
+ if (signal.aborted) throw err;
53767
+ return;
53768
+ }
53769
+ await checkResolved(host, addrs, signal);
53770
+ }
53588
53771
  function tlsName(host) {
53589
53772
  return isIP(host) === 0 ? host : void 0;
53590
53773
  }
@@ -53642,9 +53825,8 @@ async function safeFetch(url4, signal) {
53642
53825
  for (let hop = 0; ; hop += 1) {
53643
53826
  if (signal.aborted) throw fail5("ABORT_ERR");
53644
53827
  const proxy = pickProxy(current);
53645
- const origin = bare(current.hostname);
53646
- if (proxy !== void 0 && isIP(origin) !== 0) checkAddress(origin, origin);
53647
- const conn = await resolveTarget(proxy === void 0 ? current : proxy.url, signal);
53828
+ if (proxy !== void 0) await checkProxiedTarget(current, signal);
53829
+ const conn = await resolveTarget(proxy === void 0 ? current : proxy.url, signal, proxy === void 0);
53648
53830
  const res = await request(current, conn, proxy, signal);
53649
53831
  const status = res.statusCode ?? 0;
53650
53832
  const location = res.headers.location;
@@ -57513,7 +57695,7 @@ function pathItems(input, project) {
57513
57695
  const abs = resolve9(project.worktree, input.path);
57514
57696
  if (!isInside(project.containmentRoot, abs)) throw missingOrOutside(input.path, abs, project.containmentRoot);
57515
57697
  const base = relative3(project.worktree, abs);
57516
- if (statSync7(abs).isDirectory()) {
57698
+ if (statSync8(abs).isDirectory()) {
57517
57699
  return walkDir(abs, project.containmentRoot).map((f) => ({
57518
57700
  sourceKind: "path",
57519
57701
  label: pathLabel(join22(base, f.relPath)),
@@ -57673,8 +57855,11 @@ var ctxPurge = Object.freeze({
57673
57855
 
57674
57856
  // src/core/compaction/candidates.ts
57675
57857
  function firstLine3(body) {
57676
- const nl = body.indexOf("\n");
57677
- return (nl < 0 ? body : body.slice(0, nl)).replaceAll("\r", " ");
57858
+ const i = body.length - body.trimStart().length;
57859
+ if (i === body.length) return "";
57860
+ const start = i === 0 ? 0 : body.lastIndexOf("\n", i) + 1;
57861
+ const nl = body.indexOf("\n", i);
57862
+ return (start === 0 && nl < 0 ? body : body.slice(start, nl < 0 ? body.length : nl)).replaceAll("\r", " ");
57678
57863
  }
57679
57864
  function make(section, row5, text, repeatCount, query) {
57680
57865
  const bytes5 = Buffer.byteLength(text, "utf8");
@@ -58849,6 +59034,9 @@ function metaNumber(meta3, key) {
58849
59034
  function sessionIdOf(meta3, agent, env, serverId) {
58850
59035
  const fromMeta = metaString(meta3, "sessionId");
58851
59036
  if (fromMeta !== void 0) return fromMeta;
59037
+ const metaKey = agent === void 0 ? void 0 : HOST_SESSION_META[agent];
59038
+ const fromHostMeta = metaKey === void 0 ? void 0 : metaString(meta3, metaKey);
59039
+ if (fromHostMeta !== void 0) return fromHostMeta;
58852
59040
  const key = agent === void 0 ? void 0 : HOST_SESSION_ENV[agent];
58853
59041
  const fromHost = key === void 0 ? void 0 : env[key];
58854
59042
  if (typeof fromHost === "string" && fromHost !== "") return fromHost;
@@ -58964,6 +59152,8 @@ async function startServer(argv, env) {
58964
59152
  get project() {
58965
59153
  return projectOf();
58966
59154
  },
59155
+ ...agent === void 0 ? {} : { agent },
59156
+ // D-1410-DOCTOR-NO-PROJECT-1
58967
59157
  sessionId: sessionIdOf(meta3, agent, env, serverId),
58968
59158
  turn: metaNumber(meta3, "turn") ?? 0,
58969
59159
  signal: req.mcpReq.signal,