context-mode 2.0.0-next.29 → 2.0.0-next.32
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/README.md +84 -83
- package/SHA256SUMS +19 -19
- package/claude-code/skills/ctx-stats/SKILL.md +2 -2
- package/cli.mjs +342 -152
- package/codex/skills/ctx-stats/SKILL.md +2 -2
- package/copilot/plugin.json +1 -1
- package/gemini-extension.json +1 -1
- package/hook.mjs +75 -75
- package/opencode/plugin.js +1063 -309
- package/package.json +1 -1
- package/pi/index.js +1178 -425
- package/pi/skills/ctx-stats/SKILL.md +2 -2
- package/qwen-extension.json +1 -1
- package/run.mjs +84 -3
- package/search.mjs +84 -3
- package/server.mjs +1118 -365
- package/skills/ctx-stats/SKILL.md +2 -2
package/opencode/plugin.js
CHANGED
|
@@ -27,9 +27,9 @@ var REPLACE_TRIGGER_BYTES = 4096;
|
|
|
27
27
|
var REPLACE_RETURN_BYTES = 96;
|
|
28
28
|
var SHAPE_RETURN_BYTES = 256;
|
|
29
29
|
var REPLACE_CHUNK_BYTES = 48;
|
|
30
|
-
function REPLACE_HANDLE_LINE(intent, handle,
|
|
30
|
+
function REPLACE_HANDLE_LINE(intent, handle, bytes5, prefix = "", asked = "") {
|
|
31
31
|
const queries = asked === "" ? [intent] : [intent, asked];
|
|
32
|
-
return prefix + "ctx_search({queries:[" + queries.map((q) => JSON.stringify(q)).join(",") + "], source:" + JSON.stringify(handle) + "}) searches the whole output (" +
|
|
32
|
+
return prefix + "ctx_search({queries:[" + queries.map((q) => JSON.stringify(q)).join(",") + "], source:" + JSON.stringify(handle) + "}) searches the whole output (" + bytes5 + " B).";
|
|
33
33
|
}
|
|
34
34
|
var HANDLE_PROMPT_WORDS = 3;
|
|
35
35
|
var MAX_CHUNK_BYTES = 4096;
|
|
@@ -188,6 +188,7 @@ var SQLITE_NOTADB_CODE = 26;
|
|
|
188
188
|
var HOOK_P95_MS = 40;
|
|
189
189
|
var HOOK_TIMEOUT_MS = 5e3;
|
|
190
190
|
var IN_PROCESS_TIMEOUT_MS = 0;
|
|
191
|
+
var MS_PER_DAY = 864e5;
|
|
191
192
|
var PROJECT_KEY_HEX_LEN = 16;
|
|
192
193
|
var SCHEMA_VERSION = 6;
|
|
193
194
|
var RETENTION_SIZE_CAP_BYTES = 524288e3;
|
|
@@ -208,6 +209,7 @@ var SOURCE_LABEL_MAX_CHARS = 80;
|
|
|
208
209
|
var CANCELLED_LINE = "Cancelled.";
|
|
209
210
|
var BACKGROUND_REPLY_PREFIX = "started in background, pid ";
|
|
210
211
|
var PLAIN_OUTPUT_ENV = Object.freeze({ NO_COLOR: "1", FORCE_COLOR: "0" });
|
|
212
|
+
var RUN_LABEL_PREFIX = "run.mjs:";
|
|
211
213
|
var HOST_SESSION_ENV = Object.freeze({ "claude-code": "CLAUDE_CODE_SESSION_ID" });
|
|
212
214
|
var NODE_MIN = "24.15.0";
|
|
213
215
|
var DATA_ROOT = "~/.context-mode";
|
|
@@ -273,8 +275,8 @@ var HOOK_FAIL_TOOLS = Object.freeze({
|
|
|
273
275
|
grep: Object.freeze(["Grep", "grep_search"]),
|
|
274
276
|
fetch: Object.freeze(["WebFetch", "web_fetch", "fetch"])
|
|
275
277
|
});
|
|
276
|
-
function HOOK_FAIL_LINE(
|
|
277
|
-
return `${DENY_PREFIX}the hook failed (${
|
|
278
|
+
function HOOK_FAIL_LINE(label2, prefix) {
|
|
279
|
+
return `${DENY_PREFIX}the hook failed (${label2}). Fix: run ${prefix}ctx_doctor.`;
|
|
278
280
|
}
|
|
279
281
|
var HOOK_FAIL_REDIRECT = Object.freeze({
|
|
280
282
|
read: "Read the file in parts with offset and limit, or process it with ctx_execute(language, code); only what you print comes back.",
|
|
@@ -282,11 +284,11 @@ var HOOK_FAIL_REDIRECT = Object.freeze({
|
|
|
282
284
|
grep: "Search with ctx_execute(language, code), or index the files with ctx_index and query them with ctx_search.",
|
|
283
285
|
fetch: "Index the URL with ctx_index and query it with ctx_search."
|
|
284
286
|
});
|
|
285
|
-
function D5_LAST_HOOK_ERROR(ts, stage,
|
|
286
|
-
return `; last hook error ${ts} at ${stage} (${
|
|
287
|
+
function D5_LAST_HOOK_ERROR(ts, stage, label2) {
|
|
288
|
+
return `; last hook error ${ts} at ${stage} (${label2}), stack in ${HOOK_ERROR_LOG_FILE}`;
|
|
287
289
|
}
|
|
288
|
-
function D5_PAST_HOOK_ERROR(ts, stage,
|
|
289
|
-
return `; past hook error ${ts} at ${stage} (${
|
|
290
|
+
function D5_PAST_HOOK_ERROR(ts, stage, label2) {
|
|
291
|
+
return `; past hook error ${ts} at ${stage} (${label2}), before this run, stack in ${HOOK_ERROR_LOG_FILE}`;
|
|
290
292
|
}
|
|
291
293
|
var BOUNDED_COMMANDS = Object.freeze(["pwd", "whoami", "uname", "id", "realpath", "ln"]);
|
|
292
294
|
var BOUNDED_GIT_SUBCOMMANDS = Object.freeze(["status"]);
|
|
@@ -355,6 +357,59 @@ function STATS_SUMMARY(allTimePct, sessionPct) {
|
|
|
355
357
|
}
|
|
356
358
|
var STATS_COLUMNS = Object.freeze(["Scope", "Produced", "Returned", "Saved", "Reduction %"]);
|
|
357
359
|
var STATS_NO_DATA = "no data \u2014 no tool calls recorded yet";
|
|
360
|
+
var STATS_WIDTH = 80;
|
|
361
|
+
var STATS_BYTES_PER_TOKEN = 4;
|
|
362
|
+
var STATS_MAX_TOOL_ROWS = 12;
|
|
363
|
+
var STATS_LABEL_W = 21;
|
|
364
|
+
var STATS_LABEL_MAX = 20;
|
|
365
|
+
var STATS_CALLS_W = 7;
|
|
366
|
+
var STATS_NUM_W = 11;
|
|
367
|
+
var STATS_PCT_W = 8;
|
|
368
|
+
var STATS_KIND_W = 9;
|
|
369
|
+
var STATS_HEAD_BAR = 40;
|
|
370
|
+
var STATS_ROW_BAR = 8;
|
|
371
|
+
var STATS_KIND_BAR = 20;
|
|
372
|
+
var STATS_KIB = 1024;
|
|
373
|
+
var STATS_MILLION = 1e6;
|
|
374
|
+
var STATS_MS_PER_MINUTE = 6e4;
|
|
375
|
+
var STATS_MINUTES_PER_HOUR = 60;
|
|
376
|
+
var STATS_HOURS_PER_DAY = 24;
|
|
377
|
+
var STATS_CLOCK_DIGITS = 2;
|
|
378
|
+
var STATS_REPORT_TITLE = "context-mode stats";
|
|
379
|
+
var STATS_EMPTY_LINES = Object.freeze([
|
|
380
|
+
"Ready. Your savings show up here after the first tool call.",
|
|
381
|
+
"Large outputs from ctx_execute, ctx_batch and ctx_index stay in the",
|
|
382
|
+
"sandbox, and only the short answer goes to the chat."
|
|
383
|
+
]);
|
|
384
|
+
var STATS_KIND_LABELS = Object.freeze([
|
|
385
|
+
// D-STATS-FIX-1 (8): the first five rows are call kinds, so they add up to the calls of the scope line.
|
|
386
|
+
["index", "Content indexed"],
|
|
387
|
+
["edit", "File edits"],
|
|
388
|
+
["toolerr", "Issues kept"],
|
|
389
|
+
["decision", "Your decisions"],
|
|
390
|
+
["cmd", "Other tool calls"],
|
|
391
|
+
["prompt", "Your prompts"]
|
|
392
|
+
]);
|
|
393
|
+
var STATS_JOURNAL_HINTS = Object.freeze([
|
|
394
|
+
"ctx_resume brings back your last task, files changed and open issues",
|
|
395
|
+
"after a compact or a restart; ctx_search finds indexed content by words."
|
|
396
|
+
]);
|
|
397
|
+
var STATS_WINDOW_TOKENS = 2e5;
|
|
398
|
+
var STATS_THOUSAND = 1e3;
|
|
399
|
+
var STATS_WHOLE_FROM = 10;
|
|
400
|
+
var STATS_DAYS = 7;
|
|
401
|
+
var STATS_TOP_OUTPUTS = 3;
|
|
402
|
+
var STATS_CARD_W = 19;
|
|
403
|
+
var STATS_DAY_BAR = 48;
|
|
404
|
+
var STATS_TOKEN_NOTE = " (at 4 bytes per token; a Claude context window is 200K tokens)";
|
|
405
|
+
var STATS_WAYS = Object.freeze([
|
|
406
|
+
["sandbox", "\u2588", "sandbox run"],
|
|
407
|
+
["index", "\u2593", "index + search"],
|
|
408
|
+
["redirect", "\u2592", "hook sent to sandbox"],
|
|
409
|
+
["replace", "\u2591", "hook cut down"]
|
|
410
|
+
]);
|
|
411
|
+
var STATS_INDEX_TOOLS = Object.freeze(["ctx_index", "ctx_search"]);
|
|
412
|
+
var STATS_FOOTER_URL = "https://contextmode.ai/?utm_source=ctx_stats&utm_medium=stats&utm_content=footer";
|
|
358
413
|
var PURGE_SCOPES = Object.freeze(["session", "source", "project"]);
|
|
359
414
|
var PURGE_NO_SCOPE_LINE = "ctx_purge: pick one scope \u2014 session, source, or project.";
|
|
360
415
|
var PURGE_MANY_SCOPES_LINE = "ctx_purge: pick only one scope \u2014 session, source, or project.";
|
|
@@ -370,7 +425,7 @@ var DECISION_OPTION_KEY = "option";
|
|
|
370
425
|
var DECISION_LABEL_JOIN = " | ";
|
|
371
426
|
var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
|
|
372
427
|
var RELEASE_BRANCH = "release";
|
|
373
|
-
var BUNDLE_SHA = true ? "
|
|
428
|
+
var BUNDLE_SHA = true ? "feb8de116956b3d3eff56c7d5ed2d840483d0cd4" : void 0;
|
|
374
429
|
var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
|
|
375
430
|
var DOCTOR_LABEL = Object.freeze({
|
|
376
431
|
D1: "version",
|
|
@@ -400,9 +455,49 @@ function DOCTOR_FAIL_LINE(host, check2, cause, command) {
|
|
|
400
455
|
return `FAIL ${host}: ${check2} \u2014 ${cause}. Fix: ${command}`;
|
|
401
456
|
}
|
|
402
457
|
var DOCTOR_FIX_UPGRADE = "run ctx_upgrade";
|
|
403
|
-
var
|
|
404
|
-
var D1_DEV_BUILD_DETAIL = "dev build";
|
|
458
|
+
var D1_DEV_BUILD_DETAIL = "dev build: source checkout; release builds stamp the sha";
|
|
405
459
|
var D1_UPDATE_DETAIL = "update available";
|
|
460
|
+
var D1_SHORT_SHA_LEN = 7;
|
|
461
|
+
var D1_PACKAGE_FILE = "package.json";
|
|
462
|
+
function D1_PREFIX(version2, sha) {
|
|
463
|
+
return `${version2 ?? "bundle"} (${sha.slice(0, D1_SHORT_SHA_LEN)})`;
|
|
464
|
+
}
|
|
465
|
+
var D1_GIT_PASS = "latest on the release branch";
|
|
466
|
+
function D1_NPM_PASS(tag2) {
|
|
467
|
+
return `latest ${tag2} on npm`;
|
|
468
|
+
}
|
|
469
|
+
function D1_NPM_UPDATE(tag2, latest) {
|
|
470
|
+
return `${D1_UPDATE_DETAIL}, ${tag2} on npm is ${latest}`;
|
|
471
|
+
}
|
|
472
|
+
var D1_LATEST_UNKNOWN = "latest unknown";
|
|
473
|
+
var D1_GIT_MISSING = "git not found on PATH";
|
|
474
|
+
function D1_GIT_EXIT(code, stderrLine) {
|
|
475
|
+
return stderrLine === "" ? `git exit ${code}` : `git exit ${code}: ${stderrLine}`;
|
|
476
|
+
}
|
|
477
|
+
function D1_GIT_TIMEOUT(ms) {
|
|
478
|
+
return `git timed out after ${ms} ms`;
|
|
479
|
+
}
|
|
480
|
+
var D1_GIT_CANCEL = "git stopped by cancel";
|
|
481
|
+
var D1_GIT_NO_START = "git did not start";
|
|
482
|
+
var D1_GIT_NO_SHA = "git answered no sha";
|
|
483
|
+
function D1_NPM_TIMEOUT(ms) {
|
|
484
|
+
return `npm registry timed out after ${ms} ms`;
|
|
485
|
+
}
|
|
486
|
+
function D1_NPM_HTTP(status) {
|
|
487
|
+
return `npm registry answered HTTP ${status}`;
|
|
488
|
+
}
|
|
489
|
+
function D1_NPM_ERROR(cause) {
|
|
490
|
+
return `npm registry: ${cause}`;
|
|
491
|
+
}
|
|
492
|
+
function D1_NPM_NO_TAG(tag2) {
|
|
493
|
+
return `npm registry answered no ${tag2} version`;
|
|
494
|
+
}
|
|
495
|
+
var D1_CAUSE_JOIN = "; ";
|
|
496
|
+
var D1_GIT_CHECK_FIX = `git ls-remote ${RELEASE_REPO_URL} ${RELEASE_BRANCH}`;
|
|
497
|
+
var D1_NPM_CHECK_FIX = "npm view context-mode dist-tags";
|
|
498
|
+
var D1_REGISTRY_URL = "https://registry.npmjs.org/-/package/context-mode/dist-tags";
|
|
499
|
+
var D1_PRERELEASE_SEP = "-";
|
|
500
|
+
var D1_DEFAULT_TAG = "latest";
|
|
406
501
|
var GIT_LS_REMOTE = "ls-remote";
|
|
407
502
|
var D2_NODE_FIX = `install Node ${NODE_MIN} or later`;
|
|
408
503
|
function D2_NODE_DETAIL(version2) {
|
|
@@ -690,7 +785,7 @@ var V1_REASON = Object.freeze({
|
|
|
690
785
|
dataDir: "old context-mode data dir <agent home>/context-mode/",
|
|
691
786
|
dataDirShared: "old context-mode data dir ~/.gemini/context-mode/: delete only after a prompt (Antigravity shares it)",
|
|
692
787
|
dataRoot: "old context-mode content under ~/.context-mode/",
|
|
693
|
-
tmpFile: "old context-mode temp file context-mode-* under the OS temp dir: report only,
|
|
788
|
+
tmpFile: "old context-mode temp file context-mode-* under the OS temp dir: report only, safe to keep"
|
|
694
789
|
});
|
|
695
790
|
var UPGRADE_REPORT_ONLY_REASONS = Object.freeze([V1_REASON.statusLine, V1_REASON.vscodeMcp, V1_REASON.dataDirShared, V1_REASON.tmpFile, V1_REASON.kiroSteering]);
|
|
696
791
|
var PLUGIN_ID = SERVER_KEY;
|
|
@@ -732,6 +827,85 @@ var REPORT_ENV_PREFIX = "env.";
|
|
|
732
827
|
var REPORT_ENV_ENUMS = Object.freeze({
|
|
733
828
|
NODE_ENV: Object.freeze(["development", "production", "test"])
|
|
734
829
|
});
|
|
830
|
+
var DOCTOR_ENV_PREFIX = "Environment: ";
|
|
831
|
+
var DOCTOR_DOCS_URL = "https://contextmode.ai/docs/engine/doctor";
|
|
832
|
+
var DOCTOR_DOCS_ANCHOR = "checks";
|
|
833
|
+
function DOCTOR_DOCS_LINK(check2) {
|
|
834
|
+
return `${DOCTOR_DOCS_URL}?utm_source=ctx_doctor&utm_medium=doctor&utm_content=${check2}#${DOCTOR_DOCS_ANCHOR}`;
|
|
835
|
+
}
|
|
836
|
+
var DOCTOR_DOCS_LABEL = "Docs: ";
|
|
837
|
+
function D3_NO_SETUP_FIX(agent) {
|
|
838
|
+
return `context-mode setup --agents ${agent}`;
|
|
839
|
+
}
|
|
840
|
+
function D5_FIXTURE_FILE_ABSENT(file2) {
|
|
841
|
+
return `hook fixture ${file2} is absent: the round trip needs it`;
|
|
842
|
+
}
|
|
843
|
+
function D5_FIXTURE_PARSE(file2, cause) {
|
|
844
|
+
return `the hook fixture file ${file2} failed to parse: ${cause}`;
|
|
845
|
+
}
|
|
846
|
+
function D5_FIXTURE_AGENT_ABSENT(file2, keys) {
|
|
847
|
+
return `the hook fixture file ${file2} records payloads for ${keys.join(", ") || "zero agents"} only`;
|
|
848
|
+
}
|
|
849
|
+
var DOCTOR_REPORTS_DIR = "reports";
|
|
850
|
+
var DOCTOR_REPORT_FILE_PREFIX = "doctor-";
|
|
851
|
+
var DOCTOR_REPORT_LINE = "Report file: ";
|
|
852
|
+
var DOCTOR_GH_LINE = "File it: ";
|
|
853
|
+
var DOCTOR_URL_LINE = "Or open: ";
|
|
854
|
+
var DOCTOR_GH_NEXT = " --";
|
|
855
|
+
var DOCTOR_NOTE_PREFIXES = Object.freeze([
|
|
856
|
+
DOCTOR_ENV_PREFIX,
|
|
857
|
+
DOCTOR_DOCS_LABEL,
|
|
858
|
+
DOCTOR_REPORT_LINE,
|
|
859
|
+
DOCTOR_GH_LINE,
|
|
860
|
+
DOCTOR_GH_NEXT.trim(),
|
|
861
|
+
DOCTOR_URL_LINE
|
|
862
|
+
]);
|
|
863
|
+
var ISSUE_REPO_SLUG = "mksglu/context-mode";
|
|
864
|
+
var ISSUE_FORM_FILE = "agent-report.yml";
|
|
865
|
+
var ISSUE_URL_MAX = 8e3;
|
|
866
|
+
var ISSUE_FORM_HEADINGS = Object.freeze([
|
|
867
|
+
"Summary",
|
|
868
|
+
"ctx-report",
|
|
869
|
+
"What happened",
|
|
870
|
+
"Hook errors",
|
|
871
|
+
"Journal rows",
|
|
872
|
+
"Agent config",
|
|
873
|
+
"Expected",
|
|
874
|
+
"Steps",
|
|
875
|
+
"Environment"
|
|
876
|
+
]);
|
|
877
|
+
var DOCTOR_HOOK_LOG_LINES = 50;
|
|
878
|
+
var DOCTOR_JOURNAL_ROWS = 30;
|
|
879
|
+
var DOCTOR_CONFIG_LINES = 40;
|
|
880
|
+
var DOCTOR_ENV_NAMES = Object.freeze([
|
|
881
|
+
"CODEX_HOME",
|
|
882
|
+
"CLAUDE_CONFIG_DIR",
|
|
883
|
+
"CLAUDE_PLUGIN_ROOT",
|
|
884
|
+
"COPILOT_HOME",
|
|
885
|
+
"KIRO_HOME",
|
|
886
|
+
"OPENCODE_CONFIG_DIR",
|
|
887
|
+
"PI_CODING_AGENT_DIR",
|
|
888
|
+
"XDG_CONFIG_HOME",
|
|
889
|
+
"SHELL"
|
|
890
|
+
]);
|
|
891
|
+
var DOCTOR_PATH_TOOLS = Object.freeze(["node", "git", "sh"]);
|
|
892
|
+
var DOCTOR_SECRET_WORDS = Object.freeze(["token", "secret", "password", "apikey", "api_key", "authorization", "bearer"]);
|
|
893
|
+
var DOCTOR_MASK = "<masked>";
|
|
894
|
+
var NATIVE_INSTALL = Object.freeze({
|
|
895
|
+
"claude-code": ["claude plugin marketplace add mksglu/context-mode#release", "claude plugin install context-mode@context-mode"],
|
|
896
|
+
codex: ["codex plugin marketplace add mksglu/context-mode@release", "codex plugin add context-mode@context-mode"],
|
|
897
|
+
gemini: ["gemini extensions install https://github.com/mksglu/context-mode --ref release"],
|
|
898
|
+
qwen: ["qwen extensions install https://github.com/mksglu/context-mode:context-mode --ref release"],
|
|
899
|
+
opencode: ["opencode plugin add context-mode@next"],
|
|
900
|
+
pi: ["pi install npm:context-mode@next"],
|
|
901
|
+
"copilot-cli": ["npm i -g context-mode@next", "context-mode setup --agents copilot-cli"],
|
|
902
|
+
vscode: ["npm i -g context-mode@next", "context-mode setup --agents vscode"],
|
|
903
|
+
kiro: ["npm i -g context-mode@next", "context-mode setup --agents kiro"],
|
|
904
|
+
zcode: ["npm i -g context-mode@next", "context-mode setup --agents zcode"]
|
|
905
|
+
});
|
|
906
|
+
var ISSUE_FORM_URL = `https://github.com/${ISSUE_REPO_SLUG}/issues/new?template=${ISSUE_FORM_FILE}`;
|
|
907
|
+
var DOCTOR_GIT_VERSION_TIMEOUT_MS = 5e3;
|
|
908
|
+
var DOCTOR_LOG_TAIL_BYTES = 262144;
|
|
735
909
|
|
|
736
910
|
// src/core/contracts/errors.ts
|
|
737
911
|
var ERROR_TEXT = Object.freeze({
|
|
@@ -1135,8 +1309,8 @@ function decode5(raw) {
|
|
|
1135
1309
|
if (event === "SessionStart" && typeof raw.source === "string" && COPILOT_SOURCES[raw.source] !== void 0) ev.source = COPILOT_SOURCES[raw.source];
|
|
1136
1310
|
if (event === "UserPromptSubmit" && typeof raw.prompt === "string") ev.prompt = raw.prompt;
|
|
1137
1311
|
if (event === "PreToolUse" || event === "PostToolUse") {
|
|
1138
|
-
const
|
|
1139
|
-
const tool = { name:
|
|
1312
|
+
const toolName2 = String(raw[k.tool] ?? "");
|
|
1313
|
+
const tool = { name: toolName2, canonicalName: canonicalName3(toolName2), input: readArgs(raw[k.args]) };
|
|
1140
1314
|
ev.tool = tool;
|
|
1141
1315
|
}
|
|
1142
1316
|
if (event === "PostToolUse") ev.result = readResult3(raw[k.result], native.casing, native.failure);
|
|
@@ -1250,9 +1424,9 @@ function decodeCamel(p, name) {
|
|
|
1250
1424
|
if (event === "SessionStart" && typeof p.source === "string" && SESSION_SOURCES[p.source] !== void 0) ev.source = SESSION_SOURCES[p.source];
|
|
1251
1425
|
if (event === "UserPromptSubmit" && typeof p.prompt === "string") ev.prompt = p.prompt;
|
|
1252
1426
|
if (event === "PreToolUse" || event === "PostToolUse") {
|
|
1253
|
-
const
|
|
1254
|
-
const canonical = canonicalName4(
|
|
1255
|
-
ev.tool = { name:
|
|
1427
|
+
const toolName2 = String(p.toolName ?? "");
|
|
1428
|
+
const canonical = canonicalName4(toolName2);
|
|
1429
|
+
ev.tool = { name: toolName2, canonicalName: canonical, input: policyInput(toolName2, canonical, readArgs2(p.toolArgs)) };
|
|
1256
1430
|
}
|
|
1257
1431
|
if (event === "PostToolUse") ev.result = readCamelResult(p.toolResult);
|
|
1258
1432
|
return ev;
|
|
@@ -2103,10 +2277,10 @@ function lexSpan(st, from, inParen, depth, out, bodies) {
|
|
|
2103
2277
|
}
|
|
2104
2278
|
function scan(cmd) {
|
|
2105
2279
|
const st = { s: cmd, n: cmd.length, end: "complete" };
|
|
2106
|
-
const
|
|
2280
|
+
const tokens2 = [];
|
|
2107
2281
|
const heredocBodies = [];
|
|
2108
|
-
lexSpan(st, 0, false, 0,
|
|
2109
|
-
return { tokens, heredocBodies, end: st.end };
|
|
2282
|
+
lexSpan(st, 0, false, 0, tokens2, heredocBodies);
|
|
2283
|
+
return { tokens: tokens2, heredocBodies, end: st.end };
|
|
2110
2284
|
}
|
|
2111
2285
|
function dequote(word) {
|
|
2112
2286
|
let out = "";
|
|
@@ -2338,11 +2512,11 @@ function jqPath(s) {
|
|
|
2338
2512
|
function jqWhitelisted(filter2) {
|
|
2339
2513
|
const s = filter2.trim();
|
|
2340
2514
|
if (s === JQ_WHITELIST.identity || s === JQ_WHITELIST.length) return true;
|
|
2341
|
-
const
|
|
2342
|
-
if (
|
|
2343
|
-
const left = s.slice(0,
|
|
2515
|
+
const bar2 = s.indexOf(JQ_WHITELIST.pipeLength.charAt(0));
|
|
2516
|
+
if (bar2 < 0) return jqPath(s);
|
|
2517
|
+
const left = s.slice(0, bar2).trim();
|
|
2344
2518
|
const right = JQ_WHITELIST.pipeLength.slice(1).trim();
|
|
2345
|
-
return (left === JQ_WHITELIST.identity || jqPath(left)) && s.slice(
|
|
2519
|
+
return (left === JQ_WHITELIST.identity || jqPath(left)) && s.slice(bar2 + 1).trim() === right;
|
|
2346
2520
|
}
|
|
2347
2521
|
function isBoundedSink(c) {
|
|
2348
2522
|
const name = c.argv0.toLowerCase();
|
|
@@ -3549,8 +3723,8 @@ var TOOL_DESCRIPTIONS = Object.freeze({
|
|
|
3549
3723
|
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.',
|
|
3550
3724
|
ctx_search: 'Example: `ctx_search({queries:["auth middleware"]})`. Required: queries.\nSearches content stored with ctx_index and earlier sandbox output in this project. 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.',
|
|
3551
3725
|
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.",
|
|
3552
|
-
ctx_stats: "Example: `ctx_stats({})`. Required: none.\nReports
|
|
3553
|
-
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
|
|
3726
|
+
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.",
|
|
3727
|
+
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",
|
|
3554
3728
|
ctx_upgrade: "Example: `ctx_upgrade({})`. Required: none.\nUpdates context-mode to the latest release for this agent and rewrites only context-mode's own entries in the host config. User entries and user settings such as hook timeouts are kept, and old entries are erased. Returns a table of what changed and whether a restart is needed. Use it only when the user asks to update context-mode.",
|
|
3555
3729
|
ctx_purge: 'Example: `ctx_purge({source:"old-docs"})`. Required: one of session, source, project.\nDeletes stored data: one session, one indexed source, or everything stored for this project. This cannot be undone. Use it only when the user asks to forget or reset data.'
|
|
3556
3730
|
});
|
|
@@ -4063,8 +4237,8 @@ function firstLine(file2) {
|
|
|
4063
4237
|
return line === "" ? null : line;
|
|
4064
4238
|
}
|
|
4065
4239
|
function git(dir, args) {
|
|
4066
|
-
const { spawnSync:
|
|
4067
|
-
const r =
|
|
4240
|
+
const { spawnSync: spawnSync4 } = process.getBuiltinModule("node:child_process");
|
|
4241
|
+
const r = spawnSync4("git", args, { cwd: dir, shell: false, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
|
4068
4242
|
if (r.error !== void 0 || r.status !== 0) throw new CtxError("NO_GIT_DIR", { path: dir });
|
|
4069
4243
|
return r.stdout.split("\n").filter((l) => l !== "");
|
|
4070
4244
|
}
|
|
@@ -4628,7 +4802,7 @@ function buildSnippet(row5, given, maxBytes, codeMaxBytes = SNIPPET_CODE_MAX_BYT
|
|
|
4628
4802
|
terms = given.filter((t) => t.text.length >= 5).map((t) => ({ ...t, text: t.text.slice(0, Math.max(4, t.text.length - 2)) }));
|
|
4629
4803
|
pos = terms.map(find2);
|
|
4630
4804
|
}
|
|
4631
|
-
const
|
|
4805
|
+
const count2 = (ti, a, b) => {
|
|
4632
4806
|
const ps = pos[ti];
|
|
4633
4807
|
let lo = 0, hi = ps.length;
|
|
4634
4808
|
while (lo < hi) {
|
|
@@ -4643,7 +4817,7 @@ function buildSnippet(row5, given, maxBytes, codeMaxBytes = SNIPPET_CODE_MAX_BYT
|
|
|
4643
4817
|
const N = blocks.length;
|
|
4644
4818
|
const blen = blocks.map((bk2) => rangeBytes(bk2.first, bk2.last));
|
|
4645
4819
|
const avg = blen.reduce((a, b) => a + b, 0) / N || 1;
|
|
4646
|
-
const tf = blocks.map((bk2) => terms.map((_, ti) =>
|
|
4820
|
+
const tf = blocks.map((bk2) => terms.map((_, ti) => count2(ti, ls[bk2.first], le[bk2.last])));
|
|
4647
4821
|
const idf = terms.map((_, ti) => {
|
|
4648
4822
|
let df = 0;
|
|
4649
4823
|
for (let k = 0; k < N; k++) if (tf[k][ti] > 0) df++;
|
|
@@ -4665,7 +4839,7 @@ function buildSnippet(row5, given, maxBytes, codeMaxBytes = SNIPPET_CODE_MAX_BYT
|
|
|
4665
4839
|
const lineScore = (i) => {
|
|
4666
4840
|
let s = 0;
|
|
4667
4841
|
terms.forEach((_, ti) => {
|
|
4668
|
-
if (
|
|
4842
|
+
if (count2(ti, ls[i], le[i]) > 0) s += weight(ti, bk.code);
|
|
4669
4843
|
});
|
|
4670
4844
|
return s;
|
|
4671
4845
|
};
|
|
@@ -4673,7 +4847,7 @@ function buildSnippet(row5, given, maxBytes, codeMaxBytes = SNIPPET_CODE_MAX_BYT
|
|
|
4673
4847
|
let at2 = -1;
|
|
4674
4848
|
let w = -1;
|
|
4675
4849
|
terms.forEach((_, ti) => {
|
|
4676
|
-
const c =
|
|
4850
|
+
const c = count2(ti, ls[i], le[i]);
|
|
4677
4851
|
if (c === 0 || weight(ti, bk.code) <= w) return;
|
|
4678
4852
|
const ps = pos[ti];
|
|
4679
4853
|
let lo = 0, hi = ps.length;
|
|
@@ -6642,8 +6816,8 @@ function trigramMatch(q) {
|
|
|
6642
6816
|
const words = blankTokens(q);
|
|
6643
6817
|
const kept = words.filter((w) => !STOPWORDS.has(w.toLowerCase()));
|
|
6644
6818
|
const parts = new Set((kept.length > 0 ? kept : words).filter((w) => [...w].length >= 3));
|
|
6645
|
-
const
|
|
6646
|
-
if (words.length > 1 && [...
|
|
6819
|
+
const whole2 = words.join(" ");
|
|
6820
|
+
if (words.length > 1 && [...whole2].length >= 3) parts.add(whole2);
|
|
6647
6821
|
return [...parts].map((w) => `"${w.replaceAll('"', '""')}"`).join(" OR ");
|
|
6648
6822
|
}
|
|
6649
6823
|
function editDistance(a, b, max) {
|
|
@@ -6923,8 +7097,8 @@ function parseSourceHandle(s) {
|
|
|
6923
7097
|
function pathLabel(p) {
|
|
6924
7098
|
return p.includes("\\") ? p.split("\\").join("/") : p;
|
|
6925
7099
|
}
|
|
6926
|
-
function labelStored(db,
|
|
6927
|
-
return stmt(db.raw, "SELECT 1 AS x FROM sources WHERE label = ? LIMIT 1").get(
|
|
7100
|
+
function labelStored(db, label2) {
|
|
7101
|
+
return stmt(db.raw, "SELECT 1 AS x FROM sources WHERE label = ? LIMIT 1").get(label2) !== void 0;
|
|
6928
7102
|
}
|
|
6929
7103
|
function storedLabel(db, source) {
|
|
6930
7104
|
if (labelStored(db, source)) return source;
|
|
@@ -6954,9 +7128,9 @@ function insertUnits(db, sourceId, sessionId, units) {
|
|
|
6954
7128
|
let start = 0;
|
|
6955
7129
|
while (start < units.length) {
|
|
6956
7130
|
let end = start;
|
|
6957
|
-
let
|
|
6958
|
-
while (end < units.length && (end === start ||
|
|
6959
|
-
|
|
7131
|
+
let bytes5 = 0;
|
|
7132
|
+
while (end < units.length && (end === start || bytes5 + units[end].body.length <= INDEX_WRITE_CHUNK)) {
|
|
7133
|
+
bytes5 += units[end].body.length;
|
|
6960
7134
|
end++;
|
|
6961
7135
|
}
|
|
6962
7136
|
const from = start;
|
|
@@ -6990,15 +7164,15 @@ function indentOf(line) {
|
|
|
6990
7164
|
}
|
|
6991
7165
|
function buildUnits(text) {
|
|
6992
7166
|
const lines = text.split("\n");
|
|
6993
|
-
const
|
|
7167
|
+
const stack2 = [];
|
|
6994
7168
|
const out = [];
|
|
6995
7169
|
for (let i = 0; i < lines.length; i++) {
|
|
6996
7170
|
const line = lines[i].endsWith("\r") ? lines[i].slice(0, -1) : lines[i];
|
|
6997
7171
|
const indent = indentOf(line);
|
|
6998
7172
|
if (indent === line.length) continue;
|
|
6999
|
-
while (
|
|
7000
|
-
out.push({ ord: i, body: [...
|
|
7001
|
-
|
|
7173
|
+
while (stack2.length > 0 && stack2[stack2.length - 1].indent >= indent) stack2.pop();
|
|
7174
|
+
out.push({ ord: i, body: [...stack2.map((s) => s.line), line].join("\n") });
|
|
7175
|
+
stack2.push({ indent, line });
|
|
7002
7176
|
}
|
|
7003
7177
|
return out;
|
|
7004
7178
|
}
|
|
@@ -7009,9 +7183,9 @@ function firstLine2(body) {
|
|
|
7009
7183
|
return (nl < 0 ? body : body.slice(0, nl)).replaceAll("\r", " ");
|
|
7010
7184
|
}
|
|
7011
7185
|
function make(section, row5, text, repeatCount, query) {
|
|
7012
|
-
const
|
|
7013
|
-
if (
|
|
7014
|
-
return { section, seq: row5.seq, turn: row5.turn, text, bytes:
|
|
7186
|
+
const bytes5 = Buffer.byteLength(text, "utf8");
|
|
7187
|
+
if (bytes5 < 1) throw new Error("compaction: empty candidate line (DECISIONS-r9 M9).");
|
|
7188
|
+
return { section, seq: row5.seq, turn: row5.turn, text, bytes: bytes5, repeatCount, pinned: section === "last_request", query };
|
|
7015
7189
|
}
|
|
7016
7190
|
function capSection(list4) {
|
|
7017
7191
|
return list4.length > MAX_CANDIDATES ? list4.slice(list4.length - MAX_CANDIDATES) : list4;
|
|
@@ -7300,11 +7474,11 @@ function chunkText(text, kind, maxBytes = MAX_CHUNK_BYTES) {
|
|
|
7300
7474
|
}
|
|
7301
7475
|
function mdChunks(src, cap, lineCut) {
|
|
7302
7476
|
const out = [];
|
|
7303
|
-
const
|
|
7477
|
+
const stack2 = [];
|
|
7304
7478
|
let title = "";
|
|
7305
7479
|
let run = [];
|
|
7306
|
-
const push2 = (text,
|
|
7307
|
-
out.push({ ord: out.length, text, bytes:
|
|
7480
|
+
const push2 = (text, bytes5) => {
|
|
7481
|
+
out.push({ ord: out.length, text, bytes: bytes5, title });
|
|
7308
7482
|
};
|
|
7309
7483
|
const flush = () => {
|
|
7310
7484
|
if (run.length === 0) return;
|
|
@@ -7314,9 +7488,9 @@ function mdChunks(src, cap, lineCut) {
|
|
|
7314
7488
|
for (const b of lineBlocks(src, true)) {
|
|
7315
7489
|
if (b.heading !== void 0) {
|
|
7316
7490
|
flush();
|
|
7317
|
-
while (
|
|
7318
|
-
|
|
7319
|
-
title =
|
|
7491
|
+
while (stack2.length > 0 && stack2[stack2.length - 1].level >= b.heading.level) stack2.pop();
|
|
7492
|
+
stack2.push(b.heading);
|
|
7493
|
+
title = stack2.map((h) => h.text).join(" > ");
|
|
7320
7494
|
}
|
|
7321
7495
|
if (b.fence !== void 0 && utf8Bytes(src.slice(b.start, b.end)) > cap) {
|
|
7322
7496
|
const pieces = fencePieces(src, b, b.fence, cap);
|
|
@@ -7354,19 +7528,19 @@ function lineBlocks(src, md) {
|
|
|
7354
7528
|
let fenceInfo;
|
|
7355
7529
|
const close = () => {
|
|
7356
7530
|
if (start >= 0) {
|
|
7357
|
-
const
|
|
7358
|
-
if (heading !== void 0)
|
|
7359
|
-
if (fenceInfo !== void 0)
|
|
7360
|
-
out.push(
|
|
7531
|
+
const span2 = { start, end };
|
|
7532
|
+
if (heading !== void 0) span2.heading = heading;
|
|
7533
|
+
if (fenceInfo !== void 0) span2.fence = fenceInfo;
|
|
7534
|
+
out.push(span2);
|
|
7361
7535
|
}
|
|
7362
7536
|
start = -1;
|
|
7363
7537
|
heading = void 0;
|
|
7364
7538
|
fenceInfo = void 0;
|
|
7365
7539
|
};
|
|
7366
|
-
const add = (from, to,
|
|
7540
|
+
const add = (from, to, table3) => {
|
|
7367
7541
|
if (start < 0) start = from;
|
|
7368
7542
|
end = to;
|
|
7369
|
-
inTable =
|
|
7543
|
+
inTable = table3;
|
|
7370
7544
|
};
|
|
7371
7545
|
let pos = 0;
|
|
7372
7546
|
while (pos <= src.length) {
|
|
@@ -7387,9 +7561,9 @@ function lineBlocks(src, md) {
|
|
|
7387
7561
|
} else {
|
|
7388
7562
|
const opener = md ? fenceOf(line) : "";
|
|
7389
7563
|
const head = md && opener === "" ? headingOf(line) : void 0;
|
|
7390
|
-
const
|
|
7391
|
-
if (md && start >= 0 && (
|
|
7392
|
-
add(pos, eol,
|
|
7564
|
+
const table3 = md && opener === "" && head === void 0 && line.includes("|");
|
|
7565
|
+
if (md && start >= 0 && (table3 !== inTable || opener !== "" || head !== void 0)) close();
|
|
7566
|
+
add(pos, eol, table3);
|
|
7393
7567
|
fence = opener;
|
|
7394
7568
|
if (opener !== "") fenceInfo = { fence: opener, openEnd: eol, closeStart: -1 };
|
|
7395
7569
|
if (head !== void 0) {
|
|
@@ -7549,17 +7723,17 @@ function cutPoint(src, start, end, scratch) {
|
|
|
7549
7723
|
const r = encoder.encodeInto(src.slice(start, limit), scratch);
|
|
7550
7724
|
return { end: start + r.read, written: r.written };
|
|
7551
7725
|
}
|
|
7552
|
-
function merge(src, blocks,
|
|
7726
|
+
function merge(src, blocks, join25, cap, lineCut) {
|
|
7553
7727
|
const out = [];
|
|
7554
7728
|
const scratch = new Uint8Array(cap);
|
|
7555
7729
|
let wide;
|
|
7556
7730
|
let cur;
|
|
7557
7731
|
let curBytes = 0;
|
|
7558
|
-
const emit = (start, end,
|
|
7559
|
-
out.push({ ord: out.length, text: src.slice(start, end), bytes:
|
|
7732
|
+
const emit = (start, end, bytes5) => {
|
|
7733
|
+
out.push({ ord: out.length, text: src.slice(start, end), bytes: bytes5 });
|
|
7560
7734
|
};
|
|
7561
7735
|
for (const b of blocks) {
|
|
7562
|
-
if (cur !== void 0 && !
|
|
7736
|
+
if (cur !== void 0 && !join25) {
|
|
7563
7737
|
emit(cur.start, cur.end, curBytes);
|
|
7564
7738
|
cur = void 0;
|
|
7565
7739
|
}
|
|
@@ -7574,15 +7748,15 @@ function merge(src, blocks, join23, cap, lineCut) {
|
|
|
7574
7748
|
cur = void 0;
|
|
7575
7749
|
}
|
|
7576
7750
|
let start = b.start;
|
|
7577
|
-
let
|
|
7578
|
-
while (
|
|
7751
|
+
let bytes5 = utf8Bytes(src.slice(b.start, b.end));
|
|
7752
|
+
while (bytes5 > cap) {
|
|
7579
7753
|
const cut = cutPoint(src, start, b.end, scratch);
|
|
7580
7754
|
const nl = lineCut ? src.lastIndexOf("\n", cut.end - 1) : -1;
|
|
7581
7755
|
if (nl > start) {
|
|
7582
7756
|
const w = utf8Bytes(src.slice(start, nl + 1));
|
|
7583
7757
|
emit(start, nl + 1, w);
|
|
7584
7758
|
start = nl + 1;
|
|
7585
|
-
|
|
7759
|
+
bytes5 -= w;
|
|
7586
7760
|
continue;
|
|
7587
7761
|
}
|
|
7588
7762
|
if (lineCut) {
|
|
@@ -7592,23 +7766,23 @@ function merge(src, blocks, join23, cap, lineCut) {
|
|
|
7592
7766
|
if (w <= MAX_CHUNK_BYTES) {
|
|
7593
7767
|
emit(start, lineEnd, w);
|
|
7594
7768
|
start = lineEnd;
|
|
7595
|
-
|
|
7769
|
+
bytes5 -= w;
|
|
7596
7770
|
continue;
|
|
7597
7771
|
}
|
|
7598
7772
|
wide ??= new Uint8Array(MAX_CHUNK_BYTES);
|
|
7599
7773
|
const big = cutPoint(src, start, lineEnd, wide);
|
|
7600
7774
|
emit(start, big.end, big.written);
|
|
7601
7775
|
start = big.end;
|
|
7602
|
-
|
|
7776
|
+
bytes5 -= big.written;
|
|
7603
7777
|
continue;
|
|
7604
7778
|
}
|
|
7605
7779
|
emit(start, cut.end, cut.written);
|
|
7606
7780
|
start = cut.end;
|
|
7607
|
-
|
|
7781
|
+
bytes5 -= cut.written;
|
|
7608
7782
|
}
|
|
7609
7783
|
if (start >= b.end) continue;
|
|
7610
7784
|
cur = { start, end: b.end };
|
|
7611
|
-
curBytes =
|
|
7785
|
+
curBytes = bytes5;
|
|
7612
7786
|
}
|
|
7613
7787
|
if (cur !== void 0) emit(cur.start, cur.end, curBytes);
|
|
7614
7788
|
return out;
|
|
@@ -7629,7 +7803,7 @@ function selectChunks(db, sourceId, intent, budget) {
|
|
|
7629
7803
|
function selectChunksInMemory(chunks, intent, budget, source, rankQuery) {
|
|
7630
7804
|
return select(chunks, intent, budget, source, rankQuery);
|
|
7631
7805
|
}
|
|
7632
|
-
function select(chunks, intent, budget,
|
|
7806
|
+
function select(chunks, intent, budget, label2, rankQuery) {
|
|
7633
7807
|
if (chunks.length === 0) return { text: "", more: null };
|
|
7634
7808
|
const texts = chunks.map((c) => c.text);
|
|
7635
7809
|
const scores = rankQuery === void 0 ? rankTexts(texts, intent) : rankTexts(texts, rankQuery, "any");
|
|
@@ -7648,10 +7822,10 @@ function select(chunks, intent, budget, label, rankQuery) {
|
|
|
7648
7822
|
}
|
|
7649
7823
|
picked.sort((a, b) => a.ord - b.ord);
|
|
7650
7824
|
const text = picked.map((c) => c.text).join(SEP);
|
|
7651
|
-
return { text, more: skipped ? moreLine2(intent,
|
|
7825
|
+
return { text, more: skipped ? moreLine2(intent, label2) : null };
|
|
7652
7826
|
}
|
|
7653
|
-
function moreLine2(intent,
|
|
7654
|
-
const source =
|
|
7827
|
+
function moreLine2(intent, label2) {
|
|
7828
|
+
const source = label2 === void 0 ? "" : ", source:" + JSON.stringify(label2);
|
|
7655
7829
|
const query = Buffer.byteLength(intent, "utf8") > ECHO_MAX_BYTES ? "..." : JSON.stringify(intent);
|
|
7656
7830
|
return "ctx_search({queries:[" + query + "]" + source + "})";
|
|
7657
7831
|
}
|
|
@@ -7699,10 +7873,10 @@ function firstNonSpace(s) {
|
|
|
7699
7873
|
function isPlainObject(v) {
|
|
7700
7874
|
return typeof v === "object" && v !== null && !Array.isArray(v);
|
|
7701
7875
|
}
|
|
7702
|
-
function rareOfSkewed(n, counts,
|
|
7703
|
-
if (
|
|
7704
|
-
const sorted = [...
|
|
7705
|
-
if (
|
|
7876
|
+
function rareOfSkewed(n, counts, totals2) {
|
|
7877
|
+
if (totals2.size < 2 || totals2.size > SHAPE_CATEGORICAL_MAX) return [];
|
|
7878
|
+
const sorted = [...totals2.entries()].sort((a, b) => b[1] - a[1]);
|
|
7879
|
+
if (totals2.size <= SHAPE_RARE_MAX + 1) {
|
|
7706
7880
|
if (sorted[0][1] < SHAPE_DOMINANT * n || n - sorted[0][1] > SHAPE_RARE_MAX) return [];
|
|
7707
7881
|
return sorted.slice(1).flatMap(([v]) => counts.get(v) ?? []);
|
|
7708
7882
|
}
|
|
@@ -7737,7 +7911,7 @@ function jsonShape(text, query) {
|
|
|
7737
7911
|
const outliers = /* @__PURE__ */ new Map();
|
|
7738
7912
|
for (const k of keys) {
|
|
7739
7913
|
const counts = /* @__PURE__ */ new Map();
|
|
7740
|
-
const
|
|
7914
|
+
const totals2 = /* @__PURE__ */ new Map();
|
|
7741
7915
|
let scalar = true;
|
|
7742
7916
|
for (let i = 0; i < objs.length && scalar; i++) {
|
|
7743
7917
|
const v = k in objs[i] ? objs[i][k] : void 0;
|
|
@@ -7746,14 +7920,14 @@ function jsonShape(text, query) {
|
|
|
7746
7920
|
break;
|
|
7747
7921
|
}
|
|
7748
7922
|
const s = v === void 0 ? ABSENT : JSON.stringify(v);
|
|
7749
|
-
|
|
7923
|
+
totals2.set(s, (totals2.get(s) ?? 0) + 1);
|
|
7750
7924
|
const at2 = counts.get(s) ?? [];
|
|
7751
7925
|
if (at2.length <= SHAPE_RARE_MAX) at2.push(i);
|
|
7752
7926
|
counts.set(s, at2);
|
|
7753
|
-
if (
|
|
7927
|
+
if (totals2.size > SHAPE_CATEGORICAL_MAX) break;
|
|
7754
7928
|
}
|
|
7755
7929
|
if (!scalar) continue;
|
|
7756
|
-
for (const i of rareOfSkewed(objs.length, counts,
|
|
7930
|
+
for (const i of rareOfSkewed(objs.length, counts, totals2)) outliers.set(i, [...outliers.get(i) ?? [], k]);
|
|
7757
7931
|
}
|
|
7758
7932
|
if (outliers.size === 0 || outliers.size > SHAPE_RARE_UNITS_MAX) return null;
|
|
7759
7933
|
const keyScore = rankTexts(keys, query, "any");
|
|
@@ -7771,8 +7945,8 @@ function renderRow(i, row5, skewed, named, budget) {
|
|
|
7771
7945
|
return body === null ? null : prefix + body;
|
|
7772
7946
|
}
|
|
7773
7947
|
function fitRow(row5, skewed, named, budget) {
|
|
7774
|
-
const
|
|
7775
|
-
if (bytes(
|
|
7948
|
+
const whole2 = JSON.stringify(row5);
|
|
7949
|
+
if (bytes(whole2) <= budget) return whole2;
|
|
7776
7950
|
const own2 = Object.keys(row5);
|
|
7777
7951
|
const tier = (k) => skewed.includes(k) ? 0 : named.has(k) ? 1 : typeof row5[k] !== "object" || row5[k] === null ? 2 : 3;
|
|
7778
7952
|
const order = [...own2].sort((a, b) => tier(a) - tier(b) || own2.indexOf(a) - own2.indexOf(b));
|
|
@@ -7881,14 +8055,14 @@ function lineShape(text) {
|
|
|
7881
8055
|
}
|
|
7882
8056
|
|
|
7883
8057
|
// src/core/index/text.ts
|
|
7884
|
-
function storeText(db, project, sessionId, sourceKind,
|
|
8058
|
+
function storeText(db, project, sessionId, sourceKind, label2, text, kind, chunks = chunkText(text, kind)) {
|
|
7885
8059
|
const sourceId = ftsInsert(db, {
|
|
7886
8060
|
projectKey: project.projectKey,
|
|
7887
8061
|
sessionId,
|
|
7888
8062
|
worktree: project.worktree,
|
|
7889
8063
|
agent: project.agent,
|
|
7890
8064
|
kind: sourceKind,
|
|
7891
|
-
label,
|
|
8065
|
+
label: label2,
|
|
7892
8066
|
bytes: Buffer.byteLength(text, "utf8"),
|
|
7893
8067
|
chunkCount: chunks.length,
|
|
7894
8068
|
createdAt: Date.now()
|
|
@@ -7951,9 +8125,9 @@ function answerDecisions(responseText) {
|
|
|
7951
8125
|
if (!isObject2(parsed)) return [];
|
|
7952
8126
|
const out = [];
|
|
7953
8127
|
for (const [question, value] of answerPairs(parsed[DECISION_ANSWERS_KEY])) {
|
|
7954
|
-
const
|
|
7955
|
-
if (question === "" ||
|
|
7956
|
-
out.push({ key: question, body: "Q: " + question + " \u2192 A: " +
|
|
8128
|
+
const label2 = labelText(value);
|
|
8129
|
+
if (question === "" || label2 === "") continue;
|
|
8130
|
+
out.push({ key: question, body: "Q: " + question + " \u2192 A: " + label2 });
|
|
7957
8131
|
}
|
|
7958
8132
|
return out;
|
|
7959
8133
|
}
|
|
@@ -7973,9 +8147,9 @@ function fold(s) {
|
|
|
7973
8147
|
function optionEchoDecision(prompt, labels, refSeq) {
|
|
7974
8148
|
const p = fold(prompt);
|
|
7975
8149
|
if (p === "") return null;
|
|
7976
|
-
const
|
|
7977
|
-
if (
|
|
7978
|
-
return { key: DECISION_OPTION_KEY, body: "A: " +
|
|
8150
|
+
const label2 = labels.find((l) => fold(l) === p);
|
|
8151
|
+
if (label2 === void 0) return null;
|
|
8152
|
+
return { key: DECISION_OPTION_KEY, body: "A: " + label2 + "\nref: #" + refSeq };
|
|
7979
8153
|
}
|
|
7980
8154
|
|
|
7981
8155
|
// src/core/hooks/throttle.ts
|
|
@@ -7989,9 +8163,9 @@ function takeOnce(db, key) {
|
|
|
7989
8163
|
}
|
|
7990
8164
|
function takeEvery(db, key, everyN) {
|
|
7991
8165
|
const stored = metaGet(db, key);
|
|
7992
|
-
const
|
|
7993
|
-
metaSet(db, key, String(
|
|
7994
|
-
return (
|
|
8166
|
+
const count2 = (stored === null ? 0 : Number.parseInt(stored, 10)) + 1;
|
|
8167
|
+
metaSet(db, key, String(count2));
|
|
8168
|
+
return (count2 - 1) % everyN === 0;
|
|
7995
8169
|
}
|
|
7996
8170
|
function shouldHint(db, sessionId, onceKey, everyN) {
|
|
7997
8171
|
if (sessionId === "") return false;
|
|
@@ -8484,33 +8658,33 @@ async function postReplace(ev, row5, project, env, tool, result, text) {
|
|
|
8484
8658
|
if (result.bytes <= REPLACE_TRIGGER_BYTES) return ALLOW2;
|
|
8485
8659
|
if (result.keep === true) return ALLOW2;
|
|
8486
8660
|
if (!hasReplace(row5)) return ALLOW2;
|
|
8487
|
-
let
|
|
8661
|
+
let label2;
|
|
8488
8662
|
if (isSubagentCall(ev)) {
|
|
8489
8663
|
const subCase = pickSubagentCase(ev, toolSetForAgentType(ev, { projectDir: project.worktree, env }));
|
|
8490
8664
|
if (subCase === "A") return ALLOW2;
|
|
8491
|
-
|
|
8665
|
+
label2 = SUBAGENT_SOURCE_PREFIX + tool.canonicalName + ":" + String(ev.turn ?? 0);
|
|
8492
8666
|
} else {
|
|
8493
|
-
|
|
8667
|
+
label2 = mainLabel(tool, ev);
|
|
8494
8668
|
}
|
|
8495
8669
|
const intent = [tool.input.description, tool.input.command, tool.input.file_path, tool.input.pattern, tool.input.url].map(str2).find((v) => v.trim() !== "") ?? "";
|
|
8496
8670
|
const chunks = chunkText(text, "text", REPLACE_CHUNK_BYTES);
|
|
8497
8671
|
const db = await openDb(project);
|
|
8498
8672
|
let sourceId;
|
|
8499
8673
|
if (result.bytes <= SYNC_INDEX_MAX_BYTES) {
|
|
8500
|
-
sourceId = indexText(db, project, ev.sessionId,
|
|
8674
|
+
sourceId = indexText(db, project, ev.sessionId, label2, text, "text", chunks).sourceId;
|
|
8501
8675
|
insertUnits(db, sourceId, ev.sessionId, buildUnits(text));
|
|
8502
8676
|
} else {
|
|
8503
|
-
sourceId = reserveSource(db, sourceRowOf(project, ev.sessionId,
|
|
8504
|
-
indexDetached(project, ev.sessionId, sourceId,
|
|
8677
|
+
sourceId = reserveSource(db, sourceRowOf(project, ev.sessionId, label2), chunks);
|
|
8678
|
+
indexDetached(project, ev.sessionId, sourceId, label2, text, chunks);
|
|
8505
8679
|
}
|
|
8506
8680
|
const handle = sourceHandle(sourceId);
|
|
8507
8681
|
const prompt = await lastPrompt(project, ev.sessionId);
|
|
8508
8682
|
const rankQuery = prompt.trim() === "" ? void 0 : intent + " " + prompt;
|
|
8509
8683
|
const handleLine = REPLACE_HANDLE_LINE(intent, handle, result.bytes, row5.toolNamePrefix, askedWords(intent, prompt, text));
|
|
8510
|
-
const budget = replaceBudget(handleLine, moreLine2(intent,
|
|
8684
|
+
const budget = replaceBudget(handleLine, moreLine2(intent, label2));
|
|
8511
8685
|
const digest = shapeDigest(text, rankQuery ?? intent, SHAPE_RETURN_BYTES);
|
|
8512
8686
|
if (digest !== null) return { kind: "replace", output: replaceOutput(digest, handleLine) };
|
|
8513
|
-
const selected = selectChunksInMemory(chunks, intent, budget,
|
|
8687
|
+
const selected = selectChunksInMemory(chunks, intent, budget, label2, rankQuery);
|
|
8514
8688
|
return { kind: "replace", output: selected.more !== null ? replaceOutput(selected.text, handleLine) : selected.text };
|
|
8515
8689
|
}
|
|
8516
8690
|
function replaceOutput(body, handleLine) {
|
|
@@ -8541,15 +8715,15 @@ function mainLabel(tool, ev) {
|
|
|
8541
8715
|
const head = (tool.canonicalName + ":" + (nl < 0 ? cmd : cmd.slice(0, nl))).slice(0, SOURCE_LABEL_MAX_CHARS);
|
|
8542
8716
|
return head + "#" + (tool.callId ?? String(ev.turn ?? 0));
|
|
8543
8717
|
}
|
|
8544
|
-
function indexDetached(project, sessionId, sourceId,
|
|
8718
|
+
function indexDetached(project, sessionId, sourceId, label2, text, chunks) {
|
|
8545
8719
|
void openDb(project).then((db) => {
|
|
8546
|
-
finishReserved(db, sourceId, sourceRowOf(project, sessionId,
|
|
8720
|
+
finishReserved(db, sourceId, sourceRowOf(project, sessionId, label2), chunks, buildUnits(text));
|
|
8547
8721
|
}).catch((err) => {
|
|
8548
8722
|
process.stderr.write("hooks: index write failed: " + message(err) + "\n");
|
|
8549
8723
|
});
|
|
8550
8724
|
}
|
|
8551
|
-
function sourceRowOf(project, sessionId,
|
|
8552
|
-
return { sessionId, worktree: project.worktree, agent: project.agent, kind: "content", label, createdAt: Date.now() };
|
|
8725
|
+
function sourceRowOf(project, sessionId, label2) {
|
|
8726
|
+
return { sessionId, worktree: project.worktree, agent: project.agent, kind: "content", label: label2, createdAt: Date.now() };
|
|
8553
8727
|
}
|
|
8554
8728
|
async function preCompact(ev, row5, project) {
|
|
8555
8729
|
const db = await openDb(project);
|
|
@@ -12430,8 +12604,8 @@ function az_default() {
|
|
|
12430
12604
|
}
|
|
12431
12605
|
|
|
12432
12606
|
// node_modules/zod/v4/locales/be.js
|
|
12433
|
-
function getBelarusianPlural(
|
|
12434
|
-
const absCount = Math.abs(
|
|
12607
|
+
function getBelarusianPlural(count2, one, few, many) {
|
|
12608
|
+
const absCount = Math.abs(count2);
|
|
12435
12609
|
const lastDigit = absCount % 10;
|
|
12436
12610
|
const lastTwoDigits = absCount % 100;
|
|
12437
12611
|
if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
|
|
@@ -15576,8 +15750,8 @@ function pt_default() {
|
|
|
15576
15750
|
}
|
|
15577
15751
|
|
|
15578
15752
|
// node_modules/zod/v4/locales/ru.js
|
|
15579
|
-
function getRussianPlural(
|
|
15580
|
-
const absCount = Math.abs(
|
|
15753
|
+
function getRussianPlural(count2, one, few, many) {
|
|
15754
|
+
const absCount = Math.abs(count2);
|
|
15581
15755
|
const lastDigit = absCount % 10;
|
|
15582
15756
|
const lastTwoDigits = absCount % 100;
|
|
15583
15757
|
if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
|
|
@@ -19777,9 +19951,9 @@ import { accessSync, constants as fsConstants, statSync as statSync3 } from "nod
|
|
|
19777
19951
|
import path from "node:path";
|
|
19778
19952
|
|
|
19779
19953
|
// src/core/sandbox/path-entries.ts
|
|
19780
|
-
function pathEntries(value, platform = process.platform,
|
|
19954
|
+
function pathEntries(value, platform = process.platform, delimiter2 = platform === "win32" ? ";" : ":") {
|
|
19781
19955
|
const win = platform === "win32";
|
|
19782
|
-
return value.split(
|
|
19956
|
+
return value.split(delimiter2).map((e) => win && e.length >= 2 && e.startsWith('"') && e.endsWith('"') ? e.slice(1, -1) : e).filter(Boolean);
|
|
19783
19957
|
}
|
|
19784
19958
|
|
|
19785
19959
|
// src/core/sandbox/runtimes.ts
|
|
@@ -20149,7 +20323,7 @@ function relevance(db, given, scope, ctx) {
|
|
|
20149
20323
|
mine.add(hit.sourceId);
|
|
20150
20324
|
}
|
|
20151
20325
|
if (again.size > 0) {
|
|
20152
|
-
const line = "Same as above: " + [...again].map(([
|
|
20326
|
+
const line = "Same as above: " + [...again].map(([label2, ords]) => label2 + " (chunk " + ords.join(",") + ")").join("; ");
|
|
20153
20327
|
lines.push(line);
|
|
20154
20328
|
used += bytes2(line) + 1;
|
|
20155
20329
|
}
|
|
@@ -20296,7 +20470,7 @@ function shown(chunks, heads) {
|
|
|
20296
20470
|
return c.text;
|
|
20297
20471
|
});
|
|
20298
20472
|
}
|
|
20299
|
-
function indexCombined(db, ctx,
|
|
20473
|
+
function indexCombined(db, ctx, label2, ran, deadline, budgetBytes) {
|
|
20300
20474
|
const chunks = chunkText(ran.map((r) => r.block).join(BLOCK_SEP), "text");
|
|
20301
20475
|
const display = shown(chunks, ran.map((r) => r.head));
|
|
20302
20476
|
const bodies = /* @__PURE__ */ new Map();
|
|
@@ -20316,7 +20490,7 @@ function indexCombined(db, ctx, label, ran, deadline, budgetBytes) {
|
|
|
20316
20490
|
worktree: ctx.project.worktree,
|
|
20317
20491
|
agent: ctx.project.agent,
|
|
20318
20492
|
kind: "content",
|
|
20319
|
-
label,
|
|
20493
|
+
label: label2,
|
|
20320
20494
|
bytes: groupBytes,
|
|
20321
20495
|
chunkCount: group.length,
|
|
20322
20496
|
createdAt: Date.now()
|
|
@@ -20346,12 +20520,12 @@ function indexCombined(db, ctx, label, ran, deadline, budgetBytes) {
|
|
|
20346
20520
|
function bytes3(s) {
|
|
20347
20521
|
return Buffer.byteLength(s, "utf8");
|
|
20348
20522
|
}
|
|
20349
|
-
function answer(db, ctx,
|
|
20523
|
+
function answer(db, ctx, label2, queries, share, own2) {
|
|
20350
20524
|
const seen = /* @__PURE__ */ new Set();
|
|
20351
20525
|
const lines = [];
|
|
20352
20526
|
for (const [qi, q] of queries.entries()) {
|
|
20353
20527
|
if (ctx.signal.aborted) break;
|
|
20354
|
-
let hits = ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0,
|
|
20528
|
+
let hits = ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0, label2);
|
|
20355
20529
|
if (hits.length === 0) hits = ftsQuery(db, q, "session", ctx.project, ctx.sessionId, SEARCH_PAGE_SIZE, 0);
|
|
20356
20530
|
const head = "## " + (bytes3(q) > ECHO_MAX_BYTES ? "query " + (qi + 1) : q);
|
|
20357
20531
|
let used = bytes3(head) + 1;
|
|
@@ -20390,17 +20564,17 @@ async function runBatch(input, ctx, boundMs, budgetBytes) {
|
|
|
20390
20564
|
const ran = pool.results;
|
|
20391
20565
|
const last2 = ran[ran.length - 1];
|
|
20392
20566
|
const sandboxBytes = ran.reduce((n, r) => n + r.bytes, 0);
|
|
20393
|
-
const
|
|
20567
|
+
const label2 = LABEL_PREFIX + ctx.turn;
|
|
20394
20568
|
try {
|
|
20395
20569
|
const db = await openDb(ctx.project);
|
|
20396
20570
|
let sections;
|
|
20397
20571
|
let idx;
|
|
20398
20572
|
const exitLine = last2.exitCode === null || last2.exitCode === 0 ? null : "exit " + last2.exitCode;
|
|
20399
|
-
const footer = "more: ctx_search({queries:[...], source:" + JSON.stringify(
|
|
20573
|
+
const footer = "more: ctx_search({queries:[...], source:" + JSON.stringify(label2) + "})";
|
|
20400
20574
|
let notice;
|
|
20401
20575
|
let showMore;
|
|
20402
20576
|
try {
|
|
20403
|
-
idx = indexCombined(db, ctx,
|
|
20577
|
+
idx = indexCombined(db, ctx, label2, ran, deadline, budgetBytes);
|
|
20404
20578
|
const stop = last2.error;
|
|
20405
20579
|
const cut = idx.indexed < idx.total ? "Indexed " + idx.indexed + " of " + idx.total + " B." : null;
|
|
20406
20580
|
const timeout = formatError("TIMEOUT", { ms: boundMs });
|
|
@@ -20408,7 +20582,7 @@ async function runBatch(input, ctx, boundMs, budgetBytes) {
|
|
|
20408
20582
|
notice = cut === null ? stop : cause === null ? cut : cause + " " + cut;
|
|
20409
20583
|
const fixed = (exitLine === null ? 0 : bytes3(exitLine) + 1) + (notice === null ? 0 : bytes3(notice) + 1) + bytes3(footer);
|
|
20410
20584
|
const share = Math.floor((OUTPUT_CAP - fixed) / queries.length);
|
|
20411
|
-
const answered = answer(db, ctx,
|
|
20585
|
+
const answered = answer(db, ctx, label2, queries, share, idx.bodies);
|
|
20412
20586
|
sections = answered.lines;
|
|
20413
20587
|
const unseen = [...idx.bodies].filter(([k, text]) => text !== "" && !answered.seen.has(k)).map(([k]) => idx.raw.get(k));
|
|
20414
20588
|
const unseenBytes = unseen.reduce((n, t) => n + bytes3(t) + 1, 0);
|
|
@@ -20444,8 +20618,8 @@ var ctxBatch = Object.freeze({
|
|
|
20444
20618
|
});
|
|
20445
20619
|
|
|
20446
20620
|
// src/core/tools/doctor.ts
|
|
20447
|
-
import { readdirSync as readdirSync5, readFileSync as
|
|
20448
|
-
import { basename as basename4, dirname as dirname7, join as
|
|
20621
|
+
import { readdirSync as readdirSync5, readFileSync as readFileSync13, existsSync as existsSync13 } from "node:fs";
|
|
20622
|
+
import { basename as basename4, dirname as dirname7, join as join15 } from "node:path";
|
|
20449
20623
|
|
|
20450
20624
|
// src/core/ops/doctor-config.ts
|
|
20451
20625
|
import { existsSync as existsSync6, readdirSync as readdirSync3 } from "node:fs";
|
|
@@ -21615,7 +21789,7 @@ var Tokenizer = class {
|
|
|
21615
21789
|
hasUnderscore
|
|
21616
21790
|
};
|
|
21617
21791
|
}
|
|
21618
|
-
parseUnicode(
|
|
21792
|
+
parseUnicode(count2) {
|
|
21619
21793
|
const startLoc = this.codePointIterator.start;
|
|
21620
21794
|
const start = this.codePointIterator.end;
|
|
21621
21795
|
let charCount = 0;
|
|
@@ -21626,7 +21800,7 @@ var Tokenizer = class {
|
|
|
21626
21800
|
return this.reportParseError("invalid-char-in-escape-sequence");
|
|
21627
21801
|
}
|
|
21628
21802
|
charCount++;
|
|
21629
|
-
if (charCount >=
|
|
21803
|
+
if (charCount >= count2) break;
|
|
21630
21804
|
}
|
|
21631
21805
|
const end = this.codePointIterator.end;
|
|
21632
21806
|
const code = this.text.slice(start, end);
|
|
@@ -22392,17 +22566,17 @@ function generateConvertTOMLValue(convertValue) {
|
|
|
22392
22566
|
return baseTable;
|
|
22393
22567
|
},
|
|
22394
22568
|
TOMLTable(node, baseTable = {}) {
|
|
22395
|
-
const
|
|
22396
|
-
for (const body of node.body) resolveValue(body,
|
|
22569
|
+
const table3 = getTable(baseTable, resolveValue(node.key), node.kind === "array");
|
|
22570
|
+
for (const body of node.body) resolveValue(body, table3);
|
|
22397
22571
|
return baseTable;
|
|
22398
22572
|
},
|
|
22399
22573
|
TOMLArray(node) {
|
|
22400
22574
|
return node.elements.map((e) => resolveValue(e));
|
|
22401
22575
|
},
|
|
22402
22576
|
TOMLInlineTable(node) {
|
|
22403
|
-
const
|
|
22404
|
-
for (const body of node.body) resolveValue(body,
|
|
22405
|
-
return
|
|
22577
|
+
const table3 = {};
|
|
22578
|
+
for (const body of node.body) resolveValue(body, table3);
|
|
22579
|
+
return table3;
|
|
22406
22580
|
},
|
|
22407
22581
|
TOMLKey(node) {
|
|
22408
22582
|
return node.keys.map((key) => resolveValue(key));
|
|
@@ -22897,8 +23071,8 @@ function setTomlText(text, path7, value) {
|
|
|
22897
23071
|
if (sameValue(cur, value)) return text;
|
|
22898
23072
|
const inline = doc.keys.find((k) => k.inline && k.full.length < path7.length && under(path7, k.full));
|
|
22899
23073
|
if (inline !== void 0) {
|
|
22900
|
-
const
|
|
22901
|
-
return replaceToml(text, doc, inline.full,
|
|
23074
|
+
const whole2 = withValueAt(hostConfigValueAt(doc.value, inline.full), path7.slice(inline.full.length), value);
|
|
23075
|
+
return replaceToml(text, doc, inline.full, whole2);
|
|
22902
23076
|
}
|
|
22903
23077
|
if (isPlainObject3(cur) && isPlainObject3(value)) {
|
|
22904
23078
|
const names = [.../* @__PURE__ */ new Set([...Object.keys(cur), ...Object.keys(value)])].filter((k) => !sameValue(cur[k], value[k]));
|
|
@@ -23142,10 +23316,10 @@ function scanCodex(agentHome, out) {
|
|
|
23142
23316
|
}
|
|
23143
23317
|
const tomlFile = join9(agentHome, CONFIG_TOML_FILE);
|
|
23144
23318
|
const config2 = readTomlValue(tomlFile);
|
|
23145
|
-
for (const
|
|
23146
|
-
if (
|
|
23147
|
-
if (
|
|
23148
|
-
out.push(finding(tomlFile,
|
|
23319
|
+
for (const span2 of readTomlTables(tomlFile)) {
|
|
23320
|
+
if (span2.path[0] !== V1_TOML_SECTION_ROOT || span2.path[1] !== SERVER_KEY) continue;
|
|
23321
|
+
if (span2.path.length === 2 && isV2McpTable(hostConfigValueAt(config2, span2.path))) continue;
|
|
23322
|
+
out.push(finding(tomlFile, span2.header.trim(), V1_REASON.codexToml));
|
|
23149
23323
|
}
|
|
23150
23324
|
dataDir(join9(agentHome, V1_DATA_DIR_NAME), V1_REASON.dataDir, out);
|
|
23151
23325
|
}
|
|
@@ -23577,14 +23751,18 @@ function mcpWrong(row5, home, env, worktree) {
|
|
|
23577
23751
|
return true;
|
|
23578
23752
|
}
|
|
23579
23753
|
}
|
|
23754
|
+
function hookFile(row5, spec, home, env, worktree) {
|
|
23755
|
+
const root = spec.root === "plugin" ? resolvePluginRoot(row5, env, worktree) : spec.root === "home" ? home : worktree;
|
|
23756
|
+
const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
|
|
23757
|
+
const file2 = native !== null ? join11(native, CODEX_PLUGIN_HOOKS_FILE) : row5.id === "codex" ? join11(codexDirOf(env, home), HOOKS_JSON_FILE) : row5.id === "copilot-cli" ? join11(copilotDirOf(env, home), ...spec.file.slice(1)) : row5.id === "kiro" ? join11(kiroDirOf(env, home), ...spec.file.slice(1)) : join11(root, ...spec.file);
|
|
23758
|
+
return file2;
|
|
23759
|
+
}
|
|
23580
23760
|
function hookParts(row5, home, env, worktree) {
|
|
23581
23761
|
const spec = HOOK_HOST_FILE[row5.id];
|
|
23582
23762
|
if (spec === null) return [];
|
|
23583
23763
|
let block;
|
|
23584
23764
|
try {
|
|
23585
|
-
const
|
|
23586
|
-
const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
|
|
23587
|
-
const file2 = native !== null ? join11(native, CODEX_PLUGIN_HOOKS_FILE) : row5.id === "codex" ? join11(codexDirOf(env, home), HOOKS_JSON_FILE) : row5.id === "copilot-cli" ? join11(copilotDirOf(env, home), ...spec.file.slice(1)) : row5.id === "kiro" ? join11(kiroDirOf(env, home), ...spec.file.slice(1)) : join11(root, ...spec.file);
|
|
23765
|
+
const file2 = hookFile(row5, spec, home, env, worktree);
|
|
23588
23766
|
block = hostConfigValueAt(readParsed(row5.id, file2).value, spec.key);
|
|
23589
23767
|
if (row5.id === "codex") {
|
|
23590
23768
|
const config2 = readParsed(row5.id, join11(codexDirOf(env, home), CONFIG_TOML_FILE)).value;
|
|
@@ -23625,12 +23803,15 @@ function checkHostConfig(row5, env, worktree) {
|
|
|
23625
23803
|
const read3 = row5.id === "pi" ? mcpFile(row5, home, env) : null;
|
|
23626
23804
|
if (parts.length === 0) return read3 === null ? pass("D3") : { ...pass("D3"), detail: read3 };
|
|
23627
23805
|
const detail = D3_DETAIL(parts);
|
|
23628
|
-
|
|
23806
|
+
const fix = parts.includes(PART_MCP) && parts.includes(PART_HOOKS) ? D3_NO_SETUP_FIX(row5.id) : DOCTOR_FIX_UPGRADE;
|
|
23807
|
+
return fail2("D3", read3 === null ? detail : detail + D4_REASON_JOIN + read3, fix);
|
|
23629
23808
|
}
|
|
23630
23809
|
function checkV1Leftovers(agent, home, scope = {}) {
|
|
23631
23810
|
const findings = detectV1(agent, home, scope);
|
|
23632
23811
|
if (findings.length === 0) return pass("D4");
|
|
23633
|
-
|
|
23812
|
+
const detail = findings.map((f) => f.reason).join(D4_REASON_JOIN);
|
|
23813
|
+
if (findings.every((f) => f.reason === V1_REASON.tmpFile)) return { ...pass("D4"), detail };
|
|
23814
|
+
return fail2("D4", detail, DOCTOR_FIX_UPGRADE);
|
|
23634
23815
|
}
|
|
23635
23816
|
function parsedOrNull(agent, file2, jsonc) {
|
|
23636
23817
|
try {
|
|
@@ -23649,6 +23830,31 @@ function checkDoubleFire(agent, worktree) {
|
|
|
23649
23830
|
const useClaudeHooks = isObject4(vscode) && vscode[VSCODE_CLAUDE_HOOKS_SETTING] === true;
|
|
23650
23831
|
return hooksOn && useClaudeHooks ? fail2("D5b", D5B_DETAIL, D5B_FIX) : pass("D5b");
|
|
23651
23832
|
}
|
|
23833
|
+
function configPaths(row5, env, worktree) {
|
|
23834
|
+
const home = homeDirOf(env);
|
|
23835
|
+
if (home === null) return [];
|
|
23836
|
+
const out = [];
|
|
23837
|
+
const mcp = mcpFile(row5, home, env);
|
|
23838
|
+
if (mcp !== null) out.push({ label: "MCP entry", path: mcp });
|
|
23839
|
+
const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
|
|
23840
|
+
if (native !== null) out.push({ label: "Codex plugin MCP", path: join11(native, CODEX_PLUGIN_MCP_FILE) });
|
|
23841
|
+
const spec = HOOK_HOST_FILE[row5.id];
|
|
23842
|
+
if (spec !== null) {
|
|
23843
|
+
try {
|
|
23844
|
+
out.push({ label: "hook entries", path: hookFile(row5, spec, home, env, worktree) });
|
|
23845
|
+
} catch (err) {
|
|
23846
|
+
out.push({ label: "hook entries", path: err instanceof Error ? err.message : String(err) });
|
|
23847
|
+
}
|
|
23848
|
+
}
|
|
23849
|
+
if (spec !== null && spec.root === "plugin" || row5.installMode === "marketplace" || row5.installMode === "plugin") {
|
|
23850
|
+
try {
|
|
23851
|
+
out.push({ label: "plugin root", path: resolvePluginRoot(row5, env, worktree) });
|
|
23852
|
+
} catch (err) {
|
|
23853
|
+
out.push({ label: "plugin root", path: err instanceof Error ? err.message : String(err) });
|
|
23854
|
+
}
|
|
23855
|
+
}
|
|
23856
|
+
return out.filter((e, i) => out.findIndex((o) => o.path === e.path) === i);
|
|
23857
|
+
}
|
|
23652
23858
|
|
|
23653
23859
|
// src/core/ops/doctor-db.ts
|
|
23654
23860
|
import { existsSync as existsSync7 } from "node:fs";
|
|
@@ -23734,29 +23940,92 @@ async function checkIndex(project) {
|
|
|
23734
23940
|
}
|
|
23735
23941
|
|
|
23736
23942
|
// src/core/ops/doctor-env.ts
|
|
23737
|
-
import { existsSync as existsSync8, realpathSync as realpathSync5 } from "node:fs";
|
|
23738
|
-
import { isAbsolute as isAbsolute3, relative as relative2 } from "node:path";
|
|
23943
|
+
import { existsSync as existsSync8, readFileSync as readFileSync9, realpathSync as realpathSync5 } from "node:fs";
|
|
23944
|
+
import { isAbsolute as isAbsolute3, join as join12, relative as relative2 } from "node:path";
|
|
23739
23945
|
function pass3(id2, detail = DOCTOR_PASS_DETAIL) {
|
|
23740
23946
|
return { id: id2, label: DOCTOR_LABEL[id2], status: "PASS", detail };
|
|
23741
23947
|
}
|
|
23742
|
-
function unknown3(id2, detail) {
|
|
23743
|
-
return { id: id2, label: DOCTOR_LABEL[id2], status: "UNKNOWN", detail };
|
|
23948
|
+
function unknown3(id2, detail, fixCommand) {
|
|
23949
|
+
return fixCommand === void 0 ? { id: id2, label: DOCTOR_LABEL[id2], status: "UNKNOWN", detail } : { id: id2, label: DOCTOR_LABEL[id2], status: "UNKNOWN", detail, fixCommand };
|
|
23744
23950
|
}
|
|
23745
23951
|
function fail4(id2, detail, fixCommand) {
|
|
23746
23952
|
return { id: id2, label: DOCTOR_LABEL[id2], status: "FAIL", detail, fixCommand };
|
|
23747
23953
|
}
|
|
23954
|
+
function bundleVersion(bundleDir2) {
|
|
23955
|
+
try {
|
|
23956
|
+
const v = JSON.parse(readFileSync9(join12(bundleDir2, D1_PACKAGE_FILE), "utf8")).version;
|
|
23957
|
+
return typeof v === "string" && v !== "" ? v : void 0;
|
|
23958
|
+
} catch {
|
|
23959
|
+
return void 0;
|
|
23960
|
+
}
|
|
23961
|
+
}
|
|
23962
|
+
function channelOf(version2) {
|
|
23963
|
+
const at2 = version2.indexOf(D1_PRERELEASE_SEP);
|
|
23964
|
+
if (at2 < 0) return D1_DEFAULT_TAG;
|
|
23965
|
+
const pre = version2.slice(at2 + 1);
|
|
23966
|
+
const dot = pre.indexOf(".");
|
|
23967
|
+
const tag2 = dot < 0 ? pre : pre.slice(0, dot);
|
|
23968
|
+
return tag2 === "" ? D1_DEFAULT_TAG : tag2;
|
|
23969
|
+
}
|
|
23970
|
+
function firstLine3(b) {
|
|
23971
|
+
const text = b.toString("utf8").trim();
|
|
23972
|
+
const nl = text.indexOf("\n");
|
|
23973
|
+
return (nl < 0 ? text : text.slice(0, nl)).trim();
|
|
23974
|
+
}
|
|
23975
|
+
function gitCause(r, timeoutMs) {
|
|
23976
|
+
if (r.killed === "timeout") return D1_GIT_TIMEOUT(timeoutMs);
|
|
23977
|
+
if (r.killed === "cancel") return D1_GIT_CANCEL;
|
|
23978
|
+
if (r.exitCode === null) return D1_GIT_NO_START;
|
|
23979
|
+
return D1_GIT_EXIT(r.exitCode, firstLine3(r.stderr));
|
|
23980
|
+
}
|
|
23981
|
+
function fetchCause(err, timeoutMs) {
|
|
23982
|
+
const name = err instanceof Error ? err.name : "";
|
|
23983
|
+
if (name === "TimeoutError") return D1_NPM_TIMEOUT(timeoutMs);
|
|
23984
|
+
const cause = err instanceof Error && err.cause instanceof Error ? err.cause : err;
|
|
23985
|
+
const code = typeof cause === "object" && cause !== null && "code" in cause && typeof cause.code === "string" ? cause.code : "";
|
|
23986
|
+
const msg = cause instanceof Error ? cause.message : String(cause);
|
|
23987
|
+
return D1_NPM_ERROR(code !== "" && !msg.includes(code) ? `${code} ${msg}` : msg);
|
|
23988
|
+
}
|
|
23989
|
+
async function npmLatest(url2, tag2, signal, timeoutMs) {
|
|
23990
|
+
try {
|
|
23991
|
+
const res = await fetch(url2, { signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)]) });
|
|
23992
|
+
if (!res.ok) return { ok: false, cause: D1_NPM_HTTP(res.status) };
|
|
23993
|
+
const body = await res.json();
|
|
23994
|
+
const v = typeof body === "object" && body !== null ? body[tag2] : void 0;
|
|
23995
|
+
return typeof v === "string" && v !== "" ? { ok: true, version: v } : { ok: false, cause: D1_NPM_NO_TAG(tag2) };
|
|
23996
|
+
} catch (err) {
|
|
23997
|
+
return { ok: false, cause: fetchCause(err, timeoutMs) };
|
|
23998
|
+
}
|
|
23999
|
+
}
|
|
23748
24000
|
async function checkVersion(i) {
|
|
23749
24001
|
if (i.bundleSha === void 0) return unknown3("D1", D1_DEV_BUILD_DETAIL);
|
|
23750
|
-
const
|
|
23751
|
-
|
|
23752
|
-
|
|
23753
|
-
|
|
23754
|
-
|
|
23755
|
-
|
|
23756
|
-
|
|
23757
|
-
|
|
23758
|
-
|
|
23759
|
-
|
|
24002
|
+
const head = D1_PREFIX(i.version, i.bundleSha) + ": ";
|
|
24003
|
+
const git3 = findRuntime(GIT_BIN, i.env);
|
|
24004
|
+
let cause = D1_GIT_MISSING;
|
|
24005
|
+
if (git3 !== null) {
|
|
24006
|
+
const r = await runProcess([git3, GIT_LS_REMOTE, RELEASE_REPO_URL, RELEASE_BRANCH], {
|
|
24007
|
+
cwd: i.cwd,
|
|
24008
|
+
env: { ...i.env, ...GIT_NO_PROMPT_ENV },
|
|
24009
|
+
signal: i.signal,
|
|
24010
|
+
timeoutMs: i.timeoutMs
|
|
24011
|
+
});
|
|
24012
|
+
if (r.exitCode === 0 && r.killed === null) {
|
|
24013
|
+
const latest = r.stdout.toString("utf8").split(LS_REMOTE_FIELD_SEP)[0];
|
|
24014
|
+
if (latest.length === GIT_SHA_HEX_LEN) {
|
|
24015
|
+
return latest === i.bundleSha ? pass3("D1", head + D1_GIT_PASS) : fail4("D1", head + D1_UPDATE_DETAIL, DOCTOR_FIX_UPGRADE);
|
|
24016
|
+
}
|
|
24017
|
+
cause = D1_GIT_NO_SHA;
|
|
24018
|
+
} else {
|
|
24019
|
+
cause = gitCause(r, i.timeoutMs);
|
|
24020
|
+
}
|
|
24021
|
+
}
|
|
24022
|
+
const handFix = git3 === null ? D1_NPM_CHECK_FIX : D1_GIT_CHECK_FIX;
|
|
24023
|
+
if (i.version === void 0) return unknown3("D1", head + D1_LATEST_UNKNOWN + ", " + cause, handFix);
|
|
24024
|
+
const tag2 = channelOf(i.version);
|
|
24025
|
+
const npm = await npmLatest(i.registryUrl, tag2, i.signal, i.timeoutMs);
|
|
24026
|
+
if (!npm.ok) return unknown3("D1", head + D1_LATEST_UNKNOWN + ", " + cause + D1_CAUSE_JOIN + npm.cause, handFix);
|
|
24027
|
+
if (npm.version === i.version) return pass3("D1", head + D1_NPM_PASS(tag2) + D1_CAUSE_JOIN + cause);
|
|
24028
|
+
return fail4("D1", head + D1_NPM_UPDATE(tag2, npm.version) + D1_CAUSE_JOIN + cause, DOCTOR_FIX_UPGRADE);
|
|
23760
24029
|
}
|
|
23761
24030
|
function numbers(v) {
|
|
23762
24031
|
const bare2 = v.startsWith(NODE_VERSION_PREFIX) ? v.slice(NODE_VERSION_PREFIX.length) : v;
|
|
@@ -23813,7 +24082,7 @@ function checkShell(env) {
|
|
|
23813
24082
|
}
|
|
23814
24083
|
|
|
23815
24084
|
// src/core/ops/doctor-hook.ts
|
|
23816
|
-
import { existsSync as existsSync10, readFileSync as
|
|
24085
|
+
import { existsSync as existsSync10, readFileSync as readFileSync10, realpathSync as realpathSync7 } from "node:fs";
|
|
23817
24086
|
import path6 from "node:path";
|
|
23818
24087
|
|
|
23819
24088
|
// src/setup/codex-trust.ts
|
|
@@ -24035,16 +24304,19 @@ function isObject5(v) {
|
|
|
24035
24304
|
}
|
|
24036
24305
|
function loadFixture(bundleDir2, agent) {
|
|
24037
24306
|
const file2 = path6.join(bundleDir2, HOOK_FIXTURE_DIR, HOOK_FIXTURE_FILE);
|
|
24038
|
-
if (!existsSync10(file2)) return
|
|
24307
|
+
if (!existsSync10(file2)) return { cause: D5_FIXTURE_FILE_ABSENT(file2) };
|
|
24039
24308
|
let all;
|
|
24040
24309
|
try {
|
|
24041
|
-
all = JSON.parse(hostText(
|
|
24042
|
-
} catch {
|
|
24043
|
-
return
|
|
24310
|
+
all = JSON.parse(hostText(readFileSync10(file2, "utf8")));
|
|
24311
|
+
} catch (err) {
|
|
24312
|
+
return { cause: D5_FIXTURE_PARSE(file2, err instanceof Error ? err.message : String(err)) };
|
|
24044
24313
|
}
|
|
24045
|
-
if (!isObject5(all)
|
|
24314
|
+
if (!isObject5(all)) return { cause: D5_FIXTURE_PARSE(file2, "top level is not an object") };
|
|
24315
|
+
if (!Object.hasOwn(all, agent)) return { cause: D5_NO_FIXTURE_DETAIL(agent) + ": " + D5_FIXTURE_AGENT_ABSENT(file2, Object.keys(all)) };
|
|
24046
24316
|
const e = all[agent];
|
|
24047
|
-
if (!isObject5(e) || typeof e.event !== "string" || !Object.hasOwn(e, "payload"))
|
|
24317
|
+
if (!isObject5(e) || typeof e.event !== "string" || !Object.hasOwn(e, "payload")) {
|
|
24318
|
+
return { cause: D5_NO_FIXTURE_DETAIL(agent) + ": the entry lacks an event name or a payload" };
|
|
24319
|
+
}
|
|
24048
24320
|
return { event: e.event, payload: e.payload };
|
|
24049
24321
|
}
|
|
24050
24322
|
function payloadFor(payload, worktree) {
|
|
@@ -24098,7 +24370,7 @@ async function checkHookRoundTrip(i) {
|
|
|
24098
24370
|
return row("UNKNOWN", D5_CODEX_UNTRUSTED_DETAIL);
|
|
24099
24371
|
}
|
|
24100
24372
|
const fixture = loadFixture(i.bundleDir, i.agent);
|
|
24101
|
-
if (
|
|
24373
|
+
if ("cause" in fixture) return row("UNKNOWN", fixture.cause);
|
|
24102
24374
|
const now = i.now ?? (() => performance.now());
|
|
24103
24375
|
const fixed = i.samples === void 0 ? null : Math.max(1, i.samples);
|
|
24104
24376
|
const maxPairs = fixed ?? D5_MAX_PAIRS;
|
|
@@ -24134,10 +24406,10 @@ async function checkHookRoundTrip(i) {
|
|
|
24134
24406
|
import { existsSync as existsSync11, rmSync as rmSync3 } from "node:fs";
|
|
24135
24407
|
|
|
24136
24408
|
// src/core/store/owners.ts
|
|
24137
|
-
import { mkdirSync as mkdirSync4, readdirSync as readdirSync4, readFileSync as
|
|
24138
|
-
import { basename as basename3, join as
|
|
24409
|
+
import { mkdirSync as mkdirSync4, readdirSync as readdirSync4, readFileSync as readFileSync11, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";
|
|
24410
|
+
import { basename as basename3, join as join13 } from "node:path";
|
|
24139
24411
|
function ownersDir(configDir, projectKey) {
|
|
24140
|
-
return
|
|
24412
|
+
return join13(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
|
|
24141
24413
|
}
|
|
24142
24414
|
function errCode2(err) {
|
|
24143
24415
|
return err.code;
|
|
@@ -24165,10 +24437,10 @@ function listLiveOwners(configDir, projectKey) {
|
|
|
24165
24437
|
const live = [];
|
|
24166
24438
|
for (const name of names) {
|
|
24167
24439
|
if (!name.endsWith(OWNER_PID_EXT)) continue;
|
|
24168
|
-
const file2 =
|
|
24440
|
+
const file2 = join13(dir, name);
|
|
24169
24441
|
let text;
|
|
24170
24442
|
try {
|
|
24171
|
-
text =
|
|
24443
|
+
text = readFileSync11(file2, "utf8");
|
|
24172
24444
|
} catch (err) {
|
|
24173
24445
|
if (errCode2(err) === "ENOENT") continue;
|
|
24174
24446
|
throw err;
|
|
@@ -24250,8 +24522,13 @@ function envLine(key, value) {
|
|
|
24250
24522
|
const typedValue = allowed !== void 0 && allowed.includes(value) ? value : REPORT_INVALID;
|
|
24251
24523
|
return REPORT_ENV_PREFIX + typedKey + ": " + typedValue;
|
|
24252
24524
|
}
|
|
24525
|
+
function fixCell(agent, row5) {
|
|
24526
|
+
if (row5.status === "PASS") return "";
|
|
24527
|
+
if (row5.status === "FAIL") return DOCTOR_FAIL_LINE(agent, row5.id, row5.detail, row5.fixCommand ?? "");
|
|
24528
|
+
return row5.fixCommand === void 0 ? "" : "Fix: " + row5.fixCommand;
|
|
24529
|
+
}
|
|
24253
24530
|
function rowLine(agent, row5) {
|
|
24254
|
-
const fix =
|
|
24531
|
+
const fix = fixCell(agent, row5);
|
|
24255
24532
|
return "| " + [row5.id + " " + row5.label, row5.status, row5.detail, fix].join(" | ") + " |";
|
|
24256
24533
|
}
|
|
24257
24534
|
function buildReport(input) {
|
|
@@ -24281,6 +24558,196 @@ function buildReportHead(input) {
|
|
|
24281
24558
|
return lines.concat(tail).join("\n");
|
|
24282
24559
|
}
|
|
24283
24560
|
|
|
24561
|
+
// src/core/ops/doctor-issue.ts
|
|
24562
|
+
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
24563
|
+
import { closeSync, existsSync as existsSync12, fstatSync, mkdirSync as mkdirSync5, openSync, readFileSync as readFileSync12, readSync, realpathSync as realpathSync8, writeFileSync as writeFileSync3 } from "node:fs";
|
|
24564
|
+
import { delimiter, join as join14 } from "node:path";
|
|
24565
|
+
var TOKEN_PREFIXES = ["ghp_", "gho_", "github_pat_", "sk-", "xoxb-", "AKIA"];
|
|
24566
|
+
function tildeOf(env) {
|
|
24567
|
+
const home = homeDirOf(env);
|
|
24568
|
+
if (home === null || home === "") return (t) => t;
|
|
24569
|
+
const homes = [home];
|
|
24570
|
+
try {
|
|
24571
|
+
const real2 = realpathSync8.native(home);
|
|
24572
|
+
if (real2 !== home) homes.push(real2);
|
|
24573
|
+
} catch {
|
|
24574
|
+
}
|
|
24575
|
+
homes.sort((a, b) => b.length - a.length);
|
|
24576
|
+
const slash = (rest) => rest.replace(/^[^\s"'`|)>,;]*/, (run) => run.replace(/\\/g, "/"));
|
|
24577
|
+
return (t) => homes.reduce((acc, h) => acc.split(h).map((piece, n) => n === 0 ? piece : slash(piece)).join("~"), t);
|
|
24578
|
+
}
|
|
24579
|
+
function maskLine(line) {
|
|
24580
|
+
const lower = line.toLowerCase();
|
|
24581
|
+
const named = DOCTOR_SECRET_WORDS.some((w) => lower.includes(w));
|
|
24582
|
+
const token = TOKEN_PREFIXES.some((p) => line.includes(p));
|
|
24583
|
+
if (!named && !token) return line;
|
|
24584
|
+
const at2 = Math.max(line.indexOf(":"), line.indexOf("="));
|
|
24585
|
+
return at2 === -1 ? DOCTOR_MASK : line.slice(0, at2 + 1) + " " + DOCTOR_MASK;
|
|
24586
|
+
}
|
|
24587
|
+
function environmentLine(ctx, adapter, env, version2) {
|
|
24588
|
+
const sha = BUNDLE_SHA === void 0 ? "dev build" : BUNDLE_SHA.slice(0, 7);
|
|
24589
|
+
const client = ctx.clientInfo;
|
|
24590
|
+
const agent = client === void 0 ? adapter.id : client.name === adapter.id ? `${adapter.id} ${client.version}` : `${adapter.id} ${client.version} (client ${client.name})`;
|
|
24591
|
+
const shell = env.SHELL ?? env.ComSpec ?? "sh";
|
|
24592
|
+
return `${DOCTOR_ENV_PREFIX}context-mode ${version2 ?? "source checkout"} (${sha}), agent ${agent}
|
|
24593
|
+
${DOCTOR_ENV_PREFIX}${process.platform}-${process.arch}, Node ${process.version}, shell ${shell}`;
|
|
24594
|
+
}
|
|
24595
|
+
function gitVersion(env) {
|
|
24596
|
+
const r = spawnSync3("git", ["--version"], { env, encoding: "utf8", timeout: DOCTOR_GIT_VERSION_TIMEOUT_MS, windowsHide: true });
|
|
24597
|
+
if (r.status === 0) return `${r.stdout}`.trim();
|
|
24598
|
+
return `git --version: ${r.error ? r.error.message : `exit ${r.status}`}`;
|
|
24599
|
+
}
|
|
24600
|
+
function onPath(env, tool) {
|
|
24601
|
+
const names = process.platform === "win32" ? [tool + EXE_SUFFIX, tool + ".cmd", tool] : [tool];
|
|
24602
|
+
const out = [];
|
|
24603
|
+
for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter)) {
|
|
24604
|
+
if (dir === "") continue;
|
|
24605
|
+
for (const n of names) if (existsSync12(join14(dir, n))) {
|
|
24606
|
+
out.push(join14(dir, n));
|
|
24607
|
+
break;
|
|
24608
|
+
}
|
|
24609
|
+
}
|
|
24610
|
+
return out;
|
|
24611
|
+
}
|
|
24612
|
+
function hookLogTail(env) {
|
|
24613
|
+
const file2 = hookLogPath(env);
|
|
24614
|
+
if (file2 === "" || !existsSync12(file2)) return [`(${file2 || "hook-errors.log"} holds zero lines)`];
|
|
24615
|
+
try {
|
|
24616
|
+
const fd = openSync(file2, "r");
|
|
24617
|
+
try {
|
|
24618
|
+
const size = fstatSync(fd).size;
|
|
24619
|
+
const start = Math.max(0, size - DOCTOR_LOG_TAIL_BYTES);
|
|
24620
|
+
const buf = Buffer.alloc(size - start);
|
|
24621
|
+
readSync(fd, buf, 0, buf.length, start);
|
|
24622
|
+
const lines = buf.toString("utf8").split("\n").filter((l) => l.trim() !== "");
|
|
24623
|
+
if (start > 0) lines.shift();
|
|
24624
|
+
return lines.slice(-DOCTOR_HOOK_LOG_LINES).map(maskLine);
|
|
24625
|
+
} finally {
|
|
24626
|
+
closeSync(fd);
|
|
24627
|
+
}
|
|
24628
|
+
} catch (err) {
|
|
24629
|
+
return [`hook-errors.log read: ${err instanceof Error ? err.message : String(err)}`];
|
|
24630
|
+
}
|
|
24631
|
+
}
|
|
24632
|
+
async function journalRows(ctx) {
|
|
24633
|
+
const head = ["| kind | tool | bytes | ok | exit_code | created_at |", "|---|---|---|---|---|---|"];
|
|
24634
|
+
if (!existsSync12(ctx.project.dbPath)) return [`(context.db is absent at ${ctx.project.dbPath})`];
|
|
24635
|
+
try {
|
|
24636
|
+
const db = await openDb(ctx.project, { readOnly: true });
|
|
24637
|
+
try {
|
|
24638
|
+
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();
|
|
24639
|
+
const cell5 = (v) => v === null || v === void 0 ? "" : String(v);
|
|
24640
|
+
return head.concat(rows.map((r) => `| ${cell5(r.kind)} | ${cell5(r.tool)} | ${cell5(r.bytes)} | ${cell5(r.ok)} | ${cell5(r.exit_code)} | ${typeof r.created_at === "number" ? new Date(r.created_at).toISOString() : cell5(r.created_at)} |`));
|
|
24641
|
+
} finally {
|
|
24642
|
+
closeDb(db);
|
|
24643
|
+
}
|
|
24644
|
+
} catch (err) {
|
|
24645
|
+
return [`journal read: ${err instanceof Error ? err.message : String(err)}`];
|
|
24646
|
+
}
|
|
24647
|
+
}
|
|
24648
|
+
function agentConfig(adapter, env, worktree) {
|
|
24649
|
+
const home = homeDirOf(env);
|
|
24650
|
+
const files = configPaths(adapter, env, worktree);
|
|
24651
|
+
if (home !== null) {
|
|
24652
|
+
if (adapter.id === "claude-code") files.push({ label: "agent settings (enabledPlugins)", path: join14(claudeDirOf(env, home), SETTINGS_FILE) });
|
|
24653
|
+
if (adapter.id === "codex") files.push({ label: "agent config (plugins, trust)", path: join14(codexDirOf(env, home), CONFIG_TOML_FILE) });
|
|
24654
|
+
}
|
|
24655
|
+
const out = [];
|
|
24656
|
+
const seen = /* @__PURE__ */ new Set();
|
|
24657
|
+
for (const f of files) {
|
|
24658
|
+
if (seen.has(f.path)) continue;
|
|
24659
|
+
seen.add(f.path);
|
|
24660
|
+
if (!existsSync12(f.path)) {
|
|
24661
|
+
out.push(`${f.label}: ${f.path} (absent)`);
|
|
24662
|
+
continue;
|
|
24663
|
+
}
|
|
24664
|
+
let text = "";
|
|
24665
|
+
try {
|
|
24666
|
+
text = readFileSync12(f.path, "utf8");
|
|
24667
|
+
} catch (err) {
|
|
24668
|
+
out.push(`${f.label}: ${f.path} (read: ${err instanceof Error ? err.message : String(err)})`);
|
|
24669
|
+
continue;
|
|
24670
|
+
}
|
|
24671
|
+
const hit = text.split("\n").filter((l) => l.includes("context-mode") || l.includes("hook.mjs") || adapter.id === "codex" && l.includes("trust"));
|
|
24672
|
+
out.push(`${f.label}: ${f.path} (${hit.length} matching lines)`);
|
|
24673
|
+
for (const l of hit.slice(0, DOCTOR_CONFIG_LINES)) out.push(" " + maskLine(l.trimEnd()));
|
|
24674
|
+
}
|
|
24675
|
+
return out;
|
|
24676
|
+
}
|
|
24677
|
+
function failing(rows) {
|
|
24678
|
+
return rows.filter((r) => r.status === "FAIL");
|
|
24679
|
+
}
|
|
24680
|
+
function issueTitle(agent, rows) {
|
|
24681
|
+
return `ctx_doctor ${agent}: ${failing(rows).map((r) => `${r.id} ${r.label}`).join(", ")} FAIL`;
|
|
24682
|
+
}
|
|
24683
|
+
function summaryOf(agent, rows) {
|
|
24684
|
+
const f = failing(rows)[0];
|
|
24685
|
+
return f === void 0 ? `ctx_doctor ${agent}` : `${f.id} ${f.label} FAIL on ${agent}: ${f.detail}`;
|
|
24686
|
+
}
|
|
24687
|
+
async function buildIssueBody(i) {
|
|
24688
|
+
const tilde = tildeOf(i.env);
|
|
24689
|
+
const agent = i.adapter.id;
|
|
24690
|
+
const install = NATIVE_INSTALL[agent] ?? [];
|
|
24691
|
+
const failRows = i.rows.filter((r) => r.status !== "PASS");
|
|
24692
|
+
const envNames = DOCTOR_ENV_NAMES.map((n) => i.env[n] === void 0 ? `${n} (unset)` : `${n}=${i.env[n]}`);
|
|
24693
|
+
const pathTools = DOCTOR_PATH_TOOLS.map((t) => `PATH holds ${t}: ${onPath(i.env, t).join(", ") || "(absent)"}`);
|
|
24694
|
+
const sections = {
|
|
24695
|
+
"Summary": [summaryOf(agent, i.rows)],
|
|
24696
|
+
"ctx-report": [i.table],
|
|
24697
|
+
"What happened": [
|
|
24698
|
+
"Rows that need a look:",
|
|
24699
|
+
...failRows.map((r) => `- ${r.id} ${r.label} ${r.status}: ${r.detail}${r.fixCommand ? ` (Fix: ${r.fixCommand})` : ""}`),
|
|
24700
|
+
"Error code and text: <the agent fills this in: the exact error the user saw>"
|
|
24701
|
+
],
|
|
24702
|
+
"Hook errors": ["hook-errors.log, last " + DOCTOR_HOOK_LOG_LINES + " lines (UTC):", "```", ...hookLogTail(i.env), "```"],
|
|
24703
|
+
"Journal rows": ["events, newest first, last " + DOCTOR_JOURNAL_ROWS + " (bodies stay local):", ...await journalRows(i.ctx)],
|
|
24704
|
+
"Agent config": agentConfig(i.adapter, i.env, i.ctx.project.worktree),
|
|
24705
|
+
"Expected": ["Expected: <the agent fills this in: what should happen, with the byte count>"],
|
|
24706
|
+
"Steps": [
|
|
24707
|
+
"Reproduced: <yes (2 of 2) or 1 of 2>",
|
|
24708
|
+
"Prompt or command: <the agent fills this in: the exact prompt or command>",
|
|
24709
|
+
"Actual: <the agent fills this in: what context-mode did, with the byte count>",
|
|
24710
|
+
"Repro script (fresh HOME, native install for " + agent + "):",
|
|
24711
|
+
"```sh",
|
|
24712
|
+
'export HOME="$(mktemp -d)"',
|
|
24713
|
+
'cd "$HOME"',
|
|
24714
|
+
...install,
|
|
24715
|
+
"<the command or prompt above>",
|
|
24716
|
+
"```"
|
|
24717
|
+
],
|
|
24718
|
+
"Environment": [
|
|
24719
|
+
i.envLine,
|
|
24720
|
+
`context-mode bundle: ${i.bundleDir}`,
|
|
24721
|
+
`Install route: ${install.join(" && ")}`,
|
|
24722
|
+
`git: ${gitVersion(i.env)}`,
|
|
24723
|
+
...pathTools,
|
|
24724
|
+
...envNames,
|
|
24725
|
+
`Project: ${i.ctx.project.worktree} (key ${i.ctx.project.projectKey})`,
|
|
24726
|
+
"Filed by: <your agent name, version, model id>"
|
|
24727
|
+
]
|
|
24728
|
+
};
|
|
24729
|
+
const out = [];
|
|
24730
|
+
for (const h of ISSUE_FORM_HEADINGS) out.push(`### ${h}`, "", ...sections[h] ?? [], "");
|
|
24731
|
+
return tilde(out.join("\n"));
|
|
24732
|
+
}
|
|
24733
|
+
async function writeIssueReport(i) {
|
|
24734
|
+
const tilde = tildeOf(i.env);
|
|
24735
|
+
const body = await buildIssueBody(i);
|
|
24736
|
+
const dir = join14(resolveConfigDir(i.env), DOCTOR_REPORTS_DIR);
|
|
24737
|
+
mkdirSync5(dir, { recursive: true });
|
|
24738
|
+
const file2 = join14(dir, `${DOCTOR_REPORT_FILE_PREFIX}${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
|
|
24739
|
+
writeFileSync3(file2, body);
|
|
24740
|
+
const shown2 = tilde(file2);
|
|
24741
|
+
const title = issueTitle(i.adapter.id, i.rows);
|
|
24742
|
+
const gh = [`gh issue create --repo ${ISSUE_REPO_SLUG} --label bug \\`, `${DOCTOR_GH_NEXT}title ${JSON.stringify(title)} \\`, `${DOCTOR_GH_NEXT}body-file ${shown2}`];
|
|
24743
|
+
return [DOCTOR_REPORT_LINE + shown2, DOCTOR_GH_LINE + gh[0], gh[1], gh[2], DOCTOR_URL_LINE + formUrl(title, summaryOf(i.adapter.id, i.rows))];
|
|
24744
|
+
}
|
|
24745
|
+
function formUrl(title, summary) {
|
|
24746
|
+
const base = `${ISSUE_FORM_URL}&title=${encodeURIComponent(title)}`;
|
|
24747
|
+
const full = `${base}&summary=${encodeURIComponent(summary)}`;
|
|
24748
|
+
return full.length < ISSUE_URL_MAX ? full : base;
|
|
24749
|
+
}
|
|
24750
|
+
|
|
24284
24751
|
// src/core/tools/doctor.ts
|
|
24285
24752
|
var ctxDoctorSchema = external_exports.object({}).strict();
|
|
24286
24753
|
function lineOf2(err) {
|
|
@@ -24295,7 +24762,7 @@ async function guard(id2, run) {
|
|
|
24295
24762
|
}
|
|
24296
24763
|
}
|
|
24297
24764
|
async function codexDb(ctx, adapter) {
|
|
24298
|
-
if (adapter.id !== "codex" || !
|
|
24765
|
+
if (adapter.id !== "codex" || !existsSync13(ctx.project.dbPath)) return null;
|
|
24299
24766
|
try {
|
|
24300
24767
|
return await openDb(ctx.project, { readOnly: true });
|
|
24301
24768
|
} catch {
|
|
@@ -24325,11 +24792,11 @@ async function hookRow(ctx, adapter, host) {
|
|
|
24325
24792
|
}
|
|
24326
24793
|
}
|
|
24327
24794
|
function ownServerId(configDir, projectKey) {
|
|
24328
|
-
const dir =
|
|
24329
|
-
if (!
|
|
24795
|
+
const dir = join15(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
|
|
24796
|
+
if (!existsSync13(dir)) return "";
|
|
24330
24797
|
for (const name of readdirSync5(dir)) {
|
|
24331
24798
|
if (!name.endsWith(OWNER_PID_EXT)) continue;
|
|
24332
|
-
if (
|
|
24799
|
+
if (readFileSync13(join15(dir, name), "utf8").trim() === String(process.pid)) return basename4(name, OWNER_PID_EXT);
|
|
24333
24800
|
}
|
|
24334
24801
|
return "";
|
|
24335
24802
|
}
|
|
@@ -24339,7 +24806,7 @@ async function runDoctorChecks(ctx, adapter, host0) {
|
|
|
24339
24806
|
const project = ctx.project;
|
|
24340
24807
|
let integrityFailed = false;
|
|
24341
24808
|
const checks = {
|
|
24342
|
-
D1: () => checkVersion({ bundleSha: BUNDLE_SHA, env: buildChildEnv(env), cwd: project.worktree, signal: ctx.signal }),
|
|
24809
|
+
D1: () => checkVersion({ bundleSha: BUNDLE_SHA, version: bundleVersion(host.bundleDir), registryUrl: D1_REGISTRY_URL, timeoutMs: DOCTOR_GIT_TIMEOUT_MS, env: buildChildEnv(env), cwd: project.worktree, signal: ctx.signal }),
|
|
24343
24810
|
D2: () => checkNode({ nodeVersion: process.version, bunVersion: process.versions.bun }),
|
|
24344
24811
|
D3: () => checkHostConfig(adapter, env, project.worktree),
|
|
24345
24812
|
D4: () => checkV1Leftovers(adapter.id, requireHomeDir(env), { project: project.worktree, piAgentDir: piAgentDirOf(env, requireHomeDir(env)), claudeDir: claudeDirOf(env, requireHomeDir(env)), codexDir: codexDirOf(env, requireHomeDir(env)), copilotDir: copilotDirOf(env, requireHomeDir(env)), kiroDir: kiroDirOf(env, requireHomeDir(env)), opencodeDir: opencodeDirOf(env, requireHomeDir(env)) }),
|
|
@@ -24374,23 +24841,38 @@ function reportEnv(env) {
|
|
|
24374
24841
|
}
|
|
24375
24842
|
return out;
|
|
24376
24843
|
}
|
|
24377
|
-
async function
|
|
24844
|
+
async function doctorReply(ctx, host) {
|
|
24378
24845
|
const adapter = getAdapter(ctx.project.agent);
|
|
24379
|
-
const host = { env: process.env, bundleDir: dirname7(process.argv[1]), piCwd: void 0 };
|
|
24380
24846
|
const rows = await runDoctorChecks(ctx, adapter, host);
|
|
24381
|
-
const
|
|
24382
|
-
const
|
|
24383
|
-
const
|
|
24384
|
-
const
|
|
24385
|
-
|
|
24847
|
+
const failed2 = rows.some((r) => r.status === "FAIL");
|
|
24848
|
+
const command = `context-mode ${failed2 ? "setup" : "doctor"} --agents ${adapter.id}`;
|
|
24849
|
+
const input = { agent: adapter.id, rows, env: reportEnv(host.env), command };
|
|
24850
|
+
const envLine2 = environmentLine(ctx, adapter, host.env, bundleVersion(host.bundleDir));
|
|
24851
|
+
const table3 = buildReport(input);
|
|
24852
|
+
let notes = [];
|
|
24853
|
+
if (failed2) {
|
|
24854
|
+
try {
|
|
24855
|
+
notes = await writeIssueReport({ ctx, adapter, env: host.env, bundleDir: host.bundleDir, rows, envLine: envLine2, table: table3 });
|
|
24856
|
+
} catch (err) {
|
|
24857
|
+
notes = [`Report file: ${lineOf2(err)}`];
|
|
24858
|
+
}
|
|
24859
|
+
}
|
|
24860
|
+
const look = rows.find((r) => r.status === "FAIL") ?? rows.find((r) => r.status !== "PASS");
|
|
24861
|
+
const docs = look === void 0 ? [] : [DOCTOR_DOCS_LABEL + DOCTOR_DOCS_LINK(look.id)];
|
|
24862
|
+
const whole2 = [envLine2, table3, ...docs, ...notes].join("\n");
|
|
24863
|
+
const bytes5 = Buffer.byteLength(whole2, "utf8");
|
|
24864
|
+
if (bytes5 <= REPORT_CAP) return { text: whole2, isError: false, sandboxBytes: bytes5 };
|
|
24386
24865
|
const db = await openDb(ctx.project);
|
|
24387
24866
|
try {
|
|
24388
|
-
indexText(db, ctx.project, ctx.sessionId, REPORT_SOURCE_LABEL,
|
|
24867
|
+
indexText(db, ctx.project, ctx.sessionId, REPORT_SOURCE_LABEL, whole2, "text");
|
|
24389
24868
|
} finally {
|
|
24390
24869
|
closeDb(db);
|
|
24391
24870
|
}
|
|
24392
|
-
const text = buildReportHead(input);
|
|
24393
|
-
return { text, isError: false, sandboxBytes:
|
|
24871
|
+
const text = [envLine2, buildReportHead(input), ...docs, ...notes].join("\n");
|
|
24872
|
+
return { text, isError: false, sandboxBytes: bytes5 };
|
|
24873
|
+
}
|
|
24874
|
+
async function handler2(_input, ctx) {
|
|
24875
|
+
return doctorReply(ctx, { env: process.env, bundleDir: dirname7(process.argv[1]), piCwd: void 0 });
|
|
24394
24876
|
}
|
|
24395
24877
|
var ctxDoctor = Object.freeze({
|
|
24396
24878
|
name: "ctx_doctor",
|
|
@@ -24402,9 +24884,9 @@ var ctxDoctor = Object.freeze({
|
|
|
24402
24884
|
});
|
|
24403
24885
|
|
|
24404
24886
|
// src/core/tools/execute.ts
|
|
24405
|
-
import { existsSync as
|
|
24887
|
+
import { existsSync as existsSync14, mkdtempSync, rmSync as rmSync4, writeFileSync as writeFileSync4 } from "node:fs";
|
|
24406
24888
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
24407
|
-
import { dirname as dirname8, join as
|
|
24889
|
+
import { dirname as dirname8, join as join16, parse as parse3, resolve as resolve6 } from "node:path";
|
|
24408
24890
|
|
|
24409
24891
|
// src/core/sandbox/win-build.ts
|
|
24410
24892
|
var SEPARATORS2 = ";&|(\n";
|
|
@@ -24488,7 +24970,7 @@ function schemaLine(issue2) {
|
|
|
24488
24970
|
}
|
|
24489
24971
|
function fileError(given, abs, root) {
|
|
24490
24972
|
let dir = abs;
|
|
24491
|
-
while (!
|
|
24973
|
+
while (!existsSync14(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
|
|
24492
24974
|
if (isInside(root, dir)) return null;
|
|
24493
24975
|
return new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine();
|
|
24494
24976
|
}
|
|
@@ -24514,8 +24996,8 @@ function sourceLabel(code) {
|
|
|
24514
24996
|
const first = nl < 0 ? code : code.slice(0, nl);
|
|
24515
24997
|
return Array.from(TOOL2 + ":" + first).slice(0, SOURCE_LABEL_MAX_CHARS).join("");
|
|
24516
24998
|
}
|
|
24517
|
-
function moreReserve(intent,
|
|
24518
|
-
return Buffer.byteLength(moreLine2(intent,
|
|
24999
|
+
function moreReserve(intent, label2) {
|
|
25000
|
+
return Buffer.byteLength(moreLine2(intent, label2), "utf8");
|
|
24519
25001
|
}
|
|
24520
25002
|
function spawnFailed(argv0, cwd) {
|
|
24521
25003
|
return new CtxError("SPAWN_FAILED", { detail: argv0 + " gave no exit code in " + cwd }).toLine();
|
|
@@ -24532,12 +25014,12 @@ async function finish(input, ctx, r, exitCode, journal) {
|
|
|
24532
25014
|
if (intent === "" && fits) {
|
|
24533
25015
|
return { text: direct, isError, sandboxBytes: fullBytes, journal };
|
|
24534
25016
|
}
|
|
24535
|
-
const
|
|
24536
|
-
const budget = (fits ? OUTPUT_CAP : EXEC_PREVIEW_BYTES) - Buffer.byteLength(head, "utf8") - 2 - moreReserve(intent,
|
|
25017
|
+
const label2 = sourceLabel(input.code);
|
|
25018
|
+
const budget = (fits ? OUTPUT_CAP : EXEC_PREVIEW_BYTES) - Buffer.byteLength(head, "utf8") - 2 - moreReserve(intent, label2);
|
|
24537
25019
|
const db = await openDb(ctx.project);
|
|
24538
25020
|
let picked;
|
|
24539
25021
|
try {
|
|
24540
|
-
const { sourceId } = indexText(db, ctx.project, ctx.sessionId,
|
|
25022
|
+
const { sourceId } = indexText(db, ctx.project, ctx.sessionId, label2, combined, "text");
|
|
24541
25023
|
picked = selectChunks(db, sourceId, intent, budget);
|
|
24542
25024
|
} finally {
|
|
24543
25025
|
closeDb(db);
|
|
@@ -24569,9 +25051,9 @@ async function handler3(raw, ctx) {
|
|
|
24569
25051
|
if (takesDashC(input.language, runtime)) {
|
|
24570
25052
|
argv = [runtime, "-c", input.language === "shell" ? rewriteWindowsBuildTools(input.code, process.platform) : input.code];
|
|
24571
25053
|
} else {
|
|
24572
|
-
tmpDir = mkdtempSync(
|
|
24573
|
-
const file2 =
|
|
24574
|
-
|
|
25054
|
+
tmpDir = mkdtempSync(join16(tmpdir2(), TMP_PREFIX));
|
|
25055
|
+
const file2 = join16(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
|
|
25056
|
+
writeFileSync4(file2, scriptText(input.language, input.code), "utf8");
|
|
24575
25057
|
argv = scriptArgv(input.language, runtime, file2);
|
|
24576
25058
|
}
|
|
24577
25059
|
if (input.background === true) {
|
|
@@ -24605,21 +25087,21 @@ var ctxExecute = {
|
|
|
24605
25087
|
};
|
|
24606
25088
|
|
|
24607
25089
|
// src/core/tools/index.ts
|
|
24608
|
-
import { existsSync as
|
|
24609
|
-
import { dirname as dirname9, extname, join as
|
|
25090
|
+
import { existsSync as existsSync15, readFileSync as readFileSync15, statSync as statSync7 } from "node:fs";
|
|
25091
|
+
import { dirname as dirname9, extname, join as join18, relative as relative3, resolve as resolve7 } from "node:path";
|
|
24610
25092
|
|
|
24611
25093
|
// src/core/index/walk.ts
|
|
24612
|
-
import { readdirSync as readdirSync6, readFileSync as
|
|
24613
|
-
import { join as
|
|
25094
|
+
import { readdirSync as readdirSync6, readFileSync as readFileSync14, realpathSync as realpathSync9, statSync as statSync6 } from "node:fs";
|
|
25095
|
+
import { join as join17 } from "node:path";
|
|
24614
25096
|
var GITIGNORE = ".gitignore";
|
|
24615
25097
|
var GIT_DIR = ".git";
|
|
24616
25098
|
function walkDir(root, containmentRoot) {
|
|
24617
|
-
const real2 =
|
|
25099
|
+
const real2 = realpathSync9(root);
|
|
24618
25100
|
if (!isInside(containmentRoot, real2)) throw new CtxError("OUTSIDE_ROOT", { p: root, root: containmentRoot });
|
|
24619
25101
|
const found = [];
|
|
24620
25102
|
visit(real2, [], [], containmentRoot, /* @__PURE__ */ new Set([real2]), found);
|
|
24621
25103
|
found.sort(compareFound);
|
|
24622
|
-
return found.map((f) => ({ absPath: f.absPath, relPath:
|
|
25104
|
+
return found.map((f) => ({ absPath: f.absPath, relPath: join17(...f.dir, f.name) }));
|
|
24623
25105
|
}
|
|
24624
25106
|
function visit(abs, rel, parent, contain, seen, found) {
|
|
24625
25107
|
let entries;
|
|
@@ -24628,17 +25110,17 @@ function visit(abs, rel, parent, contain, seen, found) {
|
|
|
24628
25110
|
} catch {
|
|
24629
25111
|
return;
|
|
24630
25112
|
}
|
|
24631
|
-
const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(
|
|
25113
|
+
const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join17(abs, GITIGNORE), rel)) : parent;
|
|
24632
25114
|
for (const e of entries) {
|
|
24633
25115
|
if (e.name === GIT_DIR) continue;
|
|
24634
|
-
const path7 =
|
|
25116
|
+
const path7 = join17(abs, e.name);
|
|
24635
25117
|
let isDir = e.isDirectory();
|
|
24636
25118
|
let isFile = e.isFile();
|
|
24637
25119
|
let target = path7;
|
|
24638
25120
|
if (e.isSymbolicLink()) {
|
|
24639
25121
|
let resolved;
|
|
24640
25122
|
try {
|
|
24641
|
-
resolved =
|
|
25123
|
+
resolved = realpathSync9(path7);
|
|
24642
25124
|
} catch {
|
|
24643
25125
|
continue;
|
|
24644
25126
|
}
|
|
@@ -24653,7 +25135,7 @@ function visit(abs, rel, parent, contain, seen, found) {
|
|
|
24653
25135
|
if (isFile) {
|
|
24654
25136
|
found.push({ dir: rel, name: e.name, absPath: path7 });
|
|
24655
25137
|
} else if (isDir) {
|
|
24656
|
-
const key = e.isSymbolicLink() ? target :
|
|
25138
|
+
const key = e.isSymbolicLink() ? target : realpathSync9(path7);
|
|
24657
25139
|
if (seen.has(key)) continue;
|
|
24658
25140
|
seen.add(key);
|
|
24659
25141
|
visit(path7, segs, rules, contain, seen, found);
|
|
@@ -24671,7 +25153,7 @@ function compareFound(a, b) {
|
|
|
24671
25153
|
function readRules(file2, base) {
|
|
24672
25154
|
let body;
|
|
24673
25155
|
try {
|
|
24674
|
-
body =
|
|
25156
|
+
body = readFileSync14(file2, "utf8");
|
|
24675
25157
|
} catch {
|
|
24676
25158
|
return [];
|
|
24677
25159
|
}
|
|
@@ -24981,14 +25463,14 @@ function replaceCodePointXML(codePoint) {
|
|
|
24981
25463
|
|
|
24982
25464
|
// node_modules/entities/dist/internal/decode-shared.js
|
|
24983
25465
|
var BASE91_INVERSE = /* @__PURE__ */ (() => {
|
|
24984
|
-
const
|
|
25466
|
+
const table3 = new Uint8Array(127);
|
|
24985
25467
|
let code = 0;
|
|
24986
25468
|
for (let char = 33; char <= 126; char++) {
|
|
24987
25469
|
if (char !== 34 && char !== 36 && char !== 92) {
|
|
24988
|
-
|
|
25470
|
+
table3[char] = code++;
|
|
24989
25471
|
}
|
|
24990
25472
|
}
|
|
24991
|
-
return
|
|
25473
|
+
return table3;
|
|
24992
25474
|
})();
|
|
24993
25475
|
function decodeTrieDict(input, resultLength, atomCount, dict1AtomCount, ngramCount, dictSize) {
|
|
24994
25476
|
const base = 91;
|
|
@@ -25006,10 +25488,10 @@ function decodeTrieDict(input, resultLength, atomCount, dict1AtomCount, ngramCou
|
|
|
25006
25488
|
single.fill(-1, dictSize + dict2AtomCount, slotCount);
|
|
25007
25489
|
const start = new Int32Array(slotCount);
|
|
25008
25490
|
const length = new Int32Array(slotCount);
|
|
25009
|
-
function decodeDelta(
|
|
25491
|
+
function decodeDelta(count2, off) {
|
|
25010
25492
|
let previous = 0;
|
|
25011
25493
|
let slot = off;
|
|
25012
|
-
const end = off +
|
|
25494
|
+
const end = off + count2;
|
|
25013
25495
|
while (slot < end) {
|
|
25014
25496
|
const code = BASE91_INVERSE[input.charCodeAt(pos++)];
|
|
25015
25497
|
if (code < 89) {
|
|
@@ -25032,8 +25514,8 @@ function decodeTrieDict(input, resultLength, atomCount, dict1AtomCount, ngramCou
|
|
|
25032
25514
|
const references = new Int32Array(ngramCount * 2);
|
|
25033
25515
|
let poolSize = 0;
|
|
25034
25516
|
let ngramIndex = 0;
|
|
25035
|
-
function readNgramReferences(
|
|
25036
|
-
for (let index = 0; index <
|
|
25517
|
+
function readNgramReferences(count2, startSlot) {
|
|
25518
|
+
for (let index = 0; index < count2; index++) {
|
|
25037
25519
|
const slot = startSlot + index;
|
|
25038
25520
|
const a = readSlotCode();
|
|
25039
25521
|
const b = readSlotCode();
|
|
@@ -27980,11 +28462,11 @@ function getAtomFeed(feedRoot) {
|
|
|
27980
28462
|
if (href2) {
|
|
27981
28463
|
entry.link = href2;
|
|
27982
28464
|
}
|
|
27983
|
-
const description =
|
|
28465
|
+
const description = fetch2("summary", children) || fetch2("content", children);
|
|
27984
28466
|
if (description) {
|
|
27985
28467
|
entry.description = description;
|
|
27986
28468
|
}
|
|
27987
|
-
const pubDate =
|
|
28469
|
+
const pubDate = fetch2("updated", children);
|
|
27988
28470
|
if (pubDate) {
|
|
27989
28471
|
entry.pubDate = new Date(pubDate);
|
|
27990
28472
|
}
|
|
@@ -27998,7 +28480,7 @@ function getAtomFeed(feedRoot) {
|
|
|
27998
28480
|
feed.link = href;
|
|
27999
28481
|
}
|
|
28000
28482
|
addConditionally(feed, "description", "subtitle", childs);
|
|
28001
|
-
const updated =
|
|
28483
|
+
const updated = fetch2("updated", childs);
|
|
28002
28484
|
if (updated) {
|
|
28003
28485
|
feed.updated = new Date(updated);
|
|
28004
28486
|
}
|
|
@@ -28017,7 +28499,7 @@ function getRssFeed(feedRoot) {
|
|
|
28017
28499
|
addConditionally(entry, "title", "title", children);
|
|
28018
28500
|
addConditionally(entry, "link", "link", children);
|
|
28019
28501
|
addConditionally(entry, "description", "description", children);
|
|
28020
|
-
const pubDate =
|
|
28502
|
+
const pubDate = fetch2("pubDate", children) || fetch2("dc:date", children);
|
|
28021
28503
|
if (pubDate)
|
|
28022
28504
|
entry.pubDate = new Date(pubDate);
|
|
28023
28505
|
return entry;
|
|
@@ -28026,7 +28508,7 @@ function getRssFeed(feedRoot) {
|
|
|
28026
28508
|
addConditionally(feed, "title", "title", childs);
|
|
28027
28509
|
addConditionally(feed, "link", "link", childs);
|
|
28028
28510
|
addConditionally(feed, "description", "description", childs);
|
|
28029
|
-
const updated =
|
|
28511
|
+
const updated = fetch2("lastBuildDate", childs);
|
|
28030
28512
|
if (updated) {
|
|
28031
28513
|
feed.updated = new Date(updated);
|
|
28032
28514
|
}
|
|
@@ -28070,11 +28552,11 @@ function getMediaElements(where) {
|
|
|
28070
28552
|
function getOneElement(tagName, node) {
|
|
28071
28553
|
return getElementsByTagName(tagName, node, true, 1)[0];
|
|
28072
28554
|
}
|
|
28073
|
-
function
|
|
28555
|
+
function fetch2(tagName, where, recurse = false) {
|
|
28074
28556
|
return textContent(getElementsByTagName(tagName, where, recurse, 1)).trim();
|
|
28075
28557
|
}
|
|
28076
28558
|
function addConditionally(object2, property, tagName, where, recurse = false) {
|
|
28077
|
-
const value =
|
|
28559
|
+
const value = fetch2(tagName, where, recurse);
|
|
28078
28560
|
if (value)
|
|
28079
28561
|
object2[property] = value;
|
|
28080
28562
|
}
|
|
@@ -28741,8 +29223,8 @@ var EXT_KIND = Object.freeze({ ".md": "md", ".html": "html", ".htm": "html" });
|
|
|
28741
29223
|
var TYPE_KIND = Object.freeze({ "text/html": "html", "text/markdown": "md" });
|
|
28742
29224
|
var DEFAULT_CONTENT_LABEL = "content";
|
|
28743
29225
|
var utf8 = new TextDecoder("utf-8", { fatal: true });
|
|
28744
|
-
function userLabel(
|
|
28745
|
-
return
|
|
29226
|
+
function userLabel(label2) {
|
|
29227
|
+
return label2 === DECISION_SOURCE ? DECISION_USER_LABEL : label2;
|
|
28746
29228
|
}
|
|
28747
29229
|
function kindOfPath(p) {
|
|
28748
29230
|
return EXT_KIND[extname(p).toLowerCase()] ?? "text";
|
|
@@ -28754,14 +29236,14 @@ function kindOfType(contentType) {
|
|
|
28754
29236
|
}
|
|
28755
29237
|
function readUtf8(absPath) {
|
|
28756
29238
|
try {
|
|
28757
|
-
return utf8.decode(
|
|
29239
|
+
return utf8.decode(readFileSync15(absPath));
|
|
28758
29240
|
} catch {
|
|
28759
29241
|
return void 0;
|
|
28760
29242
|
}
|
|
28761
29243
|
}
|
|
28762
29244
|
function missingOrOutside(given, abs, root) {
|
|
28763
29245
|
let dir = abs;
|
|
28764
|
-
while (!
|
|
29246
|
+
while (!existsSync15(dir) && dirname9(dir) !== dir) dir = dirname9(dir);
|
|
28765
29247
|
if (dir !== abs && isInside(root, dir)) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
|
|
28766
29248
|
return new CtxError("OUTSIDE_ROOT", { p: given, root });
|
|
28767
29249
|
}
|
|
@@ -28772,7 +29254,7 @@ function pathItems(input, project) {
|
|
|
28772
29254
|
if (statSync7(abs).isDirectory()) {
|
|
28773
29255
|
return walkDir(abs, project.containmentRoot).map((f) => ({
|
|
28774
29256
|
sourceKind: "path",
|
|
28775
|
-
label: pathLabel(
|
|
29257
|
+
label: pathLabel(join18(base, f.relPath)),
|
|
28776
29258
|
kind: kindOfPath(f.relPath),
|
|
28777
29259
|
read: () => readUtf8(f.absPath)
|
|
28778
29260
|
}));
|
|
@@ -28782,9 +29264,9 @@ function pathItems(input, project) {
|
|
|
28782
29264
|
async function itemsOf(input, ctx) {
|
|
28783
29265
|
if (input.content !== void 0) {
|
|
28784
29266
|
const text2 = input.content;
|
|
28785
|
-
const
|
|
29267
|
+
const label3 = input.source ?? DEFAULT_CONTENT_LABEL;
|
|
28786
29268
|
const kind = hasMdStructure(text2) ? "md" : "text";
|
|
28787
|
-
return { items: [{ sourceKind: "content", label:
|
|
29269
|
+
return { items: [{ sourceKind: "content", label: label3, kind, read: () => text2 }], from: label3 };
|
|
28788
29270
|
}
|
|
28789
29271
|
if (input.path !== void 0) {
|
|
28790
29272
|
const items = pathItems({ ...input, path: input.path }, ctx.project);
|
|
@@ -28792,8 +29274,8 @@ async function itemsOf(input, ctx) {
|
|
|
28792
29274
|
}
|
|
28793
29275
|
const res = await safeFetch(input.url ?? "", AbortSignal.any([ctx.signal, AbortSignal.timeout(EXEC_TIMEOUT_MS)]));
|
|
28794
29276
|
const text = res.body.toString("utf8");
|
|
28795
|
-
const
|
|
28796
|
-
return { items: [{ sourceKind: "url", label, kind: kindOfType(res.contentType), read: () => text, base:
|
|
29277
|
+
const label2 = res.finalUrl;
|
|
29278
|
+
return { items: [{ sourceKind: "url", label: label2, kind: kindOfType(res.contentType), read: () => text, base: label2 }], from: label2 };
|
|
28797
29279
|
}
|
|
28798
29280
|
async function handler4(input, ctx) {
|
|
28799
29281
|
const given = INPUT_FIELDS.filter((f) => input[f] !== void 0);
|
|
@@ -28805,14 +29287,14 @@ async function handler4(input, ctx) {
|
|
|
28805
29287
|
const db = await openDb(ctx.project);
|
|
28806
29288
|
let sources = 0;
|
|
28807
29289
|
let chunks = 0;
|
|
28808
|
-
let
|
|
29290
|
+
let bytes5 = 0;
|
|
28809
29291
|
let lastId = 0;
|
|
28810
29292
|
const notes = [];
|
|
28811
29293
|
try {
|
|
28812
29294
|
for (const it of items) {
|
|
28813
29295
|
const text = it.read();
|
|
28814
29296
|
if (text === void 0) continue;
|
|
28815
|
-
|
|
29297
|
+
bytes5 += Buffer.byteLength(text, "utf8");
|
|
28816
29298
|
if (it.kind === "html") {
|
|
28817
29299
|
let readable;
|
|
28818
29300
|
try {
|
|
@@ -28849,7 +29331,7 @@ async function handler4(input, ctx) {
|
|
|
28849
29331
|
return {
|
|
28850
29332
|
text: capBytes(line, OUTPUT_CAP).text,
|
|
28851
29333
|
isError: false,
|
|
28852
|
-
sandboxBytes:
|
|
29334
|
+
sandboxBytes: bytes5,
|
|
28853
29335
|
journal: { kind: "index", key: from, path: from, exit_code: null }
|
|
28854
29336
|
};
|
|
28855
29337
|
} catch (err) {
|
|
@@ -28889,8 +29371,8 @@ function purgeScope(db, scope, input) {
|
|
|
28889
29371
|
const raw = db.raw;
|
|
28890
29372
|
if (scope === "session") return changes(raw, "DELETE FROM events WHERE session_id = ?", input.session);
|
|
28891
29373
|
if (scope === "source") {
|
|
28892
|
-
const
|
|
28893
|
-
return deleteChunkRows(raw, { label }) + changes(raw, "DELETE FROM sources WHERE label = ?",
|
|
29374
|
+
const label2 = storedLabel(db, input.source);
|
|
29375
|
+
return deleteChunkRows(raw, { label: label2 }) + changes(raw, "DELETE FROM sources WHERE label = ?", label2);
|
|
28894
29376
|
}
|
|
28895
29377
|
const chunks = deleteChunkRows(raw, "all");
|
|
28896
29378
|
return changes(raw, "DELETE FROM events") + chunks + changes(raw, "DELETE FROM sources");
|
|
@@ -28972,14 +29454,83 @@ var ctxResume = Object.freeze({
|
|
|
28972
29454
|
var ctxStatsSchema = external_exports.object({}, {
|
|
28973
29455
|
error: (issue2) => issue2.code === "unrecognized_keys" ? STATS_UNKNOWN_FIELD_LINE : void 0
|
|
28974
29456
|
}).strict();
|
|
28975
|
-
var
|
|
29457
|
+
var CALLS = "tool IS NOT NULL AND kind <> 'cost' AND tool <> 'ctx_stats'";
|
|
29458
|
+
var GROUPS = `SELECT session_id, agent, COUNT(*) AS calls, COALESCE(SUM(sandbox_bytes), 0) AS produced, COALESCE(SUM(returned_bytes), 0) AS returned FROM events WHERE ${CALLS} GROUP BY session_id, agent ORDER BY agent, session_id`;
|
|
29459
|
+
var TOOLS = `SELECT tool, COUNT(*) AS calls, COALESCE(SUM(sandbox_bytes), 0) AS produced, COALESCE(SUM(returned_bytes), 0) AS returned FROM events WHERE ${CALLS} GROUP BY tool`;
|
|
29460
|
+
var KINDS = "SELECT kind, COALESCE(SUM(session_id = ?), 0) AS s, COUNT(*) AS p FROM events WHERE kind <> 'cost' AND (tool IS NULL OR tool <> 'ctx_stats') GROUP BY kind";
|
|
29461
|
+
var META = `SELECT COUNT(DISTINCT session_id) AS sessions, COUNT(DISTINCT agent) AS agents, COUNT(DISTINCT created_at / ${MS_PER_DAY}) AS days FROM events WHERE ${CALLS}`;
|
|
29462
|
+
var SPAN = "SELECT COALESCE(MAX(created_at) - MIN(created_at), 0) AS span FROM events WHERE session_id = ? AND kind <> 'cost'";
|
|
29463
|
+
var SOURCES = "SELECT COUNT(*) AS n, COALESCE(SUM(chunk_count), 0) AS chunks, COALESCE(SUM(bytes_total), 0) AS bytes FROM sources";
|
|
29464
|
+
var HOST = "tool NOT LIKE 'ctx\\_%' ESCAPE '\\'";
|
|
29465
|
+
var REPLACED = `SELECT COUNT(*) AS n FROM events WHERE ${CALLS} AND ${HOST} AND returned_bytes < sandbox_bytes`;
|
|
29466
|
+
var RUNS = "FROM sources WHERE substr(label, 1, ?) = ?";
|
|
29467
|
+
var REDIRECTED = `SELECT COUNT(*) AS n, COALESCE(MAX(created_ts), 0) AS last ${RUNS}`;
|
|
29468
|
+
var LAST = `SELECT COALESCE(MAX(created_at), 0) AS last FROM events WHERE ${CALLS}`;
|
|
29469
|
+
var WEEK = `SELECT created_at / ${MS_PER_DAY} AS day, tool, COUNT(*) AS calls, COALESCE(SUM(sandbox_bytes), 0) AS produced, COALESCE(SUM(returned_bytes), 0) AS returned FROM events WHERE ${CALLS} AND created_at >= ? GROUP BY day, tool`;
|
|
29470
|
+
var WEEK_RUNS = `SELECT created_ts / ${MS_PER_DAY} AS day, COUNT(*) AS calls, COALESCE(SUM(MAX(0, bytes_total - ${OUTPUT_CAP})), 0) AS saved ${RUNS} AND created_ts >= ? GROUP BY day`;
|
|
29471
|
+
var TOP = `SELECT tool, 1 AS calls, sandbox_bytes AS produced, returned_bytes AS returned FROM events WHERE ${CALLS} AND sandbox_bytes > 0 ORDER BY sandbox_bytes DESC, seq ASC LIMIT ${STATS_TOP_OUTPUTS}`;
|
|
29472
|
+
function wayOf(tool) {
|
|
29473
|
+
if (STATS_INDEX_TOOLS.includes(tool)) return "index";
|
|
29474
|
+
return tool.startsWith("ctx_") ? "sandbox" : "replace";
|
|
29475
|
+
}
|
|
29476
|
+
function readWeek(raw, lastMs) {
|
|
29477
|
+
const last2 = Math.floor(lastMs / MS_PER_DAY);
|
|
29478
|
+
const first = last2 - STATS_DAYS + 1;
|
|
29479
|
+
const days = Array.from({ length: STATS_DAYS }, (_, i) => ({
|
|
29480
|
+
day: first + i,
|
|
29481
|
+
calls: 0,
|
|
29482
|
+
ways: { sandbox: 0, index: 0, redirect: 0, replace: 0 }
|
|
29483
|
+
}));
|
|
29484
|
+
const net = /* @__PURE__ */ new Map();
|
|
29485
|
+
for (const r of raw.prepare(WEEK).all(first * MS_PER_DAY)) {
|
|
29486
|
+
const d = days[Number(r.day) - first];
|
|
29487
|
+
if (d === void 0) continue;
|
|
29488
|
+
d.calls += Number(r.calls);
|
|
29489
|
+
const key = `${d.day}:${wayOf(String(r.tool))}`;
|
|
29490
|
+
net.set(key, (net.get(key) ?? 0) + Number(r.produced) - Number(r.returned));
|
|
29491
|
+
}
|
|
29492
|
+
for (const d of days) for (const [way] of STATS_WAYS) d.ways[way] = Math.max(0, net.get(`${d.day}:${way}`) ?? 0);
|
|
29493
|
+
for (const r of raw.prepare(WEEK_RUNS).all(RUN_LABEL_PREFIX.length, RUN_LABEL_PREFIX, first * MS_PER_DAY)) {
|
|
29494
|
+
const d = days[Number(r.day) - first];
|
|
29495
|
+
if (d === void 0) continue;
|
|
29496
|
+
d.calls += Number(r.calls);
|
|
29497
|
+
d.ways.redirect += Number(r.saved);
|
|
29498
|
+
}
|
|
29499
|
+
return days;
|
|
29500
|
+
}
|
|
28976
29501
|
var EMPTY5 = Object.freeze({ calls: 0, produced: 0, returned: 0, saved: 0 });
|
|
28977
|
-
function
|
|
28978
|
-
|
|
28979
|
-
|
|
28980
|
-
|
|
28981
|
-
|
|
28982
|
-
|
|
29502
|
+
function totals(r) {
|
|
29503
|
+
const produced = Number(r.produced);
|
|
29504
|
+
const returned = Number(r.returned);
|
|
29505
|
+
return { calls: Number(r.calls), produced, returned, saved: Math.max(0, produced - returned) };
|
|
29506
|
+
}
|
|
29507
|
+
function readFacts(raw, sessionId) {
|
|
29508
|
+
const groups = raw.prepare(GROUPS).all().map((r) => ({ session: String(r.session_id), agent: String(r.agent), ...totals(r) }));
|
|
29509
|
+
const tools = raw.prepare(TOOLS).all().map((r) => ({ name: String(r.tool), ...totals(r) }));
|
|
29510
|
+
const kinds = /* @__PURE__ */ new Map();
|
|
29511
|
+
for (const r of raw.prepare(KINDS).all(sessionId)) kinds.set(String(r.kind), { session: Number(r.s), project: Number(r.p) });
|
|
29512
|
+
const meta = raw.prepare(META).get();
|
|
29513
|
+
const span2 = Number(raw.prepare(SPAN).get(sessionId).span);
|
|
29514
|
+
const src = raw.prepare(SOURCES).get();
|
|
29515
|
+
const runs = raw.prepare(REDIRECTED).get(RUN_LABEL_PREFIX.length, RUN_LABEL_PREFIX);
|
|
29516
|
+
const last2 = Math.max(Number(raw.prepare(LAST).get().last), Number(runs.last));
|
|
29517
|
+
const pages = raw.prepare("PRAGMA page_count").get();
|
|
29518
|
+
const size = raw.prepare("PRAGMA page_size").get();
|
|
29519
|
+
return {
|
|
29520
|
+
groups,
|
|
29521
|
+
tools,
|
|
29522
|
+
kinds,
|
|
29523
|
+
span: span2,
|
|
29524
|
+
sessions: Number(meta.sessions),
|
|
29525
|
+
agents: Number(meta.agents),
|
|
29526
|
+
days: Number(meta.days),
|
|
29527
|
+
sources: { count: Number(src.n), chunks: Number(src.chunks), bytes: Number(src.bytes) },
|
|
29528
|
+
dbBytes: Number(pages.page_count) * Number(size.page_size),
|
|
29529
|
+
top: raw.prepare(TOP).all().map((r) => ({ name: String(r.tool), ...totals(r) })),
|
|
29530
|
+
replaced: Number(raw.prepare(REPLACED).get().n),
|
|
29531
|
+
redirected: Number(runs.n),
|
|
29532
|
+
week: readWeek(raw, last2)
|
|
29533
|
+
};
|
|
28983
29534
|
}
|
|
28984
29535
|
function sum(groups) {
|
|
28985
29536
|
return groups.reduce((t, g) => ({
|
|
@@ -28993,23 +29544,225 @@ function reductionPct(t) {
|
|
|
28993
29544
|
if (t.calls === 0) return 0;
|
|
28994
29545
|
return Number((t.saved * PERCENT_SCALE / Math.max(1, t.produced)).toFixed(1));
|
|
28995
29546
|
}
|
|
28996
|
-
function tableRow(
|
|
29547
|
+
function tableRow(label2, t) {
|
|
28997
29548
|
const last2 = t.calls === 0 ? STATS_NO_DATA : String(reductionPct(t));
|
|
28998
|
-
return "| " + [
|
|
29549
|
+
return "| " + [label2, t.produced + " B", t.returned + " B", t.saved + " B", last2].join(" | ") + " |";
|
|
29550
|
+
}
|
|
29551
|
+
var UNITS = ["KB", "MB", "GB", "TB"];
|
|
29552
|
+
var LABEL_W = STATS_LABEL_W;
|
|
29553
|
+
var NUM_W = STATS_NUM_W;
|
|
29554
|
+
var PCT_W = STATS_PCT_W;
|
|
29555
|
+
var INT = new Intl.NumberFormat("en-US", { maximumFractionDigits: 0 });
|
|
29556
|
+
function int2(n) {
|
|
29557
|
+
return INT.format(Math.round(n));
|
|
29558
|
+
}
|
|
29559
|
+
function count(n) {
|
|
29560
|
+
return n < STATS_MILLION ? int2(n) : (n / STATS_MILLION).toFixed(1) + "M";
|
|
29561
|
+
}
|
|
29562
|
+
function bytes4(n) {
|
|
29563
|
+
if (n < 0) return "-" + bytes4(-n);
|
|
29564
|
+
if (n < STATS_KIB) return int2(n) + " B";
|
|
29565
|
+
let v = n / STATS_KIB;
|
|
29566
|
+
let u = 0;
|
|
29567
|
+
while (v >= STATS_KIB && u < UNITS.length - 1) {
|
|
29568
|
+
v /= STATS_KIB;
|
|
29569
|
+
u++;
|
|
29570
|
+
}
|
|
29571
|
+
return v.toFixed(1) + " " + UNITS[u];
|
|
29572
|
+
}
|
|
29573
|
+
function pct(t) {
|
|
29574
|
+
return (t.saved * PERCENT_SCALE / Math.max(1, t.produced)).toFixed(1) + "%";
|
|
29575
|
+
}
|
|
29576
|
+
function bar(value, max, width, fill = "\u2588", rest = "") {
|
|
29577
|
+
const n = value <= 0 || max <= 0 ? 0 : Math.min(width, Math.max(1, Math.round(value / max * width)));
|
|
29578
|
+
return fill.repeat(n) + rest.repeat(width - n);
|
|
29579
|
+
}
|
|
29580
|
+
function label(s) {
|
|
29581
|
+
const chars = [...s];
|
|
29582
|
+
return (chars.length > STATS_LABEL_MAX ? chars.slice(0, STATS_LABEL_MAX - 1).join("") + "\u2026" : s).padEnd(LABEL_W);
|
|
29583
|
+
}
|
|
29584
|
+
function span(ms) {
|
|
29585
|
+
const min = Math.floor(ms / STATS_MS_PER_MINUTE);
|
|
29586
|
+
if (min < 1) return "<1m";
|
|
29587
|
+
if (min < STATS_MINUTES_PER_HOUR) return min + "m";
|
|
29588
|
+
const h = Math.floor(min / STATS_MINUTES_PER_HOUR);
|
|
29589
|
+
return h < STATS_HOURS_PER_DAY ? `${h}h ${String(min % STATS_MINUTES_PER_HOUR).padStart(STATS_CLOCK_DIGITS, "0")}m` : `${Math.floor(h / STATS_HOURS_PER_DAY)}d ${h % STATS_HOURS_PER_DAY}h`;
|
|
29590
|
+
}
|
|
29591
|
+
function plural(n, word) {
|
|
29592
|
+
return `${int2(n)} ${word}${n === 1 ? "" : "s"}`;
|
|
29593
|
+
}
|
|
29594
|
+
function table2(title, rows) {
|
|
29595
|
+
const max = Math.max(0, ...rows.map((r) => r.saved));
|
|
29596
|
+
const head = " " + title.padEnd(LABEL_W) + "Calls".padStart(STATS_CALLS_W) + "Made".padStart(NUM_W) + "Sent".padStart(NUM_W) + "Kept out".padStart(NUM_W) + "%".padStart(PCT_W);
|
|
29597
|
+
return [head, ...rows.map((r) => (" " + label(r.name) + count(r.calls).padStart(STATS_CALLS_W) + bytes4(r.produced).padStart(NUM_W) + bytes4(r.returned).padStart(NUM_W) + bytes4(r.saved).padStart(NUM_W) + pct(r).padStart(PCT_W) + " " + bar(r.saved, max, STATS_ROW_BAR)).trimEnd())];
|
|
29598
|
+
}
|
|
29599
|
+
function bySaved(a, b) {
|
|
29600
|
+
return b.saved - a.saved || b.produced - a.produced || a.returned - b.returned || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
29601
|
+
}
|
|
29602
|
+
function toolName(tool) {
|
|
29603
|
+
return tool.startsWith("ctx_") ? tool : "hook " + tool;
|
|
29604
|
+
}
|
|
29605
|
+
function joinIndex(tools) {
|
|
29606
|
+
const idx = tools.filter((t2) => STATS_INDEX_TOOLS.includes(t2.name));
|
|
29607
|
+
if (idx.length <= 1) return tools;
|
|
29608
|
+
const t = sum(idx);
|
|
29609
|
+
const one = { name: STATS_INDEX_TOOLS.join(" + ").replace(" + ctx_", " + "), ...t, saved: t.produced - t.returned };
|
|
29610
|
+
return [...tools.filter((x) => !idx.includes(x)), one];
|
|
29611
|
+
}
|
|
29612
|
+
function toolRows(tools) {
|
|
29613
|
+
const named = joinIndex(tools.map((t) => ({ ...t, saved: t.produced - t.returned }))).map((t) => ({ ...t, name: toolName(t.name) })).sort(bySaved);
|
|
29614
|
+
const zero = named.filter((t) => t.saved <= 0);
|
|
29615
|
+
const fold2 = zero.length > 1 ? zero : [];
|
|
29616
|
+
const keep = named.filter((t) => !fold2.includes(t));
|
|
29617
|
+
const room = fold2.length > 0 ? STATS_MAX_TOOL_ROWS - 1 : STATS_MAX_TOOL_ROWS;
|
|
29618
|
+
const over = keep.length > room;
|
|
29619
|
+
const shown2 = over ? keep.slice(0, STATS_MAX_TOOL_ROWS - 1) : keep;
|
|
29620
|
+
const rest = over ? [...keep.slice(STATS_MAX_TOOL_ROWS - 1), ...fold2] : fold2;
|
|
29621
|
+
return rest.length === 0 ? shown2 : [...shown2, { name: `other (${plural(rest.length, "tool")})`, ...sum(rest) }];
|
|
29622
|
+
}
|
|
29623
|
+
var TOKEN_UNITS = ["K", "M", "B", "T"];
|
|
29624
|
+
function whole(v) {
|
|
29625
|
+
return v >= STATS_WHOLE_FROM ? int2(v) : v.toFixed(1);
|
|
29626
|
+
}
|
|
29627
|
+
function tokens(n) {
|
|
29628
|
+
if (n < STATS_THOUSAND) return int2(n);
|
|
29629
|
+
let v = n / STATS_THOUSAND;
|
|
29630
|
+
let u = 0;
|
|
29631
|
+
while (v >= STATS_THOUSAND && u < TOKEN_UNITS.length - 1) {
|
|
29632
|
+
v /= STATS_THOUSAND;
|
|
29633
|
+
u++;
|
|
29634
|
+
}
|
|
29635
|
+
return whole(v) + TOKEN_UNITS[u];
|
|
29636
|
+
}
|
|
29637
|
+
function windowLine(saved) {
|
|
29638
|
+
const t = saved / STATS_BYTES_PER_TOKEN;
|
|
29639
|
+
const share = t / STATS_WINDOW_TOKENS;
|
|
29640
|
+
const win = `a ${tokens(STATS_WINDOW_TOKENS)} window`;
|
|
29641
|
+
const head = ` about ${tokens(t)} tokens kept out`;
|
|
29642
|
+
if (share >= 1) return `${head}, ${whole(share)} times ${win}`;
|
|
29643
|
+
const p = share * PERCENT_SCALE;
|
|
29644
|
+
return p * STATS_WHOLE_FROM < 1 ? head : `${head}, ${whole(p)}% of ${win}`;
|
|
29645
|
+
}
|
|
29646
|
+
function ymd(day) {
|
|
29647
|
+
return new Date(day * MS_PER_DAY).toISOString().slice(0, "yyyy-mm-dd".length);
|
|
29648
|
+
}
|
|
29649
|
+
function mmdd(day) {
|
|
29650
|
+
return ymd(day).slice("yyyy-".length);
|
|
29651
|
+
}
|
|
29652
|
+
function stack(parts, max, width) {
|
|
29653
|
+
let total = 0;
|
|
29654
|
+
let at2 = 0;
|
|
29655
|
+
let out = "";
|
|
29656
|
+
parts.forEach((v, i) => {
|
|
29657
|
+
total += v;
|
|
29658
|
+
const end = max <= 0 ? 0 : Math.round(total / max * width);
|
|
29659
|
+
if (end > at2) {
|
|
29660
|
+
out += STATS_WAYS[i][1].repeat(end - at2);
|
|
29661
|
+
at2 = end;
|
|
29662
|
+
}
|
|
29663
|
+
});
|
|
29664
|
+
if (out === "" && total > 0) out = STATS_WAYS[parts.indexOf(Math.max(...parts))][1];
|
|
29665
|
+
return out;
|
|
29666
|
+
}
|
|
29667
|
+
function cards(cells) {
|
|
29668
|
+
return (" " + cells.map((c) => c.padEnd(STATS_CARD_W)).join("")).trimEnd();
|
|
29669
|
+
}
|
|
29670
|
+
function lastDays(week, allCalls) {
|
|
29671
|
+
const saved = week.map((d) => STATS_WAYS.reduce((t, [w]) => t + d.ways[w], 0));
|
|
29672
|
+
const all = saved.reduce((a, b) => a + b, 0);
|
|
29673
|
+
const calls = week.reduce((a, d) => a + d.calls, 0);
|
|
29674
|
+
const max = Math.max(0, ...saved);
|
|
29675
|
+
const head = `Last ${STATS_DAYS} days of use \xB7 ${ymd(week[0].day)} to ${ymd(week[week.length - 1].day)}`;
|
|
29676
|
+
const card = calls < allCalls ? [
|
|
29677
|
+
cards(["Kept out", "Tokens kept out", "Calls", "Kept out per call"]),
|
|
29678
|
+
cards([bytes4(all), "about " + tokens(all / STATS_BYTES_PER_TOKEN), count(calls), bytes4(calls > 0 ? all / calls : 0)]),
|
|
29679
|
+
""
|
|
29680
|
+
] : [];
|
|
29681
|
+
return [
|
|
29682
|
+
head,
|
|
29683
|
+
...card,
|
|
29684
|
+
...week.flatMap((d, i) => saved[i] > 0 ? [" " + mmdd(d.day) + " " + stack(STATS_WAYS.map(([w]) => d.ways[w]), max, STATS_DAY_BAR).padEnd(STATS_DAY_BAR) + bytes4(saved[i]).padStart(NUM_W)] : []),
|
|
29685
|
+
" " + STATS_WAYS.map(([, ch, name]) => `${ch} ${name}`).join(" "),
|
|
29686
|
+
""
|
|
29687
|
+
];
|
|
29688
|
+
}
|
|
29689
|
+
function hookLine(redirected, replaced) {
|
|
29690
|
+
const all = redirected + replaced;
|
|
29691
|
+
if (all === 0) return [];
|
|
29692
|
+
const parts = [...redirected > 0 ? [`${int2(redirected)} sent to the sandbox`] : [], ...replaced > 0 ? [`${int2(replaced)} cut down`] : []];
|
|
29693
|
+
const what = plural(all, "large output");
|
|
29694
|
+
return [parts.length === 1 ? ` Project hooks: ${what} ${parts[0].replace(/^[\d,]+ /, "")}` : ` Project hooks: ${what} kept out \xB7 ${parts.join(", ")}`];
|
|
29695
|
+
}
|
|
29696
|
+
function fit(line) {
|
|
29697
|
+
const chars = [...line];
|
|
29698
|
+
return chars.length <= STATS_WIDTH ? line : chars.slice(0, STATS_WIDTH - 1).join("") + "\u2026";
|
|
29699
|
+
}
|
|
29700
|
+
function report(f, sessionId, agent) {
|
|
29701
|
+
const head = [STATS_REPORT_TITLE, "\u2500".repeat(STATS_WIDTH), ""];
|
|
29702
|
+
const project = sum(f.groups);
|
|
29703
|
+
if (project.calls === 0) return [...head, ...STATS_EMPTY_LINES].join("\n");
|
|
29704
|
+
const session = sum(f.groups.filter((g) => g.session === sessionId));
|
|
29705
|
+
const [scopeName, focus] = session.calls > 0 ? ["This session", session] : ["This project", project];
|
|
29706
|
+
const top = Math.max(focus.produced, focus.returned);
|
|
29707
|
+
const extra = session.calls > 0 ? ` \xB7 ${span(f.span)} active` : "";
|
|
29708
|
+
const lines = [
|
|
29709
|
+
...head,
|
|
29710
|
+
`${scopeName} \xB7 ${plural(focus.calls, "call")}${extra}`,
|
|
29711
|
+
` ${bytes4(focus.produced)} became ${bytes4(focus.returned)}: ${bytes4(focus.saved)} kept out (${pct(focus)})`,
|
|
29712
|
+
" " + "Without context-mode".padEnd(LABEL_W) + "|" + bar(focus.produced, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + bytes4(focus.produced).padStart(NUM_W),
|
|
29713
|
+
" " + "With context-mode".padEnd(LABEL_W) + "|" + bar(focus.returned, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + bytes4(focus.returned).padStart(NUM_W),
|
|
29714
|
+
...focus.saved > 0 ? [windowLine(focus.saved), STATS_TOKEN_NOTE] : [],
|
|
29715
|
+
...hookLine(f.redirected, f.replaced),
|
|
29716
|
+
"",
|
|
29717
|
+
...lastDays(f.week, project.calls + f.redirected),
|
|
29718
|
+
// D-STATS-FIX-1 (5): one DB per project holds every session of it, so project and all-time are one row.
|
|
29719
|
+
"By scope",
|
|
29720
|
+
...table2("Scope", [{ name: "session", ...session }, { name: "project (all-time)", ...project }]),
|
|
29721
|
+
"",
|
|
29722
|
+
"By tool (this project)",
|
|
29723
|
+
...table2("Tool", toolRows(f.tools)),
|
|
29724
|
+
"",
|
|
29725
|
+
...f.top.length > 0 ? [
|
|
29726
|
+
"Largest single outputs (made \u2192 sent to the chat)",
|
|
29727
|
+
...f.top.map((t) => " " + label(toolName(t.name)) + bytes4(t.produced).padStart(NUM_W) + " \u2192 " + bytes4(t.returned).padStart(NUM_W)),
|
|
29728
|
+
""
|
|
29729
|
+
] : []
|
|
29730
|
+
];
|
|
29731
|
+
const agents = /* @__PURE__ */ new Map();
|
|
29732
|
+
for (const g of f.groups) agents.set(g.agent, sum([agents.get(g.agent) ?? EMPTY5, g]));
|
|
29733
|
+
if (!agents.has(agent)) agents.set(agent, EMPTY5);
|
|
29734
|
+
lines.push("By agent (this project)", ...table2("Agent", [...agents].map(([name, t]) => ({ name, ...t })).sort(bySaved)), "");
|
|
29735
|
+
const maxKind = Math.max(0, ...[...f.kinds.values()].map((k) => k.project));
|
|
29736
|
+
lines.push("Kept in the session journal", " " + "Journal".padEnd(LABEL_W) + "Session".padStart(STATS_KIND_W) + "Project".padStart(STATS_KIND_W));
|
|
29737
|
+
for (const [kind, name] of STATS_KIND_LABELS) {
|
|
29738
|
+
const k = f.kinds.get(kind) ?? { session: 0, project: 0 };
|
|
29739
|
+
lines.push((" " + label(name) + int2(k.session).padStart(STATS_KIND_W) + int2(k.project).padStart(STATS_KIND_W) + " " + bar(k.project, maxKind, STATS_KIND_BAR)).trimEnd());
|
|
29740
|
+
}
|
|
29741
|
+
lines.push("", ...STATS_JOURNAL_HINTS.map((h) => " " + h), "");
|
|
29742
|
+
lines.push(
|
|
29743
|
+
" " + "Index and search".padEnd(LABEL_W) + `${plural(f.sources.count, "source")} \xB7 ${plural(f.sources.chunks, "chunk")} \xB7 ${bytes4(f.sources.bytes)} \xB7 ${plural(f.tools.find((t) => t.name === "ctx_search")?.calls ?? 0, "ctx_search call")}`,
|
|
29744
|
+
" " + "Database file".padEnd(LABEL_W) + bytes4(f.dbBytes),
|
|
29745
|
+
" " + "Sessions".padEnd(LABEL_W) + `${int2(f.sessions)} \xB7 agents ${int2(f.agents)} \xB7 active days ${int2(f.days)}`,
|
|
29746
|
+
"",
|
|
29747
|
+
STATS_FOOTER_URL,
|
|
29748
|
+
"github.com/" + ISSUE_REPO_SLUG
|
|
29749
|
+
);
|
|
29750
|
+
return lines.map(fit).join("\n");
|
|
28999
29751
|
}
|
|
29000
29752
|
async function handler7(_input, ctx) {
|
|
29001
29753
|
const db = await openDb(ctx.project, { readOnly: true });
|
|
29002
|
-
let
|
|
29754
|
+
let facts;
|
|
29003
29755
|
try {
|
|
29004
|
-
|
|
29756
|
+
facts = readFacts(db.raw, ctx.sessionId);
|
|
29005
29757
|
} finally {
|
|
29006
29758
|
closeDb(db);
|
|
29007
29759
|
}
|
|
29760
|
+
const groups = facts.groups;
|
|
29008
29761
|
const session = sum(groups.filter((g) => g.session === ctx.sessionId));
|
|
29009
29762
|
const project = sum(groups);
|
|
29010
29763
|
const allTime = project;
|
|
29011
29764
|
const agentIds = [.../* @__PURE__ */ new Set([...groups.map((g) => g.agent), ctx.project.agent])].sort();
|
|
29012
|
-
const
|
|
29765
|
+
const mdTable = [
|
|
29013
29766
|
"| " + STATS_COLUMNS.join(" | ") + " |",
|
|
29014
29767
|
"|" + STATS_COLUMNS.map(() => "---").join("|") + "|",
|
|
29015
29768
|
tableRow("session", session),
|
|
@@ -29018,7 +29771,8 @@ async function handler7(_input, ctx) {
|
|
|
29018
29771
|
...agentIds.map((a) => tableRow("agent " + a, sum(groups.filter((g) => g.agent === a))))
|
|
29019
29772
|
].join("\n");
|
|
29020
29773
|
const summary = STATS_SUMMARY(reductionPct(allTime), reductionPct(session));
|
|
29021
|
-
|
|
29774
|
+
const text = summary + "\n\n```text\n" + report(facts, ctx.sessionId, ctx.project.agent) + "\n```\n\n" + mdTable;
|
|
29775
|
+
return { text: capBytes(text, OUTPUT_CAP).text, isError: false, sandboxBytes: 0 };
|
|
29022
29776
|
}
|
|
29023
29777
|
var ctxStats = Object.freeze({
|
|
29024
29778
|
name: "ctx_stats",
|
|
@@ -29029,28 +29783,28 @@ var ctxStats = Object.freeze({
|
|
|
29029
29783
|
});
|
|
29030
29784
|
|
|
29031
29785
|
// src/core/tools/upgrade.ts
|
|
29032
|
-
import { existsSync as
|
|
29033
|
-
import { basename as basename6, dirname as dirname11, join as
|
|
29786
|
+
import { existsSync as existsSync21, realpathSync as realpathSync10, rmSync as rmSync9 } from "node:fs";
|
|
29787
|
+
import { basename as basename6, dirname as dirname11, join as join24 } from "node:path";
|
|
29034
29788
|
|
|
29035
29789
|
// src/core/ops/host-write.ts
|
|
29036
|
-
import { copyFileSync, existsSync as
|
|
29037
|
-
import { dirname as dirname10, join as
|
|
29790
|
+
import { copyFileSync, existsSync as existsSync16, mkdirSync as mkdirSync6, writeFileSync as writeFileSync5 } from "node:fs";
|
|
29791
|
+
import { dirname as dirname10, join as join19 } from "node:path";
|
|
29038
29792
|
function defaultWrite(file2, text) {
|
|
29039
|
-
|
|
29793
|
+
writeFileSync5(file2, text, "utf8");
|
|
29040
29794
|
}
|
|
29041
29795
|
function hostConfigPath(agent, home, env) {
|
|
29042
29796
|
const own2 = OWN_MCP_ENTRY[agent];
|
|
29043
29797
|
if (own2 !== void 0) return ownMcpFileOf(agent, own2.file, env, home);
|
|
29044
29798
|
switch (agent) {
|
|
29045
29799
|
case "opencode":
|
|
29046
|
-
return
|
|
29800
|
+
return join19(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
|
|
29047
29801
|
// D-WIN-OPENCODE-DIR-1
|
|
29048
29802
|
case "pi":
|
|
29049
|
-
return
|
|
29803
|
+
return join19(piAgentDirOf(env, home), SETTINGS_FILE);
|
|
29050
29804
|
case "copilot-cli":
|
|
29051
29805
|
return null;
|
|
29052
29806
|
default:
|
|
29053
|
-
return
|
|
29807
|
+
return join19(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
|
|
29054
29808
|
}
|
|
29055
29809
|
}
|
|
29056
29810
|
function cell3(value) {
|
|
@@ -29062,8 +29816,8 @@ function toRow(file2, edit) {
|
|
|
29062
29816
|
function writeWithRollback(file2, text, write2, atomic) {
|
|
29063
29817
|
const trash = file2 + UPGRADE_TRASH_SUFFIX;
|
|
29064
29818
|
const tmp = `${file2}${HOST_CONFIG_TMP_SUFFIX}.${process.pid}`;
|
|
29065
|
-
const had =
|
|
29066
|
-
|
|
29819
|
+
const had = existsSync16(file2);
|
|
29820
|
+
mkdirSync6(dirname10(file2), { recursive: true });
|
|
29067
29821
|
if (had) copyFileSync(file2, trash);
|
|
29068
29822
|
try {
|
|
29069
29823
|
write2(tmp, text);
|
|
@@ -29092,7 +29846,7 @@ function regenerateHostConfig(row5, home, opts = {}) {
|
|
|
29092
29846
|
if (requested === null) return [];
|
|
29093
29847
|
const current = readHostConfig(row5.id, requested);
|
|
29094
29848
|
const result = mergeOwnEntries(row5.id, current.text, current.format, row5);
|
|
29095
|
-
const exists =
|
|
29849
|
+
const exists = existsSync16(current.path);
|
|
29096
29850
|
if (exists && result.text === current.text) return [];
|
|
29097
29851
|
const text = result.text === "" && current.format !== "toml" ? JSON.stringify({}) : result.text;
|
|
29098
29852
|
writeWithRollback(current.path, current.layout === void 0 ? text : withLayout(text, current.layout), opts.write ?? defaultWrite, opts.atomic ?? {});
|
|
@@ -29100,8 +29854,8 @@ function regenerateHostConfig(row5, home, opts = {}) {
|
|
|
29100
29854
|
}
|
|
29101
29855
|
|
|
29102
29856
|
// src/core/ops/plugin-swap.ts
|
|
29103
|
-
import { existsSync as
|
|
29104
|
-
import { basename as basename5, join as
|
|
29857
|
+
import { existsSync as existsSync17, lstatSync, readdirSync as readdirSync7, readlinkSync, rmSync as rmSync5, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
|
|
29858
|
+
import { basename as basename5, join as join20, win32 as win322 } from "node:path";
|
|
29105
29859
|
function linkTarget(path7, win) {
|
|
29106
29860
|
if (!isLink(path7)) return null;
|
|
29107
29861
|
const target = readlinkSync(path7);
|
|
@@ -29120,11 +29874,11 @@ function settleLinks(link, tmp, old, opts) {
|
|
|
29120
29874
|
else renameWithRetry(old, link, opts);
|
|
29121
29875
|
}
|
|
29122
29876
|
function swapPluginCurrent(agentDir, sha, opts = {}) {
|
|
29123
|
-
const next =
|
|
29124
|
-
if (!
|
|
29877
|
+
const next = join20(agentDir, sha);
|
|
29878
|
+
if (!existsSync17(next) || !lstatSync(next).isDirectory()) {
|
|
29125
29879
|
throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename5(agentDir), path: next });
|
|
29126
29880
|
}
|
|
29127
|
-
const link =
|
|
29881
|
+
const link = join20(agentDir, PLUGIN_CURRENT_LINK);
|
|
29128
29882
|
const tmp = link + PLUGIN_LINK_TMP_SUFFIX;
|
|
29129
29883
|
const old = link + PLUGIN_LINK_OLD_SUFFIX;
|
|
29130
29884
|
settleLinks(link, tmp, old, opts);
|
|
@@ -29139,15 +29893,15 @@ function swapPluginCurrent(agentDir, sha, opts = {}) {
|
|
|
29139
29893
|
if (before !== null) unlinkSync2(old);
|
|
29140
29894
|
const keep = /* @__PURE__ */ new Set([sha]);
|
|
29141
29895
|
if (before !== null) keep.add(before);
|
|
29142
|
-
const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) =>
|
|
29896
|
+
const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join20(agentDir, name));
|
|
29143
29897
|
for (const dir of removed) rmSync5(dir, { recursive: true, force: true });
|
|
29144
|
-
const previous = before !== null &&
|
|
29898
|
+
const previous = before !== null && existsSync17(join20(agentDir, before)) ? join20(agentDir, before) : null;
|
|
29145
29899
|
return { current: next, previous, removed };
|
|
29146
29900
|
}
|
|
29147
29901
|
|
|
29148
29902
|
// src/core/ops/release-fetch.ts
|
|
29149
|
-
import { existsSync as
|
|
29150
|
-
import { join as
|
|
29903
|
+
import { existsSync as existsSync18, mkdirSync as mkdirSync7, rmSync as rmSync6 } from "node:fs";
|
|
29904
|
+
import { join as join21 } from "node:path";
|
|
29151
29905
|
function failed(r) {
|
|
29152
29906
|
if (r.exitCode === null && r.killed === null) return new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
|
|
29153
29907
|
const status = r.killed ?? String(r.exitCode);
|
|
@@ -29159,9 +29913,9 @@ async function git2(bin, args, cwd, env, signal) {
|
|
|
29159
29913
|
return r.stdout.toString().trim();
|
|
29160
29914
|
}
|
|
29161
29915
|
async function fetchRelease(agent, url2, env, signal, opts = {}) {
|
|
29162
|
-
const agentDir =
|
|
29163
|
-
|
|
29164
|
-
const fetchDir =
|
|
29916
|
+
const agentDir = join21(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, agent);
|
|
29917
|
+
mkdirSync7(agentDir, { recursive: true });
|
|
29918
|
+
const fetchDir = join21(agentDir, UPGRADE_FETCH_DIR_PREFIX + process.pid);
|
|
29165
29919
|
rmSync6(fetchDir, { recursive: true, force: true });
|
|
29166
29920
|
const gitBin = findRuntime(GIT_BIN, env);
|
|
29167
29921
|
if (gitBin === null) throw new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
|
|
@@ -29169,8 +29923,8 @@ async function fetchRelease(agent, url2, env, signal, opts = {}) {
|
|
|
29169
29923
|
try {
|
|
29170
29924
|
await git2(gitBin, [...GIT_CLONE_ARGS, RELEASE_BRANCH, url2, fetchDir], agentDir, childEnv, signal);
|
|
29171
29925
|
const sha = await git2(gitBin, GIT_HEAD_SHA_ARGS, fetchDir, childEnv, signal);
|
|
29172
|
-
const dir =
|
|
29173
|
-
if (
|
|
29926
|
+
const dir = join21(agentDir, sha);
|
|
29927
|
+
if (existsSync18(dir)) rmSync6(fetchDir, { recursive: true, force: true });
|
|
29174
29928
|
else renameWithRetry(fetchDir, dir, opts);
|
|
29175
29929
|
return { sha, dir };
|
|
29176
29930
|
} catch (e) {
|
|
@@ -29180,15 +29934,15 @@ async function fetchRelease(agent, url2, env, signal, opts = {}) {
|
|
|
29180
29934
|
}
|
|
29181
29935
|
|
|
29182
29936
|
// src/core/ops/uninstall.ts
|
|
29183
|
-
import { existsSync as
|
|
29184
|
-
import { join as
|
|
29937
|
+
import { existsSync as existsSync19, readdirSync as readdirSync8, rmSync as rmSync7, writeFileSync as writeFileSync6 } from "node:fs";
|
|
29938
|
+
import { join as join22 } from "node:path";
|
|
29185
29939
|
function row2(area, before, after) {
|
|
29186
29940
|
return { area, before, after };
|
|
29187
29941
|
}
|
|
29188
29942
|
function stopServers(configDir, projectKey) {
|
|
29189
29943
|
const stopped = listLiveOwners(configDir, projectKey);
|
|
29190
|
-
const dir =
|
|
29191
|
-
for (const serverId of stopped)
|
|
29944
|
+
const dir = join22(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
|
|
29945
|
+
for (const serverId of stopped) writeFileSync6(join22(dir, serverId + OWNER_STOP_EXT), "", "utf8");
|
|
29192
29946
|
return stopped.length === 0 ? { row: row2(UPGRADE_SERVER_AREA, "", UPGRADE_NOT_FOUND), stopped } : { row: row2(UPGRADE_SERVER_AREA, UPGRADE_SERVER_RUNNING, UPGRADE_SERVER_STOPPED), stopped };
|
|
29193
29947
|
}
|
|
29194
29948
|
function rootOrNull(adapter, env) {
|
|
@@ -29206,15 +29960,15 @@ function removeCache(adapter, env, configDir) {
|
|
|
29206
29960
|
const root = rootOrNull(adapter, env);
|
|
29207
29961
|
if (root === null) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
|
|
29208
29962
|
if (adapter.installMode === "marketplace") {
|
|
29209
|
-
const cache =
|
|
29963
|
+
const cache = join22(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
|
|
29210
29964
|
if (!isInside(cache, root) || isInside(root, cache)) return row2(UPGRADE_CACHE_AREA, root, UPGRADE_CACHE_BY_HAND);
|
|
29211
29965
|
}
|
|
29212
29966
|
rmSync7(root, { recursive: true, force: true });
|
|
29213
29967
|
return row2(UPGRADE_CACHE_AREA, root, UPGRADE_REMOVED);
|
|
29214
29968
|
}
|
|
29215
29969
|
case "plugin": {
|
|
29216
|
-
const agentDir =
|
|
29217
|
-
if (!
|
|
29970
|
+
const agentDir = join22(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
|
|
29971
|
+
if (!existsSync19(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
|
|
29218
29972
|
rmSync7(agentDir, { recursive: true, force: true });
|
|
29219
29973
|
return row2(UPGRADE_CACHE_AREA, agentDir, UPGRADE_REMOVED);
|
|
29220
29974
|
}
|
|
@@ -29259,7 +30013,7 @@ function ownEntries(agent, env) {
|
|
|
29259
30013
|
}
|
|
29260
30014
|
if (agent === "opencode") {
|
|
29261
30015
|
return [{
|
|
29262
|
-
file:
|
|
30016
|
+
file: join22(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
|
|
29263
30017
|
// D-WIN-OPENCODE-DIR-1
|
|
29264
30018
|
key: OPENCODE_PLUGIN_KEY,
|
|
29265
30019
|
shown: OPENCODE_PLUGIN_KEY,
|
|
@@ -29270,7 +30024,7 @@ function ownEntries(agent, env) {
|
|
|
29270
30024
|
if (agent === "pi") {
|
|
29271
30025
|
const agentDir = piAgentDirOf(env, home);
|
|
29272
30026
|
return [{
|
|
29273
|
-
file:
|
|
30027
|
+
file: join22(agentDir, SETTINGS_FILE),
|
|
29274
30028
|
key: PI_PACKAGES_KEY,
|
|
29275
30029
|
shown: PI_PACKAGES_KEY,
|
|
29276
30030
|
has: (v) => Array.isArray(v) && v.some((x) => piSource(x) === PI_GIT_PACKAGE),
|
|
@@ -29292,12 +30046,12 @@ function removeOwnEntries(agent, env) {
|
|
|
29292
30046
|
return rows.length === 0 ? [row2(UPGRADE_CONFIG_AREA, "", UPGRADE_NOT_FOUND)] : rows;
|
|
29293
30047
|
}
|
|
29294
30048
|
function removeProjectData(configDir, projectKey) {
|
|
29295
|
-
const projects =
|
|
29296
|
-
const dir =
|
|
29297
|
-
if (!
|
|
30049
|
+
const projects = join22(configDir, PROJECTS_DIR_NAME);
|
|
30050
|
+
const dir = join22(projects, projectKey);
|
|
30051
|
+
if (!existsSync19(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
|
|
29298
30052
|
if (dir === projects || !isInside(projects, dir)) throw new CtxError("OUTSIDE_ROOT", { p: dir, root: projects });
|
|
29299
30053
|
for (const name of readdirSync8(dir)) {
|
|
29300
|
-
if (name !== OWNERS_DIR_NAME) rmSync7(
|
|
30054
|
+
if (name !== OWNERS_DIR_NAME) rmSync7(join22(dir, name), { recursive: true, force: true });
|
|
29301
30055
|
}
|
|
29302
30056
|
return row2(UPGRADE_DATA_AREA, dir, UPGRADE_DATA_DELETED);
|
|
29303
30057
|
}
|
|
@@ -29305,12 +30059,12 @@ function runUninstall(input) {
|
|
|
29305
30059
|
const configDir = resolveConfigDir(input.env);
|
|
29306
30060
|
const stop = stopServers(configDir, input.project.projectKey);
|
|
29307
30061
|
const rows = [stop.row, removeCache(input.adapter, input.env, configDir), ...removeOwnEntries(input.adapter.id, input.env)];
|
|
29308
|
-
rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA,
|
|
30062
|
+
rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join22(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
|
|
29309
30063
|
return { rows, stopped: stop.stopped };
|
|
29310
30064
|
}
|
|
29311
30065
|
|
|
29312
30066
|
// src/core/ops/v1-remove.ts
|
|
29313
|
-
import { copyFileSync as copyFileSync2, existsSync as
|
|
30067
|
+
import { copyFileSync as copyFileSync2, existsSync as existsSync20, readFileSync as readFileSync16, rmSync as rmSync8 } from "node:fs";
|
|
29314
30068
|
var isObj4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
29315
30069
|
var areaOf = (f) => f.path === "" ? f.file : f.file + UPGRADE_AREA_KEY_SEP + f.path;
|
|
29316
30070
|
var row3 = (f, after) => ({ area: areaOf(f), before: f.reason, after });
|
|
@@ -29329,13 +30083,13 @@ function keepOriginal(file2, kept, undo) {
|
|
|
29329
30083
|
undo.push({ trash, target: file2 });
|
|
29330
30084
|
}
|
|
29331
30085
|
function cutTomlTable(text, header) {
|
|
29332
|
-
let
|
|
30086
|
+
let span2;
|
|
29333
30087
|
try {
|
|
29334
|
-
|
|
30088
|
+
span2 = tomlTableSpans(text).find((t) => t.header.trim() === header);
|
|
29335
30089
|
} catch {
|
|
29336
30090
|
return null;
|
|
29337
30091
|
}
|
|
29338
|
-
return
|
|
30092
|
+
return span2 === void 0 ? null : text.slice(0, span2.start) + text.slice(span2.end);
|
|
29339
30093
|
}
|
|
29340
30094
|
function writeAtomic(file2, text) {
|
|
29341
30095
|
atomicWriteFile(file2, text);
|
|
@@ -29354,8 +30108,8 @@ function locate(doc, path7) {
|
|
|
29354
30108
|
return null;
|
|
29355
30109
|
}
|
|
29356
30110
|
function stripJsonEntries(agent, file2, findings, kept, undo) {
|
|
29357
|
-
const layout = hostLayout(
|
|
29358
|
-
const text = hostText(
|
|
30111
|
+
const layout = hostLayout(readFileSync16(file2, "utf8"));
|
|
30112
|
+
const text = hostText(readFileSync16(file2, "utf8"));
|
|
29359
30113
|
const doc = parseHostConfig(agent, file2, text, "jsonc");
|
|
29360
30114
|
const hit = /* @__PURE__ */ new Set();
|
|
29361
30115
|
const byContainer = /* @__PURE__ */ new Map();
|
|
@@ -29391,19 +30145,19 @@ function removeV1(agent, findings) {
|
|
|
29391
30145
|
for (const f of findings) {
|
|
29392
30146
|
if (UPGRADE_REPORT_ONLY_REASONS.includes(f.reason)) done.set(f, UPGRADE_REPORT_ONLY);
|
|
29393
30147
|
else if (f.path === "") {
|
|
29394
|
-
if (
|
|
30148
|
+
if (existsSync20(f.file)) {
|
|
29395
30149
|
moveAside(f.file, undo);
|
|
29396
30150
|
done.set(f, UPGRADE_REMOVED);
|
|
29397
30151
|
} else done.set(f, UPGRADE_NOT_FOUND);
|
|
29398
30152
|
} else entries.set(f.file, [...entries.get(f.file) ?? [], f]);
|
|
29399
30153
|
}
|
|
29400
30154
|
for (const [file2, list4] of entries) {
|
|
29401
|
-
if (!
|
|
30155
|
+
if (!existsSync20(file2)) {
|
|
29402
30156
|
for (const f of list4) done.set(f, UPGRADE_NOT_FOUND);
|
|
29403
30157
|
continue;
|
|
29404
30158
|
}
|
|
29405
30159
|
if (file2.endsWith(TOML_EXT)) {
|
|
29406
|
-
const rawToml =
|
|
30160
|
+
const rawToml = readFileSync16(file2, "utf8");
|
|
29407
30161
|
const tomlLayout = hostLayout(rawToml);
|
|
29408
30162
|
let text = hostText(rawToml);
|
|
29409
30163
|
for (const f of list4) {
|
|
@@ -29431,7 +30185,7 @@ function removeV1(agent, findings) {
|
|
|
29431
30185
|
},
|
|
29432
30186
|
rollback() {
|
|
29433
30187
|
for (const u of undo.splice(0).reverse()) {
|
|
29434
|
-
if (!
|
|
30188
|
+
if (!existsSync20(u.trash)) continue;
|
|
29435
30189
|
rmSync8(u.target, { recursive: true, force: true });
|
|
29436
30190
|
renameWithRetry(u.trash, u.target);
|
|
29437
30191
|
}
|
|
@@ -29441,8 +30195,8 @@ function removeV1(agent, findings) {
|
|
|
29441
30195
|
|
|
29442
30196
|
// src/core/ops/verify-sums.ts
|
|
29443
30197
|
import { createHash as createHash2 } from "node:crypto";
|
|
29444
|
-
import { lstatSync as lstatSync2, readdirSync as readdirSync9, readFileSync as
|
|
29445
|
-
import { join as
|
|
30198
|
+
import { lstatSync as lstatSync2, readdirSync as readdirSync9, readFileSync as readFileSync17 } from "node:fs";
|
|
30199
|
+
import { join as join23 } from "node:path";
|
|
29446
30200
|
function mismatch() {
|
|
29447
30201
|
return new CtxError("BUNDLE_HASH_MISMATCH");
|
|
29448
30202
|
}
|
|
@@ -29463,24 +30217,24 @@ function walk3(dir, prefix, out) {
|
|
|
29463
30217
|
for (const entry of readdirSync9(dir, { withFileTypes: true })) {
|
|
29464
30218
|
const rel = prefix === "" ? entry.name : prefix + "/" + entry.name;
|
|
29465
30219
|
if (prefix === "" && (entry.name === GIT_DIR_NAME || entry.name === RELEASE_SUMS_FILE)) continue;
|
|
29466
|
-
const abs =
|
|
30220
|
+
const abs = join23(dir, entry.name);
|
|
29467
30221
|
if (entry.isDirectory()) walk3(abs, rel, out);
|
|
29468
30222
|
else if (entry.isFile()) out.set(rel, abs);
|
|
29469
30223
|
else throw mismatch();
|
|
29470
30224
|
}
|
|
29471
30225
|
}
|
|
29472
30226
|
function verifySums(dir) {
|
|
29473
|
-
const sumsPath =
|
|
30227
|
+
const sumsPath = join23(dir, RELEASE_SUMS_FILE);
|
|
29474
30228
|
const sumsStat = lstatSync2(sumsPath, { throwIfNoEntry: false });
|
|
29475
30229
|
if (sumsStat === void 0 || !sumsStat.isFile()) throw mismatch();
|
|
29476
|
-
const sums = parseSums(
|
|
30230
|
+
const sums = parseSums(readFileSync17(sumsPath, "utf8"));
|
|
29477
30231
|
const files = /* @__PURE__ */ new Map();
|
|
29478
30232
|
walk3(dir, "", files);
|
|
29479
30233
|
if (files.size !== sums.size) throw mismatch();
|
|
29480
30234
|
for (const [rel, abs] of files) {
|
|
29481
30235
|
const want = sums.get(rel);
|
|
29482
30236
|
if (want === void 0) throw mismatch();
|
|
29483
|
-
const got = createHash2(SUMS_HASH_ALGORITHM).update(
|
|
30237
|
+
const got = createHash2(SUMS_HASH_ALGORITHM).update(readFileSync17(abs)).digest(HASH_ENCODING);
|
|
29484
30238
|
if (got !== want) throw mismatch();
|
|
29485
30239
|
}
|
|
29486
30240
|
}
|
|
@@ -29508,8 +30262,8 @@ function pluginRootRow(adapter, env) {
|
|
|
29508
30262
|
return root === own2 ? [] : [row4(UPGRADE_PLUGIN_ROOT_AREA, root, own2)];
|
|
29509
30263
|
}
|
|
29510
30264
|
function isCurrent(agentDir, dir) {
|
|
29511
|
-
const link =
|
|
29512
|
-
return
|
|
30265
|
+
const link = join24(agentDir, PLUGIN_CURRENT_LINK);
|
|
30266
|
+
return existsSync21(link) && realpathSync10.native(link) === realpathSync10.native(dir);
|
|
29513
30267
|
}
|
|
29514
30268
|
async function checkout(adapter, deps) {
|
|
29515
30269
|
const fetched = await fetchRelease(adapter.id, deps.releaseUrl, deps.env, deps.signal);
|
|
@@ -29605,7 +30359,7 @@ function define(name) {
|
|
|
29605
30359
|
handler: built.handler
|
|
29606
30360
|
};
|
|
29607
30361
|
}
|
|
29608
|
-
var
|
|
30362
|
+
var TOOLS2 = Object.freeze(TOOL_ORDER.map(define));
|
|
29609
30363
|
function callExample(tool) {
|
|
29610
30364
|
const a = tool.description.indexOf("`");
|
|
29611
30365
|
const b = tool.description.indexOf("`", a + 1);
|
|
@@ -29649,7 +30403,7 @@ async function setupLegacy(app) {
|
|
|
29649
30403
|
function project() {
|
|
29650
30404
|
return resolveProject(AGENT, { env, argv: process.argv, cwd: cwd ?? "" });
|
|
29651
30405
|
}
|
|
29652
|
-
for (const tool of
|
|
30406
|
+
for (const tool of TOOLS2) {
|
|
29653
30407
|
app.tool(tool.name, {
|
|
29654
30408
|
description: tool.description,
|
|
29655
30409
|
args: tool.schema,
|