context-doctor 0.40.0 → 0.41.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 +9 -2
- package/dist/budget.d.ts +91 -0
- package/dist/budget.js +428 -0
- package/dist/cli.js +86 -10
- package/dist/cursor.d.ts +23 -0
- package/dist/cursor.js +120 -1
- package/dist/doctor.js +19 -0
- package/dist/fix.d.ts +21 -2
- package/dist/fix.js +60 -4
- package/dist/hook.js +32 -5
- package/dist/install.js +2 -0
- package/dist/limits.d.ts +38 -5
- package/dist/limits.js +81 -49
- package/dist/mcp.js +1 -1
- package/dist/proxy.d.ts +1 -1
- package/dist/proxy.js +1 -1
- package/dist/scan.d.ts +8 -0
- package/dist/scan.js +21 -0
- package/dist/spend.d.ts +176 -0
- package/dist/spend.js +476 -0
- package/dist/statusline.d.ts +9 -2
- package/dist/statusline.js +20 -4
- package/dist/subagentmodel.d.ts +126 -0
- package/dist/subagentmodel.js +320 -0
- package/dist/subagentpay.d.ts +11 -0
- package/dist/subagentpay.js +23 -4
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -29,6 +29,7 @@ import { autopilotOff, autopilotOn, autopilotPauseResult, autopilotPaths, autopi
|
|
|
29
29
|
import { estimateSavings, renderSavings, renderShare, savingsRows } from "./savings.js";
|
|
30
30
|
import { prescan } from "./scan.js";
|
|
31
31
|
import { REQUEST_ROWS } from "./coldresume.js";
|
|
32
|
+
import { replaySubagentModels, shares, SUBAGENT_MODEL_ENV, SUBAGENT_MODEL_FORCE_ENV, SUBAGENT_ROWS } from "./subagentmodel.js";
|
|
32
33
|
import { currentCompactWindow, estimateCompactWindows, MAX_WINDOW, MIN_WINDOW, parseWindow, renderCompactWindows, setCompactWindow, settingsPath } from "./compactwindow.js";
|
|
33
34
|
import { tilde } from "./claudedir.js";
|
|
34
35
|
import { renderPreferences, copyToClipboard, CHAT_PREFERENCES } from "./preferences.js";
|
|
@@ -70,6 +71,8 @@ import { effectiveEnv, settingsSources } from "./effective.js";
|
|
|
70
71
|
import { SettingsError } from "./settingsedit.js";
|
|
71
72
|
import { currentTtl, estimateCacheTtl, renderCacheTtl, setCacheTtl, settingKey, subagentTranscripts, ttlUnsupported, CACHE_TTL_SINCE } from "./cachettl.js";
|
|
72
73
|
import { claudeDir } from "./claudedir.js";
|
|
74
|
+
import { renderSpend, renderSpendShare, spendReport } from "./spend.js";
|
|
75
|
+
import { clearBudget, parseBudget, periodSpend, promptHookInstalled, readBudget, renderBudgetStatus, writeBudget } from "./budget.js";
|
|
73
76
|
const HELP = `context-doctor — profile and optimize LLM context windows
|
|
74
77
|
|
|
75
78
|
Start here:
|
|
@@ -89,9 +92,11 @@ Start here:
|
|
|
89
92
|
what a bare \`context-doctor\` shows
|
|
90
93
|
context-doctor fix [--apply ids|all] [--share] What to change, ranked by dollars on your own
|
|
91
94
|
sessions (compact earlier, the cache lifetime,
|
|
92
|
-
autopilot, MCP tool search, unused servers
|
|
93
|
-
applied only on a yes
|
|
94
|
-
|
|
95
|
+
autopilot, MCP tool search, unused servers, the
|
|
96
|
+
subagents' model): each applied only on a yes
|
|
97
|
+
(the subagents' model only by name, never by
|
|
98
|
+
"all"), \`fix undo\` reverts them, later runs show
|
|
99
|
+
what each saved since
|
|
95
100
|
context-doctor doctor Self-check the installation (configs, hook, skill,
|
|
96
101
|
MCP handshake) with one pasteable diagnosis
|
|
97
102
|
context-doctor uninstall Undo install
|
|
@@ -120,6 +125,12 @@ Measure:
|
|
|
120
125
|
and Codex's, the pace, when each runs out, and what
|
|
121
126
|
1M tokens of each kind cost in %, fitted on your own
|
|
122
127
|
readings with the fit's error
|
|
128
|
+
context-doctor spend [--days n] [--share [--copy]]
|
|
129
|
+
One bill across every tool here: Claude Code (with
|
|
130
|
+
its subagents), Codex, Gemini CLI and Cursor (an
|
|
131
|
+
estimate: no cache split), by project, model and
|
|
132
|
+
day, and what drives it, at list prices. --share:
|
|
133
|
+
totals only, to paste
|
|
123
134
|
context-doctor cache-misses [--days n] Requests that re-wrote the prompt cache while it was
|
|
124
135
|
still warm: priced, by model and context size, with
|
|
125
136
|
the cause where the transcript shows one
|
|
@@ -165,6 +176,12 @@ Fix automatically:
|
|
|
165
176
|
prompt cache is cold, so it never costs more.
|
|
166
177
|
Plain \`proxy\` is the optimizing mode (dedupe, trim,
|
|
167
178
|
strip base64), which can cost more on cached traffic
|
|
179
|
+
context-doctor budget [<usd>/day|<usd>/week|off] [--block]
|
|
180
|
+
A spend budget across Claude Code, Codex and Gemini
|
|
181
|
+
CLI: the every-prompt hook says what today (or this
|
|
182
|
+
week) has cost at 50%, 80% and 100% of it; --block
|
|
183
|
+
holds prompts over it until you raise it or turn it
|
|
184
|
+
off. Bare \`budget\`: where the period stands
|
|
168
185
|
|
|
169
186
|
Fix on request:
|
|
170
187
|
context-doctor optimize <file|-> [options] Apply safe fixes, print slimmed conversation
|
|
@@ -244,11 +261,13 @@ Options:
|
|
|
244
261
|
Default: dedupe, trim-tool-results, strip-base64 (lossless-ish set)
|
|
245
262
|
--keep-recent <n> (optimize) Messages at the tail to leave untouched (default 6)
|
|
246
263
|
--max-tool-tokens <n> (optimize) Token budget for trimmed tool results (default 300)
|
|
247
|
-
--limit <n> (accuracy, session --list, reads, tasks, subagents) How many to
|
|
248
|
-
or list
|
|
264
|
+
--limit <n> (accuracy, session --list, reads, tasks, subagents, spend) How many to
|
|
265
|
+
sample or list
|
|
249
266
|
--days <n> (savings, compact-window, cache-ttl, overhead, reads, tasks, subagents,
|
|
250
|
-
compactions, cache-misses, limits)
|
|
267
|
+
compactions, cache-misses, limits, spend)
|
|
251
268
|
Days of history to read (default 30; compactions 60)
|
|
269
|
+
--block (budget) Over the budget, the every-prompt hook holds the prompt and
|
|
270
|
+
says how to lift it, instead of only saying so
|
|
252
271
|
-q, --query <text> (pack) The question to rank chunks against
|
|
253
272
|
--max-tokens <n> (pack) Token budget (default 4000); (recall) default 2000; (ci) fail over
|
|
254
273
|
this many tokens
|
|
@@ -326,7 +345,7 @@ async function measureFixInputs(days) {
|
|
|
326
345
|
// Each transcript read once for every replay below; what an earlier run kept is not read again (scan.ts).
|
|
327
346
|
prescan([
|
|
328
347
|
{ paths: claudeTranscripts(days), extractors: [savingsRows(!autopilotOnNow), REQUEST_ROWS] },
|
|
329
|
-
{ paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS] },
|
|
348
|
+
{ paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS, SUBAGENT_ROWS] },
|
|
330
349
|
...(setWindow === undefined ? [{ paths: claudeTranscripts(60), extractors: [QUALITY_ROWS] }] : []),
|
|
331
350
|
], replaying.tick);
|
|
332
351
|
const report = estimateSavings(days, {}, undefined, replaying.tick, !autopilotOnNow);
|
|
@@ -350,6 +369,12 @@ async function measureFixInputs(days) {
|
|
|
350
369
|
const ttl = estimateCacheTtl(days, { onProgress: ttling.tick });
|
|
351
370
|
ttling.clear();
|
|
352
371
|
const sources = settingsSources({ cwd });
|
|
372
|
+
// The subagents' model: what the variable would move, and a value the user already set (their settings.json, or this shell).
|
|
373
|
+
const force = effectiveEnv(SUBAGENT_MODEL_FORCE_ENV, sources);
|
|
374
|
+
const subagentModel = replaySubagentModels({ since: Date.now() - days * 86_400_000, force: !!force && !/^(0|false)$/i.test(force.value.trim()) });
|
|
375
|
+
const userSm = sources.find((s) => s.name === "user")?.settings.env?.[SUBAGENT_MODEL_ENV];
|
|
376
|
+
const shellSm = process.env[SUBAGENT_MODEL_ENV];
|
|
377
|
+
const subagentModelSet = userSm !== undefined && userSm !== null ? { value: String(userSm), where: `${tilde(join(claudeDir(), "settings.json"))} env` } : shellSm?.trim() ? { value: shellSm, where: "the environment" } : undefined;
|
|
353
378
|
const ts = effectiveEnv("ENABLE_TOOL_SEARCH", sources);
|
|
354
379
|
const toolSearchOff = ts && /^(false|0|no|off)$/i.test(ts.value.trim()) ? ts.value : undefined;
|
|
355
380
|
const servers = claudeMcpConfigs(cwd).filter((c) => !/context-doctor/i.test(c.name));
|
|
@@ -374,7 +399,7 @@ async function measureFixInputs(days) {
|
|
|
374
399
|
recordProblem = e.message;
|
|
375
400
|
}
|
|
376
401
|
const sessions = report.sessions.length;
|
|
377
|
-
const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search"];
|
|
402
|
+
const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search", "subagent-model"];
|
|
378
403
|
return {
|
|
379
404
|
prunePlan,
|
|
380
405
|
inputs: {
|
|
@@ -387,6 +412,8 @@ async function measureFixInputs(days) {
|
|
|
387
412
|
toolSearchOff,
|
|
388
413
|
mcpServers: toolSearchOff ? servers.length : 0,
|
|
389
414
|
prune: prunePlan,
|
|
415
|
+
subagentModel,
|
|
416
|
+
subagentModelSet,
|
|
390
417
|
overrides: Object.fromEntries(ids.map((id) => [id, fixOverrides(id, { cwd })])),
|
|
391
418
|
recordProblem,
|
|
392
419
|
coldResume: { netUsd: Math.max(0, report.coldResumeNetUsd), returns: report.coldResumes, hooked: claudePluginEnabled() || /context-doctor|cli\.js"?\s+hook/.test(JSON.stringify(userSettings.hooks?.UserPromptSubmit ?? [])) },
|
|
@@ -406,7 +433,7 @@ const COMMANDS = [
|
|
|
406
433
|
"analyze", "optimize", "proxy", "install", "uninstall", "savings", "compact-window", "autopilot", "mcp",
|
|
407
434
|
"instructions", "session", "cursor", "statusline", "hook", "report", "doctor", "dashboard", "init",
|
|
408
435
|
"experiment", "diff", "accuracy", "overhead", "ci", "cache-plan", "compactions", "cache-misses", "cache-ttl", "fix", "limits", "subagents", "tasks",
|
|
409
|
-
"reads", "pack", "watch", "ab", "handoff", "recall", "help", "version",
|
|
436
|
+
"spend", "budget", "reads", "pack", "watch", "ab", "handoff", "recall", "help", "version",
|
|
410
437
|
];
|
|
411
438
|
/** --strategy takes one of the optimizer's ids; a typo used to run nothing and report success. */
|
|
412
439
|
function strategyArg(v) {
|
|
@@ -441,6 +468,7 @@ const FLAGS = [
|
|
|
441
468
|
{ names: ["--dry-run"], set: (a) => { a.dryRun = true; } },
|
|
442
469
|
{ names: ["--copy"], set: (a) => { a.copy = true; } },
|
|
443
470
|
{ names: ["--share"], set: (a) => { a.share = true; } },
|
|
471
|
+
{ names: ["--block"], set: (a) => { a.block = true; } },
|
|
444
472
|
{ names: ["--allow-dirty"], set: (a) => { a.allowDirty = true; } },
|
|
445
473
|
{ names: ["--statusline"], set: (a) => { a.statusLine = true; } },
|
|
446
474
|
{ names: ["--host"], value: "text", set: (a, v) => { a.host = v; } },
|
|
@@ -1191,7 +1219,7 @@ async function main() {
|
|
|
1191
1219
|
continue;
|
|
1192
1220
|
}
|
|
1193
1221
|
const kind = id === "cache-ttl" ? "main" : id === "cache-ttl-subagents" ? "subagents" : undefined;
|
|
1194
|
-
const r = await applyFix(f, { autopilotOn: () => autopilotOn(args.port ?? DEFAULT_AUTOPILOT_PORT) }, { oneHourShare: kind ? inputs.ttl?.[kind].oneHourShare : undefined, prune: prunePlan });
|
|
1222
|
+
const r = await applyFix(f, { autopilotOn: () => autopilotOn(args.port ?? DEFAULT_AUTOPILOT_PORT) }, { oneHourShare: kind ? inputs.ttl?.[kind].oneHourShare : undefined, prune: prunePlan, modelsBefore: inputs.subagentModel ? shares(inputs.subagentModel.movedFrom) : undefined });
|
|
1195
1223
|
results.push({ id, ...r });
|
|
1196
1224
|
}
|
|
1197
1225
|
// Naming fixes that are not there (or nothing at all, with "all") is not a silent success.
|
|
@@ -1292,6 +1320,54 @@ async function main() {
|
|
|
1292
1320
|
console.log(args.json ? JSON.stringify(report, null, 2) : renderLimits(report));
|
|
1293
1321
|
return;
|
|
1294
1322
|
}
|
|
1323
|
+
if (args.command === "spend") {
|
|
1324
|
+
if (args.file !== undefined)
|
|
1325
|
+
usageError(`Usage: context-doctor spend [--days n] [--limit n] [--share [--copy]] [--json]; got "${args.file}".`);
|
|
1326
|
+
if (args.share && args.json)
|
|
1327
|
+
usageError("--share and --json do not go together: --share prints a few lines to paste.");
|
|
1328
|
+
const reading = progressLine("Reading your usage across tools");
|
|
1329
|
+
const report = spendReport(args.days ?? 30, { onProgress: reading.tick });
|
|
1330
|
+
reading.clear();
|
|
1331
|
+
if (args.json)
|
|
1332
|
+
console.log(JSON.stringify(report, null, 2));
|
|
1333
|
+
else if (args.share) {
|
|
1334
|
+
const text = renderSpendShare(report);
|
|
1335
|
+
console.log(text);
|
|
1336
|
+
if (args.copy)
|
|
1337
|
+
console.log(copyToClipboard(text) ? "\n(copied to the clipboard)" : "\n(no clipboard tool found; copy the lines above)");
|
|
1338
|
+
}
|
|
1339
|
+
else
|
|
1340
|
+
console.log(renderSpend(report, args.limit ?? 8));
|
|
1341
|
+
return;
|
|
1342
|
+
}
|
|
1343
|
+
if (args.command === "budget") {
|
|
1344
|
+
const sub = args.file;
|
|
1345
|
+
const usage = "Usage: context-doctor budget [<usd>/day | <usd>/week] [--block] | budget off | budget [--json]";
|
|
1346
|
+
if ((args.positionals?.length ?? 0) > 1)
|
|
1347
|
+
usageError(`${usage}; got "${args.positionals.slice(1).join(" ")}" too.`);
|
|
1348
|
+
if (sub === "off") {
|
|
1349
|
+
if (args.block)
|
|
1350
|
+
usageError("--block goes with a budget: context-doctor budget 50/day --block.");
|
|
1351
|
+
console.log(clearBudget() ? "Budget off: the every-prompt hook no longer counts spend." : "No budget was set.");
|
|
1352
|
+
return;
|
|
1353
|
+
}
|
|
1354
|
+
if (sub !== undefined) {
|
|
1355
|
+
const parsed = parseBudget(sub);
|
|
1356
|
+
if ("error" in parsed)
|
|
1357
|
+
usageError(`${parsed.error}${didYouMean(sub, ["off"])} ${usage}.`);
|
|
1358
|
+
writeBudget({ ...parsed, block: Boolean(args.block), at: Date.now() });
|
|
1359
|
+
}
|
|
1360
|
+
else if (args.block) {
|
|
1361
|
+
usageError("--block goes with a budget: context-doctor budget 50/day --block.");
|
|
1362
|
+
}
|
|
1363
|
+
const b = readBudget();
|
|
1364
|
+
const s = b ? periodSpend(b.period) : undefined;
|
|
1365
|
+
if (args.json)
|
|
1366
|
+
console.log(JSON.stringify(b && s ? { ...b, spent: s.usd, byTool: s.byTool, periodStart: s.start, periodEnd: s.end } : null, null, 2));
|
|
1367
|
+
else
|
|
1368
|
+
console.log(withInvocation(renderBudgetStatus(b, s, promptHookInstalled())));
|
|
1369
|
+
return;
|
|
1370
|
+
}
|
|
1295
1371
|
if (args.command === "compactions") {
|
|
1296
1372
|
const days = args.days ?? 60;
|
|
1297
1373
|
const q = compactionQuality(days);
|
package/dist/cursor.d.ts
CHANGED
|
@@ -52,4 +52,27 @@ export declare function listCursorChats(limit?: number): CursorChat[];
|
|
|
52
52
|
* tool-result findings apply to Cursor chats exactly as they do elsewhere.
|
|
53
53
|
*/
|
|
54
54
|
export declare function parseCursorChat(chat: CursorChat): ParsedSession;
|
|
55
|
+
/**
|
|
56
|
+
* One Cursor agent reply that recorded its tokens (`tokenCount` on the
|
|
57
|
+
* bubble). Cursor keeps the prompt's size and the reply's, with no cache
|
|
58
|
+
* split and no price; the model is the chat's (`modelConfig.modelName`,
|
|
59
|
+
* "default" for Auto) unless the reply names its own.
|
|
60
|
+
*/
|
|
61
|
+
export interface CursorReply {
|
|
62
|
+
ts: number;
|
|
63
|
+
input: number;
|
|
64
|
+
output: number;
|
|
65
|
+
model?: string;
|
|
66
|
+
composerId: string;
|
|
67
|
+
/** The workspace folder the chat belongs to, when Cursor recorded one. */
|
|
68
|
+
folder?: string;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Every Cursor reply with token counts since `since`. Only chats updated
|
|
72
|
+
* since then are read, each by its key range (on the author's 3 GB history
|
|
73
|
+
* the chat list takes ~0.1 s, one chat's replies ~40 ms), and each chat's
|
|
74
|
+
* replies are kept until it changes, so a second run reads none of them
|
|
75
|
+
* again. Throws SqliteUnavailableError when this runtime cannot read SQLite.
|
|
76
|
+
*/
|
|
77
|
+
export declare function cursorUsage(since: number): CursorReply[];
|
|
55
78
|
export {};
|
package/dist/cursor.js
CHANGED
|
@@ -12,10 +12,11 @@
|
|
|
12
12
|
* say so plainly instead of failing obscurely.
|
|
13
13
|
*/
|
|
14
14
|
import { execFileSync } from "node:child_process";
|
|
15
|
-
import { existsSync, readdirSync, statSync } from "node:fs";
|
|
15
|
+
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
16
16
|
import { createRequire } from "node:module";
|
|
17
17
|
import { homedir, platform } from "node:os";
|
|
18
18
|
import { join } from "node:path";
|
|
19
|
+
import { readSideEntry, writeSideEntry } from "./scan.js";
|
|
19
20
|
const require = createRequire(import.meta.url);
|
|
20
21
|
/** Cursor bubble type codes. */
|
|
21
22
|
const BUBBLE_USER = 1;
|
|
@@ -76,12 +77,23 @@ export class SqliteUnavailableError extends Error {
|
|
|
76
77
|
}
|
|
77
78
|
/** Node's built-in SQLite, when this runtime has it (22.13+, or 22.5+ with --experimental-sqlite). */
|
|
78
79
|
function nodeSqlite() {
|
|
80
|
+
// Node 22-25 warns that SQLite is experimental on first load, on stderr,
|
|
81
|
+
// in the middle of a report: not something the user can act on.
|
|
82
|
+
const emit = process.emitWarning;
|
|
83
|
+
process.emitWarning = ((warning, ...rest) => {
|
|
84
|
+
if (String(warning).includes("SQLite"))
|
|
85
|
+
return;
|
|
86
|
+
return emit.call(process, warning, ...rest);
|
|
87
|
+
});
|
|
79
88
|
try {
|
|
80
89
|
return require("node:sqlite");
|
|
81
90
|
}
|
|
82
91
|
catch {
|
|
83
92
|
return undefined;
|
|
84
93
|
}
|
|
94
|
+
finally {
|
|
95
|
+
process.emitWarning = emit;
|
|
96
|
+
}
|
|
85
97
|
}
|
|
86
98
|
/**
|
|
87
99
|
* Run a read-only query against a Cursor database.
|
|
@@ -237,3 +249,110 @@ export function parseCursorChat(chat) {
|
|
|
237
249
|
path: `${chat.dbPath}#${chat.composerId}`,
|
|
238
250
|
};
|
|
239
251
|
}
|
|
252
|
+
const CURSOR_SPEND = "cursor-spend.1";
|
|
253
|
+
/** Chat id -> workspace folder, from each workspace's own state (composer.composerData, workspace.json). */
|
|
254
|
+
function cursorFolders() {
|
|
255
|
+
const out = new Map();
|
|
256
|
+
for (const dir of cursorStorageDirs()) {
|
|
257
|
+
let folder;
|
|
258
|
+
try {
|
|
259
|
+
const f = JSON.parse(readFileSync(join(dir, "workspace.json"), "utf8"))?.folder;
|
|
260
|
+
if (typeof f === "string" && f.startsWith("file://"))
|
|
261
|
+
folder = decodeURIComponent(f.slice("file://".length));
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
continue; // globalStorage, or a multi-root workspace: no one folder
|
|
265
|
+
}
|
|
266
|
+
if (!folder || !existsSync(join(dir, "state.vscdb")))
|
|
267
|
+
continue;
|
|
268
|
+
try {
|
|
269
|
+
const row = queryRows(join(dir, "state.vscdb"), "SELECT value FROM ItemTable WHERE key = 'composer.composerData'")[0];
|
|
270
|
+
const all = JSON.parse(String(row?.value ?? "{}"))?.allComposers;
|
|
271
|
+
if (Array.isArray(all))
|
|
272
|
+
for (const c of all)
|
|
273
|
+
if (typeof c?.composerId === "string")
|
|
274
|
+
out.set(c.composerId, folder);
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
/* an older or unreadable workspace database */
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return out;
|
|
281
|
+
}
|
|
282
|
+
/** A time Cursor wrote: epoch ms (as a number or digits) or an ISO string. */
|
|
283
|
+
function cursorTime(v) {
|
|
284
|
+
const n = typeof v === "number" ? v : typeof v === "string" ? (/^\d+$/.test(v) ? Number(v) : Date.parse(v)) : Number.NaN;
|
|
285
|
+
return Number.isFinite(n) && n > 0 ? n : undefined;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Every Cursor reply with token counts since `since`. Only chats updated
|
|
289
|
+
* since then are read, each by its key range (on the author's 3 GB history
|
|
290
|
+
* the chat list takes ~0.1 s, one chat's replies ~40 ms), and each chat's
|
|
291
|
+
* replies are kept until it changes, so a second run reads none of them
|
|
292
|
+
* again. Throws SqliteUnavailableError when this runtime cannot read SQLite.
|
|
293
|
+
*/
|
|
294
|
+
export function cursorUsage(since) {
|
|
295
|
+
const out = [];
|
|
296
|
+
let folders;
|
|
297
|
+
for (const dbPath of findCursorDatabases()) {
|
|
298
|
+
let composers;
|
|
299
|
+
try {
|
|
300
|
+
// A key range, not LIKE: it walks the primary key's index.
|
|
301
|
+
composers = queryRows(dbPath, "SELECT key, json_extract(value, '$.lastUpdatedAt') AS lu, json_extract(value, '$.createdAt') AS ca, json_extract(value, '$.modelConfig.modelName') AS mn " +
|
|
302
|
+
"FROM cursorDiskKV WHERE key >= 'composerData:' AND key < 'composerData;' AND json_valid(value)");
|
|
303
|
+
}
|
|
304
|
+
catch (e) {
|
|
305
|
+
if (e instanceof SqliteUnavailableError)
|
|
306
|
+
throw e;
|
|
307
|
+
continue; // no chats in this database
|
|
308
|
+
}
|
|
309
|
+
const kept = readSideEntry(dbPath, CURSOR_SPEND) ?? { composers: {} };
|
|
310
|
+
let changed = false;
|
|
311
|
+
for (const c of composers) {
|
|
312
|
+
const id = String(c.key).slice("composerData:".length);
|
|
313
|
+
const lu = cursorTime(c.lu) ?? cursorTime(c.ca) ?? 0;
|
|
314
|
+
if (lu < since || !/^[\w-]+$/.test(id))
|
|
315
|
+
continue;
|
|
316
|
+
let rows = kept.composers[id]?.lu === lu ? kept.composers[id].rows : undefined;
|
|
317
|
+
if (!rows) {
|
|
318
|
+
rows = [];
|
|
319
|
+
let bubbles = [];
|
|
320
|
+
try {
|
|
321
|
+
bubbles = queryRows(dbPath, "SELECT json_extract(value, '$.tokenCount.inputTokens') AS i, json_extract(value, '$.tokenCount.outputTokens') AS o, " +
|
|
322
|
+
"json_extract(value, '$.createdAt') AS ca, json_extract(value, '$.timingInfo.clientStartTime') AS cs, json_extract(value, '$.modelInfo.modelName') AS mn " +
|
|
323
|
+
`FROM cursorDiskKV WHERE key >= 'bubbleId:${id}:' AND key < 'bubbleId:${id};' AND json_valid(value)`);
|
|
324
|
+
}
|
|
325
|
+
catch {
|
|
326
|
+
/* an unreadable chat: nothing from it */
|
|
327
|
+
}
|
|
328
|
+
for (const b of bubbles) {
|
|
329
|
+
const i = Number(b.i) > 0 ? Number(b.i) : 0, o = Number(b.o) > 0 ? Number(b.o) : 0;
|
|
330
|
+
if (i + o === 0)
|
|
331
|
+
continue;
|
|
332
|
+
// A reply without a time of its own is placed at the chat's last update.
|
|
333
|
+
rows.push([cursorTime(b.ca) ?? cursorTime(b.cs) ?? lu, i, o, typeof b.mn === "string" && b.mn ? b.mn : null]);
|
|
334
|
+
}
|
|
335
|
+
kept.composers[id] = { lu, rows };
|
|
336
|
+
changed = true;
|
|
337
|
+
}
|
|
338
|
+
if (rows.length && !folders)
|
|
339
|
+
folders = cursorFolders();
|
|
340
|
+
const chatModel = typeof c.mn === "string" && c.mn ? c.mn : undefined;
|
|
341
|
+
for (const [ts, input, output, mn] of rows) {
|
|
342
|
+
if (ts < since)
|
|
343
|
+
continue;
|
|
344
|
+
const r = { ts, input, output, composerId: id };
|
|
345
|
+
const model = mn ?? chatModel;
|
|
346
|
+
if (model)
|
|
347
|
+
r.model = model;
|
|
348
|
+
const folder = folders?.get(id);
|
|
349
|
+
if (folder)
|
|
350
|
+
r.folder = folder;
|
|
351
|
+
out.push(r);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
if (changed)
|
|
355
|
+
writeSideEntry(dbPath, CURSOR_SPEND, kept);
|
|
356
|
+
}
|
|
357
|
+
return out.sort((a, b) => a.ts - b.ts);
|
|
358
|
+
}
|
package/dist/doctor.js
CHANGED
|
@@ -26,6 +26,7 @@ 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
28
|
import { claudeDir, claudeJsonPath } from "./claudedir.js";
|
|
29
|
+
import { periodSpend, readBudget } from "./budget.js";
|
|
29
30
|
function claudeDesktopConfigPath() {
|
|
30
31
|
switch (platform()) {
|
|
31
32
|
case "darwin": return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
|
|
@@ -728,6 +729,24 @@ export async function runDoctor() {
|
|
|
728
729
|
else {
|
|
729
730
|
checks.push({ label: "Project config", status: "skip", detail: "no .contextdoctorrc (optional; create one with: context-doctor init <preset>)" });
|
|
730
731
|
}
|
|
732
|
+
// The spend budget: set or not, where the period stands, and whether a hook is there to apply it.
|
|
733
|
+
{
|
|
734
|
+
const b = readBudget();
|
|
735
|
+
if (!b)
|
|
736
|
+
checks.push({ label: "Spend budget", status: "skip", detail: "none set (optional: context-doctor budget 50/day)" });
|
|
737
|
+
else {
|
|
738
|
+
let spent = "";
|
|
739
|
+
try {
|
|
740
|
+
const s = periodSpend(b.period);
|
|
741
|
+
spent = `; ${b.period === "day" ? "today" : "this week"} $${s.usd.toFixed(2)} (${Math.round((s.usd / b.usd) * 100)}%)`;
|
|
742
|
+
}
|
|
743
|
+
catch { /* the ledger could not be read: the budget alone */ }
|
|
744
|
+
const hooked = checks.some((c) => ["Every-prompt hook", "Codex hook", "Gemini CLI hook"].includes(c.label) && c.status === "ok");
|
|
745
|
+
checks.push(hooked
|
|
746
|
+
? { label: "Spend budget", status: "ok", detail: `$${b.usd} a ${b.period}${b.block ? ", prompts over it held" : ", warns at 50/80/100%"}${spent}` }
|
|
747
|
+
: { label: "Spend budget", status: "warn", detail: `$${b.usd} a ${b.period}${spent}, but no every-prompt hook is registered to apply it: run context-doctor install` });
|
|
748
|
+
}
|
|
749
|
+
}
|
|
731
750
|
checks.push(await checkMcpHandshake());
|
|
732
751
|
// Autopilot: optional, so "off" is a skip, not a failure. When it is on, a
|
|
733
752
|
// dead proxy or a settings file pointing elsewhere is a real problem.
|
package/dist/fix.d.ts
CHANGED
|
@@ -22,12 +22,19 @@
|
|
|
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;
|
|
@@ -47,6 +54,8 @@ export interface Fix {
|
|
|
47
54
|
value?: number | string;
|
|
48
55
|
/** What would keep it from taking effect (environment, project or managed settings, per-model values). */
|
|
49
56
|
overriddenBy?: string[];
|
|
57
|
+
/** More lines under it in the plan (the subagents' model: per agent type). */
|
|
58
|
+
detail?: string[];
|
|
50
59
|
}
|
|
51
60
|
/** The measurements a plan is made from (so the plan itself is testable without a machine's history). */
|
|
52
61
|
export interface FixInputs {
|
|
@@ -80,6 +89,13 @@ export interface FixInputs {
|
|
|
80
89
|
overrides?: Partial<Record<FixId, string[]>>;
|
|
81
90
|
/** The record of applied fixes could not be read. */
|
|
82
91
|
recordProblem?: string;
|
|
92
|
+
/** Every subagent request replayed at Sonnet 5.5 (subagentmodel.ts). */
|
|
93
|
+
subagentModel?: SubagentModelReplay;
|
|
94
|
+
/** CLAUDE_CODE_SUBAGENT_MODEL as the user set it (their settings.json env, or the environment fix runs in): never overwritten. */
|
|
95
|
+
subagentModelSet?: {
|
|
96
|
+
value: string;
|
|
97
|
+
where: string;
|
|
98
|
+
};
|
|
83
99
|
/** 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
100
|
coldResume?: {
|
|
85
101
|
netUsd: number;
|
|
@@ -108,6 +124,8 @@ export interface FixRecord {
|
|
|
108
124
|
oneHourShareBefore?: number;
|
|
109
125
|
/** For prune: the project folder. */
|
|
110
126
|
cwd?: string;
|
|
127
|
+
/** For subagent-model: the models the moved subagents ran on before the change, each one's share of their bill: the baseline "since" compares against. */
|
|
128
|
+
modelsBefore?: Record<string, number>;
|
|
111
129
|
}
|
|
112
130
|
export declare function fixRecordPath(home?: string): string;
|
|
113
131
|
/**
|
|
@@ -140,6 +158,7 @@ export declare function fixOverrides(id: FixId, deps?: {
|
|
|
140
158
|
export declare function applyFix(fix: Fix, deps?: FixDeps, context?: {
|
|
141
159
|
oneHourShare?: number;
|
|
142
160
|
prune?: ProjectPlan;
|
|
161
|
+
modelsBefore?: Record<string, number>;
|
|
143
162
|
}): Promise<{
|
|
144
163
|
ok: boolean;
|
|
145
164
|
lines: string[];
|
package/dist/fix.js
CHANGED
|
@@ -22,7 +22,13 @@
|
|
|
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 { existsSync, mkdirSync, readFileSync } from "node:fs";
|
|
28
34
|
import { dirname, join } from "node:path";
|
|
@@ -36,6 +42,7 @@ import { tilde } from "./claudedir.js";
|
|
|
36
42
|
import { applyPrune, undoPrune } from "./prune.js";
|
|
37
43
|
import { readLedger } from "./ledger.js";
|
|
38
44
|
import { claudeDir } from "./claudedir.js";
|
|
45
|
+
import { movedFromNames, renderSubagentTypes, subagentModelSavedSince, SUBAGENT_CANDIDATE, SUBAGENT_CANDIDATE_NAME, SUBAGENT_MODEL_ENV } from "./subagentmodel.js";
|
|
39
46
|
/** Below this a priced fix is not worth a setting. */
|
|
40
47
|
const MIN_USD = 1;
|
|
41
48
|
const money = (n) => (n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`);
|
|
@@ -132,6 +139,29 @@ export function planFixes(i) {
|
|
|
132
139
|
state: "available",
|
|
133
140
|
});
|
|
134
141
|
}
|
|
142
|
+
const sm = i.subagentModel;
|
|
143
|
+
const set = i.subagentModelSet;
|
|
144
|
+
if (set) {
|
|
145
|
+
const inherit = /^(inherit|default)$/i.test(set.value.trim());
|
|
146
|
+
const less = sm && sm.savedUsd >= MIN_USD ? ` (${SUBAGENT_CANDIDATE_NAME} would have cost ${money(sm.savedUsd)} less)` : "";
|
|
147
|
+
fixes.push({ id: "subagent-model", title: "Subagent model", basis: "set", quality: "", change: `env.${SUBAGENT_MODEL_ENV}`, state: inherit ? "not-here" : "applied", note: `${SUBAGENT_MODEL_ENV}=${set.value} in ${set.where}${inherit ? `: left as you set it${less}` : ""}`, value: set.value });
|
|
148
|
+
}
|
|
149
|
+
else if (sm && sm.savedUsd >= MIN_USD) {
|
|
150
|
+
const moved = sm.byType.filter((t) => t.moves);
|
|
151
|
+
const reqs = moved.reduce((s, t) => s + t.requests, 0);
|
|
152
|
+
fixes.push({
|
|
153
|
+
id: "subagent-model",
|
|
154
|
+
title: `Subagents on ${SUBAGENT_CANDIDATE_NAME}${movedFromNames(sm.movedFrom) ? `, not ${movedFromNames(sm.movedFrom)}` : ""}`,
|
|
155
|
+
savedUsd: sm.savedUsd,
|
|
156
|
+
savedShare: sm.billedUsd > 0 ? sm.savedUsd / sm.billedUsd : undefined,
|
|
157
|
+
basis: `${reqs.toLocaleString("en-US")} subagent requests priced at ${SUBAGENT_CANDIDATE_NAME} with the token counts they had (${money(sm.billedUsd)} billed for all ${sm.agents} subagents); an estimate: another model tokenizes and works differently`,
|
|
158
|
+
quality: `this changes the model your subagents run on (${moved.map((t) => t.type).join(", ")}); the quality cost is not measured here: context-doctor ab can measure it (its tasks with --model ${SUBAGENT_CANDIDATE} and without)`,
|
|
159
|
+
change: `${where}: env.${SUBAGENT_MODEL_ENV} = "${SUBAGENT_CANDIDATE}"`,
|
|
160
|
+
state: "available",
|
|
161
|
+
value: SUBAGENT_CANDIDATE,
|
|
162
|
+
detail: renderSubagentTypes(sm),
|
|
163
|
+
});
|
|
164
|
+
}
|
|
135
165
|
for (const f of fixes) {
|
|
136
166
|
const o = i.overrides?.[f.id];
|
|
137
167
|
if (o?.length && f.state === "available")
|
|
@@ -186,7 +216,10 @@ const KEY_PATH = {
|
|
|
186
216
|
"cache-ttl": ["promptCacheTtl"],
|
|
187
217
|
"cache-ttl-subagents": ["subagentPromptCacheTtl"],
|
|
188
218
|
"tool-search": ["env", "ENABLE_TOOL_SEARCH"],
|
|
219
|
+
"subagent-model": ["env", SUBAGENT_MODEL_ENV],
|
|
189
220
|
};
|
|
221
|
+
/** Fixes with a quality cost not measured here: applied only when named, never by `--apply all`. */
|
|
222
|
+
const NAMED_ONLY = new Set(["subagent-model"]);
|
|
190
223
|
/** What would keep this fix's value from taking effect, as Claude Code merges settings. */
|
|
191
224
|
export function fixOverrides(id, deps = {}) {
|
|
192
225
|
const env = deps.env ?? process.env;
|
|
@@ -204,6 +237,14 @@ export function fixOverrides(id, deps = {}) {
|
|
|
204
237
|
out.push(`ENABLE_TOOL_SEARCH=${s.settings.env.ENABLE_TOOL_SEARCH} in ${tilde(s.path)} env`);
|
|
205
238
|
return out;
|
|
206
239
|
}
|
|
240
|
+
if (id === "subagent-model") {
|
|
241
|
+
// Claude Code applies each settings file's env over the process's, the user's first: a project or managed value wins.
|
|
242
|
+
const out = [];
|
|
243
|
+
for (const s of sources)
|
|
244
|
+
if (s.name !== "user" && s.settings.env?.[SUBAGENT_MODEL_ENV] !== undefined)
|
|
245
|
+
out.push(`${SUBAGENT_MODEL_ENV}=${s.settings.env[SUBAGENT_MODEL_ENV]} in ${tilde(s.path)} env`);
|
|
246
|
+
return out;
|
|
247
|
+
}
|
|
207
248
|
return [];
|
|
208
249
|
}
|
|
209
250
|
/** Set one key of the user's settings.json, under the lock, and record it (the first record's previous value is kept). */
|
|
@@ -222,9 +263,11 @@ function applySetting(fix, home, at, extra) {
|
|
|
222
263
|
}
|
|
223
264
|
if (sameJson(now, fix.value))
|
|
224
265
|
return [`${key.join(".")} is already ${JSON.stringify(fix.value)} in ${tilde(file)}: nothing to change.`];
|
|
266
|
+
const old = records.find((r) => r.id === fix.id);
|
|
267
|
+
if (NAMED_ONLY.has(fix.id) && now !== undefined && !old)
|
|
268
|
+
throw new SettingsError(`${key.join(".")} is ${JSON.stringify(now)} in ${tilde(file)}, a value you set: left as it is. Nothing was changed.`);
|
|
225
269
|
const after = setJsonPath(cur.text, key, fix.value);
|
|
226
270
|
writeAtomic(file, after);
|
|
227
|
-
const old = records.find((r) => r.id === fix.id);
|
|
228
271
|
const before = cur.text ?? null;
|
|
229
272
|
const rec = {
|
|
230
273
|
...extra,
|
|
@@ -239,6 +282,7 @@ function applySetting(fix, home, at, extra) {
|
|
|
239
282
|
before: old ? (old.after === before ? old.before : undefined) : before,
|
|
240
283
|
after,
|
|
241
284
|
oneHourShareBefore: old?.oneHourShareBefore ?? extra.oneHourShareBefore,
|
|
285
|
+
modelsBefore: old?.modelsBefore ?? extra.modelsBefore,
|
|
242
286
|
};
|
|
243
287
|
writeFixRecords([...records.filter((r) => r.id !== fix.id), rec], home);
|
|
244
288
|
return [`✓ ${fix.change}`];
|
|
@@ -252,7 +296,11 @@ export async function applyFix(fix, deps = {}, context = {}) {
|
|
|
252
296
|
return { ok: false, lines: [`${fix.title}: ${fix.note ?? "nothing to apply here"}`] };
|
|
253
297
|
try {
|
|
254
298
|
if (KEY_PATH[fix.id]) {
|
|
255
|
-
|
|
299
|
+
// The environment Claude Code starts in is the user's too: a value there is theirs (settings.json would override it).
|
|
300
|
+
const shell = fix.id === "subagent-model" ? (deps.env ?? process.env)[SUBAGENT_MODEL_ENV] : undefined;
|
|
301
|
+
if (shell?.trim())
|
|
302
|
+
return { ok: false, lines: [`✗ ${fix.id}: ${SUBAGENT_MODEL_ENV}=${shell} in the environment, a value you set: left as it is. Nothing was changed.`] };
|
|
303
|
+
const lines = applySetting(fix, home, at, { oneHourShareBefore: context.oneHourShare, modelsBefore: context.modelsBefore });
|
|
256
304
|
const over = fixOverrides(fix.id, deps);
|
|
257
305
|
if (over.length)
|
|
258
306
|
lines.push(` ⚠ written, but it will not take effect while ${over.join("; ")} ${over.length === 1 ? "overrides" : "override"} it.`);
|
|
@@ -470,6 +518,10 @@ export function savedSince(records, opts = {}) {
|
|
|
470
518
|
const c = compactWindowSavingsSince(r.at, typeof r.previous === "number" ? r.previous : undefined, opts.paths);
|
|
471
519
|
out.push({ id: r.id, at: r.at, savedUsd: c.compactions ? c.usd : undefined, detail: c.compactions ? `${c.compactions} earlier compaction${c.compactions === 1 ? "" : "s"}, the context each removed from later requests (estimated; what the summary dropped is not priced)` : "no earlier compaction yet" });
|
|
472
520
|
}
|
|
521
|
+
else if (r.id === "subagent-model") {
|
|
522
|
+
const s = subagentModelSavedSince(r.at, r.modelsBefore, opts.subagentPaths);
|
|
523
|
+
out.push({ id: r.id, at: r.at, savedUsd: s.requests ? s.usd : undefined, detail: s.requests ? `estimated: ${s.requests.toLocaleString("en-US")} subagent requests, priced at the model they ran on before (${movedFromNames(r.modelsBefore ?? {})}) against as billed, the same token counts` : r.modelsBefore ? "no subagent requests it moves yet" : "applied; not priced" });
|
|
524
|
+
}
|
|
473
525
|
else if (r.id === "autopilot") {
|
|
474
526
|
const ledger = opts.ledger ?? readLedger();
|
|
475
527
|
const ev = ledger.filter((e) => e.ev === "proxy" && e.ts >= r.at);
|
|
@@ -490,6 +542,7 @@ const LABEL = {
|
|
|
490
542
|
autopilot: "Autopilot",
|
|
491
543
|
"tool-search": "MCP tool search",
|
|
492
544
|
prune: "Unused MCP servers and skills",
|
|
545
|
+
"subagent-model": "Subagent model",
|
|
493
546
|
};
|
|
494
547
|
export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `context-doctor ${s}`, coldResume, recordProblem) {
|
|
495
548
|
const out = [];
|
|
@@ -509,6 +562,8 @@ export function renderFixPlan(days, billedUsd, fixes, since, command = (s) => `c
|
|
|
509
562
|
out.push(` measured: ${f.basis}`);
|
|
510
563
|
out.push(` quality: ${f.quality}`);
|
|
511
564
|
out.push(` changes: ${f.change} [${f.id}]`);
|
|
565
|
+
for (const d of f.detail ?? [])
|
|
566
|
+
out.push(` ${d}`);
|
|
512
567
|
if (f.overriddenBy?.length)
|
|
513
568
|
out.push(` ⚠ would not take effect: ${f.overriddenBy.join("; ")}`);
|
|
514
569
|
});
|
|
@@ -567,8 +622,9 @@ export function renderFixShare(days, billedUsd, fixes) {
|
|
|
567
622
|
}
|
|
568
623
|
export function parseFixIds(raw, fixes) {
|
|
569
624
|
const names = raw.split(",").map((s) => s.trim()).filter(Boolean);
|
|
625
|
+
// "all" is every fix but those with an unmeasured quality cost, which apply only when named too.
|
|
570
626
|
if (names.includes("all"))
|
|
571
|
-
return { ids: fixes.filter((f) => f.state === "available").map((f) => f.id), unknown: [] };
|
|
627
|
+
return { ids: [...new Set([...fixes.filter((f) => f.state === "available" && !NAMED_ONLY.has(f.id)).map((f) => f.id), ...names.filter((n) => NAMED_ONLY.has(n))])], unknown: [] };
|
|
572
628
|
const known = new Set(Object.keys(LABEL));
|
|
573
629
|
return { ids: names.filter((n) => known.has(n)), unknown: names.filter((n) => !known.has(n)) };
|
|
574
630
|
}
|