context-mode 2.0.0-next.30 → 2.0.0-next.33
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 +23 -23
- package/SHA256SUMS +15 -15
- package/cli.mjs +328 -157
- package/copilot/plugin.json +1 -1
- package/gemini-extension.json +1 -1
- package/hook.mjs +75 -75
- package/opencode/plugin.js +720 -182
- package/package.json +1 -1
- package/pi/index.js +762 -224
- package/qwen-extension.json +1 -1
- package/run.mjs +69 -7
- package/search.mjs +69 -7
- package/server.mjs +746 -208
package/server.mjs
CHANGED
|
@@ -7,8 +7,8 @@ var __export = (target, all) => {
|
|
|
7
7
|
|
|
8
8
|
// src/entries/server.ts
|
|
9
9
|
import { randomUUID } from "node:crypto";
|
|
10
|
-
import { existsSync as
|
|
11
|
-
import { dirname as dirname11, join as
|
|
10
|
+
import { existsSync as existsSync23, realpathSync as realpathSync12, rmSync as rmSync11 } from "node:fs";
|
|
11
|
+
import { dirname as dirname11, join as join23 } from "node:path";
|
|
12
12
|
import { fileURLToPath as fileURLToPath2 } from "node:url";
|
|
13
13
|
|
|
14
14
|
// node_modules/@modelcontextprotocol/server/dist/chunk-Br0eD_fh.mjs
|
|
@@ -3487,17 +3487,17 @@ var recursive = /* @__PURE__ */ new WeakMap();
|
|
|
3487
3487
|
var NONE = 0;
|
|
3488
3488
|
var ASSUMED = 1;
|
|
3489
3489
|
var PROVEN = 2;
|
|
3490
|
-
function isRecursive(inst,
|
|
3490
|
+
function isRecursive(inst, stack2, resolve6) {
|
|
3491
3491
|
const cached4 = recursive.get(inst);
|
|
3492
3492
|
if (cached4 !== void 0)
|
|
3493
3493
|
return cached4 ? PROVEN : NONE;
|
|
3494
|
-
if (
|
|
3494
|
+
if (stack2.has(inst))
|
|
3495
3495
|
return PROVEN;
|
|
3496
|
-
|
|
3496
|
+
stack2.add(inst);
|
|
3497
3497
|
let result = NONE;
|
|
3498
3498
|
const check2 = (child) => {
|
|
3499
3499
|
if (result !== PROVEN && child?._zod) {
|
|
3500
|
-
const answer2 = isRecursive(child,
|
|
3500
|
+
const answer2 = isRecursive(child, stack2, resolve6);
|
|
3501
3501
|
if (answer2 > result)
|
|
3502
3502
|
result = answer2;
|
|
3503
3503
|
}
|
|
@@ -3508,7 +3508,7 @@ function isRecursive(inst, stack, resolve6) {
|
|
|
3508
3508
|
const desc = Object.getOwnPropertyDescriptor(sh, key);
|
|
3509
3509
|
if (spread && !desc.enumerable)
|
|
3510
3510
|
continue;
|
|
3511
|
-
const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value,
|
|
3511
|
+
const child = desc.get ? ASSUMED : desc.value?._zod ? isRecursive(desc.value, stack2, resolve6) : NONE;
|
|
3512
3512
|
if (child > answer2)
|
|
3513
3513
|
answer2 = child;
|
|
3514
3514
|
}
|
|
@@ -3573,7 +3573,7 @@ function isRecursive(inst, stack, resolve6) {
|
|
|
3573
3573
|
// `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
|
|
3574
3574
|
case "lazy": {
|
|
3575
3575
|
const inner = def._cachedInner ?? (resolve6 ? inst._zod.innerType : void 0);
|
|
3576
|
-
merge5(inner ? isRecursive(inner,
|
|
3576
|
+
merge5(inner ? isRecursive(inner, stack2, false) : ASSUMED);
|
|
3577
3577
|
break;
|
|
3578
3578
|
}
|
|
3579
3579
|
// a leaf by choice: `parts` are regex fragments, not data positions
|
|
@@ -3616,7 +3616,7 @@ function isRecursive(inst, stack, resolve6) {
|
|
|
3616
3616
|
}
|
|
3617
3617
|
}
|
|
3618
3618
|
}
|
|
3619
|
-
|
|
3619
|
+
stack2.delete(inst);
|
|
3620
3620
|
return settle(inst, result);
|
|
3621
3621
|
}
|
|
3622
3622
|
function settle(inst, answer2) {
|
|
@@ -11016,17 +11016,17 @@ var recursive2 = /* @__PURE__ */ new WeakMap();
|
|
|
11016
11016
|
var NONE2 = 0;
|
|
11017
11017
|
var ASSUMED2 = 1;
|
|
11018
11018
|
var PROVEN2 = 2;
|
|
11019
|
-
function isRecursive2(inst,
|
|
11019
|
+
function isRecursive2(inst, stack2, resolve6) {
|
|
11020
11020
|
const cached4 = recursive2.get(inst);
|
|
11021
11021
|
if (cached4 !== void 0)
|
|
11022
11022
|
return cached4 ? PROVEN2 : NONE2;
|
|
11023
|
-
if (
|
|
11023
|
+
if (stack2.has(inst))
|
|
11024
11024
|
return PROVEN2;
|
|
11025
|
-
|
|
11025
|
+
stack2.add(inst);
|
|
11026
11026
|
let result = NONE2;
|
|
11027
11027
|
const check2 = (child) => {
|
|
11028
11028
|
if (result !== PROVEN2 && child?._zod) {
|
|
11029
|
-
const answer2 = isRecursive2(child,
|
|
11029
|
+
const answer2 = isRecursive2(child, stack2, resolve6);
|
|
11030
11030
|
if (answer2 > result)
|
|
11031
11031
|
result = answer2;
|
|
11032
11032
|
}
|
|
@@ -11037,7 +11037,7 @@ function isRecursive2(inst, stack, resolve6) {
|
|
|
11037
11037
|
const desc = Object.getOwnPropertyDescriptor(sh, key);
|
|
11038
11038
|
if (spread && !desc.enumerable)
|
|
11039
11039
|
continue;
|
|
11040
|
-
const child = desc.get ? ASSUMED2 : desc.value?._zod ? isRecursive2(desc.value,
|
|
11040
|
+
const child = desc.get ? ASSUMED2 : desc.value?._zod ? isRecursive2(desc.value, stack2, resolve6) : NONE2;
|
|
11041
11041
|
if (child > answer2)
|
|
11042
11042
|
answer2 = child;
|
|
11043
11043
|
}
|
|
@@ -11102,7 +11102,7 @@ function isRecursive2(inst, stack, resolve6) {
|
|
|
11102
11102
|
// `$ZodLazy` caches its inner on the def, so a resolved edge is followed exactly
|
|
11103
11103
|
case "lazy": {
|
|
11104
11104
|
const inner = def._cachedInner ?? (resolve6 ? inst._zod.innerType : void 0);
|
|
11105
|
-
merge5(inner ? isRecursive2(inner,
|
|
11105
|
+
merge5(inner ? isRecursive2(inner, stack2, false) : ASSUMED2);
|
|
11106
11106
|
break;
|
|
11107
11107
|
}
|
|
11108
11108
|
// a leaf by choice: `parts` are regex fragments, not data positions
|
|
@@ -11145,7 +11145,7 @@ function isRecursive2(inst, stack, resolve6) {
|
|
|
11145
11145
|
}
|
|
11146
11146
|
}
|
|
11147
11147
|
}
|
|
11148
|
-
|
|
11148
|
+
stack2.delete(inst);
|
|
11149
11149
|
return settle2(inst, result);
|
|
11150
11150
|
}
|
|
11151
11151
|
function settle2(inst, answer2) {
|
|
@@ -26909,19 +26909,19 @@ function discoverAdvertisedCapabilities(capabilities) {
|
|
|
26909
26909
|
}
|
|
26910
26910
|
function toolInputElementCount(value, max) {
|
|
26911
26911
|
let count2 = 0;
|
|
26912
|
-
const
|
|
26913
|
-
while (
|
|
26914
|
-
const node3 =
|
|
26912
|
+
const stack2 = [value];
|
|
26913
|
+
while (stack2.length > 0) {
|
|
26914
|
+
const node3 = stack2.pop();
|
|
26915
26915
|
if (node3 === null || typeof node3 !== "object") continue;
|
|
26916
26916
|
if (Array.isArray(node3)) for (const child of node3) {
|
|
26917
26917
|
if (++count2 > max) return count2;
|
|
26918
|
-
if (child !== null && typeof child === "object")
|
|
26918
|
+
if (child !== null && typeof child === "object") stack2.push(child);
|
|
26919
26919
|
}
|
|
26920
26920
|
else for (const key in node3) {
|
|
26921
26921
|
if (!Object.prototype.hasOwnProperty.call(node3, key)) continue;
|
|
26922
26922
|
if (++count2 > max) return count2;
|
|
26923
26923
|
const child = node3[key];
|
|
26924
|
-
if (child !== null && typeof child === "object")
|
|
26924
|
+
if (child !== null && typeof child === "object") stack2.push(child);
|
|
26925
26925
|
}
|
|
26926
26926
|
}
|
|
26927
26927
|
return count2;
|
|
@@ -26997,9 +26997,9 @@ var McpServer = class {
|
|
|
26997
26997
|
resolveScopeChallenge = (context) => {
|
|
26998
26998
|
switch (context.request.method) {
|
|
26999
26999
|
case "tools/call": {
|
|
27000
|
-
const
|
|
27001
|
-
if (typeof
|
|
27002
|
-
const tool = this._registeredTools[
|
|
27000
|
+
const toolName2 = context.request.params?.name;
|
|
27001
|
+
if (typeof toolName2 !== "string") return;
|
|
27002
|
+
const tool = this._registeredTools[toolName2];
|
|
27003
27003
|
if (tool === void 0 || !tool.enabled) return;
|
|
27004
27004
|
return tool.scopeChallenge?.(context);
|
|
27005
27005
|
}
|
|
@@ -27083,23 +27083,23 @@ var McpServer = class {
|
|
|
27083
27083
|
/**
|
|
27084
27084
|
* Validates tool input arguments against the tool's input schema.
|
|
27085
27085
|
*/
|
|
27086
|
-
async validateToolInput(tool, args,
|
|
27087
|
-
if (this._maxToolInputElements !== void 0 && toolInputElementCount(args, this._maxToolInputElements) > this._maxToolInputElements) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid arguments for tool ${
|
|
27086
|
+
async validateToolInput(tool, args, toolName2) {
|
|
27087
|
+
if (this._maxToolInputElements !== void 0 && toolInputElementCount(args, this._maxToolInputElements) > this._maxToolInputElements) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Invalid arguments for tool ${toolName2}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);
|
|
27088
27088
|
if (!tool.inputSchema) return;
|
|
27089
27089
|
const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {});
|
|
27090
|
-
if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${
|
|
27090
|
+
if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName2}: ${parseResult.error}`);
|
|
27091
27091
|
return parseResult.data;
|
|
27092
27092
|
}
|
|
27093
27093
|
/**
|
|
27094
27094
|
* Validates tool output against the tool's output schema.
|
|
27095
27095
|
*/
|
|
27096
|
-
async validateToolOutput(tool, result,
|
|
27096
|
+
async validateToolOutput(tool, result, toolName2) {
|
|
27097
27097
|
if (!tool.outputSchema) return;
|
|
27098
27098
|
if (isInputRequiredResult(result)) return;
|
|
27099
27099
|
if (result.isError) return;
|
|
27100
|
-
if (result.structuredContent === void 0) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${
|
|
27100
|
+
if (result.structuredContent === void 0) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${toolName2} has an output schema but no structured content was provided`);
|
|
27101
27101
|
const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent);
|
|
27102
|
-
if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${
|
|
27102
|
+
if (!parseResult.success) throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName2}: ${parseResult.error}`);
|
|
27103
27103
|
}
|
|
27104
27104
|
/**
|
|
27105
27105
|
* Executes a tool handler.
|
|
@@ -28246,6 +28246,7 @@ var SOURCE_LABEL_MAX_CHARS = 80;
|
|
|
28246
28246
|
var CANCELLED_LINE = "Cancelled.";
|
|
28247
28247
|
var BACKGROUND_REPLY_PREFIX = "started in background, pid ";
|
|
28248
28248
|
var PLAIN_OUTPUT_ENV = Object.freeze({ NO_COLOR: "1", FORCE_COLOR: "0" });
|
|
28249
|
+
var RUN_LABEL_PREFIX = "run.mjs:";
|
|
28249
28250
|
var RUN_SESSION_PREFIX = "mcp:";
|
|
28250
28251
|
var HOST_SESSION_ENV = Object.freeze({ "claude-code": "CLAUDE_CODE_SESSION_ID" });
|
|
28251
28252
|
var NODE_MIN = "24.15.0";
|
|
@@ -28365,17 +28366,34 @@ var STATS_EMPTY_LINES = Object.freeze([
|
|
|
28365
28366
|
"sandbox, and only the short answer goes to the chat."
|
|
28366
28367
|
]);
|
|
28367
28368
|
var STATS_KIND_LABELS = Object.freeze([
|
|
28368
|
-
|
|
28369
|
+
// D-STATS-FIX-1 (8): the first five rows are call kinds, so they add up to the calls of the scope line.
|
|
28369
28370
|
["index", "Content indexed"],
|
|
28370
28371
|
["edit", "File edits"],
|
|
28371
|
-
["toolerr", "
|
|
28372
|
+
["toolerr", "Issues kept"],
|
|
28372
28373
|
["decision", "Your decisions"],
|
|
28374
|
+
["cmd", "Other tool calls"],
|
|
28373
28375
|
["prompt", "Your prompts"]
|
|
28374
28376
|
]);
|
|
28375
28377
|
var STATS_JOURNAL_HINTS = Object.freeze([
|
|
28376
|
-
"ctx_resume brings back your last task, files changed and open
|
|
28378
|
+
"ctx_resume brings back your last task, files changed and open issues",
|
|
28377
28379
|
"after a compact or a restart; ctx_search finds indexed content by words."
|
|
28378
28380
|
]);
|
|
28381
|
+
var STATS_WINDOW_TOKENS = 2e5;
|
|
28382
|
+
var STATS_THOUSAND = 1e3;
|
|
28383
|
+
var STATS_WHOLE_FROM = 10;
|
|
28384
|
+
var STATS_DAYS = 7;
|
|
28385
|
+
var STATS_TOP_OUTPUTS = 3;
|
|
28386
|
+
var STATS_CARD_W = 19;
|
|
28387
|
+
var STATS_DAY_BAR = 48;
|
|
28388
|
+
var STATS_TOKEN_NOTE = " (at 4 bytes per token; a Claude context window is 200K tokens)";
|
|
28389
|
+
var STATS_WAYS = Object.freeze([
|
|
28390
|
+
["sandbox", "\u2588", "sandbox run"],
|
|
28391
|
+
["index", "\u2593", "index + search"],
|
|
28392
|
+
["redirect", "\u2592", "hook sent to sandbox"],
|
|
28393
|
+
["replace", "\u2591", "hook cut down"]
|
|
28394
|
+
]);
|
|
28395
|
+
var STATS_INDEX_TOOLS = Object.freeze(["ctx_index", "ctx_search"]);
|
|
28396
|
+
var STATS_FOOTER_URL = "https://contextmode.ai/?utm_source=ctx_stats&utm_medium=stats&utm_content=footer";
|
|
28379
28397
|
var PURGE_SCOPES = Object.freeze(["session", "source", "project"]);
|
|
28380
28398
|
var PURGE_NO_SCOPE_LINE = "ctx_purge: pick one scope \u2014 session, source, or project.";
|
|
28381
28399
|
var PURGE_MANY_SCOPES_LINE = "ctx_purge: pick only one scope \u2014 session, source, or project.";
|
|
@@ -28387,7 +28405,7 @@ var DECISION_SOURCE = "decision";
|
|
|
28387
28405
|
var DECISION_USER_LABEL = "decision (user)";
|
|
28388
28406
|
var RELEASE_REPO_URL = "https://github.com/mksglu/context-mode.git";
|
|
28389
28407
|
var RELEASE_BRANCH = "release";
|
|
28390
|
-
var BUNDLE_SHA = true ? "
|
|
28408
|
+
var BUNDLE_SHA = true ? "a65cd5ad387fe1dc95f9320783843d566440d57c" : void 0;
|
|
28391
28409
|
var DOCTOR_CHECK_ORDER = Object.freeze(["D1", "D2", "D3", "D4", "D5", "D5b", "D6", "D7", "D8", "D9", "D10", "D11"]);
|
|
28392
28410
|
var DOCTOR_LABEL = Object.freeze({
|
|
28393
28411
|
D1: "version",
|
|
@@ -28417,20 +28435,25 @@ function DOCTOR_FAIL_LINE(host, check2, cause, command) {
|
|
|
28417
28435
|
return `FAIL ${host}: ${check2} \u2014 ${cause}. Fix: ${command}`;
|
|
28418
28436
|
}
|
|
28419
28437
|
var DOCTOR_FIX_UPGRADE = "run ctx_upgrade";
|
|
28420
|
-
var D1_DEV_BUILD_DETAIL = "dev build";
|
|
28438
|
+
var D1_DEV_BUILD_DETAIL = "dev build: source checkout; release builds stamp the sha";
|
|
28421
28439
|
var D1_UPDATE_DETAIL = "update available";
|
|
28422
28440
|
var D1_SHORT_SHA_LEN = 7;
|
|
28423
28441
|
var D1_PACKAGE_FILE = "package.json";
|
|
28424
28442
|
function D1_PREFIX(version4, sha) {
|
|
28425
28443
|
return `${version4 ?? "bundle"} (${sha.slice(0, D1_SHORT_SHA_LEN)})`;
|
|
28426
28444
|
}
|
|
28427
|
-
var
|
|
28428
|
-
|
|
28429
|
-
|
|
28445
|
+
var D1_SOURCE_NPM = "npm";
|
|
28446
|
+
var D1_SOURCE_TAGS = "GitHub tags";
|
|
28447
|
+
function D1_LATEST_PASS(tag, source) {
|
|
28448
|
+
return `latest ${tag} on ${source}`;
|
|
28449
|
+
}
|
|
28450
|
+
function D1_LATEST_UPDATE(tag, source, latest) {
|
|
28451
|
+
return `${D1_UPDATE_DETAIL}, ${tag} on ${source} is ${latest}`;
|
|
28430
28452
|
}
|
|
28431
|
-
function
|
|
28432
|
-
return
|
|
28453
|
+
function D1_LATEST_AHEAD(tag, source, latest) {
|
|
28454
|
+
return `ahead of ${tag} on ${source} (${latest})`;
|
|
28433
28455
|
}
|
|
28456
|
+
var D1_NO_VERSION = "no version in package.json";
|
|
28434
28457
|
var D1_LATEST_UNKNOWN = "latest unknown";
|
|
28435
28458
|
var D1_GIT_MISSING = "git not found on PATH";
|
|
28436
28459
|
function D1_GIT_EXIT(code, stderrLine) {
|
|
@@ -28441,7 +28464,9 @@ function D1_GIT_TIMEOUT(ms) {
|
|
|
28441
28464
|
}
|
|
28442
28465
|
var D1_GIT_CANCEL = "git stopped by cancel";
|
|
28443
28466
|
var D1_GIT_NO_START = "git did not start";
|
|
28444
|
-
|
|
28467
|
+
function D1_GIT_NO_TAG(tag) {
|
|
28468
|
+
return `git answered no ${tag} tag`;
|
|
28469
|
+
}
|
|
28445
28470
|
function D1_NPM_TIMEOUT(ms) {
|
|
28446
28471
|
return `npm registry timed out after ${ms} ms`;
|
|
28447
28472
|
}
|
|
@@ -28455,7 +28480,10 @@ function D1_NPM_NO_TAG(tag) {
|
|
|
28455
28480
|
return `npm registry answered no ${tag} version`;
|
|
28456
28481
|
}
|
|
28457
28482
|
var D1_CAUSE_JOIN = "; ";
|
|
28458
|
-
var
|
|
28483
|
+
var GIT_LS_REMOTE_TAG_ARGS = Object.freeze(["--tags", "--refs"]);
|
|
28484
|
+
var RELEASE_TAG_PATTERN = "v*";
|
|
28485
|
+
var RELEASE_TAG_REF_PREFIX = "refs/tags/v";
|
|
28486
|
+
var D1_GIT_CHECK_FIX = `git ls-remote --tags --refs ${RELEASE_REPO_URL} "${RELEASE_TAG_PATTERN}"`;
|
|
28459
28487
|
var D1_NPM_CHECK_FIX = "npm view context-mode dist-tags";
|
|
28460
28488
|
var D1_REGISTRY_URL = "https://registry.npmjs.org/-/package/context-mode/dist-tags";
|
|
28461
28489
|
var D1_PRERELEASE_SEP = "-";
|
|
@@ -28748,7 +28776,7 @@ var V1_REASON = Object.freeze({
|
|
|
28748
28776
|
dataDir: "old context-mode data dir <agent home>/context-mode/",
|
|
28749
28777
|
dataDirShared: "old context-mode data dir ~/.gemini/context-mode/: delete only after a prompt (Antigravity shares it)",
|
|
28750
28778
|
dataRoot: "old context-mode content under ~/.context-mode/",
|
|
28751
|
-
tmpFile: "old context-mode temp file context-mode-* under the OS temp dir: report only,
|
|
28779
|
+
tmpFile: "old context-mode temp file context-mode-* under the OS temp dir: report only, safe to keep"
|
|
28752
28780
|
});
|
|
28753
28781
|
var UPGRADE_REPORT_ONLY_REASONS = Object.freeze([V1_REASON.statusLine, V1_REASON.vscodeMcp, V1_REASON.dataDirShared, V1_REASON.tmpFile, V1_REASON.kiroSteering]);
|
|
28754
28782
|
var PLUGIN_NAME = SERVER_KEY;
|
|
@@ -28789,6 +28817,85 @@ var REPORT_ENV_PREFIX = "env.";
|
|
|
28789
28817
|
var REPORT_ENV_ENUMS = Object.freeze({
|
|
28790
28818
|
NODE_ENV: Object.freeze(["development", "production", "test"])
|
|
28791
28819
|
});
|
|
28820
|
+
var DOCTOR_ENV_PREFIX = "Environment: ";
|
|
28821
|
+
var DOCTOR_DOCS_URL = "https://contextmode.ai/docs/engine/doctor";
|
|
28822
|
+
var DOCTOR_DOCS_ANCHOR = "checks";
|
|
28823
|
+
function DOCTOR_DOCS_LINK(check2) {
|
|
28824
|
+
return `${DOCTOR_DOCS_URL}?utm_source=ctx_doctor&utm_medium=doctor&utm_content=${check2}#${DOCTOR_DOCS_ANCHOR}`;
|
|
28825
|
+
}
|
|
28826
|
+
var DOCTOR_DOCS_LABEL = "Docs: ";
|
|
28827
|
+
function D3_NO_SETUP_FIX(agent) {
|
|
28828
|
+
return `context-mode setup --agents ${agent}`;
|
|
28829
|
+
}
|
|
28830
|
+
function D5_FIXTURE_FILE_ABSENT(file2) {
|
|
28831
|
+
return `hook fixture ${file2} is absent: the round trip needs it`;
|
|
28832
|
+
}
|
|
28833
|
+
function D5_FIXTURE_PARSE(file2, cause) {
|
|
28834
|
+
return `the hook fixture file ${file2} failed to parse: ${cause}`;
|
|
28835
|
+
}
|
|
28836
|
+
function D5_FIXTURE_AGENT_ABSENT(file2, keys) {
|
|
28837
|
+
return `the hook fixture file ${file2} records payloads for ${keys.join(", ") || "zero agents"} only`;
|
|
28838
|
+
}
|
|
28839
|
+
var DOCTOR_REPORTS_DIR = "reports";
|
|
28840
|
+
var DOCTOR_REPORT_FILE_PREFIX = "doctor-";
|
|
28841
|
+
var DOCTOR_REPORT_LINE = "Report file: ";
|
|
28842
|
+
var DOCTOR_GH_LINE = "File it: ";
|
|
28843
|
+
var DOCTOR_URL_LINE = "Or open: ";
|
|
28844
|
+
var DOCTOR_GH_NEXT = " --";
|
|
28845
|
+
var DOCTOR_NOTE_PREFIXES = Object.freeze([
|
|
28846
|
+
DOCTOR_ENV_PREFIX,
|
|
28847
|
+
DOCTOR_DOCS_LABEL,
|
|
28848
|
+
DOCTOR_REPORT_LINE,
|
|
28849
|
+
DOCTOR_GH_LINE,
|
|
28850
|
+
DOCTOR_GH_NEXT.trim(),
|
|
28851
|
+
DOCTOR_URL_LINE
|
|
28852
|
+
]);
|
|
28853
|
+
var ISSUE_REPO_SLUG = "mksglu/context-mode";
|
|
28854
|
+
var ISSUE_FORM_FILE = "agent-report.yml";
|
|
28855
|
+
var ISSUE_URL_MAX = 8e3;
|
|
28856
|
+
var ISSUE_FORM_HEADINGS = Object.freeze([
|
|
28857
|
+
"Summary",
|
|
28858
|
+
"ctx-report",
|
|
28859
|
+
"What happened",
|
|
28860
|
+
"Hook errors",
|
|
28861
|
+
"Journal rows",
|
|
28862
|
+
"Agent config",
|
|
28863
|
+
"Expected",
|
|
28864
|
+
"Steps",
|
|
28865
|
+
"Environment"
|
|
28866
|
+
]);
|
|
28867
|
+
var DOCTOR_HOOK_LOG_LINES = 50;
|
|
28868
|
+
var DOCTOR_JOURNAL_ROWS = 30;
|
|
28869
|
+
var DOCTOR_CONFIG_LINES = 40;
|
|
28870
|
+
var DOCTOR_ENV_NAMES = Object.freeze([
|
|
28871
|
+
"CODEX_HOME",
|
|
28872
|
+
"CLAUDE_CONFIG_DIR",
|
|
28873
|
+
"CLAUDE_PLUGIN_ROOT",
|
|
28874
|
+
"COPILOT_HOME",
|
|
28875
|
+
"KIRO_HOME",
|
|
28876
|
+
"OPENCODE_CONFIG_DIR",
|
|
28877
|
+
"PI_CODING_AGENT_DIR",
|
|
28878
|
+
"XDG_CONFIG_HOME",
|
|
28879
|
+
"SHELL"
|
|
28880
|
+
]);
|
|
28881
|
+
var DOCTOR_PATH_TOOLS = Object.freeze(["node", "git", "sh"]);
|
|
28882
|
+
var DOCTOR_SECRET_WORDS = Object.freeze(["token", "secret", "password", "apikey", "api_key", "authorization", "bearer"]);
|
|
28883
|
+
var DOCTOR_MASK = "<masked>";
|
|
28884
|
+
var NATIVE_INSTALL = Object.freeze({
|
|
28885
|
+
"claude-code": ["claude plugin marketplace add mksglu/context-mode#release", "claude plugin install context-mode@context-mode"],
|
|
28886
|
+
codex: ["codex plugin marketplace add mksglu/context-mode@release", "codex plugin add context-mode@context-mode"],
|
|
28887
|
+
gemini: ["gemini extensions install https://github.com/mksglu/context-mode --ref release"],
|
|
28888
|
+
qwen: ["qwen extensions install https://github.com/mksglu/context-mode:context-mode --ref release"],
|
|
28889
|
+
opencode: ["opencode plugin add context-mode@next"],
|
|
28890
|
+
pi: ["pi install npm:context-mode@next"],
|
|
28891
|
+
"copilot-cli": ["npm i -g context-mode@next", "context-mode setup --agents copilot-cli"],
|
|
28892
|
+
vscode: ["npm i -g context-mode@next", "context-mode setup --agents vscode"],
|
|
28893
|
+
kiro: ["npm i -g context-mode@next", "context-mode setup --agents kiro"],
|
|
28894
|
+
zcode: ["npm i -g context-mode@next", "context-mode setup --agents zcode"]
|
|
28895
|
+
});
|
|
28896
|
+
var ISSUE_FORM_URL = `https://github.com/${ISSUE_REPO_SLUG}/issues/new?template=${ISSUE_FORM_FILE}`;
|
|
28897
|
+
var DOCTOR_GIT_VERSION_TIMEOUT_MS = 5e3;
|
|
28898
|
+
var DOCTOR_LOG_TAIL_BYTES = 262144;
|
|
28792
28899
|
|
|
28793
28900
|
// src/core/contracts/errors.ts
|
|
28794
28901
|
var ERROR_TEXT = Object.freeze({
|
|
@@ -29538,8 +29645,8 @@ function firstLine(file2) {
|
|
|
29538
29645
|
return line === "" ? null : line;
|
|
29539
29646
|
}
|
|
29540
29647
|
function git(dir, args) {
|
|
29541
|
-
const { spawnSync:
|
|
29542
|
-
const r =
|
|
29648
|
+
const { spawnSync: spawnSync4 } = process.getBuiltinModule("node:child_process");
|
|
29649
|
+
const r = spawnSync4("git", args, { cwd: dir, shell: false, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
|
|
29543
29650
|
if (r.error !== void 0 || r.status !== 0) throw new CtxError("NO_GIT_DIR", { path: dir });
|
|
29544
29651
|
return r.stdout.split("\n").filter((l) => l !== "");
|
|
29545
29652
|
}
|
|
@@ -31727,8 +31834,8 @@ function trigramMatch(q) {
|
|
|
31727
31834
|
const words = blankTokens(q);
|
|
31728
31835
|
const kept = words.filter((w) => !STOPWORDS.has(w.toLowerCase()));
|
|
31729
31836
|
const parts = new Set((kept.length > 0 ? kept : words).filter((w) => [...w].length >= 3));
|
|
31730
|
-
const
|
|
31731
|
-
if (words.length > 1 && [...
|
|
31837
|
+
const whole2 = words.join(" ");
|
|
31838
|
+
if (words.length > 1 && [...whole2].length >= 3) parts.add(whole2);
|
|
31732
31839
|
return [...parts].map((w) => `"${w.replaceAll('"', '""')}"`).join(" OR ");
|
|
31733
31840
|
}
|
|
31734
31841
|
function editDistance(a, b, max) {
|
|
@@ -43340,7 +43447,7 @@ var TOOL_DESCRIPTIONS = Object.freeze({
|
|
|
43340
43447
|
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.',
|
|
43341
43448
|
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.",
|
|
43342
43449
|
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.",
|
|
43343
|
-
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
|
|
43450
|
+
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",
|
|
43344
43451
|
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.",
|
|
43345
43452
|
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.'
|
|
43346
43453
|
});
|
|
@@ -43374,7 +43481,7 @@ function chunkText(text, kind, maxBytes = MAX_CHUNK_BYTES) {
|
|
|
43374
43481
|
}
|
|
43375
43482
|
function mdChunks(src, cap, lineCut) {
|
|
43376
43483
|
const out = [];
|
|
43377
|
-
const
|
|
43484
|
+
const stack2 = [];
|
|
43378
43485
|
let title = "";
|
|
43379
43486
|
let run = [];
|
|
43380
43487
|
const push = (text, bytes5) => {
|
|
@@ -43388,9 +43495,9 @@ function mdChunks(src, cap, lineCut) {
|
|
|
43388
43495
|
for (const b of lineBlocks(src, true)) {
|
|
43389
43496
|
if (b.heading !== void 0) {
|
|
43390
43497
|
flush();
|
|
43391
|
-
while (
|
|
43392
|
-
|
|
43393
|
-
title =
|
|
43498
|
+
while (stack2.length > 0 && stack2[stack2.length - 1].level >= b.heading.level) stack2.pop();
|
|
43499
|
+
stack2.push(b.heading);
|
|
43500
|
+
title = stack2.map((h) => h.text).join(" > ");
|
|
43394
43501
|
}
|
|
43395
43502
|
if (b.fence !== void 0 && utf8Bytes(src.slice(b.start, b.end)) > cap) {
|
|
43396
43503
|
const pieces = fencePieces(src, b, b.fence, cap);
|
|
@@ -43623,7 +43730,7 @@ function cutPoint(src, start, end, scratch) {
|
|
|
43623
43730
|
const r = encoder.encodeInto(src.slice(start, limit), scratch);
|
|
43624
43731
|
return { end: start + r.read, written: r.written };
|
|
43625
43732
|
}
|
|
43626
|
-
function merge4(src, blocks,
|
|
43733
|
+
function merge4(src, blocks, join24, cap, lineCut) {
|
|
43627
43734
|
const out = [];
|
|
43628
43735
|
const scratch = new Uint8Array(cap);
|
|
43629
43736
|
let wide;
|
|
@@ -43633,7 +43740,7 @@ function merge4(src, blocks, join23, cap, lineCut) {
|
|
|
43633
43740
|
out.push({ ord: out.length, text: src.slice(start, end), bytes: bytes5 });
|
|
43634
43741
|
};
|
|
43635
43742
|
for (const b of blocks) {
|
|
43636
|
-
if (cur !== void 0 && !
|
|
43743
|
+
if (cur !== void 0 && !join24) {
|
|
43637
43744
|
emit(cur.start, cur.end, curBytes);
|
|
43638
43745
|
cur = void 0;
|
|
43639
43746
|
}
|
|
@@ -43731,9 +43838,9 @@ import { accessSync, constants as fsConstants, statSync as statSync2 } from "nod
|
|
|
43731
43838
|
import path from "node:path";
|
|
43732
43839
|
|
|
43733
43840
|
// src/core/sandbox/path-entries.ts
|
|
43734
|
-
function pathEntries(value, platform = process.platform,
|
|
43841
|
+
function pathEntries(value, platform = process.platform, delimiter2 = platform === "win32" ? ";" : ":") {
|
|
43735
43842
|
const win = platform === "win32";
|
|
43736
|
-
return value.split(
|
|
43843
|
+
return value.split(delimiter2).map((e) => win && e.length >= 2 && e.startsWith('"') && e.endsWith('"') ? e.slice(1, -1) : e).filter(Boolean);
|
|
43737
43844
|
}
|
|
43738
43845
|
|
|
43739
43846
|
// src/core/sandbox/runtimes.ts
|
|
@@ -43965,8 +44072,8 @@ function jsonRows(text) {
|
|
|
43965
44072
|
return { objs, keys };
|
|
43966
44073
|
}
|
|
43967
44074
|
function fitRow(row5, skewed, named, budget) {
|
|
43968
|
-
const
|
|
43969
|
-
if (bytes(
|
|
44075
|
+
const whole2 = JSON.stringify(row5);
|
|
44076
|
+
if (bytes(whole2) <= budget) return whole2;
|
|
43970
44077
|
const own4 = Object.keys(row5);
|
|
43971
44078
|
const tier = (k) => skewed.includes(k) ? 0 : named.has(k) ? 1 : typeof row5[k] !== "object" || row5[k] === null ? 2 : 3;
|
|
43972
44079
|
const order = [...own4].sort((a, b) => tier(a) - tier(b) || own4.indexOf(a) - own4.indexOf(b));
|
|
@@ -44452,8 +44559,8 @@ var ctxBatch = Object.freeze({
|
|
|
44452
44559
|
});
|
|
44453
44560
|
|
|
44454
44561
|
// src/core/tools/doctor.ts
|
|
44455
|
-
import { readdirSync as readdirSync6, readFileSync as
|
|
44456
|
-
import { basename as basename4, dirname as dirname6, join as
|
|
44562
|
+
import { readdirSync as readdirSync6, readFileSync as readFileSync10, existsSync as existsSync14 } from "node:fs";
|
|
44563
|
+
import { basename as basename4, dirname as dirname6, join as join13 } from "node:path";
|
|
44457
44564
|
|
|
44458
44565
|
// src/adapters/claude-code.ts
|
|
44459
44566
|
var TOOL_NAME_PREFIX = "mcp__plugin_context-mode_context-mode__";
|
|
@@ -44781,8 +44888,8 @@ function decode7(raw) {
|
|
|
44781
44888
|
if (event === "SessionStart" && typeof raw.source === "string" && COPILOT_SOURCES[raw.source] !== void 0) ev.source = COPILOT_SOURCES[raw.source];
|
|
44782
44889
|
if (event === "UserPromptSubmit" && typeof raw.prompt === "string") ev.prompt = raw.prompt;
|
|
44783
44890
|
if (event === "PreToolUse" || event === "PostToolUse") {
|
|
44784
|
-
const
|
|
44785
|
-
const tool = { name:
|
|
44891
|
+
const toolName2 = String(raw[k.tool] ?? "");
|
|
44892
|
+
const tool = { name: toolName2, canonicalName: canonicalName3(toolName2), input: readArgs(raw[k.args]) };
|
|
44786
44893
|
ev.tool = tool;
|
|
44787
44894
|
}
|
|
44788
44895
|
if (event === "PostToolUse") ev.result = readResult3(raw[k.result], native.casing, native.failure);
|
|
@@ -44896,9 +45003,9 @@ function decodeCamel(p, name) {
|
|
|
44896
45003
|
if (event === "SessionStart" && typeof p.source === "string" && SESSION_SOURCES[p.source] !== void 0) ev.source = SESSION_SOURCES[p.source];
|
|
44897
45004
|
if (event === "UserPromptSubmit" && typeof p.prompt === "string") ev.prompt = p.prompt;
|
|
44898
45005
|
if (event === "PreToolUse" || event === "PostToolUse") {
|
|
44899
|
-
const
|
|
44900
|
-
const canonical = canonicalName4(
|
|
44901
|
-
ev.tool = { name:
|
|
45006
|
+
const toolName2 = String(p.toolName ?? "");
|
|
45007
|
+
const canonical = canonicalName4(toolName2);
|
|
45008
|
+
ev.tool = { name: toolName2, canonicalName: canonical, input: policyInput(toolName2, canonical, readArgs2(p.toolArgs)) };
|
|
44902
45009
|
}
|
|
44903
45010
|
if (event === "PostToolUse") ev.result = readCamelResult(p.toolResult);
|
|
44904
45011
|
return ev;
|
|
@@ -46195,9 +46302,9 @@ var Tokenizer = class {
|
|
|
46195
46302
|
}
|
|
46196
46303
|
NUMBER(cp) {
|
|
46197
46304
|
const start = this.text[this.tokenStart];
|
|
46198
|
-
const
|
|
46305
|
+
const sign2 = start === "+" ? CodePoint.PLUS_SIGN : start === "-" ? CodePoint.DASH : CodePoint.NULL;
|
|
46199
46306
|
if (cp === CodePoint.DIGIT_0) {
|
|
46200
|
-
if (
|
|
46307
|
+
if (sign2 === CodePoint.NULL) {
|
|
46201
46308
|
const startPos = this.codePointIterator.start;
|
|
46202
46309
|
const nextCp$1 = this.nextCode();
|
|
46203
46310
|
if (isDigit(nextCp$1)) {
|
|
@@ -46236,19 +46343,19 @@ var Tokenizer = class {
|
|
|
46236
46343
|
}
|
|
46237
46344
|
cp = this.nextCode();
|
|
46238
46345
|
if (cp === CodePoint.LATIN_SMALL_X || cp === CodePoint.LATIN_SMALL_O || cp === CodePoint.LATIN_SMALL_B) {
|
|
46239
|
-
if (
|
|
46346
|
+
if (sign2 !== CodePoint.NULL) return this.reportParseError("unexpected-char");
|
|
46240
46347
|
return cp === CodePoint.LATIN_SMALL_X ? "HEX" : cp === CodePoint.LATIN_SMALL_O ? "OCTAL" : "BINARY";
|
|
46241
46348
|
}
|
|
46242
46349
|
if (cp === CodePoint.LATIN_SMALL_E || cp === CodePoint.LATIN_CAPITAL_E) {
|
|
46243
46350
|
this.data = {
|
|
46244
|
-
minus:
|
|
46351
|
+
minus: sign2 === CodePoint.DASH,
|
|
46245
46352
|
left: [CodePoint.DIGIT_0]
|
|
46246
46353
|
};
|
|
46247
46354
|
return "EXPONENT_RIGHT";
|
|
46248
46355
|
}
|
|
46249
46356
|
if (cp === CodePoint.DOT) {
|
|
46250
46357
|
this.data = {
|
|
46251
|
-
minus:
|
|
46358
|
+
minus: sign2 === CodePoint.DASH,
|
|
46252
46359
|
absInt: [CodePoint.DIGIT_0]
|
|
46253
46360
|
};
|
|
46254
46361
|
return "FRACTIONAL_RIGHT";
|
|
@@ -46257,7 +46364,7 @@ var Tokenizer = class {
|
|
|
46257
46364
|
return this.back("DATA");
|
|
46258
46365
|
}
|
|
46259
46366
|
const { out, nextCp, hasUnderscore } = this.parseDigits(cp, isDigit);
|
|
46260
|
-
if (nextCp === CodePoint.DASH &&
|
|
46367
|
+
if (nextCp === CodePoint.DASH && sign2 === CodePoint.NULL && !hasUnderscore && out.length === 4) {
|
|
46261
46368
|
this.data = {
|
|
46262
46369
|
hasDate: true,
|
|
46263
46370
|
year: Number(String.fromCodePoint(...out)),
|
|
@@ -46269,7 +46376,7 @@ var Tokenizer = class {
|
|
|
46269
46376
|
};
|
|
46270
46377
|
return "DATE_MONTH";
|
|
46271
46378
|
}
|
|
46272
|
-
if (nextCp === CodePoint.COLON &&
|
|
46379
|
+
if (nextCp === CodePoint.COLON && sign2 === CodePoint.NULL && !hasUnderscore && out.length === 2) {
|
|
46273
46380
|
this.data = {
|
|
46274
46381
|
hasDate: false,
|
|
46275
46382
|
year: 0,
|
|
@@ -46283,19 +46390,19 @@ var Tokenizer = class {
|
|
|
46283
46390
|
}
|
|
46284
46391
|
if (nextCp === CodePoint.LATIN_SMALL_E || nextCp === CodePoint.LATIN_CAPITAL_E) {
|
|
46285
46392
|
this.data = {
|
|
46286
|
-
minus:
|
|
46393
|
+
minus: sign2 === CodePoint.DASH,
|
|
46287
46394
|
left: out
|
|
46288
46395
|
};
|
|
46289
46396
|
return "EXPONENT_RIGHT";
|
|
46290
46397
|
}
|
|
46291
46398
|
if (nextCp === CodePoint.DOT) {
|
|
46292
46399
|
this.data = {
|
|
46293
|
-
minus:
|
|
46400
|
+
minus: sign2 === CodePoint.DASH,
|
|
46294
46401
|
absInt: out
|
|
46295
46402
|
};
|
|
46296
46403
|
return "FRACTIONAL_RIGHT";
|
|
46297
46404
|
}
|
|
46298
|
-
this.endToken("Integer", "start",
|
|
46405
|
+
this.endToken("Integer", "start", sign2 === CodePoint.DASH ? String.fromCodePoint(CodePoint.DASH, ...out) : String.fromCodePoint(...out), 10);
|
|
46299
46406
|
return this.back("DATA");
|
|
46300
46407
|
}
|
|
46301
46408
|
HEX(cp) {
|
|
@@ -47814,8 +47921,8 @@ function setTomlText(text, path7, value) {
|
|
|
47814
47921
|
if (sameValue(cur, value)) return text;
|
|
47815
47922
|
const inline = doc.keys.find((k) => k.inline && k.full.length < path7.length && under(path7, k.full));
|
|
47816
47923
|
if (inline !== void 0) {
|
|
47817
|
-
const
|
|
47818
|
-
return replaceToml(text, doc, inline.full,
|
|
47924
|
+
const whole2 = withValueAt(hostConfigValueAt(doc.value, inline.full), path7.slice(inline.full.length), value);
|
|
47925
|
+
return replaceToml(text, doc, inline.full, whole2);
|
|
47819
47926
|
}
|
|
47820
47927
|
if (isPlainObject6(cur) && isPlainObject6(value)) {
|
|
47821
47928
|
const names = [.../* @__PURE__ */ new Set([...Object.keys(cur), ...Object.keys(value)])].filter((k) => !sameValue(cur[k], value[k]));
|
|
@@ -48494,14 +48601,18 @@ function mcpWrong(row5, home, env, worktree) {
|
|
|
48494
48601
|
return true;
|
|
48495
48602
|
}
|
|
48496
48603
|
}
|
|
48604
|
+
function hookFile(row5, spec, home, env, worktree) {
|
|
48605
|
+
const root = spec.root === "plugin" ? resolvePluginRoot(row5, env, worktree) : spec.root === "home" ? home : worktree;
|
|
48606
|
+
const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
|
|
48607
|
+
const file2 = native !== null ? join9(native, CODEX_PLUGIN_HOOKS_FILE) : row5.id === "codex" ? join9(codexDirOf(env, home), HOOKS_JSON_FILE) : row5.id === "copilot-cli" ? join9(copilotDirOf(env, home), ...spec.file.slice(1)) : row5.id === "kiro" ? join9(kiroDirOf(env, home), ...spec.file.slice(1)) : join9(root, ...spec.file);
|
|
48608
|
+
return file2;
|
|
48609
|
+
}
|
|
48497
48610
|
function hookParts(row5, home, env, worktree) {
|
|
48498
48611
|
const spec = HOOK_HOST_FILE[row5.id];
|
|
48499
48612
|
if (spec === null) return [];
|
|
48500
48613
|
let block;
|
|
48501
48614
|
try {
|
|
48502
|
-
const
|
|
48503
|
-
const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
|
|
48504
|
-
const file2 = native !== null ? join9(native, CODEX_PLUGIN_HOOKS_FILE) : row5.id === "codex" ? join9(codexDirOf(env, home), HOOKS_JSON_FILE) : row5.id === "copilot-cli" ? join9(copilotDirOf(env, home), ...spec.file.slice(1)) : row5.id === "kiro" ? join9(kiroDirOf(env, home), ...spec.file.slice(1)) : join9(root, ...spec.file);
|
|
48615
|
+
const file2 = hookFile(row5, spec, home, env, worktree);
|
|
48505
48616
|
block = hostConfigValueAt(readParsed(row5.id, file2).value, spec.key);
|
|
48506
48617
|
if (row5.id === "codex") {
|
|
48507
48618
|
const config4 = readParsed(row5.id, join9(codexDirOf(env, home), CONFIG_TOML_FILE)).value;
|
|
@@ -48542,12 +48653,15 @@ function checkHostConfig(row5, env, worktree) {
|
|
|
48542
48653
|
const read = row5.id === "pi" ? mcpFile(row5, home, env) : null;
|
|
48543
48654
|
if (parts.length === 0) return read === null ? pass("D3") : { ...pass("D3"), detail: read };
|
|
48544
48655
|
const detail = D3_DETAIL(parts);
|
|
48545
|
-
|
|
48656
|
+
const fix = parts.includes(PART_MCP) && parts.includes(PART_HOOKS) ? D3_NO_SETUP_FIX(row5.id) : DOCTOR_FIX_UPGRADE;
|
|
48657
|
+
return fail("D3", read === null ? detail : detail + D4_REASON_JOIN + read, fix);
|
|
48546
48658
|
}
|
|
48547
48659
|
function checkV1Leftovers(agent, home, scope = {}) {
|
|
48548
48660
|
const findings = detectV1(agent, home, scope);
|
|
48549
48661
|
if (findings.length === 0) return pass("D4");
|
|
48550
|
-
|
|
48662
|
+
const detail = findings.map((f) => f.reason).join(D4_REASON_JOIN);
|
|
48663
|
+
if (findings.every((f) => f.reason === V1_REASON.tmpFile)) return { ...pass("D4"), detail };
|
|
48664
|
+
return fail("D4", detail, DOCTOR_FIX_UPGRADE);
|
|
48551
48665
|
}
|
|
48552
48666
|
function parsedOrNull(agent, file2, jsonc) {
|
|
48553
48667
|
try {
|
|
@@ -48566,6 +48680,31 @@ function checkDoubleFire(agent, worktree) {
|
|
|
48566
48680
|
const useClaudeHooks = isObject4(vscode) && vscode[VSCODE_CLAUDE_HOOKS_SETTING] === true;
|
|
48567
48681
|
return hooksOn && useClaudeHooks ? fail("D5b", D5B_DETAIL, D5B_FIX) : pass("D5b");
|
|
48568
48682
|
}
|
|
48683
|
+
function configPaths(row5, env, worktree) {
|
|
48684
|
+
const home = homeDirOf(env);
|
|
48685
|
+
if (home === null) return [];
|
|
48686
|
+
const out = [];
|
|
48687
|
+
const mcp = mcpFile(row5, home, env);
|
|
48688
|
+
if (mcp !== null) out.push({ label: "MCP entry", path: mcp });
|
|
48689
|
+
const native = row5.id === "codex" ? codexNativeDir(env, home) : null;
|
|
48690
|
+
if (native !== null) out.push({ label: "Codex plugin MCP", path: join9(native, CODEX_PLUGIN_MCP_FILE) });
|
|
48691
|
+
const spec = HOOK_HOST_FILE[row5.id];
|
|
48692
|
+
if (spec !== null) {
|
|
48693
|
+
try {
|
|
48694
|
+
out.push({ label: "hook entries", path: hookFile(row5, spec, home, env, worktree) });
|
|
48695
|
+
} catch (err) {
|
|
48696
|
+
out.push({ label: "hook entries", path: err instanceof Error ? err.message : String(err) });
|
|
48697
|
+
}
|
|
48698
|
+
}
|
|
48699
|
+
if (spec !== null && spec.root === "plugin" || row5.installMode === "marketplace" || row5.installMode === "plugin") {
|
|
48700
|
+
try {
|
|
48701
|
+
out.push({ label: "plugin root", path: resolvePluginRoot(row5, env, worktree) });
|
|
48702
|
+
} catch (err) {
|
|
48703
|
+
out.push({ label: "plugin root", path: err instanceof Error ? err.message : String(err) });
|
|
48704
|
+
}
|
|
48705
|
+
}
|
|
48706
|
+
return out.filter((e, i) => out.findIndex((o) => o.path === e.path) === i);
|
|
48707
|
+
}
|
|
48569
48708
|
|
|
48570
48709
|
// src/core/ops/doctor-db.ts
|
|
48571
48710
|
import { existsSync as existsSync8 } from "node:fs";
|
|
@@ -48708,35 +48847,76 @@ async function npmLatest(url4, tag, signal, timeoutMs) {
|
|
|
48708
48847
|
return { ok: false, cause: fetchCause(err, timeoutMs) };
|
|
48709
48848
|
}
|
|
48710
48849
|
}
|
|
48850
|
+
function digits(s) {
|
|
48851
|
+
if (s === "") return false;
|
|
48852
|
+
for (const ch of s) if (ch < "0" || ch > "9") return false;
|
|
48853
|
+
return true;
|
|
48854
|
+
}
|
|
48855
|
+
function parseVersion(v) {
|
|
48856
|
+
const at = v.indexOf(D1_PRERELEASE_SEP);
|
|
48857
|
+
const core = (at < 0 ? v : v.slice(0, at)).split(NODE_VERSION_SEP);
|
|
48858
|
+
if (core.length !== 3 || !core.every(digits)) return null;
|
|
48859
|
+
const nums = [Number(core[0]), Number(core[1]), Number(core[2])];
|
|
48860
|
+
if (at < 0) return { core: nums, pre: [] };
|
|
48861
|
+
const pre = v.slice(at + 1).split(NODE_VERSION_SEP);
|
|
48862
|
+
if (pre[0] === "" || digits(pre[0]) || pre.length > 2) return null;
|
|
48863
|
+
if (pre.length === 1) return { core: nums, pre: [pre[0]] };
|
|
48864
|
+
return digits(pre[1]) ? { core: nums, pre: [pre[0], Number(pre[1])] } : null;
|
|
48865
|
+
}
|
|
48866
|
+
function sign(n) {
|
|
48867
|
+
return n < 0 ? -1 : n > 0 ? 1 : 0;
|
|
48868
|
+
}
|
|
48869
|
+
function compareVersions(a, b) {
|
|
48870
|
+
const x = parseVersion(a);
|
|
48871
|
+
const y = parseVersion(b);
|
|
48872
|
+
if (x === null || y === null) return null;
|
|
48873
|
+
for (let k = 0; k < 3; k++) if (x.core[k] !== y.core[k]) return sign(x.core[k] - y.core[k]);
|
|
48874
|
+
if (x.pre.length === 0 || y.pre.length === 0) return sign(y.pre.length - x.pre.length);
|
|
48875
|
+
if (x.pre[0] !== y.pre[0]) return x.pre[0] < y.pre[0] ? -1 : 1;
|
|
48876
|
+
return sign((x.pre[1] ?? -1) - (y.pre[1] ?? -1));
|
|
48877
|
+
}
|
|
48878
|
+
function highestTag(stdout, tag) {
|
|
48879
|
+
let best;
|
|
48880
|
+
for (const line of stdout.split("\n")) {
|
|
48881
|
+
const [sha, ref] = line.trim().split(LS_REMOTE_FIELD_SEP);
|
|
48882
|
+
if (sha === void 0 || sha.length !== GIT_SHA_HEX_LEN || ref === void 0 || !ref.startsWith(RELEASE_TAG_REF_PREFIX)) continue;
|
|
48883
|
+
const v = ref.slice(RELEASE_TAG_REF_PREFIX.length);
|
|
48884
|
+
if (parseVersion(v) === null || channelOf(v) !== tag) continue;
|
|
48885
|
+
if (best === void 0 || compareVersions(v, best) === 1) best = v;
|
|
48886
|
+
}
|
|
48887
|
+
return best;
|
|
48888
|
+
}
|
|
48889
|
+
function versionRow(head, installed, tag, source, latest, tail) {
|
|
48890
|
+
const cmp = compareVersions(installed, latest) ?? (installed === latest ? 0 : -1);
|
|
48891
|
+
if (cmp === 0) return pass3("D1", head + D1_LATEST_PASS(tag, source) + tail);
|
|
48892
|
+
if (cmp > 0) return pass3("D1", head + D1_LATEST_AHEAD(tag, source, latest) + tail);
|
|
48893
|
+
return fail3("D1", head + D1_LATEST_UPDATE(tag, source, latest) + tail, DOCTOR_FIX_UPGRADE);
|
|
48894
|
+
}
|
|
48711
48895
|
async function checkVersion(i) {
|
|
48712
48896
|
if (i.bundleSha === void 0) return unknown5("D1", D1_DEV_BUILD_DETAIL);
|
|
48713
48897
|
const head = D1_PREFIX(i.version, i.bundleSha) + ": ";
|
|
48898
|
+
if (i.version === void 0) return unknown5("D1", head + D1_LATEST_UNKNOWN + ", " + D1_NO_VERSION, D1_NPM_CHECK_FIX);
|
|
48899
|
+
const tag = channelOf(i.version);
|
|
48714
48900
|
const git3 = findRuntime(GIT_BIN, i.env);
|
|
48901
|
+
const npm = await npmLatest(i.registryUrl, tag, i.signal, i.timeoutMs);
|
|
48902
|
+
if (npm.ok) return versionRow(head, i.version, tag, D1_SOURCE_NPM, npm.version, "");
|
|
48715
48903
|
let cause = D1_GIT_MISSING;
|
|
48716
48904
|
if (git3 !== null) {
|
|
48717
|
-
const r = await runProcess([git3, GIT_LS_REMOTE, RELEASE_REPO_URL,
|
|
48905
|
+
const r = await runProcess([git3, GIT_LS_REMOTE, ...GIT_LS_REMOTE_TAG_ARGS, RELEASE_REPO_URL, RELEASE_TAG_PATTERN], {
|
|
48718
48906
|
cwd: i.cwd,
|
|
48719
48907
|
env: { ...i.env, ...GIT_NO_PROMPT_ENV },
|
|
48720
48908
|
signal: i.signal,
|
|
48721
48909
|
timeoutMs: i.timeoutMs
|
|
48722
48910
|
});
|
|
48723
48911
|
if (r.exitCode === 0 && r.killed === null) {
|
|
48724
|
-
const latest = r.stdout.toString("utf8")
|
|
48725
|
-
if (latest.
|
|
48726
|
-
|
|
48727
|
-
}
|
|
48728
|
-
cause = D1_GIT_NO_SHA;
|
|
48912
|
+
const latest = highestTag(r.stdout.toString("utf8"), tag);
|
|
48913
|
+
if (latest !== void 0) return versionRow(head, i.version, tag, D1_SOURCE_TAGS, latest, D1_CAUSE_JOIN + npm.cause);
|
|
48914
|
+
cause = D1_GIT_NO_TAG(tag);
|
|
48729
48915
|
} else {
|
|
48730
48916
|
cause = gitCause(r, i.timeoutMs);
|
|
48731
48917
|
}
|
|
48732
48918
|
}
|
|
48733
|
-
|
|
48734
|
-
if (i.version === void 0) return unknown5("D1", head + D1_LATEST_UNKNOWN + ", " + cause, handFix);
|
|
48735
|
-
const tag = channelOf(i.version);
|
|
48736
|
-
const npm = await npmLatest(i.registryUrl, tag, i.signal, i.timeoutMs);
|
|
48737
|
-
if (!npm.ok) return unknown5("D1", head + D1_LATEST_UNKNOWN + ", " + cause + D1_CAUSE_JOIN + npm.cause, handFix);
|
|
48738
|
-
if (npm.version === i.version) return pass3("D1", head + D1_NPM_PASS(tag) + D1_CAUSE_JOIN + cause);
|
|
48739
|
-
return fail3("D1", head + D1_NPM_UPDATE(tag, npm.version) + D1_CAUSE_JOIN + cause, DOCTOR_FIX_UPGRADE);
|
|
48919
|
+
return unknown5("D1", head + D1_LATEST_UNKNOWN + ", " + npm.cause + D1_CAUSE_JOIN + cause, git3 === null ? D1_NPM_CHECK_FIX : D1_GIT_CHECK_FIX);
|
|
48740
48920
|
}
|
|
48741
48921
|
function numbers(v) {
|
|
48742
48922
|
const bare2 = v.startsWith(NODE_VERSION_PREFIX) ? v.slice(NODE_VERSION_PREFIX.length) : v;
|
|
@@ -49015,16 +49195,19 @@ function isObject5(v) {
|
|
|
49015
49195
|
}
|
|
49016
49196
|
function loadFixture(bundleDir2, agent) {
|
|
49017
49197
|
const file2 = path6.join(bundleDir2, HOOK_FIXTURE_DIR, HOOK_FIXTURE_FILE);
|
|
49018
|
-
if (!existsSync11(file2)) return
|
|
49198
|
+
if (!existsSync11(file2)) return { cause: D5_FIXTURE_FILE_ABSENT(file2) };
|
|
49019
49199
|
let all;
|
|
49020
49200
|
try {
|
|
49021
49201
|
all = JSON.parse(hostText(readFileSync8(file2, "utf8")));
|
|
49022
|
-
} catch {
|
|
49023
|
-
return
|
|
49202
|
+
} catch (err) {
|
|
49203
|
+
return { cause: D5_FIXTURE_PARSE(file2, err instanceof Error ? err.message : String(err)) };
|
|
49024
49204
|
}
|
|
49025
|
-
if (!isObject5(all)
|
|
49205
|
+
if (!isObject5(all)) return { cause: D5_FIXTURE_PARSE(file2, "top level is not an object") };
|
|
49206
|
+
if (!Object.hasOwn(all, agent)) return { cause: D5_NO_FIXTURE_DETAIL(agent) + ": " + D5_FIXTURE_AGENT_ABSENT(file2, Object.keys(all)) };
|
|
49026
49207
|
const e = all[agent];
|
|
49027
|
-
if (!isObject5(e) || typeof e.event !== "string" || !Object.hasOwn(e, "payload"))
|
|
49208
|
+
if (!isObject5(e) || typeof e.event !== "string" || !Object.hasOwn(e, "payload")) {
|
|
49209
|
+
return { cause: D5_NO_FIXTURE_DETAIL(agent) + ": the entry lacks an event name or a payload" };
|
|
49210
|
+
}
|
|
49028
49211
|
return { event: e.event, payload: e.payload };
|
|
49029
49212
|
}
|
|
49030
49213
|
function payloadFor(payload, worktree) {
|
|
@@ -49078,7 +49261,7 @@ async function checkHookRoundTrip(i) {
|
|
|
49078
49261
|
return row("UNKNOWN", D5_CODEX_UNTRUSTED_DETAIL);
|
|
49079
49262
|
}
|
|
49080
49263
|
const fixture = loadFixture(i.bundleDir, i.agent);
|
|
49081
|
-
if (
|
|
49264
|
+
if ("cause" in fixture) return row("UNKNOWN", fixture.cause);
|
|
49082
49265
|
const now = i.now ?? (() => performance.now());
|
|
49083
49266
|
const fixed = i.samples === void 0 ? null : Math.max(1, i.samples);
|
|
49084
49267
|
const maxPairs = fixed ?? D5_MAX_PAIRS;
|
|
@@ -49218,8 +49401,13 @@ function envLine(key, value) {
|
|
|
49218
49401
|
const typedValue = allowed !== void 0 && allowed.includes(value) ? value : REPORT_INVALID;
|
|
49219
49402
|
return REPORT_ENV_PREFIX + typedKey + ": " + typedValue;
|
|
49220
49403
|
}
|
|
49404
|
+
function fixCell(agent, row5) {
|
|
49405
|
+
if (row5.status === "PASS") return "";
|
|
49406
|
+
if (row5.status === "FAIL") return DOCTOR_FAIL_LINE(agent, row5.id, row5.detail, row5.fixCommand ?? "");
|
|
49407
|
+
return row5.fixCommand === void 0 ? "" : "Fix: " + row5.fixCommand;
|
|
49408
|
+
}
|
|
49221
49409
|
function rowLine(agent, row5) {
|
|
49222
|
-
const fix =
|
|
49410
|
+
const fix = fixCell(agent, row5);
|
|
49223
49411
|
return "| " + [row5.id + " " + row5.label, row5.status, row5.detail, fix].join(" | ") + " |";
|
|
49224
49412
|
}
|
|
49225
49413
|
function buildReport(input) {
|
|
@@ -49249,6 +49437,196 @@ function buildReportHead(input) {
|
|
|
49249
49437
|
return lines.concat(tail).join("\n");
|
|
49250
49438
|
}
|
|
49251
49439
|
|
|
49440
|
+
// src/core/ops/doctor-issue.ts
|
|
49441
|
+
import { spawnSync as spawnSync3 } from "node:child_process";
|
|
49442
|
+
import { closeSync, existsSync as existsSync13, fstatSync, mkdirSync as mkdirSync5, openSync, readFileSync as readFileSync9, readSync, realpathSync as realpathSync8, writeFileSync as writeFileSync3 } from "node:fs";
|
|
49443
|
+
import { delimiter, join as join12 } from "node:path";
|
|
49444
|
+
var TOKEN_PREFIXES = ["ghp_", "gho_", "github_pat_", "sk-", "xoxb-", "AKIA"];
|
|
49445
|
+
function tildeOf(env) {
|
|
49446
|
+
const home = homeDirOf(env);
|
|
49447
|
+
if (home === null || home === "") return (t) => t;
|
|
49448
|
+
const homes = [home];
|
|
49449
|
+
try {
|
|
49450
|
+
const real2 = realpathSync8.native(home);
|
|
49451
|
+
if (real2 !== home) homes.push(real2);
|
|
49452
|
+
} catch {
|
|
49453
|
+
}
|
|
49454
|
+
homes.sort((a, b) => b.length - a.length);
|
|
49455
|
+
const slash = (rest) => rest.replace(/^[^\s"'`|)>,;]*/, (run) => run.replace(/\\/g, "/"));
|
|
49456
|
+
return (t) => homes.reduce((acc, h) => acc.split(h).map((piece, n) => n === 0 ? piece : slash(piece)).join("~"), t);
|
|
49457
|
+
}
|
|
49458
|
+
function maskLine(line) {
|
|
49459
|
+
const lower = line.toLowerCase();
|
|
49460
|
+
const named = DOCTOR_SECRET_WORDS.some((w) => lower.includes(w));
|
|
49461
|
+
const token = TOKEN_PREFIXES.some((p) => line.includes(p));
|
|
49462
|
+
if (!named && !token) return line;
|
|
49463
|
+
const at = Math.max(line.indexOf(":"), line.indexOf("="));
|
|
49464
|
+
return at === -1 ? DOCTOR_MASK : line.slice(0, at + 1) + " " + DOCTOR_MASK;
|
|
49465
|
+
}
|
|
49466
|
+
function environmentLine(ctx, adapter, env, version4) {
|
|
49467
|
+
const sha = BUNDLE_SHA === void 0 ? "dev build" : BUNDLE_SHA.slice(0, 7);
|
|
49468
|
+
const client = ctx.clientInfo;
|
|
49469
|
+
const agent = client === void 0 ? adapter.id : client.name === adapter.id ? `${adapter.id} ${client.version}` : `${adapter.id} ${client.version} (client ${client.name})`;
|
|
49470
|
+
const shell = env.SHELL ?? env.ComSpec ?? "sh";
|
|
49471
|
+
return `${DOCTOR_ENV_PREFIX}context-mode ${version4 ?? "source checkout"} (${sha}), agent ${agent}
|
|
49472
|
+
${DOCTOR_ENV_PREFIX}${process.platform}-${process.arch}, Node ${process.version}, shell ${shell}`;
|
|
49473
|
+
}
|
|
49474
|
+
function gitVersion(env) {
|
|
49475
|
+
const r = spawnSync3("git", ["--version"], { env, encoding: "utf8", timeout: DOCTOR_GIT_VERSION_TIMEOUT_MS, windowsHide: true });
|
|
49476
|
+
if (r.status === 0) return `${r.stdout}`.trim();
|
|
49477
|
+
return `git --version: ${r.error ? r.error.message : `exit ${r.status}`}`;
|
|
49478
|
+
}
|
|
49479
|
+
function onPath(env, tool) {
|
|
49480
|
+
const names = process.platform === "win32" ? [tool + EXE_SUFFIX, tool + ".cmd", tool] : [tool];
|
|
49481
|
+
const out = [];
|
|
49482
|
+
for (const dir of (env.PATH ?? env.Path ?? "").split(delimiter)) {
|
|
49483
|
+
if (dir === "") continue;
|
|
49484
|
+
for (const n of names) if (existsSync13(join12(dir, n))) {
|
|
49485
|
+
out.push(join12(dir, n));
|
|
49486
|
+
break;
|
|
49487
|
+
}
|
|
49488
|
+
}
|
|
49489
|
+
return out;
|
|
49490
|
+
}
|
|
49491
|
+
function hookLogTail(env) {
|
|
49492
|
+
const file2 = hookLogPath(env);
|
|
49493
|
+
if (file2 === "" || !existsSync13(file2)) return [`(${file2 || "hook-errors.log"} holds zero lines)`];
|
|
49494
|
+
try {
|
|
49495
|
+
const fd = openSync(file2, "r");
|
|
49496
|
+
try {
|
|
49497
|
+
const size = fstatSync(fd).size;
|
|
49498
|
+
const start = Math.max(0, size - DOCTOR_LOG_TAIL_BYTES);
|
|
49499
|
+
const buf = Buffer.alloc(size - start);
|
|
49500
|
+
readSync(fd, buf, 0, buf.length, start);
|
|
49501
|
+
const lines = buf.toString("utf8").split("\n").filter((l) => l.trim() !== "");
|
|
49502
|
+
if (start > 0) lines.shift();
|
|
49503
|
+
return lines.slice(-DOCTOR_HOOK_LOG_LINES).map(maskLine);
|
|
49504
|
+
} finally {
|
|
49505
|
+
closeSync(fd);
|
|
49506
|
+
}
|
|
49507
|
+
} catch (err) {
|
|
49508
|
+
return [`hook-errors.log read: ${err instanceof Error ? err.message : String(err)}`];
|
|
49509
|
+
}
|
|
49510
|
+
}
|
|
49511
|
+
async function journalRows(ctx) {
|
|
49512
|
+
const head = ["| kind | tool | bytes | ok | exit_code | created_at |", "|---|---|---|---|---|---|"];
|
|
49513
|
+
if (!existsSync13(ctx.project.dbPath)) return [`(context.db is absent at ${ctx.project.dbPath})`];
|
|
49514
|
+
try {
|
|
49515
|
+
const db = await openDb(ctx.project, { readOnly: true });
|
|
49516
|
+
try {
|
|
49517
|
+
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();
|
|
49518
|
+
const cell5 = (v) => v === null || v === void 0 ? "" : String(v);
|
|
49519
|
+
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)} |`));
|
|
49520
|
+
} finally {
|
|
49521
|
+
closeDb(db);
|
|
49522
|
+
}
|
|
49523
|
+
} catch (err) {
|
|
49524
|
+
return [`journal read: ${err instanceof Error ? err.message : String(err)}`];
|
|
49525
|
+
}
|
|
49526
|
+
}
|
|
49527
|
+
function agentConfig(adapter, env, worktree) {
|
|
49528
|
+
const home = homeDirOf(env);
|
|
49529
|
+
const files = configPaths(adapter, env, worktree);
|
|
49530
|
+
if (home !== null) {
|
|
49531
|
+
if (adapter.id === "claude-code") files.push({ label: "agent settings (enabledPlugins)", path: join12(claudeDirOf(env, home), SETTINGS_FILE) });
|
|
49532
|
+
if (adapter.id === "codex") files.push({ label: "agent config (plugins, trust)", path: join12(codexDirOf(env, home), CONFIG_TOML_FILE) });
|
|
49533
|
+
}
|
|
49534
|
+
const out = [];
|
|
49535
|
+
const seen = /* @__PURE__ */ new Set();
|
|
49536
|
+
for (const f of files) {
|
|
49537
|
+
if (seen.has(f.path)) continue;
|
|
49538
|
+
seen.add(f.path);
|
|
49539
|
+
if (!existsSync13(f.path)) {
|
|
49540
|
+
out.push(`${f.label}: ${f.path} (absent)`);
|
|
49541
|
+
continue;
|
|
49542
|
+
}
|
|
49543
|
+
let text = "";
|
|
49544
|
+
try {
|
|
49545
|
+
text = readFileSync9(f.path, "utf8");
|
|
49546
|
+
} catch (err) {
|
|
49547
|
+
out.push(`${f.label}: ${f.path} (read: ${err instanceof Error ? err.message : String(err)})`);
|
|
49548
|
+
continue;
|
|
49549
|
+
}
|
|
49550
|
+
const hit = text.split("\n").filter((l) => l.includes("context-mode") || l.includes("hook.mjs") || adapter.id === "codex" && l.includes("trust"));
|
|
49551
|
+
out.push(`${f.label}: ${f.path} (${hit.length} matching lines)`);
|
|
49552
|
+
for (const l of hit.slice(0, DOCTOR_CONFIG_LINES)) out.push(" " + maskLine(l.trimEnd()));
|
|
49553
|
+
}
|
|
49554
|
+
return out;
|
|
49555
|
+
}
|
|
49556
|
+
function failing(rows) {
|
|
49557
|
+
return rows.filter((r) => r.status === "FAIL");
|
|
49558
|
+
}
|
|
49559
|
+
function issueTitle(agent, rows) {
|
|
49560
|
+
return `ctx_doctor ${agent}: ${failing(rows).map((r) => `${r.id} ${r.label}`).join(", ")} FAIL`;
|
|
49561
|
+
}
|
|
49562
|
+
function summaryOf(agent, rows) {
|
|
49563
|
+
const f = failing(rows)[0];
|
|
49564
|
+
return f === void 0 ? `ctx_doctor ${agent}` : `${f.id} ${f.label} FAIL on ${agent}: ${f.detail}`;
|
|
49565
|
+
}
|
|
49566
|
+
async function buildIssueBody(i) {
|
|
49567
|
+
const tilde = tildeOf(i.env);
|
|
49568
|
+
const agent = i.adapter.id;
|
|
49569
|
+
const install = NATIVE_INSTALL[agent] ?? [];
|
|
49570
|
+
const failRows = i.rows.filter((r) => r.status !== "PASS");
|
|
49571
|
+
const envNames = DOCTOR_ENV_NAMES.map((n) => i.env[n] === void 0 ? `${n} (unset)` : `${n}=${i.env[n]}`);
|
|
49572
|
+
const pathTools = DOCTOR_PATH_TOOLS.map((t) => `PATH holds ${t}: ${onPath(i.env, t).join(", ") || "(absent)"}`);
|
|
49573
|
+
const sections = {
|
|
49574
|
+
"Summary": [summaryOf(agent, i.rows)],
|
|
49575
|
+
"ctx-report": [i.table],
|
|
49576
|
+
"What happened": [
|
|
49577
|
+
"Rows that need a look:",
|
|
49578
|
+
...failRows.map((r) => `- ${r.id} ${r.label} ${r.status}: ${r.detail}${r.fixCommand ? ` (Fix: ${r.fixCommand})` : ""}`),
|
|
49579
|
+
"Error code and text: <the agent fills this in: the exact error the user saw>"
|
|
49580
|
+
],
|
|
49581
|
+
"Hook errors": ["hook-errors.log, last " + DOCTOR_HOOK_LOG_LINES + " lines (UTC):", "```", ...hookLogTail(i.env), "```"],
|
|
49582
|
+
"Journal rows": ["events, newest first, last " + DOCTOR_JOURNAL_ROWS + " (bodies stay local):", ...await journalRows(i.ctx)],
|
|
49583
|
+
"Agent config": agentConfig(i.adapter, i.env, i.ctx.project.worktree),
|
|
49584
|
+
"Expected": ["Expected: <the agent fills this in: what should happen, with the byte count>"],
|
|
49585
|
+
"Steps": [
|
|
49586
|
+
"Reproduced: <yes (2 of 2) or 1 of 2>",
|
|
49587
|
+
"Prompt or command: <the agent fills this in: the exact prompt or command>",
|
|
49588
|
+
"Actual: <the agent fills this in: what context-mode did, with the byte count>",
|
|
49589
|
+
"Repro script (fresh HOME, native install for " + agent + "):",
|
|
49590
|
+
"```sh",
|
|
49591
|
+
'export HOME="$(mktemp -d)"',
|
|
49592
|
+
'cd "$HOME"',
|
|
49593
|
+
...install,
|
|
49594
|
+
"<the command or prompt above>",
|
|
49595
|
+
"```"
|
|
49596
|
+
],
|
|
49597
|
+
"Environment": [
|
|
49598
|
+
i.envLine,
|
|
49599
|
+
`context-mode bundle: ${i.bundleDir}`,
|
|
49600
|
+
`Install route: ${install.join(" && ")}`,
|
|
49601
|
+
`git: ${gitVersion(i.env)}`,
|
|
49602
|
+
...pathTools,
|
|
49603
|
+
...envNames,
|
|
49604
|
+
`Project: ${i.ctx.project.worktree} (key ${i.ctx.project.projectKey})`,
|
|
49605
|
+
"Filed by: <your agent name, version, model id>"
|
|
49606
|
+
]
|
|
49607
|
+
};
|
|
49608
|
+
const out = [];
|
|
49609
|
+
for (const h of ISSUE_FORM_HEADINGS) out.push(`### ${h}`, "", ...sections[h] ?? [], "");
|
|
49610
|
+
return tilde(out.join("\n"));
|
|
49611
|
+
}
|
|
49612
|
+
async function writeIssueReport(i) {
|
|
49613
|
+
const tilde = tildeOf(i.env);
|
|
49614
|
+
const body = await buildIssueBody(i);
|
|
49615
|
+
const dir = join12(resolveConfigDir(i.env), DOCTOR_REPORTS_DIR);
|
|
49616
|
+
mkdirSync5(dir, { recursive: true });
|
|
49617
|
+
const file2 = join12(dir, `${DOCTOR_REPORT_FILE_PREFIX}${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}.md`);
|
|
49618
|
+
writeFileSync3(file2, body);
|
|
49619
|
+
const shown2 = tilde(file2);
|
|
49620
|
+
const title = issueTitle(i.adapter.id, i.rows);
|
|
49621
|
+
const gh = [`gh issue create --repo ${ISSUE_REPO_SLUG} --label bug \\`, `${DOCTOR_GH_NEXT}title ${JSON.stringify(title)} \\`, `${DOCTOR_GH_NEXT}body-file ${shown2}`];
|
|
49622
|
+
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))];
|
|
49623
|
+
}
|
|
49624
|
+
function formUrl(title, summary) {
|
|
49625
|
+
const base = `${ISSUE_FORM_URL}&title=${encodeURIComponent(title)}`;
|
|
49626
|
+
const full = `${base}&summary=${encodeURIComponent(summary)}`;
|
|
49627
|
+
return full.length < ISSUE_URL_MAX ? full : base;
|
|
49628
|
+
}
|
|
49629
|
+
|
|
49252
49630
|
// src/core/index/text.ts
|
|
49253
49631
|
function storeText(db, project, sessionId, sourceKind, label2, text, kind, chunks = chunkText(text, kind)) {
|
|
49254
49632
|
const sourceId = ftsInsert(db, {
|
|
@@ -49282,7 +49660,7 @@ async function guard(id, run) {
|
|
|
49282
49660
|
}
|
|
49283
49661
|
}
|
|
49284
49662
|
async function codexDb(ctx, adapter) {
|
|
49285
|
-
if (adapter.id !== "codex" || !
|
|
49663
|
+
if (adapter.id !== "codex" || !existsSync14(ctx.project.dbPath)) return null;
|
|
49286
49664
|
try {
|
|
49287
49665
|
return await openDb(ctx.project, { readOnly: true });
|
|
49288
49666
|
} catch {
|
|
@@ -49312,11 +49690,11 @@ async function hookRow(ctx, adapter, host) {
|
|
|
49312
49690
|
}
|
|
49313
49691
|
}
|
|
49314
49692
|
function ownServerId(configDir, projectKey) {
|
|
49315
|
-
const dir =
|
|
49316
|
-
if (!
|
|
49693
|
+
const dir = join13(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
|
|
49694
|
+
if (!existsSync14(dir)) return "";
|
|
49317
49695
|
for (const name of readdirSync6(dir)) {
|
|
49318
49696
|
if (!name.endsWith(OWNER_PID_EXT)) continue;
|
|
49319
|
-
if (
|
|
49697
|
+
if (readFileSync10(join13(dir, name), "utf8").trim() === String(process.pid)) return basename4(name, OWNER_PID_EXT);
|
|
49320
49698
|
}
|
|
49321
49699
|
return "";
|
|
49322
49700
|
}
|
|
@@ -49361,24 +49739,39 @@ function reportEnv(env) {
|
|
|
49361
49739
|
}
|
|
49362
49740
|
return out;
|
|
49363
49741
|
}
|
|
49364
|
-
async function
|
|
49742
|
+
async function doctorReply(ctx, host) {
|
|
49365
49743
|
const adapter = getAdapter(ctx.project.agent);
|
|
49366
|
-
const host = { env: process.env, bundleDir: dirname6(process.argv[1]), piCwd: void 0 };
|
|
49367
49744
|
const rows = await runDoctorChecks(ctx, adapter, host);
|
|
49368
|
-
const
|
|
49369
|
-
const
|
|
49370
|
-
const
|
|
49371
|
-
const
|
|
49372
|
-
|
|
49745
|
+
const failed2 = rows.some((r) => r.status === "FAIL");
|
|
49746
|
+
const command = `context-mode ${failed2 ? "setup" : "doctor"} --agents ${adapter.id}`;
|
|
49747
|
+
const input = { agent: adapter.id, rows, env: reportEnv(host.env), command };
|
|
49748
|
+
const envLine2 = environmentLine(ctx, adapter, host.env, bundleVersion(host.bundleDir));
|
|
49749
|
+
const table3 = buildReport(input);
|
|
49750
|
+
let notes = [];
|
|
49751
|
+
if (failed2) {
|
|
49752
|
+
try {
|
|
49753
|
+
notes = await writeIssueReport({ ctx, adapter, env: host.env, bundleDir: host.bundleDir, rows, envLine: envLine2, table: table3 });
|
|
49754
|
+
} catch (err) {
|
|
49755
|
+
notes = [`Report file: ${lineOf(err)}`];
|
|
49756
|
+
}
|
|
49757
|
+
}
|
|
49758
|
+
const look = rows.find((r) => r.status === "FAIL") ?? rows.find((r) => r.status !== "PASS");
|
|
49759
|
+
const docs = look === void 0 ? [] : [DOCTOR_DOCS_LABEL + DOCTOR_DOCS_LINK(look.id)];
|
|
49760
|
+
const whole2 = [envLine2, table3, ...docs, ...notes].join("\n");
|
|
49761
|
+
const bytes5 = Buffer.byteLength(whole2, "utf8");
|
|
49762
|
+
if (bytes5 <= REPORT_CAP) return { text: whole2, isError: false, sandboxBytes: bytes5 };
|
|
49373
49763
|
const db = await openDb(ctx.project);
|
|
49374
49764
|
try {
|
|
49375
|
-
indexText(db, ctx.project, ctx.sessionId, REPORT_SOURCE_LABEL,
|
|
49765
|
+
indexText(db, ctx.project, ctx.sessionId, REPORT_SOURCE_LABEL, whole2, "text");
|
|
49376
49766
|
} finally {
|
|
49377
49767
|
closeDb(db);
|
|
49378
49768
|
}
|
|
49379
|
-
const text = buildReportHead(input);
|
|
49769
|
+
const text = [envLine2, buildReportHead(input), ...docs, ...notes].join("\n");
|
|
49380
49770
|
return { text, isError: false, sandboxBytes: bytes5 };
|
|
49381
49771
|
}
|
|
49772
|
+
async function handler2(_input, ctx) {
|
|
49773
|
+
return doctorReply(ctx, { env: process.env, bundleDir: dirname6(process.argv[1]), piCwd: void 0 });
|
|
49774
|
+
}
|
|
49382
49775
|
var ctxDoctor = Object.freeze({
|
|
49383
49776
|
name: "ctx_doctor",
|
|
49384
49777
|
schema: ctxDoctorSchema,
|
|
@@ -49389,9 +49782,9 @@ var ctxDoctor = Object.freeze({
|
|
|
49389
49782
|
});
|
|
49390
49783
|
|
|
49391
49784
|
// src/core/tools/execute.ts
|
|
49392
|
-
import { existsSync as
|
|
49785
|
+
import { existsSync as existsSync15, mkdtempSync, rmSync as rmSync5, writeFileSync as writeFileSync4 } from "node:fs";
|
|
49393
49786
|
import { tmpdir as tmpdir2 } from "node:os";
|
|
49394
|
-
import { dirname as dirname7, join as
|
|
49787
|
+
import { dirname as dirname7, join as join14, parse as parse5, resolve as resolve4 } from "node:path";
|
|
49395
49788
|
|
|
49396
49789
|
// src/core/index/select.ts
|
|
49397
49790
|
var READ_CHUNKS = "SELECT ord, body FROM chunks WHERE source_id = ?";
|
|
@@ -49514,7 +49907,7 @@ function schemaLine(issue4) {
|
|
|
49514
49907
|
}
|
|
49515
49908
|
function fileError(given, abs, root) {
|
|
49516
49909
|
let dir = abs;
|
|
49517
|
-
while (!
|
|
49910
|
+
while (!existsSync15(dir) && dirname7(dir) !== dir) dir = dirname7(dir);
|
|
49518
49911
|
if (isInside(root, dir)) return null;
|
|
49519
49912
|
return new CtxError("OUTSIDE_ROOT", { p: given, root }).toLine();
|
|
49520
49913
|
}
|
|
@@ -49595,9 +49988,9 @@ async function handler3(raw, ctx) {
|
|
|
49595
49988
|
if (takesDashC(input.language, runtime)) {
|
|
49596
49989
|
argv = [runtime, "-c", input.language === "shell" ? rewriteWindowsBuildTools(input.code, process.platform) : input.code];
|
|
49597
49990
|
} else {
|
|
49598
|
-
tmpDir = mkdtempSync(
|
|
49599
|
-
const file2 =
|
|
49600
|
-
|
|
49991
|
+
tmpDir = mkdtempSync(join14(tmpdir2(), TMP_PREFIX));
|
|
49992
|
+
const file2 = join14(tmpDir, SCRIPT_NAME + (SCRIPT_EXT[input.language] ?? ""));
|
|
49993
|
+
writeFileSync4(file2, scriptText(input.language, input.code), "utf8");
|
|
49601
49994
|
argv = scriptArgv(input.language, runtime, file2);
|
|
49602
49995
|
}
|
|
49603
49996
|
if (input.background === true) {
|
|
@@ -49631,21 +50024,21 @@ var ctxExecute = {
|
|
|
49631
50024
|
};
|
|
49632
50025
|
|
|
49633
50026
|
// src/core/tools/index.ts
|
|
49634
|
-
import { existsSync as
|
|
49635
|
-
import { dirname as dirname8, extname, join as
|
|
50027
|
+
import { existsSync as existsSync16, readFileSync as readFileSync12, statSync as statSync6 } from "node:fs";
|
|
50028
|
+
import { dirname as dirname8, extname, join as join16, relative as relative2, resolve as resolve5 } from "node:path";
|
|
49636
50029
|
|
|
49637
50030
|
// src/core/index/walk.ts
|
|
49638
|
-
import { readdirSync as readdirSync7, readFileSync as
|
|
49639
|
-
import { join as
|
|
50031
|
+
import { readdirSync as readdirSync7, readFileSync as readFileSync11, realpathSync as realpathSync9, statSync as statSync5 } from "node:fs";
|
|
50032
|
+
import { join as join15 } from "node:path";
|
|
49640
50033
|
var GITIGNORE = ".gitignore";
|
|
49641
50034
|
var GIT_DIR = ".git";
|
|
49642
50035
|
function walkDir(root, containmentRoot) {
|
|
49643
|
-
const real2 =
|
|
50036
|
+
const real2 = realpathSync9(root);
|
|
49644
50037
|
if (!isInside(containmentRoot, real2)) throw new CtxError("OUTSIDE_ROOT", { p: root, root: containmentRoot });
|
|
49645
50038
|
const found = [];
|
|
49646
50039
|
visit(real2, [], [], containmentRoot, /* @__PURE__ */ new Set([real2]), found);
|
|
49647
50040
|
found.sort(compareFound);
|
|
49648
|
-
return found.map((f) => ({ absPath: f.absPath, relPath:
|
|
50041
|
+
return found.map((f) => ({ absPath: f.absPath, relPath: join15(...f.dir, f.name) }));
|
|
49649
50042
|
}
|
|
49650
50043
|
function visit(abs, rel, parent, contain, seen, found) {
|
|
49651
50044
|
let entries;
|
|
@@ -49654,17 +50047,17 @@ function visit(abs, rel, parent, contain, seen, found) {
|
|
|
49654
50047
|
} catch {
|
|
49655
50048
|
return;
|
|
49656
50049
|
}
|
|
49657
|
-
const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(
|
|
50050
|
+
const rules = entries.some((e) => e.name === GITIGNORE && e.isFile()) ? parent.concat(readRules(join15(abs, GITIGNORE), rel)) : parent;
|
|
49658
50051
|
for (const e of entries) {
|
|
49659
50052
|
if (e.name === GIT_DIR) continue;
|
|
49660
|
-
const path7 =
|
|
50053
|
+
const path7 = join15(abs, e.name);
|
|
49661
50054
|
let isDir = e.isDirectory();
|
|
49662
50055
|
let isFile = e.isFile();
|
|
49663
50056
|
let target = path7;
|
|
49664
50057
|
if (e.isSymbolicLink()) {
|
|
49665
50058
|
let resolved;
|
|
49666
50059
|
try {
|
|
49667
|
-
resolved =
|
|
50060
|
+
resolved = realpathSync9(path7);
|
|
49668
50061
|
} catch {
|
|
49669
50062
|
continue;
|
|
49670
50063
|
}
|
|
@@ -49679,7 +50072,7 @@ function visit(abs, rel, parent, contain, seen, found) {
|
|
|
49679
50072
|
if (isFile) {
|
|
49680
50073
|
found.push({ dir: rel, name: e.name, absPath: path7 });
|
|
49681
50074
|
} else if (isDir) {
|
|
49682
|
-
const key = e.isSymbolicLink() ? target :
|
|
50075
|
+
const key = e.isSymbolicLink() ? target : realpathSync9(path7);
|
|
49683
50076
|
if (seen.has(key)) continue;
|
|
49684
50077
|
seen.add(key);
|
|
49685
50078
|
visit(path7, segs, rules, contain, seen, found);
|
|
@@ -49697,7 +50090,7 @@ function compareFound(a, b) {
|
|
|
49697
50090
|
function readRules(file2, base) {
|
|
49698
50091
|
let body;
|
|
49699
50092
|
try {
|
|
49700
|
-
body =
|
|
50093
|
+
body = readFileSync11(file2, "utf8");
|
|
49701
50094
|
} catch {
|
|
49702
50095
|
return [];
|
|
49703
50096
|
}
|
|
@@ -53780,14 +54173,14 @@ function kindOfType(contentType) {
|
|
|
53780
54173
|
}
|
|
53781
54174
|
function readUtf8(absPath) {
|
|
53782
54175
|
try {
|
|
53783
|
-
return utf8.decode(
|
|
54176
|
+
return utf8.decode(readFileSync12(absPath));
|
|
53784
54177
|
} catch {
|
|
53785
54178
|
return void 0;
|
|
53786
54179
|
}
|
|
53787
54180
|
}
|
|
53788
54181
|
function missingOrOutside(given, abs, root) {
|
|
53789
54182
|
let dir = abs;
|
|
53790
|
-
while (!
|
|
54183
|
+
while (!existsSync16(dir) && dirname8(dir) !== dir) dir = dirname8(dir);
|
|
53791
54184
|
if (dir !== abs && isInside(root, dir)) return new CtxError("INVALID_ARGS", { field: "path", action: "pass an existing file or folder" });
|
|
53792
54185
|
return new CtxError("OUTSIDE_ROOT", { p: given, root });
|
|
53793
54186
|
}
|
|
@@ -53798,7 +54191,7 @@ function pathItems(input, project) {
|
|
|
53798
54191
|
if (statSync6(abs).isDirectory()) {
|
|
53799
54192
|
return walkDir(abs, project.containmentRoot).map((f) => ({
|
|
53800
54193
|
sourceKind: "path",
|
|
53801
|
-
label: pathLabel(
|
|
54194
|
+
label: pathLabel(join16(base, f.relPath)),
|
|
53802
54195
|
kind: kindOfPath(f.relPath),
|
|
53803
54196
|
read: () => readUtf8(f.absPath)
|
|
53804
54197
|
}));
|
|
@@ -54270,6 +54663,43 @@ var KINDS = "SELECT kind, COALESCE(SUM(session_id = ?), 0) AS s, COUNT(*) AS p F
|
|
|
54270
54663
|
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}`;
|
|
54271
54664
|
var SPAN = "SELECT COALESCE(MAX(created_at) - MIN(created_at), 0) AS span FROM events WHERE session_id = ? AND kind <> 'cost'";
|
|
54272
54665
|
var SOURCES = "SELECT COUNT(*) AS n, COALESCE(SUM(chunk_count), 0) AS chunks, COALESCE(SUM(bytes_total), 0) AS bytes FROM sources";
|
|
54666
|
+
var HOST = "tool NOT LIKE 'ctx\\_%' ESCAPE '\\'";
|
|
54667
|
+
var REPLACED = `SELECT COUNT(*) AS n FROM events WHERE ${CALLS} AND ${HOST} AND returned_bytes < sandbox_bytes`;
|
|
54668
|
+
var RUNS = "FROM sources WHERE substr(label, 1, ?) = ?";
|
|
54669
|
+
var REDIRECTED = `SELECT COUNT(*) AS n, COALESCE(MAX(created_ts), 0) AS last ${RUNS}`;
|
|
54670
|
+
var LAST = `SELECT COALESCE(MAX(created_at), 0) AS last FROM events WHERE ${CALLS}`;
|
|
54671
|
+
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`;
|
|
54672
|
+
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`;
|
|
54673
|
+
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}`;
|
|
54674
|
+
function wayOf(tool) {
|
|
54675
|
+
if (STATS_INDEX_TOOLS.includes(tool)) return "index";
|
|
54676
|
+
return tool.startsWith("ctx_") ? "sandbox" : "replace";
|
|
54677
|
+
}
|
|
54678
|
+
function readWeek(raw, lastMs) {
|
|
54679
|
+
const last2 = Math.floor(lastMs / MS_PER_DAY);
|
|
54680
|
+
const first = last2 - STATS_DAYS + 1;
|
|
54681
|
+
const days = Array.from({ length: STATS_DAYS }, (_, i) => ({
|
|
54682
|
+
day: first + i,
|
|
54683
|
+
calls: 0,
|
|
54684
|
+
ways: { sandbox: 0, index: 0, redirect: 0, replace: 0 }
|
|
54685
|
+
}));
|
|
54686
|
+
const net = /* @__PURE__ */ new Map();
|
|
54687
|
+
for (const r of raw.prepare(WEEK).all(first * MS_PER_DAY)) {
|
|
54688
|
+
const d = days[Number(r.day) - first];
|
|
54689
|
+
if (d === void 0) continue;
|
|
54690
|
+
d.calls += Number(r.calls);
|
|
54691
|
+
const key = `${d.day}:${wayOf(String(r.tool))}`;
|
|
54692
|
+
net.set(key, (net.get(key) ?? 0) + Number(r.produced) - Number(r.returned));
|
|
54693
|
+
}
|
|
54694
|
+
for (const d of days) for (const [way] of STATS_WAYS) d.ways[way] = Math.max(0, net.get(`${d.day}:${way}`) ?? 0);
|
|
54695
|
+
for (const r of raw.prepare(WEEK_RUNS).all(RUN_LABEL_PREFIX.length, RUN_LABEL_PREFIX, first * MS_PER_DAY)) {
|
|
54696
|
+
const d = days[Number(r.day) - first];
|
|
54697
|
+
if (d === void 0) continue;
|
|
54698
|
+
d.calls += Number(r.calls);
|
|
54699
|
+
d.ways.redirect += Number(r.saved);
|
|
54700
|
+
}
|
|
54701
|
+
return days;
|
|
54702
|
+
}
|
|
54273
54703
|
var EMPTY3 = Object.freeze({ calls: 0, produced: 0, returned: 0, saved: 0 });
|
|
54274
54704
|
function totals(r) {
|
|
54275
54705
|
const produced = Number(r.produced);
|
|
@@ -54284,6 +54714,8 @@ function readFacts(raw, sessionId) {
|
|
|
54284
54714
|
const meta3 = raw.prepare(META).get();
|
|
54285
54715
|
const span2 = Number(raw.prepare(SPAN).get(sessionId).span);
|
|
54286
54716
|
const src = raw.prepare(SOURCES).get();
|
|
54717
|
+
const runs = raw.prepare(REDIRECTED).get(RUN_LABEL_PREFIX.length, RUN_LABEL_PREFIX);
|
|
54718
|
+
const last2 = Math.max(Number(raw.prepare(LAST).get().last), Number(runs.last));
|
|
54287
54719
|
const pages = raw.prepare("PRAGMA page_count").get();
|
|
54288
54720
|
const size = raw.prepare("PRAGMA page_size").get();
|
|
54289
54721
|
return {
|
|
@@ -54295,7 +54727,11 @@ function readFacts(raw, sessionId) {
|
|
|
54295
54727
|
agents: Number(meta3.agents),
|
|
54296
54728
|
days: Number(meta3.days),
|
|
54297
54729
|
sources: { count: Number(src.n), chunks: Number(src.chunks), bytes: Number(src.bytes) },
|
|
54298
|
-
dbBytes: Number(pages.page_count) * Number(size.page_size)
|
|
54730
|
+
dbBytes: Number(pages.page_count) * Number(size.page_size),
|
|
54731
|
+
top: raw.prepare(TOP).all().map((r) => ({ name: String(r.tool), ...totals(r) })),
|
|
54732
|
+
replaced: Number(raw.prepare(REPLACED).get().n),
|
|
54733
|
+
redirected: Number(runs.n),
|
|
54734
|
+
week: readWeek(raw, last2)
|
|
54299
54735
|
};
|
|
54300
54736
|
}
|
|
54301
54737
|
function sum(groups) {
|
|
@@ -54326,6 +54762,7 @@ function count(n) {
|
|
|
54326
54762
|
return n < STATS_MILLION ? int4(n) : (n / STATS_MILLION).toFixed(1) + "M";
|
|
54327
54763
|
}
|
|
54328
54764
|
function bytes4(n) {
|
|
54765
|
+
if (n < 0) return "-" + bytes4(-n);
|
|
54329
54766
|
if (n < STATS_KIB) return int4(n) + " B";
|
|
54330
54767
|
let v = n / STATS_KIB;
|
|
54331
54768
|
let u = 0;
|
|
@@ -54358,17 +54795,105 @@ function plural(n, word) {
|
|
|
54358
54795
|
}
|
|
54359
54796
|
function table2(title, rows) {
|
|
54360
54797
|
const max = Math.max(0, ...rows.map((r) => r.saved));
|
|
54361
|
-
const head = " " + title.padEnd(LABEL_W) + "Calls".padStart(STATS_CALLS_W) + "
|
|
54798
|
+
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);
|
|
54362
54799
|
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())];
|
|
54363
54800
|
}
|
|
54364
54801
|
function bySaved(a, b) {
|
|
54365
54802
|
return b.saved - a.saved || b.produced - a.produced || a.returned - b.returned || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
|
|
54366
54803
|
}
|
|
54804
|
+
function toolName(tool) {
|
|
54805
|
+
return tool.startsWith("ctx_") ? tool : "hook " + tool;
|
|
54806
|
+
}
|
|
54807
|
+
function joinIndex(tools) {
|
|
54808
|
+
const idx = tools.filter((t2) => STATS_INDEX_TOOLS.includes(t2.name));
|
|
54809
|
+
if (idx.length <= 1) return tools;
|
|
54810
|
+
const t = sum(idx);
|
|
54811
|
+
const one = { name: STATS_INDEX_TOOLS.join(" + ").replace(" + ctx_", " + "), ...t, saved: t.produced - t.returned };
|
|
54812
|
+
return [...tools.filter((x) => !idx.includes(x)), one];
|
|
54813
|
+
}
|
|
54367
54814
|
function toolRows(tools) {
|
|
54368
|
-
const named = tools.map((t) => ({ ...t,
|
|
54369
|
-
|
|
54370
|
-
const
|
|
54371
|
-
|
|
54815
|
+
const named = joinIndex(tools.map((t) => ({ ...t, saved: t.produced - t.returned }))).map((t) => ({ ...t, name: toolName(t.name) })).sort(bySaved);
|
|
54816
|
+
const zero = named.filter((t) => t.saved <= 0);
|
|
54817
|
+
const fold = zero.length > 1 ? zero : [];
|
|
54818
|
+
const keep = named.filter((t) => !fold.includes(t));
|
|
54819
|
+
const room = fold.length > 0 ? STATS_MAX_TOOL_ROWS - 1 : STATS_MAX_TOOL_ROWS;
|
|
54820
|
+
const over = keep.length > room;
|
|
54821
|
+
const shown2 = over ? keep.slice(0, STATS_MAX_TOOL_ROWS - 1) : keep;
|
|
54822
|
+
const rest = over ? [...keep.slice(STATS_MAX_TOOL_ROWS - 1), ...fold] : fold;
|
|
54823
|
+
return rest.length === 0 ? shown2 : [...shown2, { name: `other (${plural(rest.length, "tool")})`, ...sum(rest) }];
|
|
54824
|
+
}
|
|
54825
|
+
var TOKEN_UNITS = ["K", "M", "B", "T"];
|
|
54826
|
+
function whole(v) {
|
|
54827
|
+
return v >= STATS_WHOLE_FROM ? int4(v) : v.toFixed(1);
|
|
54828
|
+
}
|
|
54829
|
+
function tokens(n) {
|
|
54830
|
+
if (n < STATS_THOUSAND) return int4(n);
|
|
54831
|
+
let v = n / STATS_THOUSAND;
|
|
54832
|
+
let u = 0;
|
|
54833
|
+
while (v >= STATS_THOUSAND && u < TOKEN_UNITS.length - 1) {
|
|
54834
|
+
v /= STATS_THOUSAND;
|
|
54835
|
+
u++;
|
|
54836
|
+
}
|
|
54837
|
+
return whole(v) + TOKEN_UNITS[u];
|
|
54838
|
+
}
|
|
54839
|
+
function windowLine(saved) {
|
|
54840
|
+
const t = saved / STATS_BYTES_PER_TOKEN;
|
|
54841
|
+
const share = t / STATS_WINDOW_TOKENS;
|
|
54842
|
+
const win = `a ${tokens(STATS_WINDOW_TOKENS)} window`;
|
|
54843
|
+
const head = ` about ${tokens(t)} tokens kept out`;
|
|
54844
|
+
if (share >= 1) return `${head}, ${whole(share)} times ${win}`;
|
|
54845
|
+
const p = share * PERCENT_SCALE;
|
|
54846
|
+
return p * STATS_WHOLE_FROM < 1 ? head : `${head}, ${whole(p)}% of ${win}`;
|
|
54847
|
+
}
|
|
54848
|
+
function ymd(day) {
|
|
54849
|
+
return new Date(day * MS_PER_DAY).toISOString().slice(0, "yyyy-mm-dd".length);
|
|
54850
|
+
}
|
|
54851
|
+
function mmdd(day) {
|
|
54852
|
+
return ymd(day).slice("yyyy-".length);
|
|
54853
|
+
}
|
|
54854
|
+
function stack(parts, max, width) {
|
|
54855
|
+
let total = 0;
|
|
54856
|
+
let at = 0;
|
|
54857
|
+
let out = "";
|
|
54858
|
+
parts.forEach((v, i) => {
|
|
54859
|
+
total += v;
|
|
54860
|
+
const end = max <= 0 ? 0 : Math.round(total / max * width);
|
|
54861
|
+
if (end > at) {
|
|
54862
|
+
out += STATS_WAYS[i][1].repeat(end - at);
|
|
54863
|
+
at = end;
|
|
54864
|
+
}
|
|
54865
|
+
});
|
|
54866
|
+
if (out === "" && total > 0) out = STATS_WAYS[parts.indexOf(Math.max(...parts))][1];
|
|
54867
|
+
return out;
|
|
54868
|
+
}
|
|
54869
|
+
function cards(cells) {
|
|
54870
|
+
return (" " + cells.map((c) => c.padEnd(STATS_CARD_W)).join("")).trimEnd();
|
|
54871
|
+
}
|
|
54872
|
+
function lastDays(week, allCalls) {
|
|
54873
|
+
const saved = week.map((d) => STATS_WAYS.reduce((t, [w]) => t + d.ways[w], 0));
|
|
54874
|
+
const all = saved.reduce((a, b) => a + b, 0);
|
|
54875
|
+
const calls = week.reduce((a, d) => a + d.calls, 0);
|
|
54876
|
+
const max = Math.max(0, ...saved);
|
|
54877
|
+
const head = `Last ${STATS_DAYS} days of use \xB7 ${ymd(week[0].day)} to ${ymd(week[week.length - 1].day)}`;
|
|
54878
|
+
const card = calls < allCalls ? [
|
|
54879
|
+
cards(["Kept out", "Tokens kept out", "Calls", "Kept out per call"]),
|
|
54880
|
+
cards([bytes4(all), "about " + tokens(all / STATS_BYTES_PER_TOKEN), count(calls), bytes4(calls > 0 ? all / calls : 0)]),
|
|
54881
|
+
""
|
|
54882
|
+
] : [];
|
|
54883
|
+
return [
|
|
54884
|
+
head,
|
|
54885
|
+
...card,
|
|
54886
|
+
...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)] : []),
|
|
54887
|
+
" " + STATS_WAYS.map(([, ch, name]) => `${ch} ${name}`).join(" "),
|
|
54888
|
+
""
|
|
54889
|
+
];
|
|
54890
|
+
}
|
|
54891
|
+
function hookLine(redirected, replaced) {
|
|
54892
|
+
const all = redirected + replaced;
|
|
54893
|
+
if (all === 0) return [];
|
|
54894
|
+
const parts = [...redirected > 0 ? [`${int4(redirected)} sent to the sandbox`] : [], ...replaced > 0 ? [`${int4(replaced)} cut down`] : []];
|
|
54895
|
+
const what = plural(all, "large output");
|
|
54896
|
+
return [parts.length === 1 ? ` Project hooks: ${what} ${parts[0].replace(/^[\d,]+ /, "")}` : ` Project hooks: ${what} kept out \xB7 ${parts.join(", ")}`];
|
|
54372
54897
|
}
|
|
54373
54898
|
function fit(line) {
|
|
54374
54899
|
const chars = [...line];
|
|
@@ -54385,20 +54910,30 @@ function report(f, sessionId, agent) {
|
|
|
54385
54910
|
const lines = [
|
|
54386
54911
|
...head,
|
|
54387
54912
|
`${scopeName} \xB7 ${plural(focus.calls, "call")}${extra}`,
|
|
54913
|
+
` ${bytes4(focus.produced)} became ${bytes4(focus.returned)}: ${bytes4(focus.saved)} kept out (${pct(focus)})`,
|
|
54388
54914
|
" " + "Without context-mode".padEnd(LABEL_W) + "|" + bar(focus.produced, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + bytes4(focus.produced).padStart(NUM_W),
|
|
54389
54915
|
" " + "With context-mode".padEnd(LABEL_W) + "|" + bar(focus.returned, top, STATS_HEAD_BAR, "\u2588", "\u2591") + "|" + bytes4(focus.returned).padStart(NUM_W),
|
|
54390
|
-
|
|
54916
|
+
...focus.saved > 0 ? [windowLine(focus.saved), STATS_TOKEN_NOTE] : [],
|
|
54917
|
+
...hookLine(f.redirected, f.replaced),
|
|
54391
54918
|
"",
|
|
54392
|
-
...
|
|
54919
|
+
...lastDays(f.week, project.calls + f.redirected),
|
|
54920
|
+
// D-STATS-FIX-1 (5): one DB per project holds every session of it, so project and all-time are one row.
|
|
54921
|
+
"By scope",
|
|
54922
|
+
...table2("Scope", [{ name: "session", ...session }, { name: "project (all-time)", ...project }]),
|
|
54393
54923
|
"",
|
|
54394
|
-
"
|
|
54924
|
+
"By tool (this project)",
|
|
54395
54925
|
...table2("Tool", toolRows(f.tools)),
|
|
54396
|
-
""
|
|
54926
|
+
"",
|
|
54927
|
+
...f.top.length > 0 ? [
|
|
54928
|
+
"Largest single outputs (made \u2192 sent to the chat)",
|
|
54929
|
+
...f.top.map((t) => " " + label(toolName(t.name)) + bytes4(t.produced).padStart(NUM_W) + " \u2192 " + bytes4(t.returned).padStart(NUM_W)),
|
|
54930
|
+
""
|
|
54931
|
+
] : []
|
|
54397
54932
|
];
|
|
54398
54933
|
const agents = /* @__PURE__ */ new Map();
|
|
54399
54934
|
for (const g of f.groups) agents.set(g.agent, sum([agents.get(g.agent) ?? EMPTY3, g]));
|
|
54400
54935
|
if (!agents.has(agent)) agents.set(agent, EMPTY3);
|
|
54401
|
-
lines.push(...table2("Agent", [...agents].map(([name, t]) => ({ name, ...t })).sort(bySaved)), "");
|
|
54936
|
+
lines.push("By agent (this project)", ...table2("Agent", [...agents].map(([name, t]) => ({ name, ...t })).sort(bySaved)), "");
|
|
54402
54937
|
const maxKind = Math.max(0, ...[...f.kinds.values()].map((k) => k.project));
|
|
54403
54938
|
lines.push("Kept in the session journal", " " + "Journal".padEnd(LABEL_W) + "Session".padStart(STATS_KIND_W) + "Project".padStart(STATS_KIND_W));
|
|
54404
54939
|
for (const [kind, name] of STATS_KIND_LABELS) {
|
|
@@ -54407,9 +54942,12 @@ function report(f, sessionId, agent) {
|
|
|
54407
54942
|
}
|
|
54408
54943
|
lines.push("", ...STATS_JOURNAL_HINTS.map((h) => " " + h), "");
|
|
54409
54944
|
lines.push(
|
|
54410
|
-
" " + "
|
|
54945
|
+
" " + "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")}`,
|
|
54411
54946
|
" " + "Database file".padEnd(LABEL_W) + bytes4(f.dbBytes),
|
|
54412
|
-
" " + "Sessions".padEnd(LABEL_W) + `${int4(f.sessions)} \xB7 agents ${int4(f.agents)} \xB7 active days ${int4(f.days)}
|
|
54947
|
+
" " + "Sessions".padEnd(LABEL_W) + `${int4(f.sessions)} \xB7 agents ${int4(f.agents)} \xB7 active days ${int4(f.days)}`,
|
|
54948
|
+
"",
|
|
54949
|
+
STATS_FOOTER_URL,
|
|
54950
|
+
"github.com/" + ISSUE_REPO_SLUG
|
|
54413
54951
|
);
|
|
54414
54952
|
return lines.map(fit).join("\n");
|
|
54415
54953
|
}
|
|
@@ -54447,28 +54985,28 @@ var ctxStats = Object.freeze({
|
|
|
54447
54985
|
});
|
|
54448
54986
|
|
|
54449
54987
|
// src/core/tools/upgrade.ts
|
|
54450
|
-
import { existsSync as
|
|
54451
|
-
import { basename as basename6, dirname as dirname10, join as
|
|
54988
|
+
import { existsSync as existsSync22, realpathSync as realpathSync10, rmSync as rmSync10 } from "node:fs";
|
|
54989
|
+
import { basename as basename6, dirname as dirname10, join as join22 } from "node:path";
|
|
54452
54990
|
|
|
54453
54991
|
// src/core/ops/host-write.ts
|
|
54454
|
-
import { copyFileSync, existsSync as
|
|
54455
|
-
import { dirname as dirname9, join as
|
|
54992
|
+
import { copyFileSync, existsSync as existsSync17, mkdirSync as mkdirSync6, writeFileSync as writeFileSync5 } from "node:fs";
|
|
54993
|
+
import { dirname as dirname9, join as join17 } from "node:path";
|
|
54456
54994
|
function defaultWrite(file2, text) {
|
|
54457
|
-
|
|
54995
|
+
writeFileSync5(file2, text, "utf8");
|
|
54458
54996
|
}
|
|
54459
54997
|
function hostConfigPath(agent, home, env) {
|
|
54460
54998
|
const own4 = OWN_MCP_ENTRY[agent];
|
|
54461
54999
|
if (own4 !== void 0) return ownMcpFileOf(agent, own4.file, env, home);
|
|
54462
55000
|
switch (agent) {
|
|
54463
55001
|
case "opencode":
|
|
54464
|
-
return
|
|
55002
|
+
return join17(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE);
|
|
54465
55003
|
// D-WIN-OPENCODE-DIR-1
|
|
54466
55004
|
case "pi":
|
|
54467
|
-
return
|
|
55005
|
+
return join17(piAgentDirOf(env, home), SETTINGS_FILE);
|
|
54468
55006
|
case "copilot-cli":
|
|
54469
55007
|
return null;
|
|
54470
55008
|
default:
|
|
54471
|
-
return
|
|
55009
|
+
return join17(home, ...AGENT_HOME_DIR[agent], SETTINGS_FILE);
|
|
54472
55010
|
}
|
|
54473
55011
|
}
|
|
54474
55012
|
function cell3(value) {
|
|
@@ -54480,8 +55018,8 @@ function toRow(file2, edit) {
|
|
|
54480
55018
|
function writeWithRollback(file2, text, write, atomic) {
|
|
54481
55019
|
const trash = file2 + UPGRADE_TRASH_SUFFIX;
|
|
54482
55020
|
const tmp = `${file2}${HOST_CONFIG_TMP_SUFFIX}.${process.pid}`;
|
|
54483
|
-
const had =
|
|
54484
|
-
|
|
55021
|
+
const had = existsSync17(file2);
|
|
55022
|
+
mkdirSync6(dirname9(file2), { recursive: true });
|
|
54485
55023
|
if (had) copyFileSync(file2, trash);
|
|
54486
55024
|
try {
|
|
54487
55025
|
write(tmp, text);
|
|
@@ -54510,7 +55048,7 @@ function regenerateHostConfig(row5, home, opts = {}) {
|
|
|
54510
55048
|
if (requested === null) return [];
|
|
54511
55049
|
const current = readHostConfig(row5.id, requested);
|
|
54512
55050
|
const result = mergeOwnEntries(row5.id, current.text, current.format, row5);
|
|
54513
|
-
const exists =
|
|
55051
|
+
const exists = existsSync17(current.path);
|
|
54514
55052
|
if (exists && result.text === current.text) return [];
|
|
54515
55053
|
const text = result.text === "" && current.format !== "toml" ? JSON.stringify({}) : result.text;
|
|
54516
55054
|
writeWithRollback(current.path, current.layout === void 0 ? text : withLayout(text, current.layout), opts.write ?? defaultWrite, opts.atomic ?? {});
|
|
@@ -54518,8 +55056,8 @@ function regenerateHostConfig(row5, home, opts = {}) {
|
|
|
54518
55056
|
}
|
|
54519
55057
|
|
|
54520
55058
|
// src/core/ops/plugin-swap.ts
|
|
54521
|
-
import { existsSync as
|
|
54522
|
-
import { basename as basename5, join as
|
|
55059
|
+
import { existsSync as existsSync18, lstatSync, readdirSync as readdirSync8, readlinkSync, rmSync as rmSync6, symlinkSync, unlinkSync as unlinkSync2 } from "node:fs";
|
|
55060
|
+
import { basename as basename5, join as join18, win32 as win322 } from "node:path";
|
|
54523
55061
|
function linkTarget(path7, win) {
|
|
54524
55062
|
if (!isLink(path7)) return null;
|
|
54525
55063
|
const target = readlinkSync(path7);
|
|
@@ -54538,11 +55076,11 @@ function settleLinks(link, tmp, old, opts) {
|
|
|
54538
55076
|
else renameWithRetry(old, link, opts);
|
|
54539
55077
|
}
|
|
54540
55078
|
function swapPluginCurrent(agentDir, sha, opts = {}) {
|
|
54541
|
-
const next =
|
|
54542
|
-
if (!
|
|
55079
|
+
const next = join18(agentDir, sha);
|
|
55080
|
+
if (!existsSync18(next) || !lstatSync(next).isDirectory()) {
|
|
54543
55081
|
throw new CtxError("PLUGIN_ROOT_MISSING", { agent: basename5(agentDir), path: next });
|
|
54544
55082
|
}
|
|
54545
|
-
const link =
|
|
55083
|
+
const link = join18(agentDir, PLUGIN_CURRENT_LINK);
|
|
54546
55084
|
const tmp = link + PLUGIN_LINK_TMP_SUFFIX;
|
|
54547
55085
|
const old = link + PLUGIN_LINK_OLD_SUFFIX;
|
|
54548
55086
|
settleLinks(link, tmp, old, opts);
|
|
@@ -54557,15 +55095,15 @@ function swapPluginCurrent(agentDir, sha, opts = {}) {
|
|
|
54557
55095
|
if (before !== null) unlinkSync2(old);
|
|
54558
55096
|
const keep = /* @__PURE__ */ new Set([sha]);
|
|
54559
55097
|
if (before !== null) keep.add(before);
|
|
54560
|
-
const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) =>
|
|
55098
|
+
const removed = generations(agentDir).filter((name) => !keep.has(name)).map((name) => join18(agentDir, name));
|
|
54561
55099
|
for (const dir of removed) rmSync6(dir, { recursive: true, force: true });
|
|
54562
|
-
const previous = before !== null &&
|
|
55100
|
+
const previous = before !== null && existsSync18(join18(agentDir, before)) ? join18(agentDir, before) : null;
|
|
54563
55101
|
return { current: next, previous, removed };
|
|
54564
55102
|
}
|
|
54565
55103
|
|
|
54566
55104
|
// src/core/ops/release-fetch.ts
|
|
54567
|
-
import { existsSync as
|
|
54568
|
-
import { join as
|
|
55105
|
+
import { existsSync as existsSync19, mkdirSync as mkdirSync7, rmSync as rmSync7 } from "node:fs";
|
|
55106
|
+
import { join as join19 } from "node:path";
|
|
54569
55107
|
function failed(r) {
|
|
54570
55108
|
if (r.exitCode === null && r.killed === null) return new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
|
|
54571
55109
|
const status = r.killed ?? String(r.exitCode);
|
|
@@ -54577,9 +55115,9 @@ async function git2(bin, args, cwd, env, signal) {
|
|
|
54577
55115
|
return r.stdout.toString().trim();
|
|
54578
55116
|
}
|
|
54579
55117
|
async function fetchRelease(agent, url4, env, signal, opts = {}) {
|
|
54580
|
-
const agentDir =
|
|
54581
|
-
|
|
54582
|
-
const fetchDir =
|
|
55118
|
+
const agentDir = join19(resolveConfigDir(env), DATA_PLUGINS_DIR_NAME, agent);
|
|
55119
|
+
mkdirSync7(agentDir, { recursive: true });
|
|
55120
|
+
const fetchDir = join19(agentDir, UPGRADE_FETCH_DIR_PREFIX + process.pid);
|
|
54583
55121
|
rmSync7(fetchDir, { recursive: true, force: true });
|
|
54584
55122
|
const gitBin = findRuntime(GIT_BIN, env);
|
|
54585
55123
|
if (gitBin === null) throw new CtxError("FETCH_FAILED", { code: GIT_NOT_STARTED });
|
|
@@ -54587,8 +55125,8 @@ async function fetchRelease(agent, url4, env, signal, opts = {}) {
|
|
|
54587
55125
|
try {
|
|
54588
55126
|
await git2(gitBin, [...GIT_CLONE_ARGS, RELEASE_BRANCH, url4, fetchDir], agentDir, childEnv, signal);
|
|
54589
55127
|
const sha = await git2(gitBin, GIT_HEAD_SHA_ARGS, fetchDir, childEnv, signal);
|
|
54590
|
-
const dir =
|
|
54591
|
-
if (
|
|
55128
|
+
const dir = join19(agentDir, sha);
|
|
55129
|
+
if (existsSync19(dir)) rmSync7(fetchDir, { recursive: true, force: true });
|
|
54592
55130
|
else renameWithRetry(fetchDir, dir, opts);
|
|
54593
55131
|
return { sha, dir };
|
|
54594
55132
|
} catch (e) {
|
|
@@ -54598,15 +55136,15 @@ async function fetchRelease(agent, url4, env, signal, opts = {}) {
|
|
|
54598
55136
|
}
|
|
54599
55137
|
|
|
54600
55138
|
// src/core/ops/uninstall.ts
|
|
54601
|
-
import { existsSync as
|
|
54602
|
-
import { join as
|
|
55139
|
+
import { existsSync as existsSync20, readdirSync as readdirSync9, rmSync as rmSync8, writeFileSync as writeFileSync6 } from "node:fs";
|
|
55140
|
+
import { join as join20 } from "node:path";
|
|
54603
55141
|
function row2(area, before, after) {
|
|
54604
55142
|
return { area, before, after };
|
|
54605
55143
|
}
|
|
54606
55144
|
function stopServers(configDir, projectKey) {
|
|
54607
55145
|
const stopped = listLiveOwners(configDir, projectKey);
|
|
54608
|
-
const dir =
|
|
54609
|
-
for (const serverId of stopped)
|
|
55146
|
+
const dir = join20(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME);
|
|
55147
|
+
for (const serverId of stopped) writeFileSync6(join20(dir, serverId + OWNER_STOP_EXT), "", "utf8");
|
|
54610
55148
|
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 };
|
|
54611
55149
|
}
|
|
54612
55150
|
function rootOrNull(adapter, env) {
|
|
@@ -54624,15 +55162,15 @@ function removeCache(adapter, env, configDir) {
|
|
|
54624
55162
|
const root = rootOrNull(adapter, env);
|
|
54625
55163
|
if (root === null) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
|
|
54626
55164
|
if (adapter.installMode === "marketplace") {
|
|
54627
|
-
const cache =
|
|
55165
|
+
const cache = join20(claudeDirOf(env, requireHomeDir(env)), HOST_PLUGINS_DIR_NAME, PLUGIN_CACHE_DIR_NAME);
|
|
54628
55166
|
if (!isInside(cache, root) || isInside(root, cache)) return row2(UPGRADE_CACHE_AREA, root, UPGRADE_CACHE_BY_HAND);
|
|
54629
55167
|
}
|
|
54630
55168
|
rmSync8(root, { recursive: true, force: true });
|
|
54631
55169
|
return row2(UPGRADE_CACHE_AREA, root, UPGRADE_REMOVED);
|
|
54632
55170
|
}
|
|
54633
55171
|
case "plugin": {
|
|
54634
|
-
const agentDir =
|
|
54635
|
-
if (!
|
|
55172
|
+
const agentDir = join20(configDir, DATA_PLUGINS_DIR_NAME, adapter.id);
|
|
55173
|
+
if (!existsSync20(agentDir)) return row2(UPGRADE_CACHE_AREA, "", UPGRADE_NOT_FOUND);
|
|
54636
55174
|
rmSync8(agentDir, { recursive: true, force: true });
|
|
54637
55175
|
return row2(UPGRADE_CACHE_AREA, agentDir, UPGRADE_REMOVED);
|
|
54638
55176
|
}
|
|
@@ -54677,7 +55215,7 @@ function ownEntries(agent, env) {
|
|
|
54677
55215
|
}
|
|
54678
55216
|
if (agent === "opencode") {
|
|
54679
55217
|
return [{
|
|
54680
|
-
file:
|
|
55218
|
+
file: join20(opencodeDirOf(env, home), OPENCODE_BASE_CONFIG_FILE),
|
|
54681
55219
|
// D-WIN-OPENCODE-DIR-1
|
|
54682
55220
|
key: OPENCODE_PLUGIN_KEY,
|
|
54683
55221
|
shown: OPENCODE_PLUGIN_KEY,
|
|
@@ -54688,7 +55226,7 @@ function ownEntries(agent, env) {
|
|
|
54688
55226
|
if (agent === "pi") {
|
|
54689
55227
|
const agentDir = piAgentDirOf(env, home);
|
|
54690
55228
|
return [{
|
|
54691
|
-
file:
|
|
55229
|
+
file: join20(agentDir, SETTINGS_FILE),
|
|
54692
55230
|
key: PI_PACKAGES_KEY,
|
|
54693
55231
|
shown: PI_PACKAGES_KEY,
|
|
54694
55232
|
has: (v) => Array.isArray(v) && v.some((x) => piSource(x) === PI_GIT_PACKAGE),
|
|
@@ -54710,12 +55248,12 @@ function removeOwnEntries(agent, env) {
|
|
|
54710
55248
|
return rows.length === 0 ? [row2(UPGRADE_CONFIG_AREA, "", UPGRADE_NOT_FOUND)] : rows;
|
|
54711
55249
|
}
|
|
54712
55250
|
function removeProjectData(configDir, projectKey) {
|
|
54713
|
-
const projects =
|
|
54714
|
-
const dir =
|
|
54715
|
-
if (!
|
|
55251
|
+
const projects = join20(configDir, PROJECTS_DIR_NAME);
|
|
55252
|
+
const dir = join20(projects, projectKey);
|
|
55253
|
+
if (!existsSync20(dir)) return row2(UPGRADE_DATA_AREA, "", UPGRADE_NOT_FOUND);
|
|
54716
55254
|
if (dir === projects || !isInside(projects, dir)) throw new CtxError("OUTSIDE_ROOT", { p: dir, root: projects });
|
|
54717
55255
|
for (const name of readdirSync9(dir)) {
|
|
54718
|
-
if (name !== OWNERS_DIR_NAME) rmSync8(
|
|
55256
|
+
if (name !== OWNERS_DIR_NAME) rmSync8(join20(dir, name), { recursive: true, force: true });
|
|
54719
55257
|
}
|
|
54720
55258
|
return row2(UPGRADE_DATA_AREA, dir, UPGRADE_DATA_DELETED);
|
|
54721
55259
|
}
|
|
@@ -54723,12 +55261,12 @@ function runUninstall(input) {
|
|
|
54723
55261
|
const configDir = resolveConfigDir(input.env);
|
|
54724
55262
|
const stop = stopServers(configDir, input.project.projectKey);
|
|
54725
55263
|
const rows = [stop.row, removeCache(input.adapter, input.env, configDir), ...removeOwnEntries(input.adapter.id, input.env)];
|
|
54726
|
-
rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA,
|
|
55264
|
+
rows.push(input.confirmDelete ? removeProjectData(configDir, input.project.projectKey) : row2(UPGRADE_DATA_AREA, join20(configDir, PROJECTS_DIR_NAME, input.project.projectKey), UPGRADE_DATA_KEPT));
|
|
54727
55265
|
return { rows, stopped: stop.stopped };
|
|
54728
55266
|
}
|
|
54729
55267
|
|
|
54730
55268
|
// src/core/ops/v1-remove.ts
|
|
54731
|
-
import { copyFileSync as copyFileSync2, existsSync as
|
|
55269
|
+
import { copyFileSync as copyFileSync2, existsSync as existsSync21, readFileSync as readFileSync13, rmSync as rmSync9 } from "node:fs";
|
|
54732
55270
|
var isObj4 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
54733
55271
|
var areaOf = (f) => f.path === "" ? f.file : f.file + UPGRADE_AREA_KEY_SEP + f.path;
|
|
54734
55272
|
var row3 = (f, after) => ({ area: areaOf(f), before: f.reason, after });
|
|
@@ -54772,8 +55310,8 @@ function locate(doc, path7) {
|
|
|
54772
55310
|
return null;
|
|
54773
55311
|
}
|
|
54774
55312
|
function stripJsonEntries(agent, file2, findings, kept, undo) {
|
|
54775
|
-
const layout = hostLayout(
|
|
54776
|
-
const text = hostText(
|
|
55313
|
+
const layout = hostLayout(readFileSync13(file2, "utf8"));
|
|
55314
|
+
const text = hostText(readFileSync13(file2, "utf8"));
|
|
54777
55315
|
const doc = parseHostConfig(agent, file2, text, "jsonc");
|
|
54778
55316
|
const hit = /* @__PURE__ */ new Set();
|
|
54779
55317
|
const byContainer = /* @__PURE__ */ new Map();
|
|
@@ -54809,19 +55347,19 @@ function removeV1(agent, findings) {
|
|
|
54809
55347
|
for (const f of findings) {
|
|
54810
55348
|
if (UPGRADE_REPORT_ONLY_REASONS.includes(f.reason)) done.set(f, UPGRADE_REPORT_ONLY);
|
|
54811
55349
|
else if (f.path === "") {
|
|
54812
|
-
if (
|
|
55350
|
+
if (existsSync21(f.file)) {
|
|
54813
55351
|
moveAside(f.file, undo);
|
|
54814
55352
|
done.set(f, UPGRADE_REMOVED);
|
|
54815
55353
|
} else done.set(f, UPGRADE_NOT_FOUND);
|
|
54816
55354
|
} else entries.set(f.file, [...entries.get(f.file) ?? [], f]);
|
|
54817
55355
|
}
|
|
54818
55356
|
for (const [file2, list3] of entries) {
|
|
54819
|
-
if (!
|
|
55357
|
+
if (!existsSync21(file2)) {
|
|
54820
55358
|
for (const f of list3) done.set(f, UPGRADE_NOT_FOUND);
|
|
54821
55359
|
continue;
|
|
54822
55360
|
}
|
|
54823
55361
|
if (file2.endsWith(TOML_EXT)) {
|
|
54824
|
-
const rawToml =
|
|
55362
|
+
const rawToml = readFileSync13(file2, "utf8");
|
|
54825
55363
|
const tomlLayout = hostLayout(rawToml);
|
|
54826
55364
|
let text = hostText(rawToml);
|
|
54827
55365
|
for (const f of list3) {
|
|
@@ -54849,7 +55387,7 @@ function removeV1(agent, findings) {
|
|
|
54849
55387
|
},
|
|
54850
55388
|
rollback() {
|
|
54851
55389
|
for (const u of undo.splice(0).reverse()) {
|
|
54852
|
-
if (!
|
|
55390
|
+
if (!existsSync21(u.trash)) continue;
|
|
54853
55391
|
rmSync9(u.target, { recursive: true, force: true });
|
|
54854
55392
|
renameWithRetry(u.trash, u.target);
|
|
54855
55393
|
}
|
|
@@ -54859,8 +55397,8 @@ function removeV1(agent, findings) {
|
|
|
54859
55397
|
|
|
54860
55398
|
// src/core/ops/verify-sums.ts
|
|
54861
55399
|
import { createHash as createHash2 } from "node:crypto";
|
|
54862
|
-
import { lstatSync as lstatSync2, readdirSync as readdirSync10, readFileSync as
|
|
54863
|
-
import { join as
|
|
55400
|
+
import { lstatSync as lstatSync2, readdirSync as readdirSync10, readFileSync as readFileSync14 } from "node:fs";
|
|
55401
|
+
import { join as join21 } from "node:path";
|
|
54864
55402
|
function mismatch() {
|
|
54865
55403
|
return new CtxError("BUNDLE_HASH_MISMATCH");
|
|
54866
55404
|
}
|
|
@@ -54881,24 +55419,24 @@ function walk2(dir, prefix, out) {
|
|
|
54881
55419
|
for (const entry of readdirSync10(dir, { withFileTypes: true })) {
|
|
54882
55420
|
const rel = prefix === "" ? entry.name : prefix + "/" + entry.name;
|
|
54883
55421
|
if (prefix === "" && (entry.name === GIT_DIR_NAME || entry.name === RELEASE_SUMS_FILE)) continue;
|
|
54884
|
-
const abs =
|
|
55422
|
+
const abs = join21(dir, entry.name);
|
|
54885
55423
|
if (entry.isDirectory()) walk2(abs, rel, out);
|
|
54886
55424
|
else if (entry.isFile()) out.set(rel, abs);
|
|
54887
55425
|
else throw mismatch();
|
|
54888
55426
|
}
|
|
54889
55427
|
}
|
|
54890
55428
|
function verifySums(dir) {
|
|
54891
|
-
const sumsPath =
|
|
55429
|
+
const sumsPath = join21(dir, RELEASE_SUMS_FILE);
|
|
54892
55430
|
const sumsStat = lstatSync2(sumsPath, { throwIfNoEntry: false });
|
|
54893
55431
|
if (sumsStat === void 0 || !sumsStat.isFile()) throw mismatch();
|
|
54894
|
-
const sums = parseSums(
|
|
55432
|
+
const sums = parseSums(readFileSync14(sumsPath, "utf8"));
|
|
54895
55433
|
const files = /* @__PURE__ */ new Map();
|
|
54896
55434
|
walk2(dir, "", files);
|
|
54897
55435
|
if (files.size !== sums.size) throw mismatch();
|
|
54898
55436
|
for (const [rel, abs] of files) {
|
|
54899
55437
|
const want = sums.get(rel);
|
|
54900
55438
|
if (want === void 0) throw mismatch();
|
|
54901
|
-
const got = createHash2(SUMS_HASH_ALGORITHM).update(
|
|
55439
|
+
const got = createHash2(SUMS_HASH_ALGORITHM).update(readFileSync14(abs)).digest(HASH_ENCODING);
|
|
54902
55440
|
if (got !== want) throw mismatch();
|
|
54903
55441
|
}
|
|
54904
55442
|
}
|
|
@@ -54926,8 +55464,8 @@ function pluginRootRow(adapter, env) {
|
|
|
54926
55464
|
return root === own4 ? [] : [row4(UPGRADE_PLUGIN_ROOT_AREA, root, own4)];
|
|
54927
55465
|
}
|
|
54928
55466
|
function isCurrent(agentDir, dir) {
|
|
54929
|
-
const link =
|
|
54930
|
-
return
|
|
55467
|
+
const link = join22(agentDir, PLUGIN_CURRENT_LINK);
|
|
55468
|
+
return existsSync22(link) && realpathSync10.native(link) === realpathSync10.native(dir);
|
|
54931
55469
|
}
|
|
54932
55470
|
async function checkout(adapter, deps) {
|
|
54933
55471
|
const fetched = await fetchRelease(adapter.id, deps.releaseUrl, deps.env, deps.signal);
|
|
@@ -55046,12 +55584,12 @@ function checkCall(tool, input) {
|
|
|
55046
55584
|
}
|
|
55047
55585
|
|
|
55048
55586
|
// src/entries/is-entry.ts
|
|
55049
|
-
import { realpathSync as
|
|
55587
|
+
import { realpathSync as realpathSync11 } from "node:fs";
|
|
55050
55588
|
function isEntry(main, argv1, self) {
|
|
55051
55589
|
if (main !== void 0) return main;
|
|
55052
55590
|
if (argv1 === void 0 || argv1 === "") return false;
|
|
55053
55591
|
try {
|
|
55054
|
-
return
|
|
55592
|
+
return realpathSync11(argv1) === realpathSync11(self);
|
|
55055
55593
|
} catch {
|
|
55056
55594
|
return false;
|
|
55057
55595
|
}
|
|
@@ -55127,7 +55665,7 @@ function workspaceFromMeta(meta3) {
|
|
|
55127
55665
|
}
|
|
55128
55666
|
function realOrSame(p) {
|
|
55129
55667
|
try {
|
|
55130
|
-
return
|
|
55668
|
+
return realpathSync12.native(p);
|
|
55131
55669
|
} catch {
|
|
55132
55670
|
return p;
|
|
55133
55671
|
}
|
|
@@ -55175,15 +55713,15 @@ async function startServer(argv, env) {
|
|
|
55175
55713
|
opening.catch(() => pending.delete(project.dbPath));
|
|
55176
55714
|
}
|
|
55177
55715
|
const db = await opening;
|
|
55178
|
-
if (!
|
|
55716
|
+
if (!existsSync23(db.path)) throw new CtxError("DB_GONE");
|
|
55179
55717
|
return db;
|
|
55180
55718
|
}
|
|
55181
55719
|
function stopMarker(configDir, projectKey) {
|
|
55182
|
-
return
|
|
55720
|
+
return join23(configDir, PROJECTS_DIR_NAME, projectKey, OWNERS_DIR_NAME, serverId + OWNER_STOP_EXT);
|
|
55183
55721
|
}
|
|
55184
55722
|
function stopRequested() {
|
|
55185
55723
|
const configDir = resolveConfigDir(process.env);
|
|
55186
|
-
return held.some((db) =>
|
|
55724
|
+
return held.some((db) => existsSync23(stopMarker(configDir, db.projectKey)));
|
|
55187
55725
|
}
|
|
55188
55726
|
async function journal(project, ctx, name, reply4) {
|
|
55189
55727
|
const db = await ownDb(project);
|