context-doctor 0.41.0 → 0.43.0
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/README.md +7 -4
- package/dist/ab.js +3 -1
- package/dist/autopilot.d.ts +1 -1
- package/dist/autopilot.js +38 -24
- package/dist/budget.d.ts +54 -1
- package/dist/budget.js +207 -53
- package/dist/cachettl.js +12 -9
- package/dist/claudedir.d.ts +8 -0
- package/dist/claudedir.js +19 -0
- package/dist/cli.js +90 -15
- package/dist/codexcompact.d.ts +116 -0
- package/dist/codexcompact.js +415 -0
- package/dist/codexdir.d.ts +11 -0
- package/dist/codexdir.js +20 -0
- package/dist/codexroute.d.ts +1 -0
- package/dist/codexroute.js +3 -1
- package/dist/compactwindow.js +12 -9
- package/dist/cursor.js +20 -5
- package/dist/doctor.d.ts +9 -0
- package/dist/doctor.js +42 -14
- package/dist/effective.d.ts +18 -0
- package/dist/effective.js +39 -4
- package/dist/extract.d.ts +12 -3
- package/dist/extract.js +39 -12
- package/dist/fileparams.d.ts +1 -1
- package/dist/fileparams.js +8 -8
- package/dist/fix.d.ts +33 -4
- package/dist/fix.js +221 -19
- package/dist/hook.js +35 -5
- package/dist/install.js +106 -47
- package/dist/ledger.d.ts +17 -1
- package/dist/ledger.js +31 -1
- package/dist/limits.d.ts +15 -1
- package/dist/limits.js +71 -28
- package/dist/mcp.js +58 -58
- package/dist/overhead.js +2 -1
- package/dist/pack.js +3 -2
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/recall.js +3 -2
- package/dist/scan.d.ts +2 -0
- package/dist/scan.js +2 -1
- package/dist/session.js +2 -1
- package/dist/sessionprice.d.ts +71 -0
- package/dist/sessionprice.js +216 -0
- package/dist/settingsedit.d.ts +4 -0
- package/dist/settingsedit.js +61 -3
- package/dist/spend.d.ts +8 -1
- package/dist/spend.js +27 -10
- package/dist/subagentmodel.d.ts +19 -4
- package/dist/subagentmodel.js +116 -28
- package/dist/tooloutput.d.ts +118 -0
- package/dist/tooloutput.js +355 -0
- package/package.json +1 -1
package/dist/doctor.js
CHANGED
|
@@ -25,8 +25,10 @@ import { describeDesktopUsage, desktopUsage } from "./desktopusage.js";
|
|
|
25
25
|
import { withInvocation } from "./invocation.js";
|
|
26
26
|
import { describeInstalls, modelSwitchReadiness, PRE_MODEL_SWITCH_SINCE } from "./modelswitch.js";
|
|
27
27
|
import { describeCosts, subagentCostsPath } from "./fanout.js";
|
|
28
|
-
import { claudeDir, claudeJsonPath } from "./claudedir.js";
|
|
28
|
+
import { claudeCodePresent, claudeDir, claudeJsonPath } from "./claudedir.js";
|
|
29
|
+
import { codexDir } from "./codexdir.js";
|
|
29
30
|
import { periodSpend, readBudget } from "./budget.js";
|
|
31
|
+
import { sessionPriceThresholds } from "./sessionprice.js";
|
|
30
32
|
function claudeDesktopConfigPath() {
|
|
31
33
|
switch (platform()) {
|
|
32
34
|
case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
|
|
@@ -410,16 +412,30 @@ function vsCodeDuplicateCheck() {
|
|
|
410
412
|
function hooksDisabled(layers) {
|
|
411
413
|
return layers.reduce((off, s) => (typeof s.disableAllHooks === "boolean" ? s.disableAllHooks : off), false);
|
|
412
414
|
}
|
|
415
|
+
/**
|
|
416
|
+
* How long the handshake may take: 15 s, or CONTEXT_DOCTOR_MCP_HANDSHAKE_MS.
|
|
417
|
+
* 5 s failed on a loaded machine (Node starting the server is most of it); a
|
|
418
|
+
* server that crashes is reported as soon as it exits, so only one that
|
|
419
|
+
* hangs alive waits this long.
|
|
420
|
+
*/
|
|
421
|
+
export function handshakeTimeoutMs(env = process.env) {
|
|
422
|
+
const v = Number(env.CONTEXT_DOCTOR_MCP_HANDSHAKE_MS);
|
|
423
|
+
return Number.isFinite(v) && v > 0 ? v : 15_000;
|
|
424
|
+
}
|
|
413
425
|
/** Spawn our own MCP server and run the initialize handshake over stdio. */
|
|
414
|
-
function checkMcpHandshake() {
|
|
426
|
+
export function checkMcpHandshake(mcpPath = join(dirname(fileURLToPath(import.meta.url)), "mcp.js"), timeoutMs = handshakeTimeoutMs()) {
|
|
415
427
|
const label = "MCP server handshake";
|
|
416
|
-
const mcpPath = join(dirname(fileURLToPath(import.meta.url)), "mcp.js");
|
|
417
428
|
return new Promise((resolve) => {
|
|
418
429
|
const child = spawn(process.execPath, [mcpPath], { stdio: ["pipe", "pipe", "ignore"] });
|
|
419
430
|
const timer = setTimeout(() => {
|
|
420
431
|
child.kill();
|
|
421
|
-
resolve({ label, status: "fail", detail:
|
|
422
|
-
},
|
|
432
|
+
resolve({ label, status: "fail", detail: `no initialize response within ${Math.round(timeoutMs / 100) / 10}s` });
|
|
433
|
+
}, timeoutMs);
|
|
434
|
+
// A server that dies before answering is a failure now, not after the timeout (after its output, so a last reply still counts).
|
|
435
|
+
child.on("close", (code, signal) => {
|
|
436
|
+
clearTimeout(timer);
|
|
437
|
+
resolve({ label, status: "fail", detail: `the server exited (${signal ?? `code ${code}`}) before answering initialize` });
|
|
438
|
+
});
|
|
423
439
|
let out = "";
|
|
424
440
|
child.stdout.on("data", (d) => {
|
|
425
441
|
out += d.toString();
|
|
@@ -443,6 +459,7 @@ function checkMcpHandshake() {
|
|
|
443
459
|
clearTimeout(timer);
|
|
444
460
|
resolve({ label, status: "fail", detail: e.message });
|
|
445
461
|
});
|
|
462
|
+
child.stdin.on("error", () => { });
|
|
446
463
|
child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "doctor", version: "1" } } }) + "\n");
|
|
447
464
|
});
|
|
448
465
|
}
|
|
@@ -467,7 +484,7 @@ export async function runDoctor() {
|
|
|
467
484
|
// Hook registration. ~/.claude without a settings.json is Claude Code with
|
|
468
485
|
// no hook registered, not Claude Code absent.
|
|
469
486
|
const settingsPath = join(claudeDir(), "settings.json");
|
|
470
|
-
if (existsSync(settingsPath) ||
|
|
487
|
+
if (existsSync(settingsPath) || claudeCodePresent()) {
|
|
471
488
|
try {
|
|
472
489
|
const settings = readConfig(settingsPath) ?? {};
|
|
473
490
|
const entries = settings.hooks?.UserPromptSubmit ?? [];
|
|
@@ -527,7 +544,7 @@ export async function runDoctor() {
|
|
|
527
544
|
});
|
|
528
545
|
}
|
|
529
546
|
// Codex (OpenAI): MCP table in config.toml, hook in hooks.json, skill.
|
|
530
|
-
const codexHome =
|
|
547
|
+
const codexHome = codexDir();
|
|
531
548
|
if (existsSync(codexHome)) {
|
|
532
549
|
const toml = existsSync(join(codexHome, "config.toml")) ? readFileSync(join(codexHome, "config.toml"), "utf8") : "";
|
|
533
550
|
// Parsed rather than searched for one exact header: a quoted key or a
|
|
@@ -540,7 +557,7 @@ export async function runDoctor() {
|
|
|
540
557
|
: { label: "Codex MCP", status: "fail", detail: "Codex detected but not wired — run: context-doctor install" }
|
|
541
558
|
: launcherNamesMissingPackage(codexEntry)
|
|
542
559
|
? missingPackageCheck("Codex MCP")
|
|
543
|
-
: { label: "Codex MCP", status: "ok", detail:
|
|
560
|
+
: { label: "Codex MCP", status: "ok", detail: `wired in ${tilde(join(codexHome, "config.toml"))}` };
|
|
544
561
|
checks.push(codexMcp);
|
|
545
562
|
const codexSkill = join(codexHome, "skills", "context-doctor", "SKILL.md");
|
|
546
563
|
if (existsSync(codexSkill))
|
|
@@ -557,24 +574,24 @@ export async function runDoctor() {
|
|
|
557
574
|
const missing = hookBinaryMissing(ours);
|
|
558
575
|
checks.push(missing
|
|
559
576
|
? { label: "Codex hook", status: "fail", detail: `registered, but ${missing} no longer exists — re-run: context-doctor install` }
|
|
560
|
-
: { label: "Codex hook", status: "ok", detail:
|
|
577
|
+
: { label: "Codex hook", status: "ok", detail: `registered in ${tilde(join(codexHome, "hooks.json"))} (Codex must trust it once: /hooks)` });
|
|
561
578
|
}
|
|
562
579
|
}
|
|
563
580
|
catch (e) {
|
|
564
|
-
checks.push({ label: "Codex hook", status: "fail", detail:
|
|
581
|
+
checks.push({ label: "Codex hook", status: "fail", detail: `${tilde(join(codexHome, "hooks.json"))} unreadable (${e.message})` });
|
|
565
582
|
}
|
|
566
583
|
// Autopilot reaches Codex through openai_base_url (OPENAI_BASE_URL no
|
|
567
584
|
// longer routes it), and only on an API key.
|
|
568
585
|
const route = codexRouting(homedir());
|
|
569
586
|
const local = route.baseUrl && /^http:\/\/(127\.0\.0\.1|localhost):\d+\/v1\/?$/.test(route.baseUrl);
|
|
570
587
|
if (local && route.auth !== "apikey") {
|
|
571
|
-
checks.push({ label: "Codex autopilot", status: "warn", detail: `openai_base_url points at ${route.baseUrl} while Codex signs in ${route.auth === "chatgpt" ? "with ChatGPT" : "without an API key"}: autopilot routes Codex only on an API key (the proxy relays ChatGPT traffic unedited meanwhile); remove the line from
|
|
588
|
+
checks.push({ label: "Codex autopilot", status: "warn", detail: `openai_base_url points at ${route.baseUrl} while Codex signs in ${route.auth === "chatgpt" ? "with ChatGPT" : "without an API key"}: autopilot routes Codex only on an API key (the proxy relays ChatGPT traffic unedited meanwhile); remove the line from ${tilde(join(codexHome, "config.toml"))}` });
|
|
572
589
|
}
|
|
573
590
|
else if (local) {
|
|
574
591
|
checks.push({ label: "Codex autopilot", status: "ok", detail: `Codex (API key) sends its requests through ${route.baseUrl}` });
|
|
575
592
|
}
|
|
576
593
|
else if (process.env.OPENAI_BASE_URL && route.auth === "apikey") {
|
|
577
|
-
checks.push({ label: "Codex autopilot", status: "warn", detail:
|
|
594
|
+
checks.push({ label: "Codex autopilot", status: "warn", detail: `OPENAI_BASE_URL is set, but Codex no longer reads it: \`context-doctor autopilot on\` sets openai_base_url in ${tilde(join(codexHome, "config.toml"))}` });
|
|
578
595
|
}
|
|
579
596
|
}
|
|
580
597
|
else {
|
|
@@ -742,11 +759,22 @@ export async function runDoctor() {
|
|
|
742
759
|
}
|
|
743
760
|
catch { /* the ledger could not be read: the budget alone */ }
|
|
744
761
|
const hooked = checks.some((c) => ["Every-prompt hook", "Codex hook", "Gemini CLI hook"].includes(c.label) && c.status === "ok");
|
|
762
|
+
// As `budget` writes it: $50, $1,000, $12.50 (it printed $12.5 and $1000).
|
|
763
|
+
const usd = Number.isInteger(b.usd) ? `$${b.usd.toLocaleString("en-US")}` : `$${b.usd.toFixed(2)}`;
|
|
745
764
|
checks.push(hooked
|
|
746
|
-
? { label: "Spend budget", status: "ok", detail:
|
|
747
|
-
: { label: "Spend budget", status: "warn", detail:
|
|
765
|
+
? { label: "Spend budget", status: "ok", detail: `${usd} a ${b.period}${b.block ? ", prompts over it held" : ", warns at 50/80/100%"}${spent}` }
|
|
766
|
+
: { label: "Spend budget", status: "warn", detail: `${usd} a ${b.period}${spent}, but no every-prompt hook is registered to apply it: run context-doctor install` });
|
|
748
767
|
}
|
|
749
768
|
}
|
|
769
|
+
// The session price: where the every-prompt hook speaks, and how to change or stop it.
|
|
770
|
+
{
|
|
771
|
+
const at = sessionPriceThresholds();
|
|
772
|
+
const hooked = checks.some((c) => ["Every-prompt hook", "Codex hook", "Gemini CLI hook"].includes(c.label) && c.status === "ok");
|
|
773
|
+
if (!at.length)
|
|
774
|
+
checks.push({ label: "Session price", status: "skip", detail: "off (CONTEXT_DOCTOR_NO_SESSION_PRICE=1)" });
|
|
775
|
+
else if (hooked)
|
|
776
|
+
checks.push({ label: "Session price", status: "ok", detail: `said once when a session passes ${at.map((t) => `$${t.toLocaleString("en-US")}`).join(", ").replace(/, ([^,]+)$/, " and $1")} (CONTEXT_DOCTOR_SESSION_PRICE to change; CONTEXT_DOCTOR_NO_SESSION_PRICE=1 for off)` });
|
|
777
|
+
}
|
|
750
778
|
checks.push(await checkMcpHandshake());
|
|
751
779
|
// Autopilot: optional, so "off" is a skip, not a failure. When it is on, a
|
|
752
780
|
// dead proxy or a settings file pointing elsewhere is a real problem.
|
package/dist/effective.d.ts
CHANGED
|
@@ -25,6 +25,8 @@ export interface SettingsSource {
|
|
|
25
25
|
path: string;
|
|
26
26
|
settings: Record<string, any>;
|
|
27
27
|
}
|
|
28
|
+
/** The platform's folder for managed (policy) configuration; undefined when context-doctor is told to ignore it. */
|
|
29
|
+
export declare function managedDir(env?: NodeJS.ProcessEnv): string | undefined;
|
|
28
30
|
/** Managed (policy) settings files: CLAUDE_CODE_MANAGED_SETTINGS_PATH, else the platform's place and its drop-in folder. */
|
|
29
31
|
export declare function managedSettingsPaths(env?: NodeJS.ProcessEnv): string[];
|
|
30
32
|
/** The settings files that apply in `cwd`, highest precedence first; unreadable ones are skipped. */
|
|
@@ -33,6 +35,22 @@ export declare function settingsSources(opts?: {
|
|
|
33
35
|
cwd?: string;
|
|
34
36
|
env?: NodeJS.ProcessEnv;
|
|
35
37
|
}): SettingsSource[];
|
|
38
|
+
/** Run from inside a Claude Code session (its Bash tool, a plugin command): Claude Code sets CLAUDECODE for its children. */
|
|
39
|
+
export declare function underClaudeCode(env?: NodeJS.ProcessEnv): boolean;
|
|
40
|
+
/**
|
|
41
|
+
* Where a value found in the process environment came from, for messages.
|
|
42
|
+
* Inside a Claude Code session the process carries every settings file's
|
|
43
|
+
* `env` as it was when the session started, so a value no settings file
|
|
44
|
+
* holds now is the launching shell's or one removed from settings since.
|
|
45
|
+
*/
|
|
46
|
+
export declare function processEnvWhere(name: string, value: string, env?: NodeJS.ProcessEnv): string;
|
|
47
|
+
/**
|
|
48
|
+
* Is the process's value of `name` one the user set in their shell? Not when
|
|
49
|
+
* a settings file's `env` holds the same value (Claude Code copied it into
|
|
50
|
+
* the session this runs in), nor, inside Claude Code, when it is `written`,
|
|
51
|
+
* the value context-doctor itself wrote: a copy left from before an undo.
|
|
52
|
+
*/
|
|
53
|
+
export declare function shellSet(name: string, sources: SettingsSource[], env?: NodeJS.ProcessEnv, written?: string): boolean;
|
|
36
54
|
/** An environment variable as Claude Code sees it: a settings file's `env` (highest first), else the process. */
|
|
37
55
|
export declare function effectiveEnv(name: string, sources: SettingsSource[], env?: NodeJS.ProcessEnv): {
|
|
38
56
|
value: string;
|
package/dist/effective.js
CHANGED
|
@@ -23,15 +23,21 @@ import { existsSync, readdirSync } from "node:fs";
|
|
|
23
23
|
import { join } from "node:path";
|
|
24
24
|
import { claudeDir, tilde } from "./claudedir.js";
|
|
25
25
|
import { readSettings } from "./settingsedit.js";
|
|
26
|
+
/** The platform's folder for managed (policy) configuration; undefined when context-doctor is told to ignore it. */
|
|
27
|
+
export function managedDir(env = process.env) {
|
|
28
|
+
if (env.CONTEXT_DOCTOR_NO_MANAGED_SETTINGS)
|
|
29
|
+
return undefined;
|
|
30
|
+
return process.platform === "darwin" ? "/Library/Application Support/ClaudeCode"
|
|
31
|
+
: process.platform === "win32" ? join(env.ProgramFiles ?? "C:\\Program Files", "ClaudeCode")
|
|
32
|
+
: "/etc/claude-code";
|
|
33
|
+
}
|
|
26
34
|
/** Managed (policy) settings files: CLAUDE_CODE_MANAGED_SETTINGS_PATH, else the platform's place and its drop-in folder. */
|
|
27
35
|
export function managedSettingsPaths(env = process.env) {
|
|
28
36
|
if (env.CONTEXT_DOCTOR_NO_MANAGED_SETTINGS)
|
|
29
37
|
return [];
|
|
30
38
|
if (env.CLAUDE_CODE_MANAGED_SETTINGS_PATH)
|
|
31
39
|
return [env.CLAUDE_CODE_MANAGED_SETTINGS_PATH];
|
|
32
|
-
const dir =
|
|
33
|
-
: process.platform === "win32" ? join(env.ProgramFiles ?? "C:\\Program Files", "ClaudeCode")
|
|
34
|
-
: "/etc/claude-code";
|
|
40
|
+
const dir = managedDir(env);
|
|
35
41
|
const out = [join(dir, "managed-settings.json")];
|
|
36
42
|
try {
|
|
37
43
|
for (const f of readdirSync(join(dir, "managed-settings.d")).sort())
|
|
@@ -72,6 +78,35 @@ export function settingsSources(opts = {}) {
|
|
|
72
78
|
}
|
|
73
79
|
return out;
|
|
74
80
|
}
|
|
81
|
+
/** Run from inside a Claude Code session (its Bash tool, a plugin command): Claude Code sets CLAUDECODE for its children. */
|
|
82
|
+
export function underClaudeCode(env = process.env) {
|
|
83
|
+
return !!env.CLAUDECODE?.trim();
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Where a value found in the process environment came from, for messages.
|
|
87
|
+
* Inside a Claude Code session the process carries every settings file's
|
|
88
|
+
* `env` as it was when the session started, so a value no settings file
|
|
89
|
+
* holds now is the launching shell's or one removed from settings since.
|
|
90
|
+
*/
|
|
91
|
+
export function processEnvWhere(name, value, env = process.env) {
|
|
92
|
+
return underClaudeCode(env)
|
|
93
|
+
? `${name}=${value} in this Claude Code session's environment (from the shell that started it, or a settings env removed since: a new session reads settings again)`
|
|
94
|
+
: `${name}=${value} in the environment`;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Is the process's value of `name` one the user set in their shell? Not when
|
|
98
|
+
* a settings file's `env` holds the same value (Claude Code copied it into
|
|
99
|
+
* the session this runs in), nor, inside Claude Code, when it is `written`,
|
|
100
|
+
* the value context-doctor itself wrote: a copy left from before an undo.
|
|
101
|
+
*/
|
|
102
|
+
export function shellSet(name, sources, env = process.env, written) {
|
|
103
|
+
const v = env[name];
|
|
104
|
+
if (v === undefined || v.trim() === "")
|
|
105
|
+
return false;
|
|
106
|
+
if (sources.some((s) => s.settings.env?.[name] !== undefined && s.settings.env[name] !== null && String(s.settings.env[name]) === v))
|
|
107
|
+
return false;
|
|
108
|
+
return !(underClaudeCode(env) && written !== undefined && v === written);
|
|
109
|
+
}
|
|
75
110
|
/** An environment variable as Claude Code sees it: a settings file's `env` (highest first), else the process. */
|
|
76
111
|
export function effectiveEnv(name, sources, env = process.env) {
|
|
77
112
|
for (const s of sources) {
|
|
@@ -81,7 +116,7 @@ export function effectiveEnv(name, sources, env = process.env) {
|
|
|
81
116
|
}
|
|
82
117
|
const v = env[name];
|
|
83
118
|
if (v !== undefined && v.trim() !== "")
|
|
84
|
-
return { value: v, where:
|
|
119
|
+
return { value: v, where: processEnvWhere(name, v, env) };
|
|
85
120
|
return undefined;
|
|
86
121
|
}
|
|
87
122
|
const truthy = (v) => v !== "0" && v.toLowerCase() !== "false";
|
package/dist/extract.d.ts
CHANGED
|
@@ -30,10 +30,19 @@ export declare function extractText(path: string): {
|
|
|
30
30
|
/** Default time budget for one extraction call in the MCP server. */
|
|
31
31
|
export declare const EXTRACT_BUDGET_MS = 20000;
|
|
32
32
|
/**
|
|
33
|
-
*
|
|
34
|
-
*
|
|
33
|
+
* Milliseconds on a monotonic clock. The budget is counted on it, never on
|
|
34
|
+
* Date.now(): a wall clock can jump forward (time sync after a boot), and a
|
|
35
|
+
* jump read as the budget running out.
|
|
35
36
|
*/
|
|
36
|
-
export declare
|
|
37
|
+
export declare const monotonicNow: () => number;
|
|
38
|
+
/**
|
|
39
|
+
* extractText for a server: asynchronous, and bounded by `end` (on the
|
|
40
|
+
* monotonic clock, monotonicNow()) across every tool it tries. Past it the
|
|
41
|
+
* reason says so. A caller with one budget for several documents sets one
|
|
42
|
+
* `end` on the same clock: a deadline on the wall clock, converted per
|
|
43
|
+
* document, let a clock jump between two documents cut the later ones short.
|
|
44
|
+
*/
|
|
45
|
+
export declare function extractTextAsync(path: string, end?: number): Promise<{
|
|
37
46
|
text: string;
|
|
38
47
|
} | {
|
|
39
48
|
error: string;
|
package/dist/extract.js
CHANGED
|
@@ -101,14 +101,34 @@ export function extractText(path) {
|
|
|
101
101
|
}
|
|
102
102
|
/** Default time budget for one extraction call in the MCP server. */
|
|
103
103
|
export const EXTRACT_BUDGET_MS = 20_000;
|
|
104
|
+
/**
|
|
105
|
+
* Milliseconds on a monotonic clock. The budget is counted on it, never on
|
|
106
|
+
* Date.now(): a wall clock can jump forward (time sync after a boot), and a
|
|
107
|
+
* jump read as the budget running out.
|
|
108
|
+
*/
|
|
109
|
+
export const monotonicNow = () => performance.now();
|
|
110
|
+
/**
|
|
111
|
+
* The longest one tool may run: half the time left (at least 2 s), and never
|
|
112
|
+
* more than the 30 s the synchronous path gives a tool. One form of
|
|
113
|
+
* pdftotext hanging used to take the whole budget, so the next form was
|
|
114
|
+
* never tried: Windows runners reported a PDF as "not read: the time ran
|
|
115
|
+
* out" inside a 60 s budget that the synchronous read of the same file
|
|
116
|
+
* (30 s a tool) got through.
|
|
117
|
+
*/
|
|
118
|
+
function toolCap(left) {
|
|
119
|
+
return Math.min(left, 30_000, Math.max(2_000, left / 2));
|
|
120
|
+
}
|
|
104
121
|
/**
|
|
105
122
|
* A command's stdout, or undefined, without blocking the event loop: killed
|
|
106
|
-
* (SIGKILL) when
|
|
123
|
+
* (SIGKILL) when its share of the time (toolCap) runs out. `timedOut` is set
|
|
124
|
+
* only when `end` (on the monotonic clock) has passed: a tool stopped
|
|
125
|
+
* earlier is a failed tool, and the next one is tried.
|
|
107
126
|
*/
|
|
108
|
-
function runAsync(cmd, args,
|
|
109
|
-
const
|
|
110
|
-
if (
|
|
127
|
+
function runAsync(cmd, args, end) {
|
|
128
|
+
const left = Math.ceil(end - monotonicNow());
|
|
129
|
+
if (left <= 0)
|
|
111
130
|
return Promise.resolve({ timedOut: true });
|
|
131
|
+
const timeout = Math.ceil(toolCap(left));
|
|
112
132
|
return new Promise((resolve) => {
|
|
113
133
|
let settled = false;
|
|
114
134
|
const finish = (r) => {
|
|
@@ -124,7 +144,7 @@ function runAsync(cmd, args, deadline) {
|
|
|
124
144
|
// deadline whatever the pipes do.
|
|
125
145
|
const timer = setTimeout(() => {
|
|
126
146
|
child?.kill("SIGKILL");
|
|
127
|
-
finish({ timedOut:
|
|
147
|
+
finish({ timedOut: monotonicNow() >= end - 50 });
|
|
128
148
|
}, timeout);
|
|
129
149
|
try {
|
|
130
150
|
child = execFile(cmd, args, { encoding: "utf8", timeout, killSignal: "SIGKILL", maxBuffer: 64 * 1024 * 1024, windowsHide: true }, (err, stdout) => {
|
|
@@ -132,10 +152,14 @@ function runAsync(cmd, args, deadline) {
|
|
|
132
152
|
// reason (seen on Windows runners, well inside a 60 s budget) is a
|
|
133
153
|
// failed tool, and the next one is tried.
|
|
134
154
|
if (err)
|
|
135
|
-
return finish({ timedOut:
|
|
155
|
+
return finish({ timedOut: monotonicNow() >= end - 50 });
|
|
136
156
|
finish({ out: typeof stdout === "string" && stdout.trim() ? stdout : undefined, timedOut: false });
|
|
137
157
|
});
|
|
138
158
|
child.on("error", () => finish({ timedOut: false }));
|
|
159
|
+
// No input, as spawnSync gives the synchronous path: a converter that
|
|
160
|
+
// reads stdin gets end-of-file instead of waiting out the budget.
|
|
161
|
+
child.stdin?.on("error", () => { });
|
|
162
|
+
child.stdin?.end();
|
|
139
163
|
}
|
|
140
164
|
catch {
|
|
141
165
|
finish({ timedOut: false });
|
|
@@ -143,10 +167,13 @@ function runAsync(cmd, args, deadline) {
|
|
|
143
167
|
});
|
|
144
168
|
}
|
|
145
169
|
/**
|
|
146
|
-
* extractText for a server: asynchronous, and bounded by `
|
|
147
|
-
*
|
|
170
|
+
* extractText for a server: asynchronous, and bounded by `end` (on the
|
|
171
|
+
* monotonic clock, monotonicNow()) across every tool it tries. Past it the
|
|
172
|
+
* reason says so. A caller with one budget for several documents sets one
|
|
173
|
+
* `end` on the same clock: a deadline on the wall clock, converted per
|
|
174
|
+
* document, let a clock jump between two documents cut the later ones short.
|
|
148
175
|
*/
|
|
149
|
-
export async function extractTextAsync(path,
|
|
176
|
+
export async function extractTextAsync(path, end = monotonicNow() + EXTRACT_BUDGET_MS) {
|
|
150
177
|
const ext = extname(path).toLowerCase();
|
|
151
178
|
const mac = process.platform === "darwin";
|
|
152
179
|
let text;
|
|
@@ -154,7 +181,7 @@ export async function extractTextAsync(path, deadline = Date.now() + EXTRACT_BUD
|
|
|
154
181
|
const tryRun = async (cmd, args) => {
|
|
155
182
|
if (text || timedOut)
|
|
156
183
|
return;
|
|
157
|
-
const r = await runAsync(cmd, args,
|
|
184
|
+
const r = await runAsync(cmd, args, end);
|
|
158
185
|
if (r.timedOut)
|
|
159
186
|
timedOut = true;
|
|
160
187
|
else
|
|
@@ -167,7 +194,7 @@ export async function extractTextAsync(path, deadline = Date.now() + EXTRACT_BUD
|
|
|
167
194
|
if (!text && !timedOut) {
|
|
168
195
|
const out = join(mkdtempSync(join(tmpdir(), "cd-pdf-")), "out.txt");
|
|
169
196
|
try {
|
|
170
|
-
const r = await runAsync("pdftotext", [path, out],
|
|
197
|
+
const r = await runAsync("pdftotext", [path, out], end);
|
|
171
198
|
if (r.timedOut)
|
|
172
199
|
timedOut = true;
|
|
173
200
|
else if (existsSync(out))
|
|
@@ -192,7 +219,7 @@ export async function extractTextAsync(path, deadline = Date.now() + EXTRACT_BUD
|
|
|
192
219
|
if (!text && !timedOut) {
|
|
193
220
|
const members = ext === ".docx" ? ["word/document.xml"] : ext === ".pptx" ? ["ppt/slides/*.xml"] : ext === ".odt" ? ["content.xml"] : [];
|
|
194
221
|
if (members.length) {
|
|
195
|
-
const r = await runAsync("unzip", ["-p", path, ...members],
|
|
222
|
+
const r = await runAsync("unzip", ["-p", path, ...members], end);
|
|
196
223
|
if (r.timedOut)
|
|
197
224
|
timedOut = true;
|
|
198
225
|
else if (r.out)
|
package/dist/fileparams.d.ts
CHANGED
|
@@ -43,7 +43,7 @@ export declare function checkFileUrl(raw: string, env?: NodeJS.ProcessEnv): {
|
|
|
43
43
|
};
|
|
44
44
|
/**
|
|
45
45
|
* Download one file, following at most FILE_LIMITS.redirects https redirects,
|
|
46
|
-
* within FILE_LIMITS.timeoutMs (or the caller's earlier `deadline
|
|
46
|
+
* within FILE_LIMITS.timeoutMs (or the caller's earlier `deadline`, on the monotonic clock: monotonicNow()) and
|
|
47
47
|
* `maxBytes` (default the per-file limit). Never throws.
|
|
48
48
|
*/
|
|
49
49
|
export declare function downloadFile(raw: string, env?: NodeJS.ProcessEnv, { deadline: callDeadline, maxBytes }?: {
|
package/dist/fileparams.js
CHANGED
|
@@ -24,7 +24,7 @@ import { isIP } from "node:net";
|
|
|
24
24
|
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
|
25
25
|
import { tmpdir } from "node:os";
|
|
26
26
|
import { extname, join } from "node:path";
|
|
27
|
-
import { EXTRACT_BUDGET_MS, EXTRACTABLE, extractTextAsync } from "./extract.js";
|
|
27
|
+
import { EXTRACT_BUDGET_MS, EXTRACTABLE, extractTextAsync, monotonicNow } from "./extract.js";
|
|
28
28
|
/** Per file: bytes and time. Per call: files, bytes and time (downloads and extraction together). */
|
|
29
29
|
export const FILE_LIMITS = { files: 10, bytes: 5 * 1024 * 1024, totalBytes: 20 * 1024 * 1024, timeoutMs: 20_000, redirects: 3, callMs: 60_000 };
|
|
30
30
|
const MIME_EXT = {
|
|
@@ -169,7 +169,7 @@ function getOnce(url, env, deadline, maxBytes) {
|
|
|
169
169
|
clearTimeout(overall);
|
|
170
170
|
resolve(r);
|
|
171
171
|
};
|
|
172
|
-
const timeout = Math.max(1, deadline -
|
|
172
|
+
const timeout = Math.max(1, deadline - monotonicNow());
|
|
173
173
|
// The socket timeout is an idle timeout; a server dripping a byte at a
|
|
174
174
|
// time would never trip it. This one bounds the whole download.
|
|
175
175
|
const overall = setTimeout(() => {
|
|
@@ -220,18 +220,18 @@ function getOnce(url, env, deadline, maxBytes) {
|
|
|
220
220
|
}
|
|
221
221
|
/**
|
|
222
222
|
* Download one file, following at most FILE_LIMITS.redirects https redirects,
|
|
223
|
-
* within FILE_LIMITS.timeoutMs (or the caller's earlier `deadline
|
|
223
|
+
* within FILE_LIMITS.timeoutMs (or the caller's earlier `deadline`, on the monotonic clock: monotonicNow()) and
|
|
224
224
|
* `maxBytes` (default the per-file limit). Never throws.
|
|
225
225
|
*/
|
|
226
226
|
export async function downloadFile(raw, env = process.env, { deadline: callDeadline, maxBytes = FILE_LIMITS.bytes } = {}) {
|
|
227
|
-
const deadline = Math.min(
|
|
227
|
+
const deadline = Math.min(monotonicNow() + FILE_LIMITS.timeoutMs, callDeadline ?? Infinity);
|
|
228
228
|
const limit = Math.max(0, Math.min(maxBytes, FILE_LIMITS.bytes));
|
|
229
229
|
let current = raw;
|
|
230
230
|
for (let hop = 0; hop <= FILE_LIMITS.redirects; hop++) {
|
|
231
231
|
const checked = checkFileUrl(current, env);
|
|
232
232
|
if ("error" in checked)
|
|
233
233
|
return { error: hop === 0 ? `refused: ${checked.error}` : `refused a redirect: ${checked.error}` };
|
|
234
|
-
if (
|
|
234
|
+
if (monotonicNow() >= deadline)
|
|
235
235
|
return { error: "timed out" };
|
|
236
236
|
const r = await getOnce(checked.url, env, deadline, limit);
|
|
237
237
|
if (r.error)
|
|
@@ -263,10 +263,10 @@ export async function sourcesFromOpenAiFiles(files, env = process.env) {
|
|
|
263
263
|
const skipped = [];
|
|
264
264
|
let total = 0;
|
|
265
265
|
// One budget for the whole call, downloads and extraction together.
|
|
266
|
-
const callDeadline =
|
|
266
|
+
const callDeadline = monotonicNow() + FILE_LIMITS.callMs;
|
|
267
267
|
for (const f of files.slice(0, FILE_LIMITS.files)) {
|
|
268
268
|
const name = safeName(f);
|
|
269
|
-
if (
|
|
269
|
+
if (monotonicNow() >= callDeadline) {
|
|
270
270
|
skipped.push(`${name}: not read, the ${FILE_LIMITS.callMs / 1000} s allowed for one call ran out`);
|
|
271
271
|
continue;
|
|
272
272
|
}
|
|
@@ -285,7 +285,7 @@ export async function sourcesFromOpenAiFiles(files, env = process.env) {
|
|
|
285
285
|
const path = join(dir, `upload${docExt}`);
|
|
286
286
|
writeFileSync(path, got.body, { mode: 0o600 });
|
|
287
287
|
// Asynchronous and bounded: a hostile document cannot hold the server.
|
|
288
|
-
const text = await extractTextAsync(path, Math.min(
|
|
288
|
+
const text = await extractTextAsync(path, Math.min(monotonicNow() + EXTRACT_BUDGET_MS, callDeadline));
|
|
289
289
|
if ("error" in text)
|
|
290
290
|
skipped.push(`${name}: ${text.error}`);
|
|
291
291
|
else
|
package/dist/fix.d.ts
CHANGED
|
@@ -24,7 +24,10 @@
|
|
|
24
24
|
* priced);
|
|
25
25
|
* - autopilot: what the proxy recorded saving since (its own ledger);
|
|
26
26
|
* - the subagents' model: the requests it moved, priced at the model they
|
|
27
|
-
* ran on before against as billed (the same token counts: an estimate)
|
|
27
|
+
* ran on before against as billed (the same token counts: an estimate);
|
|
28
|
+
* - long Bash output: the results moved to a file that the cap before left
|
|
29
|
+
* inline, priced at the requests that re-read them no more (an estimate:
|
|
30
|
+
* a file the model opens again is not counted).
|
|
28
31
|
*
|
|
29
32
|
* The subagents' model is the one lever with a quality cost `fix` cannot
|
|
30
33
|
* measure: it is offered with that said, applied only when named (never by
|
|
@@ -34,13 +37,17 @@ import { type CacheTtlReport, type CurrentTtl } from "./cachettl.js";
|
|
|
34
37
|
import { type ProjectPlan } from "./prune.js";
|
|
35
38
|
import { readLedger } from "./ledger.js";
|
|
36
39
|
import { type SubagentModelReplay } from "./subagentmodel.js";
|
|
37
|
-
|
|
40
|
+
import { type ToolOutputReplay } from "./tooloutput.js";
|
|
41
|
+
import { type CodexCompactReport } from "./codexcompact.js";
|
|
42
|
+
export type FixId = "compact-window" | "cache-ttl" | "cache-ttl-subagents" | "autopilot" | "tool-search" | "prune" | "subagent-model" | "tool-output" | "codex-compact";
|
|
38
43
|
export interface Fix {
|
|
39
44
|
id: FixId;
|
|
40
45
|
title: string;
|
|
41
46
|
/** Saved over the measured period, when it can be priced. */
|
|
42
47
|
savedUsd?: number;
|
|
43
48
|
savedShare?: number;
|
|
49
|
+
/** What the share is of, when it is not the input the plan's first line names ("of subagents"). */
|
|
50
|
+
shareOf?: string;
|
|
44
51
|
/** How the figure was measured. */
|
|
45
52
|
basis: string;
|
|
46
53
|
/** What it costs in quality, plainly. */
|
|
@@ -102,6 +109,21 @@ export interface FixInputs {
|
|
|
102
109
|
returns: number;
|
|
103
110
|
hooked: boolean;
|
|
104
111
|
};
|
|
112
|
+
/** Every Bash and MCP result replayed at lower caps (tooloutput.ts). */
|
|
113
|
+
toolOutput?: ToolOutputReplay;
|
|
114
|
+
/** bashOutputMaxChars in the user's settings.json, or BASH_MAX_OUTPUT_LENGTH as the user set it (the setting would replace it): never overwritten. */
|
|
115
|
+
toolOutputSet?: {
|
|
116
|
+
name: string;
|
|
117
|
+
value: string | number;
|
|
118
|
+
where: string;
|
|
119
|
+
};
|
|
120
|
+
/** Codex's rollouts replayed at earlier auto-compact limits (codexcompact.ts). */
|
|
121
|
+
codexCompact?: CodexCompactReport;
|
|
122
|
+
/** model_auto_compact_token_limit at the top of the user's config.toml, as written: never overwritten. */
|
|
123
|
+
codexCompactSet?: {
|
|
124
|
+
raw: string;
|
|
125
|
+
where: string;
|
|
126
|
+
};
|
|
105
127
|
}
|
|
106
128
|
export declare function planFixes(i: FixInputs): Fix[];
|
|
107
129
|
export interface FixRecord {
|
|
@@ -124,9 +146,15 @@ export interface FixRecord {
|
|
|
124
146
|
oneHourShareBefore?: number;
|
|
125
147
|
/** For prune: the project folder. */
|
|
126
148
|
cwd?: string;
|
|
127
|
-
/** For subagent-model: the models the moved subagents ran on before the change, each one's share of their
|
|
149
|
+
/** For subagent-model: the models the moved types' subagents ran on before the change, each one's share of their tokens (Sonnet-or-cheaper ones included): the baseline "since" compares against. */
|
|
128
150
|
modelsBefore?: Record<string, number>;
|
|
129
151
|
}
|
|
152
|
+
/**
|
|
153
|
+
* ~/.claude/.context-doctor-fixes.json, as always. On a machine with no
|
|
154
|
+
* ~/.claude (Codex only), the state folder the ledger falls back to: `fix`
|
|
155
|
+
* must not make a ~/.claude there. Once records are in that folder they stay
|
|
156
|
+
* there, so a Claude Code installed later does not strand them.
|
|
157
|
+
*/
|
|
130
158
|
export declare function fixRecordPath(home?: string): string;
|
|
131
159
|
/**
|
|
132
160
|
* The records, strictly: an absent file is none; a file that is not ours to
|
|
@@ -185,9 +213,10 @@ export declare function compactWindowSavingsSince(since: number, previousWindow:
|
|
|
185
213
|
export declare function savedSince(records: FixRecord[], opts?: {
|
|
186
214
|
paths?: string[];
|
|
187
215
|
subagentPaths?: string[];
|
|
216
|
+
codexPaths?: string[];
|
|
188
217
|
ledger?: ReturnType<typeof readLedger>;
|
|
189
218
|
}): SinceResult[];
|
|
190
|
-
export declare function renderFixPlan(days: number, billedUsd: number, fixes: Fix[], since: SinceResult[], command?: (s: string) => string, coldResume?: FixInputs["coldResume"], recordProblem?: string): string;
|
|
219
|
+
export declare function renderFixPlan(days: number, billedUsd: number, fixes: Fix[], since: SinceResult[], command?: (s: string) => string, coldResume?: FixInputs["coldResume"], recordProblem?: string, codexBilledUsd?: number): string;
|
|
191
220
|
export declare function renderFixShare(days: number, billedUsd: number, fixes: Fix[]): string;
|
|
192
221
|
export declare function parseFixIds(raw: string, fixes: Fix[]): {
|
|
193
222
|
ids: FixId[];
|