context-doctor 0.40.0 → 0.42.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 +12 -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 +102 -0
- package/dist/budget.js +550 -0
- package/dist/cachettl.js +12 -9
- package/dist/claudedir.d.ts +8 -0
- package/dist/claudedir.js +19 -0
- package/dist/cli.js +145 -15
- 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.d.ts +23 -0
- package/dist/cursor.js +140 -6
- package/dist/doctor.d.ts +9 -0
- package/dist/doctor.js +49 -12
- 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 +23 -2
- package/dist/fix.js +86 -10
- package/dist/hook.js +45 -7
- package/dist/install.js +108 -47
- package/dist/ledger.d.ts +15 -0
- package/dist/ledger.js +30 -1
- package/dist/limits.d.ts +53 -6
- package/dist/limits.js +152 -77
- 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 +10 -0
- package/dist/scan.js +23 -1
- package/dist/session.js +2 -1
- package/dist/settingsedit.d.ts +4 -0
- package/dist/settingsedit.js +61 -3
- package/dist/spend.d.ts +183 -0
- package/dist/spend.js +493 -0
- package/dist/statusline.d.ts +9 -2
- package/dist/statusline.js +20 -4
- package/dist/subagentmodel.d.ts +141 -0
- package/dist/subagentmodel.js +408 -0
- package/dist/subagentpay.d.ts +11 -0
- package/dist/subagentpay.js +23 -4
- package/package.json +1 -1
package/dist/doctor.js
CHANGED
|
@@ -25,7 +25,9 @@ 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";
|
|
30
|
+
import { periodSpend, readBudget } from "./budget.js";
|
|
29
31
|
function claudeDesktopConfigPath() {
|
|
30
32
|
switch (platform()) {
|
|
31
33
|
case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
|
|
@@ -409,16 +411,30 @@ function vsCodeDuplicateCheck() {
|
|
|
409
411
|
function hooksDisabled(layers) {
|
|
410
412
|
return layers.reduce((off, s) => (typeof s.disableAllHooks === "boolean" ? s.disableAllHooks : off), false);
|
|
411
413
|
}
|
|
414
|
+
/**
|
|
415
|
+
* How long the handshake may take: 15 s, or CONTEXT_DOCTOR_MCP_HANDSHAKE_MS.
|
|
416
|
+
* 5 s failed on a loaded machine (Node starting the server is most of it); a
|
|
417
|
+
* server that crashes is reported as soon as it exits, so only one that
|
|
418
|
+
* hangs alive waits this long.
|
|
419
|
+
*/
|
|
420
|
+
export function handshakeTimeoutMs(env = process.env) {
|
|
421
|
+
const v = Number(env.CONTEXT_DOCTOR_MCP_HANDSHAKE_MS);
|
|
422
|
+
return Number.isFinite(v) && v > 0 ? v : 15_000;
|
|
423
|
+
}
|
|
412
424
|
/** Spawn our own MCP server and run the initialize handshake over stdio. */
|
|
413
|
-
function checkMcpHandshake() {
|
|
425
|
+
export function checkMcpHandshake(mcpPath = join(dirname(fileURLToPath(import.meta.url)), "mcp.js"), timeoutMs = handshakeTimeoutMs()) {
|
|
414
426
|
const label = "MCP server handshake";
|
|
415
|
-
const mcpPath = join(dirname(fileURLToPath(import.meta.url)), "mcp.js");
|
|
416
427
|
return new Promise((resolve) => {
|
|
417
428
|
const child = spawn(process.execPath, [mcpPath], { stdio: ["pipe", "pipe", "ignore"] });
|
|
418
429
|
const timer = setTimeout(() => {
|
|
419
430
|
child.kill();
|
|
420
|
-
resolve({ label, status: "fail", detail:
|
|
421
|
-
},
|
|
431
|
+
resolve({ label, status: "fail", detail: `no initialize response within ${Math.round(timeoutMs / 100) / 10}s` });
|
|
432
|
+
}, timeoutMs);
|
|
433
|
+
// A server that dies before answering is a failure now, not after the timeout (after its output, so a last reply still counts).
|
|
434
|
+
child.on("close", (code, signal) => {
|
|
435
|
+
clearTimeout(timer);
|
|
436
|
+
resolve({ label, status: "fail", detail: `the server exited (${signal ?? `code ${code}`}) before answering initialize` });
|
|
437
|
+
});
|
|
422
438
|
let out = "";
|
|
423
439
|
child.stdout.on("data", (d) => {
|
|
424
440
|
out += d.toString();
|
|
@@ -442,6 +458,7 @@ function checkMcpHandshake() {
|
|
|
442
458
|
clearTimeout(timer);
|
|
443
459
|
resolve({ label, status: "fail", detail: e.message });
|
|
444
460
|
});
|
|
461
|
+
child.stdin.on("error", () => { });
|
|
445
462
|
child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2024-11-05", capabilities: {}, clientInfo: { name: "doctor", version: "1" } } }) + "\n");
|
|
446
463
|
});
|
|
447
464
|
}
|
|
@@ -466,7 +483,7 @@ export async function runDoctor() {
|
|
|
466
483
|
// Hook registration. ~/.claude without a settings.json is Claude Code with
|
|
467
484
|
// no hook registered, not Claude Code absent.
|
|
468
485
|
const settingsPath = join(claudeDir(), "settings.json");
|
|
469
|
-
if (existsSync(settingsPath) ||
|
|
486
|
+
if (existsSync(settingsPath) || claudeCodePresent()) {
|
|
470
487
|
try {
|
|
471
488
|
const settings = readConfig(settingsPath) ?? {};
|
|
472
489
|
const entries = settings.hooks?.UserPromptSubmit ?? [];
|
|
@@ -526,7 +543,7 @@ export async function runDoctor() {
|
|
|
526
543
|
});
|
|
527
544
|
}
|
|
528
545
|
// Codex (OpenAI): MCP table in config.toml, hook in hooks.json, skill.
|
|
529
|
-
const codexHome =
|
|
546
|
+
const codexHome = codexDir();
|
|
530
547
|
if (existsSync(codexHome)) {
|
|
531
548
|
const toml = existsSync(join(codexHome, "config.toml")) ? readFileSync(join(codexHome, "config.toml"), "utf8") : "";
|
|
532
549
|
// Parsed rather than searched for one exact header: a quoted key or a
|
|
@@ -539,7 +556,7 @@ export async function runDoctor() {
|
|
|
539
556
|
: { label: "Codex MCP", status: "fail", detail: "Codex detected but not wired — run: context-doctor install" }
|
|
540
557
|
: launcherNamesMissingPackage(codexEntry)
|
|
541
558
|
? missingPackageCheck("Codex MCP")
|
|
542
|
-
: { label: "Codex MCP", status: "ok", detail:
|
|
559
|
+
: { label: "Codex MCP", status: "ok", detail: `wired in ${tilde(join(codexHome, "config.toml"))}` };
|
|
543
560
|
checks.push(codexMcp);
|
|
544
561
|
const codexSkill = join(codexHome, "skills", "context-doctor", "SKILL.md");
|
|
545
562
|
if (existsSync(codexSkill))
|
|
@@ -556,24 +573,24 @@ export async function runDoctor() {
|
|
|
556
573
|
const missing = hookBinaryMissing(ours);
|
|
557
574
|
checks.push(missing
|
|
558
575
|
? { label: "Codex hook", status: "fail", detail: `registered, but ${missing} no longer exists — re-run: context-doctor install` }
|
|
559
|
-
: { label: "Codex hook", status: "ok", detail:
|
|
576
|
+
: { label: "Codex hook", status: "ok", detail: `registered in ${tilde(join(codexHome, "hooks.json"))} (Codex must trust it once: /hooks)` });
|
|
560
577
|
}
|
|
561
578
|
}
|
|
562
579
|
catch (e) {
|
|
563
|
-
checks.push({ label: "Codex hook", status: "fail", detail:
|
|
580
|
+
checks.push({ label: "Codex hook", status: "fail", detail: `${tilde(join(codexHome, "hooks.json"))} unreadable (${e.message})` });
|
|
564
581
|
}
|
|
565
582
|
// Autopilot reaches Codex through openai_base_url (OPENAI_BASE_URL no
|
|
566
583
|
// longer routes it), and only on an API key.
|
|
567
584
|
const route = codexRouting(homedir());
|
|
568
585
|
const local = route.baseUrl && /^http:\/\/(127\.0\.0\.1|localhost):\d+\/v1\/?$/.test(route.baseUrl);
|
|
569
586
|
if (local && route.auth !== "apikey") {
|
|
570
|
-
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
|
|
587
|
+
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"))}` });
|
|
571
588
|
}
|
|
572
589
|
else if (local) {
|
|
573
590
|
checks.push({ label: "Codex autopilot", status: "ok", detail: `Codex (API key) sends its requests through ${route.baseUrl}` });
|
|
574
591
|
}
|
|
575
592
|
else if (process.env.OPENAI_BASE_URL && route.auth === "apikey") {
|
|
576
|
-
checks.push({ label: "Codex autopilot", status: "warn", detail:
|
|
593
|
+
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"))}` });
|
|
577
594
|
}
|
|
578
595
|
}
|
|
579
596
|
else {
|
|
@@ -728,6 +745,26 @@ export async function runDoctor() {
|
|
|
728
745
|
else {
|
|
729
746
|
checks.push({ label: "Project config", status: "skip", detail: "no .contextdoctorrc (optional; create one with: context-doctor init <preset>)" });
|
|
730
747
|
}
|
|
748
|
+
// The spend budget: set or not, where the period stands, and whether a hook is there to apply it.
|
|
749
|
+
{
|
|
750
|
+
const b = readBudget();
|
|
751
|
+
if (!b)
|
|
752
|
+
checks.push({ label: "Spend budget", status: "skip", detail: "none set (optional: context-doctor budget 50/day)" });
|
|
753
|
+
else {
|
|
754
|
+
let spent = "";
|
|
755
|
+
try {
|
|
756
|
+
const s = periodSpend(b.period);
|
|
757
|
+
spent = `; ${b.period === "day" ? "today" : "this week"} $${s.usd.toFixed(2)} (${Math.round((s.usd / b.usd) * 100)}%)`;
|
|
758
|
+
}
|
|
759
|
+
catch { /* the ledger could not be read: the budget alone */ }
|
|
760
|
+
const hooked = checks.some((c) => ["Every-prompt hook", "Codex hook", "Gemini CLI hook"].includes(c.label) && c.status === "ok");
|
|
761
|
+
// As `budget` writes it: $50, $1,000, $12.50 (it printed $12.5 and $1000).
|
|
762
|
+
const usd = Number.isInteger(b.usd) ? `$${b.usd.toLocaleString("en-US")}` : `$${b.usd.toFixed(2)}`;
|
|
763
|
+
checks.push(hooked
|
|
764
|
+
? { label: "Spend budget", status: "ok", detail: `${usd} a ${b.period}${b.block ? ", prompts over it held" : ", warns at 50/80/100%"}${spent}` }
|
|
765
|
+
: { 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` });
|
|
766
|
+
}
|
|
767
|
+
}
|
|
731
768
|
checks.push(await checkMcpHandshake());
|
|
732
769
|
// Autopilot: optional, so "off" is a skip, not a failure. When it is on, a
|
|
733
770
|
// 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
|
@@ -22,18 +22,27 @@
|
|
|
22
22
|
* the session would have reached the old window, less the compaction's
|
|
23
23
|
* own request and summary (an estimate: what the summary dropped is not
|
|
24
24
|
* priced);
|
|
25
|
-
* - autopilot: what the proxy recorded saving since (its own ledger)
|
|
25
|
+
* - autopilot: what the proxy recorded saving since (its own ledger);
|
|
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).
|
|
28
|
+
*
|
|
29
|
+
* The subagents' model is the one lever with a quality cost `fix` cannot
|
|
30
|
+
* measure: it is offered with that said, applied only when named (never by
|
|
31
|
+
* `--apply all`), and never over a value the user set.
|
|
26
32
|
*/
|
|
27
33
|
import { type CacheTtlReport, type CurrentTtl } from "./cachettl.js";
|
|
28
34
|
import { type ProjectPlan } from "./prune.js";
|
|
29
35
|
import { readLedger } from "./ledger.js";
|
|
30
|
-
|
|
36
|
+
import { type SubagentModelReplay } from "./subagentmodel.js";
|
|
37
|
+
export type FixId = "compact-window" | "cache-ttl" | "cache-ttl-subagents" | "autopilot" | "tool-search" | "prune" | "subagent-model";
|
|
31
38
|
export interface Fix {
|
|
32
39
|
id: FixId;
|
|
33
40
|
title: string;
|
|
34
41
|
/** Saved over the measured period, when it can be priced. */
|
|
35
42
|
savedUsd?: number;
|
|
36
43
|
savedShare?: number;
|
|
44
|
+
/** What the share is of, when it is not the input the plan's first line names ("of subagents"). */
|
|
45
|
+
shareOf?: string;
|
|
37
46
|
/** How the figure was measured. */
|
|
38
47
|
basis: string;
|
|
39
48
|
/** What it costs in quality, plainly. */
|
|
@@ -47,6 +56,8 @@ export interface Fix {
|
|
|
47
56
|
value?: number | string;
|
|
48
57
|
/** What would keep it from taking effect (environment, project or managed settings, per-model values). */
|
|
49
58
|
overriddenBy?: string[];
|
|
59
|
+
/** More lines under it in the plan (the subagents' model: per agent type). */
|
|
60
|
+
detail?: string[];
|
|
50
61
|
}
|
|
51
62
|
/** The measurements a plan is made from (so the plan itself is testable without a machine's history). */
|
|
52
63
|
export interface FixInputs {
|
|
@@ -80,6 +91,13 @@ export interface FixInputs {
|
|
|
80
91
|
overrides?: Partial<Record<FixId, string[]>>;
|
|
81
92
|
/** The record of applied fixes could not be read. */
|
|
82
93
|
recordProblem?: string;
|
|
94
|
+
/** Every subagent request replayed at Sonnet 5.5 (subagentmodel.ts). */
|
|
95
|
+
subagentModel?: SubagentModelReplay;
|
|
96
|
+
/** CLAUDE_CODE_SUBAGENT_MODEL as the user set it (their settings.json env, or the environment fix runs in): never overwritten. */
|
|
97
|
+
subagentModelSet?: {
|
|
98
|
+
value: string;
|
|
99
|
+
where: string;
|
|
100
|
+
};
|
|
83
101
|
/** The /compact offer at cold returns: advice, not a setting; `hooked` when the every-prompt hook (or the plugin) is there to make it. */
|
|
84
102
|
coldResume?: {
|
|
85
103
|
netUsd: number;
|
|
@@ -108,6 +126,8 @@ export interface FixRecord {
|
|
|
108
126
|
oneHourShareBefore?: number;
|
|
109
127
|
/** For prune: the project folder. */
|
|
110
128
|
cwd?: string;
|
|
129
|
+
/** 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. */
|
|
130
|
+
modelsBefore?: Record<string, number>;
|
|
111
131
|
}
|
|
112
132
|
export declare function fixRecordPath(home?: string): string;
|
|
113
133
|
/**
|
|
@@ -140,6 +160,7 @@ export declare function fixOverrides(id: FixId, deps?: {
|
|
|
140
160
|
export declare function applyFix(fix: Fix, deps?: FixDeps, context?: {
|
|
141
161
|
oneHourShare?: number;
|
|
142
162
|
prune?: ProjectPlan;
|
|
163
|
+
modelsBefore?: Record<string, number>;
|
|
143
164
|
}): Promise<{
|
|
144
165
|
ok: boolean;
|
|
145
166
|
lines: string[];
|