context-doctor 0.46.0 → 0.47.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 -2
- package/dist/autopilot.js +9 -5
- package/dist/blob.js +66 -12
- package/dist/budget.d.ts +8 -2
- package/dist/budget.js +30 -7
- package/dist/ci.js +2 -1
- package/dist/claudeplugin.d.ts +97 -0
- package/dist/claudeplugin.js +142 -0
- package/dist/cli.js +109 -36
- package/dist/compactcost.d.ts +74 -0
- package/dist/compactcost.js +115 -0
- package/dist/cursor.js +2 -0
- package/dist/doctor.js +90 -18
- package/dist/extract.js +4 -3
- package/dist/fanout.d.ts +15 -0
- package/dist/fanout.js +30 -9
- package/dist/firstfix.d.ts +43 -0
- package/dist/firstfix.js +80 -0
- package/dist/fix.d.ts +46 -2
- package/dist/fix.js +95 -10
- package/dist/httpguard.d.ts +13 -0
- package/dist/httpguard.js +22 -0
- package/dist/install.d.ts +21 -9
- package/dist/install.js +211 -40
- package/dist/limits.d.ts +5 -0
- package/dist/limits.js +26 -2
- package/dist/mcp.js +60 -59
- package/dist/missledger.js +5 -3
- package/dist/mod/api.d.ts +8 -2
- package/dist/mod/api.js +2 -2
- package/dist/mod/logic.d.ts +13 -1
- package/dist/mod/logic.js +24 -2
- package/dist/mod/register.d.ts +2 -0
- package/dist/mod/register.js +19 -5
- package/dist/modelids.d.ts +4 -3
- package/dist/modelids.js +23 -7
- package/dist/modelswitch.js +8 -4
- package/dist/modmeasure.js +13 -1
- package/dist/orgrates.d.ts +18 -0
- package/dist/orgrates.js +51 -2
- package/dist/pack.d.ts +13 -0
- package/dist/pack.js +38 -2
- package/dist/preferences.js +2 -1
- package/dist/pricing.d.ts +8 -0
- package/dist/pricing.js +16 -0
- package/dist/progresssummaries.d.ts +148 -0
- package/dist/progresssummaries.js +248 -0
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/prune.d.ts +8 -0
- package/dist/prune.js +11 -1
- package/dist/spend.d.ts +34 -0
- package/dist/spend.js +48 -4
- package/dist/subagentmodel.d.ts +12 -0
- package/dist/subagentmodel.js +17 -4
- package/dist/subagentpay.d.ts +8 -0
- package/dist/subagentpay.js +8 -1
- package/dist/toolcwd.d.ts +14 -0
- package/dist/toolcwd.js +17 -0
- package/package.json +1 -1
package/dist/doctor.js
CHANGED
|
@@ -14,6 +14,7 @@ import { dirname, join } from "node:path";
|
|
|
14
14
|
import { fileURLToPath } from "node:url";
|
|
15
15
|
import { ledgerPath, readLedger } from "./ledger.js";
|
|
16
16
|
import { costCheck } from "./modmeasure.js";
|
|
17
|
+
import { ago, MOD_SINCE, modActivity, modReadiness, PLUGIN_KEY, pluginStage, readPluginMarker } from "./claudeplugin.js";
|
|
17
18
|
import { loadConfig } from "./config.js";
|
|
18
19
|
import { codexRouting } from "./codexroute.js";
|
|
19
20
|
import { CURSOR_HOOK_EVENTS } from "./install.js";
|
|
@@ -32,7 +33,7 @@ import { periodSpend, readBudget } from "./budget.js";
|
|
|
32
33
|
import { sessionPriceThresholds } from "./sessionprice.js";
|
|
33
34
|
import { claudeSpend, codexSpend } from "./spend.js";
|
|
34
35
|
import { hasKnownPrice, isUnbilledModel, priceChangedText } from "./pricing.js";
|
|
35
|
-
import { orgRatesLine } from "./orgrates.js";
|
|
36
|
+
import { managedSourcesLine, orgRatesLine } from "./orgrates.js";
|
|
36
37
|
function claudeDesktopConfigPath() {
|
|
37
38
|
switch (platform()) {
|
|
38
39
|
case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
|
|
@@ -180,6 +181,23 @@ function hookBinaryMissing(command) {
|
|
|
180
181
|
* Claude Code's settings files, lowest precedence first: user, project,
|
|
181
182
|
* local. A later file's value for a key wins, as in Claude Code itself.
|
|
182
183
|
*/
|
|
184
|
+
/**
|
|
185
|
+
* A hooks event's entries, whatever the file holds there. A config written
|
|
186
|
+
* by hand can hold an object, a string or a null where a list belongs; the
|
|
187
|
+
* app ignores it, and doctor must not stop at it (it printed "settings.json
|
|
188
|
+
* unreadable (entries.map is not a function)").
|
|
189
|
+
*/
|
|
190
|
+
function hookEntries(v) {
|
|
191
|
+
return Array.isArray(v) ? v.filter(isObject) : [];
|
|
192
|
+
}
|
|
193
|
+
/** The first command of a Claude Code-shaped hook entry ({ hooks: [{ command }] }), or "". */
|
|
194
|
+
function firstCommand(e) {
|
|
195
|
+
const h = Array.isArray(e.hooks) ? e.hooks[0] : undefined;
|
|
196
|
+
return isObject(h) && typeof h.command === "string" ? h.command : "";
|
|
197
|
+
}
|
|
198
|
+
function isObject(v) {
|
|
199
|
+
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
200
|
+
}
|
|
183
201
|
function claudeSettingsLayers() {
|
|
184
202
|
const paths = [
|
|
185
203
|
join(claudeDir(), "settings.json"),
|
|
@@ -188,7 +206,9 @@ function claudeSettingsLayers() {
|
|
|
188
206
|
];
|
|
189
207
|
return [...new Set(paths)].flatMap((p) => {
|
|
190
208
|
try {
|
|
191
|
-
|
|
209
|
+
const v = existsSync(p) ? JSON.parse(readFileSync(p, "utf8")) : undefined;
|
|
210
|
+
// A file holding null, an array or a number is no settings at all (Claude Code ignores it).
|
|
211
|
+
return isObject(v) ? [v] : [];
|
|
192
212
|
}
|
|
193
213
|
catch {
|
|
194
214
|
return []; // an unreadable user settings.json is reported by the hook check
|
|
@@ -205,13 +225,62 @@ function claudeSettingsLayers() {
|
|
|
205
225
|
function pluginEnabled(layers) {
|
|
206
226
|
const state = new Map();
|
|
207
227
|
for (const s of layers) {
|
|
208
|
-
for (const [key, on] of Object.entries((s.enabledPlugins
|
|
228
|
+
for (const [key, on] of Object.entries(isObject(s.enabledPlugins) ? s.enabledPlugins : {})) {
|
|
209
229
|
if (isOurPluginKey(key))
|
|
210
230
|
state.set(key, on === true);
|
|
211
231
|
}
|
|
212
232
|
}
|
|
213
233
|
return [...state.values()].some(Boolean);
|
|
214
234
|
}
|
|
235
|
+
/** A mod reading older than this is no longer "recording". */
|
|
236
|
+
const MOD_FRESH_MS = 24 * 3600_000;
|
|
237
|
+
/**
|
|
238
|
+
* Which way Claude Code gets context-doctor (claudeplugin.ts): the plugin,
|
|
239
|
+
* and how far Claude Code has got with it, or install's own wiring and why;
|
|
240
|
+
* then whether the mod is recording, from when it last wrote its ledgers.
|
|
241
|
+
*/
|
|
242
|
+
function claudeRouteChecks(layers, plugin, now = Date.now()) {
|
|
243
|
+
const readiness = modReadiness(claudeCodeInstallsFromEnv());
|
|
244
|
+
const userOff = layers.some((s) => isObject(s.enabledPlugins) && s.enabledPlugins[PLUGIN_KEY] === false);
|
|
245
|
+
if (!plugin) {
|
|
246
|
+
const why = userOff
|
|
247
|
+
? "the context-doctor plugin is turned off in your settings"
|
|
248
|
+
: readiness.ok
|
|
249
|
+
? `every Claude Code here runs mods (${describeInstalls(readiness.installs)}): run context-doctor install to move to the plugin and its mod`
|
|
250
|
+
: readiness.old.length > 0
|
|
251
|
+
? `${describeInstalls(readiness.old)} predates mods (${MOD_SINCE}), and every Claude Code here reads the same settings`
|
|
252
|
+
: `no Claude Code version found to check (the plugin's mod needs ${MOD_SINCE} or later)`;
|
|
253
|
+
const mod = { label: "Mod", status: readiness.ok && !userOff ? "warn" : "skip", detail: `not running: ${why}` };
|
|
254
|
+
// Nothing of ours in Claude Code at all is the hook check's failure, above.
|
|
255
|
+
return claudeInstalledCopies().length > 0 ? [{ label: "Claude Code route", status: "ok", detail: "install's own MCP server, skill and hooks, not the plugin" }, mod] : [mod];
|
|
256
|
+
}
|
|
257
|
+
const by = readPluginMarker() ? "enabled by install" : "enabled in your settings";
|
|
258
|
+
const st = pluginStage();
|
|
259
|
+
const route = st.stage === "installed"
|
|
260
|
+
? { label: "Claude Code route", status: "ok", detail: `the context-doctor plugin (${by}), downloaded${st.version ? ` (${st.version})` : ""}: its MCP server, skills, hooks and mod` }
|
|
261
|
+
: {
|
|
262
|
+
label: "Claude Code route",
|
|
263
|
+
status: "warn",
|
|
264
|
+
detail: `the context-doctor plugin (${by}), ${st.stage === "registered" ? "its marketplace fetched but the plugin not downloaded yet" : "not fetched yet"}: Claude Code does that in the background at its next start and loads it from the session after (or at once: /reload-plugins)`,
|
|
265
|
+
};
|
|
266
|
+
let mod;
|
|
267
|
+
const act = modActivity();
|
|
268
|
+
const limits = act.limits ? `; limits ledger written ${ago(act.limits, now)}` : "; no limit reading yet (Claude Code hands them over on Pro and Max plans)";
|
|
269
|
+
if (process.env.CONTEXT_DOCTOR_NO_MOD === "1") {
|
|
270
|
+
mod = { label: "Mod", status: "skip", detail: "off: CONTEXT_DOCTOR_NO_MOD=1" };
|
|
271
|
+
}
|
|
272
|
+
else if (act.cost && now - act.cost < MOD_FRESH_MS) {
|
|
273
|
+
mod = { label: "Mod", status: "ok", detail: `recording: last measured ${ago(act.cost, now)} (~/.claude/.context-doctor-session-cost.jsonl)${limits}` };
|
|
274
|
+
}
|
|
275
|
+
else if (act.cost) {
|
|
276
|
+
mod = { label: "Mod", status: "warn", detail: `last measured ${ago(act.cost, now)}: no session that loaded the plugin since, or the mod stopped${limits}` };
|
|
277
|
+
}
|
|
278
|
+
else {
|
|
279
|
+
const old = readiness.old.length > 0 ? `; ${describeInstalls(readiness.old)} predates mods and never will` : "";
|
|
280
|
+
mod = { label: "Mod", status: "warn", detail: `has not measured yet: it records after each turn of a session that loaded the plugin (Claude Code ${MOD_SINCE}+ in the Desktop app, 2.1.287+ in a terminal)${old}` };
|
|
281
|
+
}
|
|
282
|
+
return [route, mod];
|
|
283
|
+
}
|
|
215
284
|
/** "headroom (pid 4242)", or "another program". */
|
|
216
285
|
function occupantName(o) {
|
|
217
286
|
return `${o.name ?? "another program"}${o.pid ? ` (pid ${o.pid})` : ""}`;
|
|
@@ -223,8 +292,7 @@ function occupantName(o) {
|
|
|
223
292
|
*/
|
|
224
293
|
function fanoutCheck(settings, plugin) {
|
|
225
294
|
const label = "Subagent price";
|
|
226
|
-
const
|
|
227
|
-
const ours = entries.find((e) => /context-doctor|cli\.js"?\s+hook/.test(e.hooks?.[0]?.command ?? ""));
|
|
295
|
+
const ours = hookEntries(settings.hooks?.PreToolUse).find((e) => /context-doctor|cli\.js"?\s+hook/.test(firstCommand(e)));
|
|
228
296
|
let costs;
|
|
229
297
|
try {
|
|
230
298
|
costs = JSON.parse(readFileSync(subagentCostsPath(), "utf8"));
|
|
@@ -246,8 +314,7 @@ function fanoutCheck(settings, plugin) {
|
|
|
246
314
|
*/
|
|
247
315
|
function modelSwitchCheck(settings, plugin) {
|
|
248
316
|
const label = "Model-switch warning";
|
|
249
|
-
const
|
|
250
|
-
const ours = entries.some((e) => /context-doctor|cli\.js"?\s+hook/.test(e.hooks?.[0]?.command ?? ""));
|
|
317
|
+
const ours = hookEntries(settings.hooks?.PreModelSwitch).some((e) => /context-doctor|cli\.js"?\s+hook/.test(firstCommand(e)));
|
|
251
318
|
const readiness = modelSwitchReadiness(claudeCodeInstallsFromEnv());
|
|
252
319
|
if (Array.isArray(settings.hooks?.PreModelSwitch) && readiness.old.length > 0) {
|
|
253
320
|
return {
|
|
@@ -535,8 +602,7 @@ export async function runDoctor() {
|
|
|
535
602
|
if (existsSync(settingsPath) || claudeCodePresent()) {
|
|
536
603
|
try {
|
|
537
604
|
const settings = readConfig(settingsPath) ?? {};
|
|
538
|
-
const
|
|
539
|
-
const ours = entries.map((e) => e.hooks?.[0]?.command ?? "").find((c) => /context-doctor|cli\.js"?\s+hook/.test(c));
|
|
605
|
+
const ours = hookEntries(settings.hooks?.UserPromptSubmit).map(firstCommand).find((c) => /context-doctor|cli\.js"?\s+hook/.test(c));
|
|
540
606
|
if (hooksDisabled(layers)) {
|
|
541
607
|
// Registered or not, nothing runs: say that first, it is the fix.
|
|
542
608
|
checks.push({
|
|
@@ -561,8 +627,7 @@ export async function runDoctor() {
|
|
|
561
627
|
checks.push(missing
|
|
562
628
|
? { label: "Every-prompt hook", status: "fail", detail: `registered, but ${missing} no longer exists — re-run: context-doctor install` }
|
|
563
629
|
: { label: "Every-prompt hook", status: "ok", detail: "registered in ~/.claude/settings.json; command resolves" });
|
|
564
|
-
const
|
|
565
|
-
const preOurs = plugin || pre.some((e) => /context-doctor|cli\.js"?\s+hook/.test(e.hooks?.[0]?.command ?? ""));
|
|
630
|
+
const preOurs = plugin || hookEntries(settings.hooks?.PreCompact).some((e) => /context-doctor|cli\.js"?\s+hook/.test(firstCommand(e)));
|
|
566
631
|
checks.push(preOurs
|
|
567
632
|
? { label: "Compaction hook", status: "ok", detail: "PreCompact: each compaction's summary keeps the session's files, open tasks, your instructions and failing commands" }
|
|
568
633
|
: { label: "Compaction hook", status: "warn", detail: "not registered: compactions use generic instructions; run context-doctor install" });
|
|
@@ -588,9 +653,11 @@ export async function runDoctor() {
|
|
|
588
653
|
label: "Plugin + install",
|
|
589
654
|
status: "warn",
|
|
590
655
|
detail: `the context-doctor plugin is enabled and \`install\` also wired Claude Code (${copies.join(", ")}), so its instructions and tools load twice. ` +
|
|
591
|
-
"
|
|
656
|
+
"Run `context-doctor install`: it takes its own copies out while the plugin is on. Or disable the plugin",
|
|
592
657
|
});
|
|
593
658
|
}
|
|
659
|
+
if (claudeCodePresent())
|
|
660
|
+
checks.push(...claudeRouteChecks(layers, plugin));
|
|
594
661
|
// Codex (OpenAI): MCP table in config.toml, hook in hooks.json, skill.
|
|
595
662
|
const codexHome = codexDir();
|
|
596
663
|
if (existsSync(codexHome)) {
|
|
@@ -613,8 +680,7 @@ export async function runDoctor() {
|
|
|
613
680
|
try {
|
|
614
681
|
const hooksPath = join(codexHome, "hooks.json");
|
|
615
682
|
const hooks = readConfig(hooksPath) ?? {};
|
|
616
|
-
const
|
|
617
|
-
const ours = entries.map((e) => e.hooks?.[0]?.command ?? "").find((c) => /context-doctor|cli\.js"?\s+hook/.test(c));
|
|
683
|
+
const ours = hookEntries(hooks.hooks?.UserPromptSubmit).map(firstCommand).find((c) => /context-doctor|cli\.js"?\s+hook/.test(c));
|
|
618
684
|
if (!ours) {
|
|
619
685
|
checks.push(missingHook("Codex hook", codexMcp));
|
|
620
686
|
}
|
|
@@ -660,8 +726,7 @@ export async function runDoctor() {
|
|
|
660
726
|
? missingPackageCheck("Gemini CLI MCP")
|
|
661
727
|
: { label: "Gemini CLI MCP", status: "ok", detail: "wired in ~/.gemini/settings.json" };
|
|
662
728
|
checks.push(geminiMcp);
|
|
663
|
-
const
|
|
664
|
-
const ours = entries.map((e) => e.hooks?.[0]?.command ?? "").find((c) => /context-doctor|cli\.js"?\s+hook/.test(c));
|
|
729
|
+
const ours = hookEntries(settings.hooks?.BeforeAgent).map(firstCommand).find((c) => /context-doctor|cli\.js"?\s+hook/.test(c));
|
|
665
730
|
const missing = ours ? hookBinaryMissing(ours) : undefined;
|
|
666
731
|
checks.push(!ours
|
|
667
732
|
? missingHook("Gemini CLI hook", geminiMcp)
|
|
@@ -712,7 +777,7 @@ export async function runDoctor() {
|
|
|
712
777
|
const hooksPath = join(homedir(), ".cursor", "hooks.json");
|
|
713
778
|
try {
|
|
714
779
|
const hooks = readConfig(hooksPath, ["version"]) ?? {};
|
|
715
|
-
const oursIn = (event) => (hooks.hooks?.[event]
|
|
780
|
+
const oursIn = (event) => hookEntries(hooks.hooks?.[event]).map((e) => (typeof e.command === "string" ? e.command : "")).find((c) => /(cli\.js|context-doctor(\.cmd|\.exe|\.bat)?)"?\s+hook\s*$/.test(c));
|
|
716
781
|
const ours = oursIn("postToolUse");
|
|
717
782
|
const missing = ours ? hookBinaryMissing(ours) : undefined;
|
|
718
783
|
const fallbacks = CURSOR_HOOK_EVENTS.filter((e) => !oursIn(e));
|
|
@@ -769,7 +834,10 @@ export async function runDoctor() {
|
|
|
769
834
|
const skillPath = join(claudeDir(), "skills", "context-doctor", "SKILL.md");
|
|
770
835
|
checks.push(existsSync(skillPath)
|
|
771
836
|
? skillCheck("Agent Skill", [skillPath])
|
|
772
|
-
:
|
|
837
|
+
: plugin
|
|
838
|
+
// The plugin carries the skill, and install skips it while the plugin is on: "run install" sent people round in a circle.
|
|
839
|
+
? { label: "Agent Skill", status: "ok", detail: "provided by the context-doctor plugin" }
|
|
840
|
+
: { label: "Agent Skill", status: "skip", detail: "not installed (run context-doctor install on a Claude Code machine)" });
|
|
773
841
|
// Ledger writable. Tested without writing an entry: recordLedger swallows
|
|
774
842
|
// errors (so this could never fail), and the entry it wrote counted as a
|
|
775
843
|
// hook check in every report.
|
|
@@ -843,6 +911,10 @@ export async function runDoctor() {
|
|
|
843
911
|
const org = orgRatesLine();
|
|
844
912
|
if (org)
|
|
845
913
|
checks.push({ label: "Prices", status: "ok", detail: org });
|
|
914
|
+
// Server-managed settings or an MDM profile come before the files in Claude Code, and alone: rates context-doctor cannot see.
|
|
915
|
+
const ahead = managedSourcesLine();
|
|
916
|
+
if (ahead)
|
|
917
|
+
checks.push({ label: "Prices", status: "warn", detail: ahead });
|
|
846
918
|
}
|
|
847
919
|
checks.push(await checkMcpHandshake());
|
|
848
920
|
// Autopilot: optional, so "off" is a skip, not a failure. When it is on, a
|
package/dist/extract.js
CHANGED
|
@@ -22,11 +22,12 @@ import { execFile, spawnSync } from "node:child_process";
|
|
|
22
22
|
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
|
|
23
23
|
import { tmpdir } from "node:os";
|
|
24
24
|
import { dirname, extname, join, resolve } from "node:path";
|
|
25
|
+
import { toolCwd } from "./toolcwd.js";
|
|
25
26
|
export const EXTRACTABLE = new Set([".pdf", ".docx", ".doc", ".rtf", ".odt", ".pptx"]);
|
|
26
27
|
const RUN = { encoding: "utf8", timeout: 30_000, maxBuffer: 64 * 1024 * 1024 };
|
|
27
28
|
function run(cmd, args) {
|
|
28
29
|
try {
|
|
29
|
-
const r = spawnSync(cmd, args, RUN);
|
|
30
|
+
const r = spawnSync(cmd, args, { ...RUN, cwd: toolCwd() });
|
|
30
31
|
return r.status === 0 && typeof r.stdout === "string" && r.stdout.trim() ? r.stdout : undefined;
|
|
31
32
|
}
|
|
32
33
|
catch {
|
|
@@ -47,7 +48,7 @@ function pdftotext(path) {
|
|
|
47
48
|
return direct;
|
|
48
49
|
const out = join(mkdtempSync(join(tmpdir(), "cd-pdf-")), "out.txt");
|
|
49
50
|
try {
|
|
50
|
-
spawnSync("pdftotext", [path, out], RUN);
|
|
51
|
+
spawnSync("pdftotext", [path, out], { ...RUN, cwd: toolCwd() });
|
|
51
52
|
const text = existsSync(out) ? readFileSync(out, "utf8") : "";
|
|
52
53
|
return text.trim() ? text : undefined;
|
|
53
54
|
}
|
|
@@ -157,7 +158,7 @@ function runAsync(cmd, args, end) {
|
|
|
157
158
|
finish({ timedOut: monotonicNow() >= end - 50 });
|
|
158
159
|
}, timeout);
|
|
159
160
|
try {
|
|
160
|
-
child = execFile(cmd, args, { encoding: "utf8", timeout, killSignal: "SIGKILL", maxBuffer: 64 * 1024 * 1024, windowsHide: true }, (err, stdout) => {
|
|
161
|
+
child = execFile(cmd, args, { cwd: toolCwd(), encoding: "utf8", timeout, killSignal: "SIGKILL", maxBuffer: 64 * 1024 * 1024, windowsHide: true }, (err, stdout) => {
|
|
161
162
|
// Only the clock says the budget ran out: a child killed for another
|
|
162
163
|
// reason (seen on Windows runners, well inside a 60 s budget) is a
|
|
163
164
|
// failed tool, and the next one is tried.
|
package/dist/fanout.d.ts
CHANGED
|
@@ -28,6 +28,12 @@ export interface CostStat {
|
|
|
28
28
|
p90: number;
|
|
29
29
|
/** The model most of these ran on. */
|
|
30
30
|
model?: string;
|
|
31
|
+
/**
|
|
32
|
+
* Their tokens, summed, as [uncached input, cache reads, cache writes,
|
|
33
|
+
* output, requests]: what another model's price of them is worked out
|
|
34
|
+
* from, rate by rate (absent in a cache written before it was kept).
|
|
35
|
+
*/
|
|
36
|
+
tok?: [number, number, number, number, number];
|
|
31
37
|
}
|
|
32
38
|
export interface SubagentCosts {
|
|
33
39
|
computedAt: number;
|
|
@@ -41,6 +47,15 @@ export interface SubagentCosts {
|
|
|
41
47
|
byModel: Record<string, CostStat>;
|
|
42
48
|
}
|
|
43
49
|
export declare function subagentCostsPath(): string;
|
|
50
|
+
/**
|
|
51
|
+
* What runs like `s` cost on `to` against `from`: their own tokens priced
|
|
52
|
+
* at each model's rates (rateCard: its tier for their average prompt, the
|
|
53
|
+
* organization's rates), each category at its own rate. Fable 5.2 reads at
|
|
54
|
+
* 2.5% of its input and Sonnet 5.5 at 5%: by the input price alone a
|
|
55
|
+
* read-heavy run on Sonnet came out at half its price. The input ratio only
|
|
56
|
+
* for a stat kept without its tokens.
|
|
57
|
+
*/
|
|
58
|
+
export declare function priceRatio(from: string | undefined, to: string | undefined, s?: CostStat): number;
|
|
44
59
|
/**
|
|
45
60
|
* Each subagent's bill in the last `days`, newest transcripts first, by
|
|
46
61
|
* type and model. `limit` and `budgetMs` bound the work when the hook has
|
package/dist/fanout.js
CHANGED
|
@@ -26,7 +26,7 @@ import { basename, dirname, join } from "node:path";
|
|
|
26
26
|
import { statePath } from "./ledger.js";
|
|
27
27
|
import { listSessions, isClaudeSession } from "./session.js";
|
|
28
28
|
import { scanSubagent } from "./subagentpay.js";
|
|
29
|
-
import { formatUsd, pricingFor } from "./pricing.js";
|
|
29
|
+
import { formatUsd, pricingFor, rateCard, ratesAt, usageCost } from "./pricing.js";
|
|
30
30
|
import { tailUsage } from "./statusline.js";
|
|
31
31
|
/** The subagent tool, by its current name and its pre-2.1.63 alias. */
|
|
32
32
|
export const FANOUT_MATCHER = "Agent|Task";
|
|
@@ -42,13 +42,38 @@ function stat(costs) {
|
|
|
42
42
|
for (const c of costs)
|
|
43
43
|
if (c.model)
|
|
44
44
|
models.set(c.model, (models.get(c.model) ?? 0) + 1);
|
|
45
|
+
const tok = costs.every((c) => c.tok) ? costs.reduce((t, c) => t.map((v, i) => v + c.tok[i]), [0, 0, 0, 0, 0]) : undefined;
|
|
45
46
|
return {
|
|
46
47
|
n: s.length,
|
|
47
48
|
median: s[Math.floor(s.length / 2)],
|
|
48
49
|
p90: s[Math.min(s.length - 1, Math.floor(s.length * 0.9))],
|
|
49
50
|
model: [...models.entries()].sort((a, b) => b[1] - a[1])[0]?.[0],
|
|
51
|
+
...(tok ? { tok } : {}),
|
|
50
52
|
};
|
|
51
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* What runs like `s` cost on `to` against `from`: their own tokens priced
|
|
56
|
+
* at each model's rates (rateCard: its tier for their average prompt, the
|
|
57
|
+
* organization's rates), each category at its own rate. Fable 5.2 reads at
|
|
58
|
+
* 2.5% of its input and Sonnet 5.5 at 5%: by the input price alone a
|
|
59
|
+
* read-heavy run on Sonnet came out at half its price. The input ratio only
|
|
60
|
+
* for a stat kept without its tokens.
|
|
61
|
+
*/
|
|
62
|
+
export function priceRatio(from, to, s) {
|
|
63
|
+
if (!from || !to || from === to)
|
|
64
|
+
return 1;
|
|
65
|
+
if (s?.tok && s.tok[4] > 0) {
|
|
66
|
+
const [input, read, write, output, requests] = s.tok;
|
|
67
|
+
const u = { input_tokens: input, cache_read_input_tokens: read, cache_creation_input_tokens: write, output_tokens: output };
|
|
68
|
+
const prompt = (input + read + write) / requests;
|
|
69
|
+
const at = (m) => { const c = rateCard(m); return c ? usageCost(u, ratesAt(c, prompt)).totalUsd : undefined; };
|
|
70
|
+
const a = at(from), b = at(to);
|
|
71
|
+
if (a !== undefined && b !== undefined && a > 0)
|
|
72
|
+
return b / a;
|
|
73
|
+
}
|
|
74
|
+
const a = pricingFor(from), b = pricingFor(to);
|
|
75
|
+
return a && b && a.inputPerM > 0 ? b.inputPerM / a.inputPerM : 1;
|
|
76
|
+
}
|
|
52
77
|
/**
|
|
53
78
|
* Each subagent's bill in the last `days`, newest transcripts first, by
|
|
54
79
|
* type and model. `limit` and `budgetMs` bound the work when the hook has
|
|
@@ -96,7 +121,7 @@ export function measureSubagentCosts(days = 30, opts = {}) {
|
|
|
96
121
|
type = String(JSON.parse(readFileSync(f.meta, "utf8"))?.agentType ?? "unknown").slice(0, 60);
|
|
97
122
|
}
|
|
98
123
|
catch { /* older Claude Code: no meta */ }
|
|
99
|
-
runs.push({ type, model: s.model, usd: s.costUsd });
|
|
124
|
+
runs.push({ type, model: s.model, usd: s.costUsd, tok: [s.tokens.input, s.tokens.read, s.tokens.write, s.tokens.output, s.steps] });
|
|
100
125
|
}
|
|
101
126
|
catch { /* unreadable */ }
|
|
102
127
|
}
|
|
@@ -192,23 +217,19 @@ export function estimateSubagent(costs, type, modelAlias, parentModel) {
|
|
|
192
217
|
// inherits the parent's model (general-purpose and Explore ran on several
|
|
193
218
|
// families on the author's history: they follow the parent).
|
|
194
219
|
const model = (modelAlias ? aliasModel(modelAlias, costs) : undefined) ?? pinnedModel(costs, type) ?? parentModel ?? (byType && byType.n >= MIN_RUNS ? byType.model : undefined);
|
|
195
|
-
const scale = (from, to) => {
|
|
196
|
-
const a = pricingFor(from), b = pricingFor(to);
|
|
197
|
-
return a && b && a.inputPerM > 0 ? b.inputPerM / a.inputPerM : 1;
|
|
198
|
-
};
|
|
199
220
|
let base, factor = 1;
|
|
200
221
|
const exact = model ? costs.byTypeModel[`${type}|${model}`] : undefined;
|
|
201
222
|
if (exact && exact.n >= MIN_RUNS)
|
|
202
223
|
base = exact;
|
|
203
224
|
else if (byType && byType.n >= MIN_RUNS) {
|
|
204
225
|
base = byType;
|
|
205
|
-
factor =
|
|
226
|
+
factor = priceRatio(byType.model, model ?? byType.model, byType);
|
|
206
227
|
}
|
|
207
228
|
else if (model && costs.byModel[model]?.n >= MIN_RUNS)
|
|
208
229
|
base = costs.byModel[model];
|
|
209
230
|
else if (costs.all && costs.all.n >= MIN_RUNS) {
|
|
210
231
|
base = costs.all;
|
|
211
|
-
factor =
|
|
232
|
+
factor = priceRatio(costs.all.model, model ?? costs.all.model, costs.all);
|
|
212
233
|
}
|
|
213
234
|
if (!base)
|
|
214
235
|
return undefined;
|
|
@@ -219,7 +240,7 @@ export function estimateSubagent(costs, type, modelAlias, parentModel) {
|
|
|
219
240
|
const measured = costs.byTypeModel[`${type}|${sonnet}`];
|
|
220
241
|
est.cheaper = measured && measured.n >= MIN_RUNS
|
|
221
242
|
? { model: sonnet, median: measured.median, measured: true }
|
|
222
|
-
: { model: sonnet, median: est.median *
|
|
243
|
+
: { model: sonnet, median: est.median * priceRatio(est.model, sonnet, base), measured: false };
|
|
223
244
|
if (!(est.cheaper.median < est.median))
|
|
224
245
|
delete est.cheaper;
|
|
225
246
|
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a bare `context-doctor` shows in a terminal with Claude Code history:
|
|
3
|
+
* the plan, not the report, and one question.
|
|
4
|
+
*
|
|
5
|
+
* `fix` lists every lever with how it was measured, what it costs in quality
|
|
6
|
+
* and what it writes: 30 to 50 lines and a question per lever. The author,
|
|
7
|
+
* who wrote every lever, applied none of them that way. So the first screen
|
|
8
|
+
* splits `fix`'s own plan (the same replays, one scan) in two:
|
|
9
|
+
* - the fixes whose quality line is "none" (`Fix.qualityFree`: the model
|
|
10
|
+
* sees the same content, or the same content moved where it can open it,
|
|
11
|
+
* on the same model), one line each with one total and ONE y/N question
|
|
12
|
+
* that applies them all through `applyFix`, as `fix --apply <ids>` does;
|
|
13
|
+
* - the ones that trade something (compacting earlier, autopilot clearing
|
|
14
|
+
* output, the subagents' model, Codex's limit), one line each with their
|
|
15
|
+
* dollars and the command that applies each, after reading it in `fix`.
|
|
16
|
+
* Nothing is written without a `y` typed in a terminal.
|
|
17
|
+
*/
|
|
18
|
+
import { type Fix } from "./fix.js";
|
|
19
|
+
export interface FirstSplit {
|
|
20
|
+
/** Offered under the one question: available and quality-free, in the plan's order. */
|
|
21
|
+
free: Fix[];
|
|
22
|
+
/** Available, with a quality cost (or one not measured): pointed at `fix`. */
|
|
23
|
+
other: Fix[];
|
|
24
|
+
/** Applied before (by `fix` or by hand). */
|
|
25
|
+
applied: Fix[];
|
|
26
|
+
}
|
|
27
|
+
export declare function splitFirstFixes(fixes: Fix[]): FirstSplit;
|
|
28
|
+
export interface FirstScreen {
|
|
29
|
+
days: number;
|
|
30
|
+
billedUsd: number;
|
|
31
|
+
codexBilledUsd?: number;
|
|
32
|
+
fixes: Fix[];
|
|
33
|
+
/** `context-doctor <rest>`, or `npx context-doctor <rest>` (invocation.ts). */
|
|
34
|
+
command: (rest: string) => string;
|
|
35
|
+
/** The record of applied fixes is damaged: `fix` refuses to apply, so nothing is asked. */
|
|
36
|
+
recordProblem?: string;
|
|
37
|
+
/** The question follows (stdin and stdout are a terminal); otherwise the last line says how to apply them. */
|
|
38
|
+
ask: boolean;
|
|
39
|
+
}
|
|
40
|
+
/** The screen, everything but the question itself (under 25 lines whatever the plan). */
|
|
41
|
+
export declare function renderFirstScreen(s: FirstScreen): string;
|
|
42
|
+
/** The one question, for the quality-free fixes together. */
|
|
43
|
+
export declare function firstQuestion(n: number, command: (rest: string) => string): string;
|
package/dist/firstfix.js
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a bare `context-doctor` shows in a terminal with Claude Code history:
|
|
3
|
+
* the plan, not the report, and one question.
|
|
4
|
+
*
|
|
5
|
+
* `fix` lists every lever with how it was measured, what it costs in quality
|
|
6
|
+
* and what it writes: 30 to 50 lines and a question per lever. The author,
|
|
7
|
+
* who wrote every lever, applied none of them that way. So the first screen
|
|
8
|
+
* splits `fix`'s own plan (the same replays, one scan) in two:
|
|
9
|
+
* - the fixes whose quality line is "none" (`Fix.qualityFree`: the model
|
|
10
|
+
* sees the same content, or the same content moved where it can open it,
|
|
11
|
+
* on the same model), one line each with one total and ONE y/N question
|
|
12
|
+
* that applies them all through `applyFix`, as `fix --apply <ids>` does;
|
|
13
|
+
* - the ones that trade something (compacting earlier, autopilot clearing
|
|
14
|
+
* output, the subagents' model, Codex's limit), one line each with their
|
|
15
|
+
* dollars and the command that applies each, after reading it in `fix`.
|
|
16
|
+
* Nothing is written without a `y` typed in a terminal.
|
|
17
|
+
*/
|
|
18
|
+
import { money, overlaps } from "./fix.js";
|
|
19
|
+
import { priceBasis } from "./orgrates.js";
|
|
20
|
+
export function splitFirstFixes(fixes) {
|
|
21
|
+
const avail = fixes.filter((f) => f.state === "available");
|
|
22
|
+
return {
|
|
23
|
+
free: avail.filter((f) => f.qualityFree === true),
|
|
24
|
+
other: avail.filter((f) => f.qualityFree !== true),
|
|
25
|
+
applied: fixes.filter((f) => f.state === "applied"),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
const fixes = (n) => `${n} fix${n === 1 ? "" : "es"}`;
|
|
29
|
+
const amount = (f) => (f.savedUsd !== undefined ? money(f.savedUsd) : "not priced").padStart(10);
|
|
30
|
+
/** The screen, everything but the question itself (under 25 lines whatever the plan). */
|
|
31
|
+
export function renderFirstScreen(s) {
|
|
32
|
+
const { free, other, applied } = splitFirstFixes(s.fixes);
|
|
33
|
+
const codex = s.codexBilledUsd ?? 0;
|
|
34
|
+
const out = [];
|
|
35
|
+
if (s.recordProblem)
|
|
36
|
+
out.push(`⚠ ${s.recordProblem}`);
|
|
37
|
+
if (codex > 0 && s.billedUsd > 0)
|
|
38
|
+
out.push(`context-doctor: your last ${s.days} days, Claude Code ${money(s.billedUsd)} of input and Codex ${money(codex)}, ${priceBasis()}`);
|
|
39
|
+
else if (codex > 0)
|
|
40
|
+
out.push(`context-doctor: your last ${s.days} days of Codex, ${money(codex)} of input ${priceBasis()}`);
|
|
41
|
+
else
|
|
42
|
+
out.push(`context-doctor: your last ${s.days} days of Claude Code, ${money(s.billedUsd)} of input ${priceBasis()}`);
|
|
43
|
+
if (s.billedUsd + codex <= 0) {
|
|
44
|
+
out.push(`No Claude Code sessions in the last ${s.days} days to measure yet, so no fix can be priced; ${s.command("fix")} once there are.`);
|
|
45
|
+
return out.join("\n");
|
|
46
|
+
}
|
|
47
|
+
const per = s.days === 30 ? "a month" : `in ${s.days} days`;
|
|
48
|
+
if (free.length) {
|
|
49
|
+
const priced = free.filter((f) => f.savedUsd !== undefined);
|
|
50
|
+
const total = priced.reduce((t, f) => t + f.savedUsd, 0);
|
|
51
|
+
const sum = priced.length ? `${money(total)} ${per}${priced.length < free.length ? ` (${free.length - priced.length} more not priced)` : ""}` : `${fixes(free.length)}, not priced`;
|
|
52
|
+
out.push("");
|
|
53
|
+
out.push(`Free of any quality cost: ${sum}`);
|
|
54
|
+
for (const f of free)
|
|
55
|
+
out.push(` ${amount(f)} ${f.title}${f.overriddenBy?.length ? " (⚠ overridden here: see fix)" : ""}`);
|
|
56
|
+
// Each lever is replayed alone; two that save part of the same dollars do not add up.
|
|
57
|
+
if (overlaps(priced).length)
|
|
58
|
+
out.push(" each measured alone; they overlap, so together a little less");
|
|
59
|
+
}
|
|
60
|
+
if (other.length) {
|
|
61
|
+
out.push("");
|
|
62
|
+
out.push(`These trade something for money; read each in ${s.command("fix")} first:`);
|
|
63
|
+
const width = Math.min(60, Math.max(...other.map((f) => f.title.length)));
|
|
64
|
+
for (const f of other)
|
|
65
|
+
out.push(` ${amount(f)} ${f.title.padEnd(width)} ${s.command(`fix --apply ${f.id}`)}`);
|
|
66
|
+
}
|
|
67
|
+
out.push("");
|
|
68
|
+
if (applied.length)
|
|
69
|
+
out.push(`Applied before: ${applied.map((f) => f.id).join(", ")}; ${s.command("fix")} shows what each saved since.`);
|
|
70
|
+
out.push(`The full report: ${s.command("savings")}. All commands: ${s.command("--help")}`);
|
|
71
|
+
if (!free.length)
|
|
72
|
+
out.push(`Nothing to apply without a quality cost here; ${s.command("fix")} shows every lever, measured.`);
|
|
73
|
+
else if (!s.ask && !s.recordProblem)
|
|
74
|
+
out.push(`Apply ${free.length === 1 ? "it" : "them"}: ${s.command(`fix --apply ${free.map((f) => f.id).join(",")}`)} (undo any time: ${s.command("fix undo")})`);
|
|
75
|
+
return out.join("\n");
|
|
76
|
+
}
|
|
77
|
+
/** The one question, for the quality-free fixes together. */
|
|
78
|
+
export function firstQuestion(n, command) {
|
|
79
|
+
return `Apply ${n === 1 ? "this fix" : `these ${n} fixes`}? (undo any time: ${command("fix undo")}) [y/N] `;
|
|
80
|
+
}
|
package/dist/fix.d.ts
CHANGED
|
@@ -27,7 +27,10 @@
|
|
|
27
27
|
* ran on before against as billed (the same token counts: an estimate);
|
|
28
28
|
* - long Bash output: the results moved to a file that the cap before left
|
|
29
29
|
* inline, priced at the requests that re-read them no more (an estimate:
|
|
30
|
-
* a file the model opens again is not counted)
|
|
30
|
+
* a file the model opens again is not counted);
|
|
31
|
+
* - subagent progress summaries: the summaries Claude Code would have
|
|
32
|
+
* written for the background subagents since (2.1.318+, which read the
|
|
33
|
+
* variable), estimated as `spend` estimates them (progresssummaries.ts).
|
|
31
34
|
*
|
|
32
35
|
* The subagents' model is the one lever with a quality cost `fix` cannot
|
|
33
36
|
* measure: it is offered with that said, applied only when named (never by
|
|
@@ -39,8 +42,9 @@ import { type ProjectPlan } from "./prune.js";
|
|
|
39
42
|
import { readLedger } from "./ledger.js";
|
|
40
43
|
import { type SubagentModelReplay } from "./subagentmodel.js";
|
|
41
44
|
import { type ToolOutputReplay } from "./tooloutput.js";
|
|
45
|
+
import { type ProgressSummaryEstimate } from "./progresssummaries.js";
|
|
42
46
|
import { type CodexCompactReport } from "./codexcompact.js";
|
|
43
|
-
export type FixId = "compact-window" | "cache-ttl" | "cache-ttl-subagents" | "autopilot" | "tool-search" | "prune" | "subagent-model" | "tool-output" | "codex-compact";
|
|
47
|
+
export type FixId = "compact-window" | "cache-ttl" | "cache-ttl-subagents" | "autopilot" | "tool-search" | "prune" | "subagent-model" | "tool-output" | "codex-compact" | "progress-summaries";
|
|
44
48
|
export interface Fix {
|
|
45
49
|
id: FixId;
|
|
46
50
|
title: string;
|
|
@@ -53,6 +57,12 @@ export interface Fix {
|
|
|
53
57
|
basis: string;
|
|
54
58
|
/** What it costs in quality, plainly. */
|
|
55
59
|
quality: string;
|
|
60
|
+
/**
|
|
61
|
+
* The quality line is "none": the model sees the same content, or the same
|
|
62
|
+
* content moved where it can still open it, and runs on the same model. A
|
|
63
|
+
* bare `context-doctor` offers these together under one question (firstfix.ts).
|
|
64
|
+
*/
|
|
65
|
+
qualityFree?: boolean;
|
|
56
66
|
/** What it writes, where. */
|
|
57
67
|
change: string;
|
|
58
68
|
state: "available" | "applied" | "not-here";
|
|
@@ -129,7 +139,17 @@ export interface FixInputs {
|
|
|
129
139
|
raw: string;
|
|
130
140
|
where: string;
|
|
131
141
|
};
|
|
142
|
+
/** The subagents' progress summaries Claude Code wrote, estimated (progresssummaries.ts). */
|
|
143
|
+
progressSummaries?: ProgressSummaryEstimate;
|
|
144
|
+
/** CLAUDE_CODE_DISABLE_AGENT_PROGRESS_SUMMARIES where it is set (progressSummariesState): never overwritten. */
|
|
145
|
+
progressSummariesSet?: {
|
|
146
|
+
value: string;
|
|
147
|
+
where: string;
|
|
148
|
+
};
|
|
132
149
|
}
|
|
150
|
+
export declare const money: (n: number) => string;
|
|
151
|
+
/** " (48%)", or " (37% of subagents)" for a share of something else. */
|
|
152
|
+
export declare const share: (f: Fix) => string;
|
|
133
153
|
export declare function planFixes(i: FixInputs): Fix[];
|
|
134
154
|
export interface FixRecord {
|
|
135
155
|
id: FixId;
|
|
@@ -198,6 +218,30 @@ export declare function applyFix(fix: Fix, deps?: FixDeps, context?: {
|
|
|
198
218
|
}>;
|
|
199
219
|
/** Undo what fix applied: every fix, or the ones named. Returns what it did, line by line. */
|
|
200
220
|
export declare function undoFixes(ids: FixId[] | undefined, deps?: FixDeps): Promise<string[]>;
|
|
221
|
+
/**
|
|
222
|
+
* Where CLAUDE_CODE_DISABLE_AGENT_PROGRESS_SUMMARIES is set, as Claude Code
|
|
223
|
+
* sees it: the highest settings file whose env names it (managed, local,
|
|
224
|
+
* project, user: each applied over the one before and over the shell), else
|
|
225
|
+
* the shell's own value. A project's or managed value that keeps them is not
|
|
226
|
+
* the user's (fixOverrides names it); the user's own one is never
|
|
227
|
+
* overwritten. `offSince`: when fix turned them off (its record).
|
|
228
|
+
* `forkGateOff`: CLAUDE_CODE_FORK_SUBAGENT off, which in a terminal session
|
|
229
|
+
* also keeps ordinary background subagents from getting summaries.
|
|
230
|
+
*/
|
|
231
|
+
export declare function progressSummariesState(deps?: {
|
|
232
|
+
home?: string;
|
|
233
|
+
cwd?: string;
|
|
234
|
+
env?: NodeJS.ProcessEnv;
|
|
235
|
+
}): {
|
|
236
|
+
set?: {
|
|
237
|
+
value: string;
|
|
238
|
+
where: string;
|
|
239
|
+
};
|
|
240
|
+
offSince?: number;
|
|
241
|
+
forkGateOff: boolean;
|
|
242
|
+
};
|
|
243
|
+
/** The summaries fix's variable stopped since `at`: the background subagents on Claude Code 2.1.318+ since, estimated as if it were not set. */
|
|
244
|
+
export declare function progressSummariesSavedSince(at: number, subagentPaths?: string[], forkGateOff?: boolean): ProgressSummaryEstimate;
|
|
201
245
|
export interface SinceResult {
|
|
202
246
|
id: FixId;
|
|
203
247
|
at: number;
|