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.
Files changed (53) hide show
  1. package/README.md +12 -4
  2. package/dist/ab.js +3 -1
  3. package/dist/autopilot.d.ts +1 -1
  4. package/dist/autopilot.js +38 -24
  5. package/dist/budget.d.ts +102 -0
  6. package/dist/budget.js +550 -0
  7. package/dist/cachettl.js +12 -9
  8. package/dist/claudedir.d.ts +8 -0
  9. package/dist/claudedir.js +19 -0
  10. package/dist/cli.js +145 -15
  11. package/dist/codexdir.d.ts +11 -0
  12. package/dist/codexdir.js +20 -0
  13. package/dist/codexroute.d.ts +1 -0
  14. package/dist/codexroute.js +3 -1
  15. package/dist/compactwindow.js +12 -9
  16. package/dist/cursor.d.ts +23 -0
  17. package/dist/cursor.js +140 -6
  18. package/dist/doctor.d.ts +9 -0
  19. package/dist/doctor.js +49 -12
  20. package/dist/effective.d.ts +18 -0
  21. package/dist/effective.js +39 -4
  22. package/dist/extract.d.ts +12 -3
  23. package/dist/extract.js +39 -12
  24. package/dist/fileparams.d.ts +1 -1
  25. package/dist/fileparams.js +8 -8
  26. package/dist/fix.d.ts +23 -2
  27. package/dist/fix.js +86 -10
  28. package/dist/hook.js +45 -7
  29. package/dist/install.js +108 -47
  30. package/dist/ledger.d.ts +15 -0
  31. package/dist/ledger.js +30 -1
  32. package/dist/limits.d.ts +53 -6
  33. package/dist/limits.js +152 -77
  34. package/dist/mcp.js +58 -58
  35. package/dist/overhead.js +2 -1
  36. package/dist/pack.js +3 -2
  37. package/dist/proxy.d.ts +1 -1
  38. package/dist/proxy.js +1 -1
  39. package/dist/recall.js +3 -2
  40. package/dist/scan.d.ts +10 -0
  41. package/dist/scan.js +23 -1
  42. package/dist/session.js +2 -1
  43. package/dist/settingsedit.d.ts +4 -0
  44. package/dist/settingsedit.js +61 -3
  45. package/dist/spend.d.ts +183 -0
  46. package/dist/spend.js +493 -0
  47. package/dist/statusline.d.ts +9 -2
  48. package/dist/statusline.js +20 -4
  49. package/dist/subagentmodel.d.ts +141 -0
  50. package/dist/subagentmodel.js +408 -0
  51. package/dist/subagentpay.d.ts +11 -0
  52. package/dist/subagentpay.js +23 -4
  53. 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";
@@ -56,7 +57,7 @@ import { renderReads, repeatedReads } from "./reads.js";
56
57
  import { costPerTask, renderTasks } from "./tasks.js";
57
58
  import { planCache, renderCachePlan } from "./cacheplan.js";
58
59
  import { cacheMisses, cacheMissesLine, cacheMissesSignificant, renderCacheMisses, MISS_ROWS } from "./cachemisses.js";
59
- import { renderPayback, subagentPayback } from "./subagentpay.js";
60
+ import { renderPayback, subagentPayback, SUBAGENT_CANDIDATE } from "./subagentpay.js";
60
61
  import { compactionQuality, renderCompactionQuality, QUALITY_ROWS } from "./compactquality.js";
61
62
  import { isHandoffId, listHandoffs, readHandoff, renderHandoffList, stripControls } from "./handoff.js";
62
63
  import { claudeLimitFit, limitSavingsLines, limitsReport, renderLimits } from "./limits.js";
@@ -66,10 +67,37 @@ import { applyPrune, canonical, installedSkills, planPrune, renderPrune, undoPru
66
67
  import { lensOverSessions, renderLens, sessionLens, LENS_ROWS } from "./lens.js";
67
68
  import { applyFix, fixOverrides, loadFixRecords, parseFixIds, planFixes, readFixRecords, renderFixPlan, renderFixShare, savedSince, undoFixes } from "./fix.js";
68
69
  import { claudeMcpConfigs, MCP_ROWS } from "./mcpschema.js";
69
- import { effectiveEnv, settingsSources } from "./effective.js";
70
+ import { effectiveEnv, settingsSources, shellSet, underClaudeCode } 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";
76
+ /**
77
+ * The commands that print JSON with --json. Any other command refuses the
78
+ * flag: it used to print its text report anyway and exit 0, so a script
79
+ * piping it into a JSON parser failed far from the cause.
80
+ */
81
+ const JSON_COMMANDS = [
82
+ "analyze", "optimize", "session", "cursor", "savings", "fix", "spend", "budget", "limits", "subagents", "tasks",
83
+ "reads", "compactions", "cache-misses", "cache-ttl", "compact-window", "overhead", "accuracy", "recall", "handoff",
84
+ "pack", "cache-plan", "ci", "experiment", "ab",
85
+ ];
86
+ /** An option's description, wrapped under the option column as the help text is (98 columns). */
87
+ function optionText(text) {
88
+ const lines = [];
89
+ let line = "";
90
+ for (const word of text.split(" ")) {
91
+ if (line && 26 + line.length + 1 + word.length > 98) {
92
+ lines.push(line);
93
+ line = word;
94
+ }
95
+ else
96
+ line = line ? `${line} ${word}` : word;
97
+ }
98
+ lines.push(line);
99
+ return lines.join(`\n${" ".repeat(26)}`);
100
+ }
73
101
  const HELP = `context-doctor — profile and optimize LLM context windows
74
102
 
75
103
  Start here:
@@ -89,9 +117,11 @@ Start here:
89
117
  what a bare \`context-doctor\` shows
90
118
  context-doctor fix [--apply ids|all] [--share] What to change, ranked by dollars on your own
91
119
  sessions (compact earlier, the cache lifetime,
92
- autopilot, MCP tool search, unused servers): each
93
- applied only on a yes, \`fix undo\` reverts them,
94
- later runs show what each saved since
120
+ autopilot, MCP tool search, unused servers, the
121
+ subagents' model): each applied only on a yes
122
+ (the subagents' model only by name, never by
123
+ "all"), \`fix undo\` reverts them, later runs show
124
+ what each saved since
95
125
  context-doctor doctor Self-check the installation (configs, hook, skill,
96
126
  MCP handshake) with one pasteable diagnosis
97
127
  context-doctor uninstall Undo install
@@ -120,6 +150,12 @@ Measure:
120
150
  and Codex's, the pace, when each runs out, and what
121
151
  1M tokens of each kind cost in %, fitted on your own
122
152
  readings with the fit's error
153
+ context-doctor spend [--days n] [--share [--copy]]
154
+ One bill across every tool here: Claude Code (with
155
+ its subagents), Codex, Gemini CLI and Cursor (an
156
+ estimate: no cache split), by project, model and
157
+ day, and what drives it, at list prices. --share:
158
+ totals only, to paste
123
159
  context-doctor cache-misses [--days n] Requests that re-wrote the prompt cache while it was
124
160
  still warm: priced, by model and context size, with
125
161
  the cause where the transcript shows one
@@ -165,6 +201,12 @@ Fix automatically:
165
201
  prompt cache is cold, so it never costs more.
166
202
  Plain \`proxy\` is the optimizing mode (dedupe, trim,
167
203
  strip base64), which can cost more on cached traffic
204
+ context-doctor budget [<usd>/day|<usd>/week|off] [--block]
205
+ A spend budget across Claude Code, Codex and Gemini
206
+ CLI: the every-prompt hook says what today (or this
207
+ week) has cost at 50%, 80% and 100% of it; --block
208
+ holds prompts over it until you raise it or turn it
209
+ off. Bare \`budget\`: where the period stands
168
210
 
169
211
  Fix on request:
170
212
  context-doctor optimize <file|-> [options] Apply safe fixes, print slimmed conversation
@@ -234,7 +276,7 @@ Options:
234
276
  Claude models (needs ANTHROPIC_API_KEY), tiktoken for GPT (if installed)
235
277
  --redact Mask message previews and file paths in the report, so it can be
236
278
  shared in a bug report without leaking conversation content
237
- --json Machine-readable output
279
+ --json ${optionText(`(${JSON_COMMANDS.join(", ")}) Machine-readable output on stdout`)}
238
280
  --fail-over-budget (analyze/session) Exit 1 when the .contextdoctorrc budget is
239
281
  exceeded — lets CI gate a pull request on context size
240
282
  --out <file> (optimize) Write result to file instead of stdout
@@ -244,11 +286,13 @@ Options:
244
286
  Default: dedupe, trim-tool-results, strip-base64 (lossless-ish set)
245
287
  --keep-recent <n> (optimize) Messages at the tail to leave untouched (default 6)
246
288
  --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 sample
248
- or list
249
- --days <n> (savings, compact-window, cache-ttl, overhead, reads, tasks, subagents,
250
- compactions, cache-misses, limits)
289
+ --limit <n> (accuracy, session --list, reads, tasks, subagents, spend) How many to
290
+ sample or list
291
+ --days <n> (savings, fix, compact-window, cache-ttl, overhead, reads, tasks, subagents,
292
+ compactions, cache-misses, limits, spend)
251
293
  Days of history to read (default 30; compactions 60)
294
+ --block (budget) Over the budget, the every-prompt hook holds the prompt and
295
+ says how to lift it, instead of only saying so
252
296
  -q, --query <text> (pack) The question to rank chunks against
253
297
  --max-tokens <n> (pack) Token budget (default 4000); (recall) default 2000; (ci) fail over
254
298
  this many tokens
@@ -304,6 +348,7 @@ Start here
304
348
  context-doctor fix what to change, ranked by what it saves you; applied only on a yes
305
349
  context-doctor install wire the MCP server, skill and hooks into the apps it finds
306
350
  context-doctor savings what your recent sessions cost, and what each fix would save
351
+ context-doctor spend one bill across Claude Code, Codex, Gemini CLI and Cursor
307
352
  context-doctor doctor check the installation
308
353
 
309
354
  All commands: context-doctor --help
@@ -326,7 +371,7 @@ async function measureFixInputs(days) {
326
371
  // Each transcript read once for every replay below; what an earlier run kept is not read again (scan.ts).
327
372
  prescan([
328
373
  { paths: claudeTranscripts(days), extractors: [savingsRows(!autopilotOnNow), REQUEST_ROWS] },
329
- { paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS] },
374
+ { paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS, SUBAGENT_ROWS] },
330
375
  ...(setWindow === undefined ? [{ paths: claudeTranscripts(60), extractors: [QUALITY_ROWS] }] : []),
331
376
  ], replaying.tick);
332
377
  const report = estimateSavings(days, {}, undefined, replaying.tick, !autopilotOnNow);
@@ -350,6 +395,20 @@ async function measureFixInputs(days) {
350
395
  const ttl = estimateCacheTtl(days, { onProgress: ttling.tick });
351
396
  ttling.clear();
352
397
  const sources = settingsSources({ cwd });
398
+ // The subagents' model: what the variable would move, and a value the user already set (their settings.json, or this shell).
399
+ const force = effectiveEnv(SUBAGENT_MODEL_FORCE_ENV, sources);
400
+ const subagentModel = replaySubagentModels({ since: Date.now() - days * 86_400_000, force: !!force && !/^(0|false)$/i.test(force.value.trim()) });
401
+ const userSm = sources.find((s) => s.name === "user")?.settings.env?.[SUBAGENT_MODEL_ENV];
402
+ const shellSm = process.env[SUBAGENT_MODEL_ENV];
403
+ // Inside a Claude Code session (the plugin's /context-doctor:fix) the
404
+ // process carries the settings files' env as the session started: a
405
+ // project's or managed value is that file's (named as an override, not as
406
+ // "a value you set"), and fix's own value just undone is no one's.
407
+ const subagentModelSet = userSm !== undefined && userSm !== null
408
+ ? { value: String(userSm), where: `${tilde(join(claudeDir(), "settings.json"))} env` }
409
+ : shellSet(SUBAGENT_MODEL_ENV, sources, process.env, SUBAGENT_CANDIDATE)
410
+ ? { value: shellSm, where: underClaudeCode() ? "this Claude Code session's environment (from the shell that started it, or a settings env removed since: a new session reads settings again)" : "the environment" }
411
+ : undefined;
353
412
  const ts = effectiveEnv("ENABLE_TOOL_SEARCH", sources);
354
413
  const toolSearchOff = ts && /^(false|0|no|off)$/i.test(ts.value.trim()) ? ts.value : undefined;
355
414
  const servers = claudeMcpConfigs(cwd).filter((c) => !/context-doctor/i.test(c.name));
@@ -374,7 +433,7 @@ async function measureFixInputs(days) {
374
433
  recordProblem = e.message;
375
434
  }
376
435
  const sessions = report.sessions.length;
377
- const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search"];
436
+ const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search", "subagent-model"];
378
437
  return {
379
438
  prunePlan,
380
439
  inputs: {
@@ -387,6 +446,8 @@ async function measureFixInputs(days) {
387
446
  toolSearchOff,
388
447
  mcpServers: toolSearchOff ? servers.length : 0,
389
448
  prune: prunePlan,
449
+ subagentModel,
450
+ subagentModelSet,
390
451
  overrides: Object.fromEntries(ids.map((id) => [id, fixOverrides(id, { cwd })])),
391
452
  recordProblem,
392
453
  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 +467,7 @@ const COMMANDS = [
406
467
  "analyze", "optimize", "proxy", "install", "uninstall", "savings", "compact-window", "autopilot", "mcp",
407
468
  "instructions", "session", "cursor", "statusline", "hook", "report", "doctor", "dashboard", "init",
408
469
  "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",
470
+ "spend", "budget", "reads", "pack", "watch", "ab", "handoff", "recall", "help", "version",
410
471
  ];
411
472
  /** --strategy takes one of the optimizer's ids; a typo used to run nothing and report success. */
412
473
  function strategyArg(v) {
@@ -441,11 +502,12 @@ const FLAGS = [
441
502
  { names: ["--dry-run"], set: (a) => { a.dryRun = true; } },
442
503
  { names: ["--copy"], set: (a) => { a.copy = true; } },
443
504
  { names: ["--share"], set: (a) => { a.share = true; } },
505
+ { names: ["--block"], set: (a) => { a.block = true; } },
444
506
  { names: ["--allow-dirty"], set: (a) => { a.allowDirty = true; } },
445
507
  { names: ["--statusline"], set: (a) => { a.statusLine = true; } },
446
508
  { names: ["--host"], value: "text", set: (a, v) => { a.host = v; } },
447
509
  { names: ["--token"], value: "text", set: (a, v) => { a.token = v; } },
448
- { names: ["--days"], value: "number", num: { min: 1 }, set: (a, v) => { a.days = v; } },
510
+ { names: ["--days"], value: "number", num: { min: 1, integer: true }, set: (a, v) => { a.days = v; } },
449
511
  { names: ["--autopilot"], set: (a) => { a.autopilot = true; } },
450
512
  { names: ["--autopilot-state"], value: "text", set: (a, v) => { a.autopilotState = v; } },
451
513
  { names: ["--autopilot-pause-file"], value: "text", set: (a, v) => { a.autopilotPauseFile = v; } },
@@ -648,6 +710,9 @@ async function main() {
648
710
  console.log((topic && commandHelp(HELP, topic)) || HELP);
649
711
  return;
650
712
  }
713
+ if (args.json && args.command && !JSON_COMMANDS.includes(args.command)) {
714
+ usageError(`${args.command} has no --json output. Commands with one: ${JSON_COMMANDS.join(", ")}.`);
715
+ }
651
716
  // Run by hand in a terminal, these waited forever for JSON that only
652
717
  // Claude Code sends.
653
718
  if ((args.command === "hook" || args.command === "statusline") && process.stdin.isTTY) {
@@ -765,6 +830,10 @@ async function main() {
765
830
  process.exit(1);
766
831
  }
767
832
  if (args.list) {
833
+ if (args.json) {
834
+ console.log(JSON.stringify(chats.map((c) => ({ id: c.composerId, title: c.title ?? null, messages: c.messageCount })), null, 2));
835
+ return;
836
+ }
768
837
  for (const c of chats) {
769
838
  console.log(`${String(c.messageCount).padStart(5)} msgs ${(c.title ?? "(untitled)").slice(0, 48).padEnd(50)} ${c.composerId}`);
770
839
  }
@@ -798,6 +867,10 @@ async function main() {
798
867
  if (args.command === "session") {
799
868
  if (args.list) {
800
869
  const sessions = listSessions(args.limit ?? 20);
870
+ if (args.json) {
871
+ console.log(JSON.stringify(sessions.map((s) => ({ path: s.path, modifiedAt: s.modifiedAt.toISOString(), sizeBytes: s.sizeBytes })), null, 2));
872
+ return;
873
+ }
801
874
  if (sessions.length === 0) {
802
875
  console.log("No sessions found under ~/.claude/projects or ~/.codex/sessions.");
803
876
  return;
@@ -1022,6 +1095,10 @@ async function main() {
1022
1095
  const replaying = progressLine("Replaying your sessions at each window");
1023
1096
  const cw = estimateCompactWindows(windows.sort((a, b) => a - b), args.days ?? 30, undefined, reread, replaying.tick);
1024
1097
  replaying.clear();
1098
+ if (args.json) {
1099
+ console.log(JSON.stringify({ ...cw, current: current ?? null }, null, 2));
1100
+ return;
1101
+ }
1025
1102
  const limitFit = claudeLimitFit(limitsReport(cw.days, { claudeOnly: true }));
1026
1103
  console.log(renderCompactWindows(cw, current, (estimates) => limitSavingsLines(limitFit, estimates.map((e) => [`${Math.round(e.window / 1000)}k window`, Math.max(0, e.savedUsd)]), cw.days)));
1027
1104
  return;
@@ -1191,7 +1268,7 @@ async function main() {
1191
1268
  continue;
1192
1269
  }
1193
1270
  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 });
1271
+ 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.before) : undefined });
1195
1272
  results.push({ id, ...r });
1196
1273
  }
1197
1274
  // Naming fixes that are not there (or nothing at all, with "all") is not a silent success.
@@ -1292,6 +1369,59 @@ async function main() {
1292
1369
  console.log(args.json ? JSON.stringify(report, null, 2) : renderLimits(report));
1293
1370
  return;
1294
1371
  }
1372
+ if (args.command === "spend") {
1373
+ if (args.file !== undefined)
1374
+ usageError(`Usage: context-doctor spend [--days n] [--limit n] [--share [--copy]] [--json]; got "${args.file}".`);
1375
+ if (args.share && args.json)
1376
+ usageError("--share and --json do not go together: --share prints a few lines to paste.");
1377
+ const reading = progressLine("Reading your usage across tools");
1378
+ const report = spendReport(args.days ?? 30, { onProgress: reading.tick });
1379
+ reading.clear();
1380
+ if (args.json)
1381
+ console.log(JSON.stringify(report, null, 2));
1382
+ else if (args.share) {
1383
+ const text = renderSpendShare(report);
1384
+ console.log(text);
1385
+ if (args.copy)
1386
+ console.log(copyToClipboard(text) ? "\n(copied to the clipboard)" : "\n(no clipboard tool found; copy the lines above)");
1387
+ }
1388
+ else
1389
+ console.log(renderSpend(report, args.limit ?? 8));
1390
+ return;
1391
+ }
1392
+ if (args.command === "budget") {
1393
+ const sub = args.file;
1394
+ const usage = "Usage: context-doctor budget [<usd>/day | <usd>/week] [--block] | budget off | budget [--json]";
1395
+ if ((args.positionals?.length ?? 0) > 1)
1396
+ usageError(`${usage}; got "${args.positionals.slice(1).join(" ")}" too.`);
1397
+ if (sub === "off") {
1398
+ if (args.block)
1399
+ usageError("--block goes with a budget: context-doctor budget 50/day --block.");
1400
+ const was = clearBudget();
1401
+ // --json: the budget as it now stands, as `budget --json` prints it (none).
1402
+ console.log(args.json ? "null" : was ? "Budget off: the every-prompt hook no longer counts spend." : "No budget was set.");
1403
+ return;
1404
+ }
1405
+ if (sub !== undefined) {
1406
+ const parsed = parseBudget(sub);
1407
+ if ("error" in parsed)
1408
+ usageError(`${parsed.error}${didYouMean(sub, ["off"])} ${usage}.`);
1409
+ writeBudget({ ...parsed, block: Boolean(args.block), at: Date.now() });
1410
+ // Rounded to the cent: said, on stderr under --json so stdout stays JSON.
1411
+ if (parsed.note)
1412
+ (args.json ? console.error : console.log)(parsed.note);
1413
+ }
1414
+ else if (args.block) {
1415
+ usageError("--block goes with a budget: context-doctor budget 50/day --block.");
1416
+ }
1417
+ const b = readBudget();
1418
+ const s = b ? periodSpend(b.period) : undefined;
1419
+ if (args.json)
1420
+ console.log(JSON.stringify(b && s ? { ...b, spent: s.usd, byTool: s.byTool, periodStart: s.start, periodEnd: s.end, unpriced: s.unpriced ?? null } : null, null, 2));
1421
+ else
1422
+ console.log(withInvocation(renderBudgetStatus(b, s, promptHookInstalled())));
1423
+ return;
1424
+ }
1295
1425
  if (args.command === "compactions") {
1296
1426
  const days = args.days ?? 60;
1297
1427
  const q = compactionQuality(days);
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Where Codex keeps its home: `~/.codex` (config.toml, hooks.json, auth.json,
3
+ * AGENTS.md, skills/, sessions/, archived_sessions/), unless CODEX_HOME
4
+ * names another folder. Read from the Codex binary (ChatGPT.app's, 2026-09):
5
+ * a non-empty CODEX_HOME is used as given (it must exist; Codex refuses to
6
+ * start otherwise), else `~/.codex`. As with CLAUDE_CONFIG_DIR (claudedir.ts),
7
+ * a caller that passes its own `home` (tests, a throwaway home) gets that
8
+ * home's folder: the variable describes the real user's setup.
9
+ */
10
+ /** `~/.codex`, or CODEX_HOME. */
11
+ export declare function codexDir(home?: string, env?: NodeJS.ProcessEnv): string;
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Where Codex keeps its home: `~/.codex` (config.toml, hooks.json, auth.json,
3
+ * AGENTS.md, skills/, sessions/, archived_sessions/), unless CODEX_HOME
4
+ * names another folder. Read from the Codex binary (ChatGPT.app's, 2026-09):
5
+ * a non-empty CODEX_HOME is used as given (it must exist; Codex refuses to
6
+ * start otherwise), else `~/.codex`. As with CLAUDE_CONFIG_DIR (claudedir.ts),
7
+ * a caller that passes its own `home` (tests, a throwaway home) gets that
8
+ * home's folder: the variable describes the real user's setup.
9
+ */
10
+ import { homedir } from "node:os";
11
+ import { join, resolve } from "node:path";
12
+ /** `~/.codex`, or CODEX_HOME. */
13
+ export function codexDir(home, env = process.env) {
14
+ if (home === undefined || home === homedir()) {
15
+ const v = env.CODEX_HOME?.trim();
16
+ if (v)
17
+ return resolve(v);
18
+ }
19
+ return join(home ?? homedir(), ".codex");
20
+ }
@@ -21,6 +21,7 @@
21
21
  * config.toml is the user's file: only our one top-level line is ever
22
22
  * added, replaced or removed, and a value someone else set is left alone.
23
23
  */
24
+ /** Codex's home for `home`: CODEX_HOME when `home` is this user's (codexdir.ts). */
24
25
  export declare function codexHomeIn(home: string): string;
25
26
  /** How Codex signs in, from auth.json: "apikey", "chatgpt", another mode, or undefined (none yet). */
26
27
  export declare function codexAuthMode(codexHome: string): string | undefined;
@@ -23,11 +23,13 @@
23
23
  */
24
24
  import { existsSync, readFileSync, writeFileSync, copyFileSync } from "node:fs";
25
25
  import { join } from "node:path";
26
+ import { codexDir } from "./codexdir.js";
26
27
  const KEY = "openai_base_url";
27
28
  const ANY_HEADER = /^\s*\[/;
28
29
  const keyLine = (key) => new RegExp(String.raw `^\s*(?:${key}|"${key}"|'${key}')\s*=\s*(?:"([^"]*)"|'([^']*)')\s*(?:#.*)?$`);
30
+ /** Codex's home for `home`: CODEX_HOME when `home` is this user's (codexdir.ts). */
29
31
  export function codexHomeIn(home) {
30
- return join(home, ".codex");
32
+ return codexDir(home);
31
33
  }
32
34
  /** How Codex signs in, from auth.json: "apikey", "chatgpt", another mode, or undefined (none yet). */
33
35
  export function codexAuthMode(codexHome) {
@@ -25,7 +25,7 @@ import { listSessions, replyCounter, isClaudeSession } from "./session.js";
25
25
  import { cacheWriteSplit, pricingFor, usageCost, writeMultiplier } from "./pricing.js";
26
26
  import { realModel } from "./tokens.js";
27
27
  import { backupOnce } from "./install.js";
28
- import { ABSENT, readSettings, setJsonPath, writeAtomic } from "./settingsedit.js";
28
+ import { ABSENT, readSettings, setJsonPath, withSettingsLock, writeAtomic } from "./settingsedit.js";
29
29
  import { compactWindowOverrides, effectiveCompactWindow, settingsSources } from "./effective.js";
30
30
  import { withInvocation } from "./invocation.js";
31
31
  import { idleCompactMinTokens, isIdleCompactNotice, REQUEST_ROWS } from "./coldresume.js";
@@ -254,14 +254,17 @@ export function setCompactWindow(window, home) {
254
254
  throw new Error(`window must be a whole number of tokens between ${MIN_WINDOW} and ${MAX_WINDOW}`);
255
255
  }
256
256
  const p = settingsPath(home);
257
- const cur = readSettings(p);
258
- const previous = cur.data.autoCompactWindow;
259
- if (window === undefined ? previous === undefined : previous === window)
260
- return { changed: false, created: false, ...(previous !== undefined ? { previous } : {}) };
261
- const next = setJsonPath(cur.text, ["autoCompactWindow"], window === undefined ? ABSENT : window);
262
- backupOnce(p);
263
- writeAtomic(p, next);
264
- return { changed: true, created: cur.text === undefined, backup: cur.text !== undefined ? `${p}.context-doctor.backup` : undefined, previous };
257
+ // Read and written under the lock fix and autopilot take: a concurrent writer's key is not lost.
258
+ return withSettingsLock(p, () => {
259
+ const cur = readSettings(p);
260
+ const previous = cur.data.autoCompactWindow;
261
+ if (window === undefined ? previous === undefined : previous === window)
262
+ return { changed: false, created: false, ...(previous !== undefined ? { previous } : {}) };
263
+ const next = setJsonPath(cur.text, ["autoCompactWindow"], window === undefined ? ABSENT : window);
264
+ backupOnce(p);
265
+ writeAtomic(p, next);
266
+ return { changed: true, created: cur.text === undefined, backup: cur.text !== undefined ? `${p}.context-doctor.backup` : undefined, previous };
267
+ });
265
268
  }
266
269
  /** "400k" / "400000" / "0.4m" -> 400000. Undefined when unparseable. */
267
270
  export function parseWindow(raw) {
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,12 @@
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 { pathToFileURL } from "node:url";
20
+ import { readSideEntry, writeSideEntry } from "./scan.js";
19
21
  const require = createRequire(import.meta.url);
20
22
  /** Cursor bubble type codes. */
21
23
  const BUBBLE_USER = 1;
@@ -76,12 +78,23 @@ export class SqliteUnavailableError extends Error {
76
78
  }
77
79
  /** Node's built-in SQLite, when this runtime has it (22.13+, or 22.5+ with --experimental-sqlite). */
78
80
  function nodeSqlite() {
81
+ // Node 22-25 warns that SQLite is experimental on first load, on stderr,
82
+ // in the middle of a report: not something the user can act on.
83
+ const emit = process.emitWarning;
84
+ process.emitWarning = ((warning, ...rest) => {
85
+ if (String(warning).includes("SQLite"))
86
+ return;
87
+ return emit.call(process, warning, ...rest);
88
+ });
79
89
  try {
80
90
  return require("node:sqlite");
81
91
  }
82
92
  catch {
83
93
  return undefined;
84
94
  }
95
+ finally {
96
+ process.emitWarning = emit;
97
+ }
85
98
  }
86
99
  /**
87
100
  * Run a read-only query against a Cursor database.
@@ -113,12 +126,26 @@ export function queryRows(dbPath, sql) {
113
126
  }
114
127
  }
115
128
  // Fallback: the sqlite3 CLI, if the user has it.
129
+ const cli = (target) => execFileSync("sqlite3", ["-readonly", "-json", target, sql], {
130
+ encoding: "utf8",
131
+ maxBuffer: 512 * 1024 * 1024,
132
+ stdio: ["ignore", "pipe", "ignore"], // a missing table is expected on some DBs
133
+ });
116
134
  try {
117
- const out = execFileSync("sqlite3", ["-readonly", "-json", dbPath, sql], {
118
- encoding: "utf8",
119
- maxBuffer: 512 * 1024 * 1024,
120
- stdio: ["ignore", "pipe", "ignore"], // a missing table is expected on some DBs
121
- });
135
+ let out;
136
+ try {
137
+ out = cli(dbPath);
138
+ }
139
+ catch (e) {
140
+ // macOS's own sqlite3 cannot open a WAL database read-only once its
141
+ // -wal and -shm files are gone, which is how Cursor leaves it when it
142
+ // quits ("unable to open database file"): every Cursor read failed
143
+ // there on Node < 22.13. With no -wal file nothing is writing it, so
144
+ // it is read as immutable.
145
+ if (e.code === "ENOENT" || existsSync(`${dbPath}-wal`))
146
+ throw e;
147
+ out = cli(`${pathToFileURL(dbPath).href}?immutable=1`);
148
+ }
122
149
  return out.trim() ? JSON.parse(out) : [];
123
150
  }
124
151
  catch (cliErr) {
@@ -237,3 +264,110 @@ export function parseCursorChat(chat) {
237
264
  path: `${chat.dbPath}#${chat.composerId}`,
238
265
  };
239
266
  }
267
+ const CURSOR_SPEND = "cursor-spend.1";
268
+ /** Chat id -> workspace folder, from each workspace's own state (composer.composerData, workspace.json). */
269
+ function cursorFolders() {
270
+ const out = new Map();
271
+ for (const dir of cursorStorageDirs()) {
272
+ let folder;
273
+ try {
274
+ const f = JSON.parse(readFileSync(join(dir, "workspace.json"), "utf8"))?.folder;
275
+ if (typeof f === "string" && f.startsWith("file://"))
276
+ folder = decodeURIComponent(f.slice("file://".length));
277
+ }
278
+ catch {
279
+ continue; // globalStorage, or a multi-root workspace: no one folder
280
+ }
281
+ if (!folder || !existsSync(join(dir, "state.vscdb")))
282
+ continue;
283
+ try {
284
+ const row = queryRows(join(dir, "state.vscdb"), "SELECT value FROM ItemTable WHERE key = 'composer.composerData'")[0];
285
+ const all = JSON.parse(String(row?.value ?? "{}"))?.allComposers;
286
+ if (Array.isArray(all))
287
+ for (const c of all)
288
+ if (typeof c?.composerId === "string")
289
+ out.set(c.composerId, folder);
290
+ }
291
+ catch {
292
+ /* an older or unreadable workspace database */
293
+ }
294
+ }
295
+ return out;
296
+ }
297
+ /** A time Cursor wrote: epoch ms (as a number or digits) or an ISO string. */
298
+ function cursorTime(v) {
299
+ const n = typeof v === "number" ? v : typeof v === "string" ? (/^\d+$/.test(v) ? Number(v) : Date.parse(v)) : Number.NaN;
300
+ return Number.isFinite(n) && n > 0 ? n : undefined;
301
+ }
302
+ /**
303
+ * Every Cursor reply with token counts since `since`. Only chats updated
304
+ * since then are read, each by its key range (on the author's 3 GB history
305
+ * the chat list takes ~0.1 s, one chat's replies ~40 ms), and each chat's
306
+ * replies are kept until it changes, so a second run reads none of them
307
+ * again. Throws SqliteUnavailableError when this runtime cannot read SQLite.
308
+ */
309
+ export function cursorUsage(since) {
310
+ const out = [];
311
+ let folders;
312
+ for (const dbPath of findCursorDatabases()) {
313
+ let composers;
314
+ try {
315
+ // A key range, not LIKE: it walks the primary key's index.
316
+ composers = queryRows(dbPath, "SELECT key, json_extract(value, '$.lastUpdatedAt') AS lu, json_extract(value, '$.createdAt') AS ca, json_extract(value, '$.modelConfig.modelName') AS mn " +
317
+ "FROM cursorDiskKV WHERE key >= 'composerData:' AND key < 'composerData;' AND json_valid(value)");
318
+ }
319
+ catch (e) {
320
+ if (e instanceof SqliteUnavailableError)
321
+ throw e;
322
+ continue; // no chats in this database
323
+ }
324
+ const kept = readSideEntry(dbPath, CURSOR_SPEND) ?? { composers: {} };
325
+ let changed = false;
326
+ for (const c of composers) {
327
+ const id = String(c.key).slice("composerData:".length);
328
+ const lu = cursorTime(c.lu) ?? cursorTime(c.ca) ?? 0;
329
+ if (lu < since || !/^[\w-]+$/.test(id))
330
+ continue;
331
+ let rows = kept.composers[id]?.lu === lu ? kept.composers[id].rows : undefined;
332
+ if (!rows) {
333
+ rows = [];
334
+ let bubbles = [];
335
+ try {
336
+ bubbles = queryRows(dbPath, "SELECT json_extract(value, '$.tokenCount.inputTokens') AS i, json_extract(value, '$.tokenCount.outputTokens') AS o, " +
337
+ "json_extract(value, '$.createdAt') AS ca, json_extract(value, '$.timingInfo.clientStartTime') AS cs, json_extract(value, '$.modelInfo.modelName') AS mn " +
338
+ `FROM cursorDiskKV WHERE key >= 'bubbleId:${id}:' AND key < 'bubbleId:${id};' AND json_valid(value)`);
339
+ }
340
+ catch {
341
+ /* an unreadable chat: nothing from it */
342
+ }
343
+ for (const b of bubbles) {
344
+ const i = Number(b.i) > 0 ? Number(b.i) : 0, o = Number(b.o) > 0 ? Number(b.o) : 0;
345
+ if (i + o === 0)
346
+ continue;
347
+ // A reply without a time of its own is placed at the chat's last update.
348
+ rows.push([cursorTime(b.ca) ?? cursorTime(b.cs) ?? lu, i, o, typeof b.mn === "string" && b.mn ? b.mn : null]);
349
+ }
350
+ kept.composers[id] = { lu, rows };
351
+ changed = true;
352
+ }
353
+ if (rows.length && !folders)
354
+ folders = cursorFolders();
355
+ const chatModel = typeof c.mn === "string" && c.mn ? c.mn : undefined;
356
+ for (const [ts, input, output, mn] of rows) {
357
+ if (ts < since)
358
+ continue;
359
+ const r = { ts, input, output, composerId: id };
360
+ const model = mn ?? chatModel;
361
+ if (model)
362
+ r.model = model;
363
+ const folder = folders?.get(id);
364
+ if (folder)
365
+ r.folder = folder;
366
+ out.push(r);
367
+ }
368
+ }
369
+ if (changed)
370
+ writeSideEntry(dbPath, CURSOR_SPEND, kept);
371
+ }
372
+ return out.sort((a, b) => a.ts - b.ts);
373
+ }
package/dist/doctor.d.ts CHANGED
@@ -37,6 +37,15 @@ export declare function cacheTtlCheck(home?: string, env?: NodeJS.ProcessEnv): C
37
37
  * rather than nothing or a false "ok".
38
38
  */
39
39
  export declare function devinCheck(home?: string): Check;
40
+ /**
41
+ * How long the handshake may take: 15 s, or CONTEXT_DOCTOR_MCP_HANDSHAKE_MS.
42
+ * 5 s failed on a loaded machine (Node starting the server is most of it); a
43
+ * server that crashes is reported as soon as it exits, so only one that
44
+ * hangs alive waits this long.
45
+ */
46
+ export declare function handshakeTimeoutMs(env?: NodeJS.ProcessEnv): number;
47
+ /** Spawn our own MCP server and run the initialize handshake over stdio. */
48
+ export declare function checkMcpHandshake(mcpPath?: string, timeoutMs?: number): Promise<Check>;
40
49
  export declare function runDoctor(): Promise<void>;
41
50
  /**
42
51
  * The Cursor version here: the newest one that ran the hook (its input