context-mode 2.2.2 → 2.2.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude-plugin/marketplace.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.zcode-plugin/plugin.json +1 -1
- package/README.md +72 -72
- package/SHA256SUMS +16 -16
- package/cli.mjs +35 -16
- package/copilot/plugin.json +1 -1
- package/gemini-extension.json +1 -1
- package/hook.mjs +106 -99
- package/opencode/plugin.js +311 -69
- package/package.json +1 -1
- package/pi/index.js +373 -69
- package/qwen-extension.json +1 -1
- package/run.mjs +14 -12
- package/search.mjs +14 -12
- package/server.mjs +270 -42
package/pi/index.js
CHANGED
|
@@ -11162,14 +11162,8 @@ 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
|
|
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"]);
|
|
11175
11169
|
var SKILL_LOAD_TOOLS = Object.freeze(["Skill"]);
|
|
@@ -11365,7 +11359,7 @@ var TOOLS_TTL_MS = 36e5;
|
|
|
11365
11359
|
var IN_PROCESS_TIMEOUT_MS = 0;
|
|
11366
11360
|
var MS_PER_DAY = 864e5;
|
|
11367
11361
|
var PROJECT_KEY_HEX_LEN = 16;
|
|
11368
|
-
var SCHEMA_VERSION =
|
|
11362
|
+
var SCHEMA_VERSION = 7;
|
|
11369
11363
|
var RETENTION_IDLE_DAYS = 30;
|
|
11370
11364
|
var RETENTION_SIZE_CAP_BYTES = 524288e3;
|
|
11371
11365
|
var PROJECT_DEAD_IDLE_DAYS = 14;
|
|
@@ -11544,6 +11538,8 @@ var RECALL_BUDGET_BYTES = 2048;
|
|
|
11544
11538
|
var RECALL_MIN_SCORE = 5;
|
|
11545
11539
|
var RECALL_MAX_ROWS = 340;
|
|
11546
11540
|
var COMPACTED_META_PREFIX = "compacted:";
|
|
11541
|
+
var BET_META_PREFIX = "bet:";
|
|
11542
|
+
var LOSTBET_META_PREFIX = "lostbet:";
|
|
11547
11543
|
var RECALL_UNITS_SEEN_META_PREFIX = "recall_units_seen:";
|
|
11548
11544
|
var UNITS_ANCESTOR_FACTOR = 8;
|
|
11549
11545
|
var RECALL_QUERY_MAX_TERMS = 64;
|
|
@@ -11640,7 +11636,7 @@ var DECISION_ANSWERS_KEY = "answers";
|
|
|
11640
11636
|
var DECISION_OPTION_KEY = "option";
|
|
11641
11637
|
var DECISION_LABEL_JOIN = " | ";
|
|
11642
11638
|
var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
|
|
11643
|
-
var BUNDLE_SHA = true ? "
|
|
11639
|
+
var BUNDLE_SHA = true ? "f41c429ae530a3fec5bda3c12a8ecdc2a5f14ada" : void 0;
|
|
11644
11640
|
var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
|
|
11645
11641
|
var DOCTOR_LABEL = Object.freeze({
|
|
11646
11642
|
D1: "version",
|
|
@@ -12080,6 +12076,7 @@ var OMP_CONTENT_INFO = "OMP keeps tool output in content; context-mode writes it
|
|
|
12080
12076
|
var OMP_PRINT_MODE_INFO = "Print mode sends no prompt event. Use omp or omp --mode rpc to keep prompts.";
|
|
12081
12077
|
var OMP_SCRIPTS_INFO = "Add < /dev/null in scripts.";
|
|
12082
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}.`;
|
|
12083
12080
|
var PI_CURRENT_MAJOR = 2;
|
|
12084
12081
|
var V1_OPENCODE_PLUGIN_SPEC = "context-mode";
|
|
12085
12082
|
var V1_TMP_PREFIX = "context-mode-";
|
|
@@ -12099,6 +12096,10 @@ var OPENCODE_CONFIG_DIR_ENV = "OPENCODE_CONFIG_DIR";
|
|
|
12099
12096
|
var APPDATA_ENV = "APPDATA";
|
|
12100
12097
|
var VSCODE_USER_DIR_SEGMENTS = Object.freeze(["Code", "User"]);
|
|
12101
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";
|
|
12102
12103
|
var CONFIG_TOML_FILE = "config.toml";
|
|
12103
12104
|
var CONFIG_JSON_FILE = "config.json";
|
|
12104
12105
|
var ZCODE_CLI_DIR = "cli";
|
|
@@ -12378,7 +12379,8 @@ var ERROR_TEXT = Object.freeze({
|
|
|
12378
12379
|
NO_RUNTIME: "No <lang> runtime on PATH. Fix: install it or pick another language.",
|
|
12379
12380
|
FETCH_FAILED: "Fetch failed: <code>. Fix: check the URL or proxy.",
|
|
12380
12381
|
SSRF: "Blocked private address <host>. Fix: use a public URL.",
|
|
12381
|
-
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
|
|
12382
12384
|
INVALID_ARGS: "Invalid argument <field>. Fix: <action>.",
|
|
12383
12385
|
ONE_OF_INPUT: "Pass exactly one of <names>. Fix: drop the extra field.",
|
|
12384
12386
|
SPAWN_FAILED: "Failed to start the process: <detail>. Fix: check the command and PATH.",
|
|
@@ -14880,6 +14882,24 @@ function piAgentDirOf(env, home) {
|
|
|
14880
14882
|
const dir = env[PI_AGENT_DIR_ENV];
|
|
14881
14883
|
return dir !== void 0 && dir !== "" ? dir : join(home, ...AGENT_HOME_DIR.pi, PI_AGENT_DIR);
|
|
14882
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
|
+
}
|
|
14883
14903
|
function vscodeUserDirOf(env, home, platform = process.platform) {
|
|
14884
14904
|
const set3 = (v) => v !== void 0 && v !== "";
|
|
14885
14905
|
const p = platform === "win32" ? win32 : posix;
|
|
@@ -15431,7 +15451,7 @@ var TOOL_DESCRIPTIONS = Object.freeze({
|
|
|
15431
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.',
|
|
15432
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.',
|
|
15433
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.',
|
|
15434
|
-
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.',
|
|
15435
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.",
|
|
15436
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.",
|
|
15437
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",
|
|
@@ -15479,6 +15499,10 @@ function isInside(root, p) {
|
|
|
15479
15499
|
}
|
|
15480
15500
|
return true;
|
|
15481
15501
|
}
|
|
15502
|
+
function allowedRootOf(containmentRoot, hostRoots, p) {
|
|
15503
|
+
if (isInside(containmentRoot, p)) return containmentRoot;
|
|
15504
|
+
return hostRoots?.find((r) => isInside(r, p));
|
|
15505
|
+
}
|
|
15482
15506
|
var rootReal = /* @__PURE__ */ new Map();
|
|
15483
15507
|
function realRoot(root) {
|
|
15484
15508
|
const hit = rootReal.get(root);
|
|
@@ -16259,13 +16283,22 @@ CREATE VIRTUAL TABLE line_units USING fts5(
|
|
|
16259
16283
|
var DDL_V6 = `
|
|
16260
16284
|
UPDATE sources SET label = replace(label, char(92), '/') WHERE kind = 'path' AND instr(label, char(92)) > 0;
|
|
16261
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
|
+
`;
|
|
16262
16294
|
var MIGRATIONS = [
|
|
16263
16295
|
{ version: 1, sql: DDL },
|
|
16264
16296
|
{ version: 2, sql: DDL_V2 },
|
|
16265
16297
|
{ version: 3, sql: DDL_V3 },
|
|
16266
16298
|
{ version: 4, sql: DDL_V4 },
|
|
16267
16299
|
{ version: 5, sql: DDL_V5 },
|
|
16268
|
-
{ version: 6, sql: DDL_V6 }
|
|
16300
|
+
{ version: 6, sql: DDL_V6 },
|
|
16301
|
+
{ version: 7, sql: DDL_V7 }
|
|
16269
16302
|
];
|
|
16270
16303
|
function applyMigrations(db, fromVersion) {
|
|
16271
16304
|
if (fromVersion === SCHEMA_VERSION2) return;
|
|
@@ -16465,6 +16498,51 @@ function metaTake(db, key) {
|
|
|
16465
16498
|
});
|
|
16466
16499
|
}
|
|
16467
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
|
+
|
|
16468
16546
|
// src/core/journal/append.ts
|
|
16469
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
|
|
16470
16548
|
var INSERT_SQL = "INSERT INTO " + COLUMNS;
|
|
@@ -18608,11 +18686,13 @@ function deleteChunkRows(raw, scope) {
|
|
|
18608
18686
|
if (scope === "all") {
|
|
18609
18687
|
raw.exec("INSERT INTO chunks_tri(chunks_tri) VALUES ('delete-all')");
|
|
18610
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");
|
|
18611
18690
|
return Number(raw.prepare("DELETE FROM chunks").run().changes);
|
|
18612
18691
|
}
|
|
18613
|
-
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 = ?"];
|
|
18614
18693
|
raw.prepare(TRI_DELETE + " WHERE " + where).run(arg);
|
|
18615
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);
|
|
18616
18696
|
return Number(raw.prepare("DELETE FROM chunks WHERE " + where).run(arg).changes);
|
|
18617
18697
|
}
|
|
18618
18698
|
function toMatch(q) {
|
|
@@ -19129,10 +19209,15 @@ function insertUnits(db, sourceId, sessionId, units) {
|
|
|
19129
19209
|
const from = start;
|
|
19130
19210
|
withWrite(db, (h) => {
|
|
19131
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;
|
|
19132
19214
|
for (let i = from; i < end; i++) {
|
|
19133
19215
|
const u = units[i];
|
|
19134
|
-
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;
|
|
19135
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);
|
|
19136
19221
|
});
|
|
19137
19222
|
start = end;
|
|
19138
19223
|
}
|
|
@@ -19164,9 +19249,15 @@ function readMaxSourceId(db) {
|
|
|
19164
19249
|
function queryUnits(db, sessionId, q, limit, maxSourceId = Number.MAX_SAFE_INTEGER) {
|
|
19165
19250
|
const match = searchTerms(q).join(" OR ");
|
|
19166
19251
|
if (match === "" || sessionId === "") return [];
|
|
19167
|
-
const
|
|
19168
|
-
|
|
19169
|
-
|
|
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);
|
|
19170
19261
|
return rows.map((r) => ({ sourceId: Number(r.source_id), ord: Number(r.ord), label: r.label, body: r.body, score: r.score }));
|
|
19171
19262
|
}
|
|
19172
19263
|
|
|
@@ -20087,6 +20178,7 @@ function buildUnits(text) {
|
|
|
20087
20178
|
|
|
20088
20179
|
// src/core/hooks/spool.ts
|
|
20089
20180
|
var { mkdirSync: mkdirSync3, readdirSync: readdirSync3, readFileSync: readFileSync5, renameSync: renameSync2, statSync: statSync4, unlinkSync, utimesSync, writeFileSync } = process.getBuiltinModule("node:fs");
|
|
20181
|
+
var SEEN_TAG = ".seen";
|
|
20090
20182
|
var OP_SUFFIX = ".json";
|
|
20091
20183
|
var CLAIM_SUFFIX = ".claim";
|
|
20092
20184
|
var TMP_SUFFIX = ".tmp";
|
|
@@ -20115,13 +20207,21 @@ function spool(project, op) {
|
|
|
20115
20207
|
const name = String(Date.now()).padStart(NAME_TIME_DIGITS, "0") + "-" + String(process.pid) + "-" + String(nameSeq++).padStart(NAME_SEQ_DIGITS, "0");
|
|
20116
20208
|
const tmp = join7(dir, name + TMP_SUFFIX);
|
|
20117
20209
|
writeFileSync(tmp, JSON.stringify(op));
|
|
20118
|
-
renameSync2(tmp, join7(dir, name + OP_SUFFIX));
|
|
20210
|
+
renameSync2(tmp, join7(dir, name + (op.t === "seen" ? SEEN_TAG : "") + OP_SUFFIX));
|
|
20119
20211
|
}
|
|
20120
20212
|
function runOp(db, op, chunks, cur) {
|
|
20121
20213
|
if (op.t === "row") {
|
|
20122
20214
|
appendEvent(db, op.row, op.at);
|
|
20123
20215
|
return null;
|
|
20124
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
|
+
}
|
|
20125
20225
|
const c = chunks ?? chunkText(op.text, "text", op.max);
|
|
20126
20226
|
let id = op.id;
|
|
20127
20227
|
if (id === null) {
|
|
@@ -20150,12 +20250,47 @@ function runOp(db, op, chunks, cur) {
|
|
|
20150
20250
|
}
|
|
20151
20251
|
return id;
|
|
20152
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;
|
|
20153
20287
|
function writeOrSpool(project, db, op, chunks) {
|
|
20154
20288
|
const cur = { op };
|
|
20155
20289
|
try {
|
|
20156
20290
|
return runOp(db, op, chunks, cur);
|
|
20157
20291
|
} catch (err) {
|
|
20158
20292
|
if (!isBusy(err)) throw err;
|
|
20293
|
+
busyUntil = Date.now() + HOOK_BUSY_MS;
|
|
20159
20294
|
spool(project, cur.op);
|
|
20160
20295
|
return cur.op.t === "src" ? cur.op.id : null;
|
|
20161
20296
|
}
|
|
@@ -20164,11 +20299,18 @@ function writeDetached(project, op, what, chunks) {
|
|
|
20164
20299
|
void (async () => {
|
|
20165
20300
|
try {
|
|
20166
20301
|
const db = await hookDb(project);
|
|
20167
|
-
if (
|
|
20168
|
-
|
|
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
|
+
}
|
|
20169
20310
|
} catch (err) {
|
|
20170
20311
|
try {
|
|
20171
20312
|
if (!isBusy(err)) throw err;
|
|
20313
|
+
busyUntil = Date.now() + HOOK_BUSY_MS;
|
|
20172
20314
|
spool(project, op);
|
|
20173
20315
|
} catch (e) {
|
|
20174
20316
|
process.stderr.write("hooks: " + what + " write failed: " + message(e) + "\n");
|
|
@@ -20586,6 +20728,7 @@ function compactText(db, ev, row5) {
|
|
|
20586
20728
|
}
|
|
20587
20729
|
async function sessionStart(ev, row5, project) {
|
|
20588
20730
|
if (ev.source === "compact" && hasRecall(row5)) markCompacted(await hookDb(project), ev.sessionId);
|
|
20731
|
+
if (ev.source === "compact") endLostBets(await hookDb(project), ev.sessionId);
|
|
20589
20732
|
if (ev.source === "compact" && row5.compactDelivery === "sessionstart") {
|
|
20590
20733
|
const db2 = await hookDb(project);
|
|
20591
20734
|
const onceKey = COMPACT_STATE_KEY + ":" + lastSessionSeq(db2, ev.sessionId);
|
|
@@ -20654,24 +20797,6 @@ function compactBoundary(value) {
|
|
|
20654
20797
|
return all;
|
|
20655
20798
|
}
|
|
20656
20799
|
}
|
|
20657
|
-
function seenSeqs(value) {
|
|
20658
|
-
if (value === null) return [];
|
|
20659
|
-
try {
|
|
20660
|
-
const v = JSON.parse(value);
|
|
20661
|
-
return Array.isArray(v) ? v.filter((n) => typeof n === "number") : [];
|
|
20662
|
-
} catch {
|
|
20663
|
-
return [];
|
|
20664
|
-
}
|
|
20665
|
-
}
|
|
20666
|
-
function seenUnitKeys(value) {
|
|
20667
|
-
if (value === null) return [];
|
|
20668
|
-
try {
|
|
20669
|
-
const v = JSON.parse(value);
|
|
20670
|
-
return Array.isArray(v) ? v.filter((k) => typeof k === "string") : [];
|
|
20671
|
-
} catch {
|
|
20672
|
-
return [];
|
|
20673
|
-
}
|
|
20674
|
-
}
|
|
20675
20800
|
async function recall(ev, row5, project, prompt) {
|
|
20676
20801
|
if (!hasRecall(row5) || ev.sessionId === "") return ALLOW2;
|
|
20677
20802
|
const db = await hookDb(project);
|
|
@@ -20679,15 +20804,15 @@ async function recall(ev, row5, project, prompt) {
|
|
|
20679
20804
|
if (compacted === null) return ALLOW2;
|
|
20680
20805
|
const boundary = compactBoundary(compacted);
|
|
20681
20806
|
const seenKey = RECALL_SEEN_META_PREFIX + ev.sessionId;
|
|
20682
|
-
const seen =
|
|
20807
|
+
const seen = readSeen(project, db, seenKey).filter((n) => typeof n === "number");
|
|
20683
20808
|
const unitsKey = RECALL_UNITS_SEEN_META_PREFIX + ev.sessionId;
|
|
20684
|
-
const seenUnits =
|
|
20809
|
+
const seenUnits = readSeen(project, db, unitsKey).filter((k) => typeof k === "string");
|
|
20685
20810
|
const units = queryUnits(db, ev.sessionId, recallQueryText(prompt), RECALL_UNIT_CANDIDATES, boundary.source);
|
|
20686
20811
|
const rows = readRecallRows(db, ev.sessionId, project.worktree, RECALL_MAX_ROWS, boundary.seq);
|
|
20687
20812
|
const picked = pickRecall(rows, prompt, new Set(seen), units, new Set(seenUnits));
|
|
20688
20813
|
if (picked.text === "") return ALLOW2;
|
|
20689
|
-
if (picked.seqs.length > 0)
|
|
20690
|
-
if (picked.units !== void 0)
|
|
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");
|
|
20691
20816
|
return { kind: "hint", text: picked.text, onceKey: RECALL_KEY };
|
|
20692
20817
|
}
|
|
20693
20818
|
function optionsKey(sessionId) {
|
|
@@ -20870,8 +20995,11 @@ function ownRead(ev, tool, env) {
|
|
|
20870
20995
|
return p !== void 0 && isOwnFile(ev.agent, ev.cwd, p, env);
|
|
20871
20996
|
}
|
|
20872
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
|
+
}
|
|
20873
21002
|
if (result.bytes <= REPLACE_TRIGGER_BYTES) return ALLOW2;
|
|
20874
|
-
if (boundedRead(tool)) return ALLOW2;
|
|
20875
21003
|
if (ompRangedRead(ev, tool)) return ALLOW2;
|
|
20876
21004
|
if (ownRead(ev, tool, env)) return ALLOW2;
|
|
20877
21005
|
if (SKILL_LOAD_TOOLS.includes(tool.canonicalName)) return ALLOW2;
|
|
@@ -20898,6 +21026,8 @@ async function postReplace(ev, row5, project, env, tool, result, text, persisted
|
|
|
20898
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;
|
|
20899
21027
|
const chunks = chunkText(text, "text", REPLACE_CHUNK_BYTES);
|
|
20900
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;
|
|
20901
21031
|
const op = { t: "src", id: null, src: sourceRowOf(project, ev.sessionId, label2), text, max: REPLACE_CHUNK_BYTES, units: true };
|
|
20902
21032
|
let sourceId;
|
|
20903
21033
|
if (result.bytes <= SYNC_INDEX_MAX_BYTES) {
|
|
@@ -20908,6 +21038,7 @@ async function postReplace(ev, row5, project, env, tool, result, text, persisted
|
|
|
20908
21038
|
}
|
|
20909
21039
|
if (pluginMcpCall(tool)) return ALLOW2;
|
|
20910
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);
|
|
20911
21042
|
const prompt = await lastPrompt(project, ev.sessionId);
|
|
20912
21043
|
const rankQuery = prompt.trim() === "" ? void 0 : intent + " " + prompt;
|
|
20913
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);
|
|
@@ -20918,6 +21049,23 @@ async function postReplace(ev, row5, project, env, tool, result, text, persisted
|
|
|
20918
21049
|
const selected = selectChunksInMemory(chunks, intent, budget, label2, rankQuery);
|
|
20919
21050
|
return { kind: "replace", output: selected.more !== null ? replaceOutput(selected.text, pointer) : selected.text };
|
|
20920
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
|
+
}
|
|
20921
21069
|
function pluginMcpCall(tool) {
|
|
20922
21070
|
return tool.callId !== void 0 && tool.callId.startsWith(PLUGIN_CALL_ID_PREFIX) && tool.name.startsWith(MCP_SERVER_TOOL_PREFIX);
|
|
20923
21071
|
}
|
|
@@ -21035,8 +21183,15 @@ async function preCompact(ev, row5, project) {
|
|
|
21035
21183
|
const db = await hookDb(project);
|
|
21036
21184
|
metaSet(db, PENDING_COMPACT_META_PREFIX + ev.sessionId, PENDING_COMPACT_FLAG);
|
|
21037
21185
|
if (hasRecall(row5)) markCompacted(db, ev.sessionId);
|
|
21186
|
+
endLostBets(db, ev.sessionId);
|
|
21038
21187
|
return ALLOW2;
|
|
21039
21188
|
}
|
|
21189
|
+
function endLostBets(db, sessionId) {
|
|
21190
|
+
try {
|
|
21191
|
+
clearLostBets(db, sessionId);
|
|
21192
|
+
} catch {
|
|
21193
|
+
}
|
|
21194
|
+
}
|
|
21040
21195
|
function usage(ev, project) {
|
|
21041
21196
|
appendDetached(project, ev.sessionId, {
|
|
21042
21197
|
session_id: ev.sessionId,
|
|
@@ -21484,9 +21639,9 @@ function unknownSource(db, scope, ctx, given) {
|
|
|
21484
21639
|
return line + "\nStored sources, newest first: " + names.join(", ") + more + ". " + callText([], scope, void 0, 'sort:"timeline"') + " lists them all.";
|
|
21485
21640
|
}
|
|
21486
21641
|
function named(given, pick4) {
|
|
21487
|
-
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 };
|
|
21488
21643
|
const arg = pick4.id !== null && isLongLabel(given) ? sourceHandle(pick4.id) : given;
|
|
21489
|
-
return { arg, note: collisionLine(given, pick4), pick: pick4 };
|
|
21644
|
+
return { arg, note: collisionLine(given, pick4), pick: pick4, lost: null };
|
|
21490
21645
|
}
|
|
21491
21646
|
function sourceCard(db, id, input, scope, arg) {
|
|
21492
21647
|
const row5 = sourceCardRow(db, id);
|
|
@@ -21510,7 +21665,7 @@ function decisionQueries(input) {
|
|
|
21510
21665
|
function pageSize(input) {
|
|
21511
21666
|
return input.source === DECISION_SOURCE ? SEARCH_PAGE_SIZE : SEARCH_REPLY_HITS;
|
|
21512
21667
|
}
|
|
21513
|
-
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 }) {
|
|
21514
21669
|
const size = pageSize(input) + extra;
|
|
21515
21670
|
if (input.source === DECISION_SOURCE && q.trim() === "") {
|
|
21516
21671
|
return ftsListSource(db, DECISION_SOURCE, scope, ctx.project, ctx.sessionId, size, offset);
|
|
@@ -21519,6 +21674,8 @@ function page(db, q, input, scope, ctx, offset, extra = 0) {
|
|
|
21519
21674
|
if (hits.length > 0 || input.source === void 0) return hits;
|
|
21520
21675
|
const any3 = offset === 0 ? hits : ftsQuery(db, q, scope, ctx.project, ctx.sessionId, 1, 0, input.source);
|
|
21521
21676
|
if (any3.length > 0) return hits;
|
|
21677
|
+
h9.n++;
|
|
21678
|
+
if (!h9.list) return [];
|
|
21522
21679
|
return ftsListSource(db, input.source, scope, ctx.project, ctx.sessionId, size, offset);
|
|
21523
21680
|
}
|
|
21524
21681
|
var JSON_ROWS_PAGE = 5;
|
|
@@ -21607,15 +21764,27 @@ function relevance(db, given, scope, ctx, nm, ms, indexed) {
|
|
|
21607
21764
|
const size = pageSize(input);
|
|
21608
21765
|
const mem = ms.named || offset === 0 ? memoryChunks(ms.rows) : [];
|
|
21609
21766
|
const count2 = (hits, n) => ms.named ? Math.min(n, hits.length) : contentIn(hits, n);
|
|
21610
|
-
const
|
|
21767
|
+
const h9 = { n: 0, list: false };
|
|
21768
|
+
const listed = [];
|
|
21769
|
+
const fetched = input.queries.map((q, qi) => {
|
|
21611
21770
|
if (ms.named) {
|
|
21612
21771
|
const want = offset + size + 1;
|
|
21613
21772
|
const content2 = indexed ? ftsQuery(db, q, scope, ctx.project, ctx.sessionId, want, 0, input.source) : [];
|
|
21614
21773
|
return mergeMemory(content2, memoryHits(mem, q, want)).slice(offset, want);
|
|
21615
21774
|
}
|
|
21616
|
-
const
|
|
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);
|
|
21617
21778
|
return mem.length === 0 ? content : mergeMemory(content, memoryHits(mem, q, MEMORY_HITS));
|
|
21618
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
|
+
}
|
|
21619
21788
|
const take = fetched.map((h) => replyHits(h, size));
|
|
21620
21789
|
const pages = fetched.map((h, i) => h.slice(0, take[i]));
|
|
21621
21790
|
if (pages.every((p) => p.length === 0)) return zeroHits(db, scope, ctx, input.source, ms, nm, input.queries, offset);
|
|
@@ -21680,6 +21849,49 @@ function relevance(db, given, scope, ctx, nm, ms, indexed) {
|
|
|
21680
21849
|
for (const [pos, qs] of byPos) moreLines.push("More: " + callText(qs, scope, nm.arg, "offset:" + pos));
|
|
21681
21850
|
return reply(lines.concat(moreLines).join("\n"), false);
|
|
21682
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
|
+
}
|
|
21683
21895
|
function timelineLine(r) {
|
|
21684
21896
|
const nl = r.text.indexOf("\n");
|
|
21685
21897
|
const first = nl < 0 ? r.text : r.text.slice(0, nl);
|
|
@@ -21740,6 +21952,7 @@ async function handler(input, ctx) {
|
|
|
21740
21952
|
}
|
|
21741
21953
|
const scope = input.scope ?? "worktree";
|
|
21742
21954
|
const db = await openDb(ctx.project, { readOnly: true });
|
|
21955
|
+
let lost = null;
|
|
21743
21956
|
try {
|
|
21744
21957
|
const given = input.source;
|
|
21745
21958
|
const within = { scope, sessionId: ctx.sessionId, worktree: ctx.project.worktree };
|
|
@@ -21755,11 +21968,24 @@ async function handler(input, ctx) {
|
|
|
21755
21968
|
nm.note = nm.note === null ? both : nm.note + "\n" + both;
|
|
21756
21969
|
}
|
|
21757
21970
|
const out = answer(db, input, scope, ctx, nm, ms, indexed, sort, pick4);
|
|
21971
|
+
lost = nm.lost;
|
|
21758
21972
|
if (file2 === null || scope !== "session") return out;
|
|
21759
21973
|
const call = callText(input.queries, "worktree", nm.arg, sort === "timeline" ? 'sort:"timeline"' : "");
|
|
21760
21974
|
return reply(out.text + "\nMemory file " + file2.label + ' is in scope "worktree": ' + call + " searches it.", out.isError);
|
|
21761
21975
|
} finally {
|
|
21762
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 {
|
|
21763
21989
|
}
|
|
21764
21990
|
}
|
|
21765
21991
|
var ctxSearch = Object.freeze({
|
|
@@ -25334,8 +25560,8 @@ var ENABLED_PROVIDERS = "enabledProviders";
|
|
|
25334
25560
|
var DISABLED_PROVIDERS = "disabledProviders";
|
|
25335
25561
|
var CLAUDE_PROVIDER = "claude";
|
|
25336
25562
|
var ALL_PROVIDERS = ["*", "all"];
|
|
25337
|
-
function ompImportFiles(home) {
|
|
25338
|
-
const agentDir =
|
|
25563
|
+
function ompImportFiles(env, home) {
|
|
25564
|
+
const agentDir = ompAgentDirOf(env, home);
|
|
25339
25565
|
return { config: join16(agentDir, OMP_CONFIG_FILE), mcp: join16(agentDir, OMP_MCP_FILE), claude: join16(home, CLAUDE_USER_CONFIG_FILE) };
|
|
25340
25566
|
}
|
|
25341
25567
|
function readText2(file2) {
|
|
@@ -25718,7 +25944,7 @@ function checkHostConfig(row5, env, worktree) {
|
|
|
25718
25944
|
if ("installs" in choice) return fail3("D3", D3_ROOT_DETAIL(choice.installs.map((r) => r.installPath)), D3_ROOT_FIX(choice.installs));
|
|
25719
25945
|
}
|
|
25720
25946
|
if (row5.id === "pi") return checkPiInstall(env, home, worktree);
|
|
25721
|
-
if (row5.id === "omp") return checkOmpInstall(home);
|
|
25947
|
+
if (row5.id === "omp") return checkOmpInstall(env, home);
|
|
25722
25948
|
const parts = [...mcpWrong(row5, home, env, worktree) ? [PART_MCP] : [], ...hookParts(row5, home, env, worktree)];
|
|
25723
25949
|
if (parts.length === 0) return pass2("D3");
|
|
25724
25950
|
const detail = D3_DETAIL(parts);
|
|
@@ -25730,7 +25956,6 @@ function checkPiInstall(env, home, worktree) {
|
|
|
25730
25956
|
if (found !== void 0) return { ...pass2("D3"), detail: found };
|
|
25731
25957
|
return fail3("D3", D3_DETAIL([PART_MCP]) + D4_REASON_JOIN + join17(piAgentDirOf(env, home), SETTINGS_FILE), NATIVE_INSTALL.pi[0]);
|
|
25732
25958
|
}
|
|
25733
|
-
var OMP_PLUGINS_DIR = "plugins";
|
|
25734
25959
|
var OMP_LOCK_FILE = "omp-plugins.lock.json";
|
|
25735
25960
|
function readJson2(file2) {
|
|
25736
25961
|
try {
|
|
@@ -25744,8 +25969,8 @@ function ownEntry(doc, key) {
|
|
|
25744
25969
|
const map2 = doc?.[key];
|
|
25745
25970
|
return typeof map2 === "object" && map2 !== null ? map2[SERVER_KEY] : void 0;
|
|
25746
25971
|
}
|
|
25747
|
-
function checkOmpInstall(home) {
|
|
25748
|
-
const dir =
|
|
25972
|
+
function checkOmpInstall(env, home) {
|
|
25973
|
+
const dir = ompPluginsDirOf(env, home);
|
|
25749
25974
|
const lock = join17(dir, OMP_LOCK_FILE);
|
|
25750
25975
|
const pkg = join17(dir, PI_PACKAGE_JSON_FILE);
|
|
25751
25976
|
const entry = ownEntry(readJson2(lock), "plugins");
|
|
@@ -25761,12 +25986,26 @@ function ompInfoLines(env, version4) {
|
|
|
25761
25986
|
out.push(OMP_CONTENT_INFO, OMP_PRINT_MODE_INFO, OMP_SCRIPTS_INFO);
|
|
25762
25987
|
const home = homeDirOf(env);
|
|
25763
25988
|
if (home === null) return out;
|
|
25764
|
-
const files = ompImportFiles(home);
|
|
25989
|
+
const files = ompImportFiles(env, home);
|
|
25765
25990
|
if (!ompImportsUs(files, env)) return out;
|
|
25766
25991
|
const listed = readJson2(files.mcp)?.[OMP_DISABLED_SERVERS_KEY];
|
|
25767
25992
|
if (!(Array.isArray(listed) && listed.includes(SERVER_KEY))) out.push(OMP_IMPORT_INFO(files.claude, files.mcp));
|
|
25768
25993
|
return out;
|
|
25769
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
|
+
}
|
|
25770
26009
|
function checkV1Leftovers(agent, home, scope = {}) {
|
|
25771
26010
|
const findings = detectV1(agent, home, scope);
|
|
25772
26011
|
if (findings.length === 0) return pass2("D4");
|
|
@@ -28851,10 +29090,12 @@ async function doctorReply(ctx, host) {
|
|
|
28851
29090
|
const look = rows.find((r) => r.status === "FAIL") ?? rows.find((r) => r.status !== "PASS");
|
|
28852
29091
|
const docs = look === void 0 ? [] : [DOCTOR_DOCS_LABEL + DOCTOR_DOCS_LINK(look.id)];
|
|
28853
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));
|
|
28854
29095
|
const whole2 = [envLine2, table3, ...docs, ...info, ...notes].join("\n");
|
|
28855
29096
|
const bytes5 = Buffer.byteLength(whole2, "utf8");
|
|
28856
29097
|
if (bytes5 <= REPORT_CAP) return { text: whole2, isError: false, sandboxBytes: bytes5 };
|
|
28857
|
-
const p =
|
|
29098
|
+
const p = known;
|
|
28858
29099
|
if ("missing" in p) return { text: whole2, isError: false, sandboxBytes: bytes5 };
|
|
28859
29100
|
const db = await openDb(p.project);
|
|
28860
29101
|
try {
|
|
@@ -28966,11 +29207,11 @@ function schemaLine(issue4) {
|
|
|
28966
29207
|
if (issue4.code === "unrecognized_keys") return new CtxError("UNKNOWN_FIELD", { f: issue4.keys[0] }).toLine();
|
|
28967
29208
|
return issue4.message;
|
|
28968
29209
|
}
|
|
28969
|
-
function fileError(given, abs, root) {
|
|
29210
|
+
function fileError(given, abs, root, hostRoots) {
|
|
28970
29211
|
let dir = abs;
|
|
28971
29212
|
while (!existsSync18(dir) && dirname12(dir) !== dir) dir = dirname12(dir);
|
|
28972
|
-
if (
|
|
28973
|
-
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 };
|
|
28974
29215
|
}
|
|
28975
29216
|
function takesDashC(language, runtime) {
|
|
28976
29217
|
if (language === "shell") return true;
|
|
@@ -29033,8 +29274,8 @@ async function handler3(raw, ctx) {
|
|
|
29033
29274
|
const extra = { ...PLAIN_OUTPUT_ENV2 };
|
|
29034
29275
|
if (input.file !== void 0) {
|
|
29035
29276
|
const abs = resolve11(cwd, input.file);
|
|
29036
|
-
const bad = fileError(input.file, abs, ctx.project.containmentRoot);
|
|
29037
|
-
if (bad !== null) return
|
|
29277
|
+
const bad = fileError(input.file, abs, ctx.project.containmentRoot, ctx.hostRoots);
|
|
29278
|
+
if (bad !== null) return bad;
|
|
29038
29279
|
extra.CTX_FILE = abs;
|
|
29039
29280
|
}
|
|
29040
29281
|
let runtime;
|
|
@@ -33351,18 +33592,19 @@ function readUtf8(absPath) {
|
|
|
33351
33592
|
return void 0;
|
|
33352
33593
|
}
|
|
33353
33594
|
}
|
|
33354
|
-
function missingOrOutside(given, abs, root) {
|
|
33595
|
+
function missingOrOutside(given, abs, root, hostRoots) {
|
|
33355
33596
|
let dir = abs;
|
|
33356
33597
|
while (!existsSync19(dir) && dirname13(dir) !== dir) dir = dirname13(dir);
|
|
33357
|
-
if (dir !== abs &&
|
|
33598
|
+
if (dir !== abs && allowedRootOf(root, hostRoots, dir) !== void 0) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
|
|
33358
33599
|
return new CtxError("OUTSIDE_ROOT", { p: given, root });
|
|
33359
33600
|
}
|
|
33360
|
-
function pathItems(input, project) {
|
|
33601
|
+
function pathItems(input, project, hostRoots) {
|
|
33361
33602
|
const abs = resolve12(project.worktree, input.path);
|
|
33362
|
-
|
|
33603
|
+
const allowed = allowedRootOf(project.containmentRoot, hostRoots, abs);
|
|
33604
|
+
if (allowed === void 0) throw missingOrOutside(input.path, abs, project.containmentRoot, hostRoots);
|
|
33363
33605
|
const base = relative5(project.worktree, abs);
|
|
33364
33606
|
if (statSync10(abs).isDirectory()) {
|
|
33365
|
-
return walkDir(abs,
|
|
33607
|
+
return walkDir(abs, allowed).map((f) => ({
|
|
33366
33608
|
sourceKind: "path",
|
|
33367
33609
|
label: pathLabel(join25(base, f.relPath)),
|
|
33368
33610
|
kind: kindOfPath(f.relPath),
|
|
@@ -33379,7 +33621,7 @@ async function itemsOf(input, ctx) {
|
|
|
33379
33621
|
return { items: [{ sourceKind: "content", label: label3, kind, read: () => text2 }], from: label3 };
|
|
33380
33622
|
}
|
|
33381
33623
|
if (input.path !== void 0) {
|
|
33382
|
-
const items = pathItems({ ...input, path: input.path }, ctx.project);
|
|
33624
|
+
const items = pathItems({ ...input, path: input.path }, ctx.project, ctx.hostRoots);
|
|
33383
33625
|
return { items, from: items.length === 1 ? items[0].label : pathLabel(input.path) };
|
|
33384
33626
|
}
|
|
33385
33627
|
const res = await safeFetch(input.url ?? "", AbortSignal.any([ctx.signal, AbortSignal.timeout(EXEC_TIMEOUT_MS)]));
|
|
@@ -33446,7 +33688,7 @@ async function handler4(input, ctx) {
|
|
|
33446
33688
|
journal: { kind: "index", key: from, path: from, exit_code: null }
|
|
33447
33689
|
};
|
|
33448
33690
|
} catch (err) {
|
|
33449
|
-
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 } : {} };
|
|
33450
33692
|
throw err;
|
|
33451
33693
|
}
|
|
33452
33694
|
}
|
|
@@ -34076,7 +34318,7 @@ function ownEntries2(agent, env) {
|
|
|
34076
34318
|
}
|
|
34077
34319
|
if (agent === "omp") {
|
|
34078
34320
|
return [{
|
|
34079
|
-
file: ompImportFiles(home).mcp,
|
|
34321
|
+
file: ompImportFiles(env, home).mcp,
|
|
34080
34322
|
key: OMP_DISABLED_SERVERS_KEY,
|
|
34081
34323
|
shown: OMP_DISABLED_SERVERS_KEY,
|
|
34082
34324
|
has: (v) => Array.isArray(v) && v.includes(SERVER_KEY),
|
|
@@ -52070,6 +52312,29 @@ var inputRequired = Object.assign(buildInputRequired, {
|
|
|
52070
52312
|
return { method: "roots/list" };
|
|
52071
52313
|
}
|
|
52072
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
|
+
}
|
|
52073
52338
|
var REQUEST_STATE_ONLY_LEG_PACING_MS = 250;
|
|
52074
52339
|
function inputRequiredRoundsExceededMessage(method, maxRounds) {
|
|
52075
52340
|
return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`;
|
|
@@ -62615,6 +62880,38 @@ function workspaceFromMeta(meta3) {
|
|
|
62615
62880
|
return void 0;
|
|
62616
62881
|
}
|
|
62617
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
|
+
}
|
|
62618
62915
|
function realOrSame(p) {
|
|
62619
62916
|
try {
|
|
62620
62917
|
return realpathSync12.native(p);
|
|
@@ -62702,6 +62999,8 @@ async function startServer(argv, env) {
|
|
|
62702
62999
|
const agent = resolveAgent(argv, env);
|
|
62703
63000
|
const fromRoots = agent === "vscode" && !hasWorkspaceFolder(argv) ? await workspaceFromRoots(server) : void 0;
|
|
62704
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 ?? []];
|
|
62705
63004
|
let project;
|
|
62706
63005
|
const projectOf = () => {
|
|
62707
63006
|
if (agent === void 0) throw new CtxError("NO_PROJECT", { kind: "--agent" });
|
|
@@ -62714,6 +63013,8 @@ async function startServer(argv, env) {
|
|
|
62714
63013
|
},
|
|
62715
63014
|
...agent === void 0 ? {} : { agent },
|
|
62716
63015
|
// D-1410-DOCTOR-NO-PROJECT-1
|
|
63016
|
+
...hostRoots.length === 0 ? {} : { hostRoots },
|
|
63017
|
+
// D-1398-HOST-ROOTS-1
|
|
62717
63018
|
sessionId: sessionIdOf(meta3, agent, env, serverId),
|
|
62718
63019
|
turn: metaNumber(meta3, "turn") ?? 0,
|
|
62719
63020
|
signal: req.mcpReq.signal,
|
|
@@ -62731,6 +63032,9 @@ async function startServer(argv, env) {
|
|
|
62731
63032
|
reply4 = errorReply(err);
|
|
62732
63033
|
}
|
|
62733
63034
|
}
|
|
63035
|
+
if (reply4.outsideRoot === true && fromInput === void 0 && listsRoots(req.mcpReq.envelope)) {
|
|
63036
|
+
return inputRequired({ inputRequests: { [HOST_ROOTS_INPUT_KEY]: inputRequired.listRoots() } });
|
|
63037
|
+
}
|
|
62734
63038
|
if (stopRequested()) {
|
|
62735
63039
|
setTimeout(stopSelf, UPGRADE_STOP_DELAY_MS);
|
|
62736
63040
|
return { content: [{ type: "text", text: reply4.text }], isError: reply4.isError };
|