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.
Files changed (61) hide show
  1. package/README.md +7 -4
  2. package/dist/ab.js +3 -2
  3. package/dist/autopilot.js +9 -5
  4. package/dist/blob.js +66 -12
  5. package/dist/budget.d.ts +8 -2
  6. package/dist/budget.js +30 -7
  7. package/dist/ci.js +2 -1
  8. package/dist/claudeplugin.d.ts +97 -0
  9. package/dist/claudeplugin.js +142 -0
  10. package/dist/cli.js +109 -36
  11. package/dist/compactcost.d.ts +74 -0
  12. package/dist/compactcost.js +115 -0
  13. package/dist/cursor.js +2 -0
  14. package/dist/doctor.js +90 -18
  15. package/dist/extract.js +4 -3
  16. package/dist/fanout.d.ts +15 -0
  17. package/dist/fanout.js +30 -9
  18. package/dist/firstfix.d.ts +43 -0
  19. package/dist/firstfix.js +80 -0
  20. package/dist/fix.d.ts +46 -2
  21. package/dist/fix.js +95 -10
  22. package/dist/httpguard.d.ts +13 -0
  23. package/dist/httpguard.js +22 -0
  24. package/dist/install.d.ts +21 -9
  25. package/dist/install.js +211 -40
  26. package/dist/limits.d.ts +5 -0
  27. package/dist/limits.js +26 -2
  28. package/dist/mcp.js +60 -59
  29. package/dist/missledger.js +5 -3
  30. package/dist/mod/api.d.ts +8 -2
  31. package/dist/mod/api.js +2 -2
  32. package/dist/mod/logic.d.ts +13 -1
  33. package/dist/mod/logic.js +24 -2
  34. package/dist/mod/register.d.ts +2 -0
  35. package/dist/mod/register.js +19 -5
  36. package/dist/modelids.d.ts +4 -3
  37. package/dist/modelids.js +23 -7
  38. package/dist/modelswitch.js +8 -4
  39. package/dist/modmeasure.js +13 -1
  40. package/dist/orgrates.d.ts +18 -0
  41. package/dist/orgrates.js +51 -2
  42. package/dist/pack.d.ts +13 -0
  43. package/dist/pack.js +38 -2
  44. package/dist/preferences.js +2 -1
  45. package/dist/pricing.d.ts +8 -0
  46. package/dist/pricing.js +16 -0
  47. package/dist/progresssummaries.d.ts +148 -0
  48. package/dist/progresssummaries.js +248 -0
  49. package/dist/proxy.d.ts +1 -1
  50. package/dist/proxy.js +1 -1
  51. package/dist/prune.d.ts +8 -0
  52. package/dist/prune.js +11 -1
  53. package/dist/spend.d.ts +34 -0
  54. package/dist/spend.js +48 -4
  55. package/dist/subagentmodel.d.ts +12 -0
  56. package/dist/subagentmodel.js +17 -4
  57. package/dist/subagentpay.d.ts +8 -0
  58. package/dist/subagentpay.js +8 -1
  59. package/dist/toolcwd.d.ts +14 -0
  60. package/dist/toolcwd.js +17 -0
  61. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -68,7 +68,9 @@ import { currentTranscript, findSession, recall, renderRecall } from "./recall.j
68
68
  import { measureSubagentCosts, renderCostMedians, saveSubagentCosts } from "./fanout.js";
69
69
  import { applyPrune, canonical, installedSkills, planPrune, renderPrune, undoPrune } from "./prune.js";
70
70
  import { lensOverSessions, renderLens, sessionLens, LENS_ROWS } from "./lens.js";
71
- import { applyFix, fixOverrides, loadFixRecords, parseFixIds, planFixes, readFixRecords, renderFixPlan, renderFixShare, savedSince, undoFixes } from "./fix.js";
71
+ import { applyFix, fixOverrides, loadFixRecords, parseFixIds, planFixes, progressSummariesState, readFixRecords, renderFixPlan, renderFixShare, savedSince, undoFixes } from "./fix.js";
72
+ import { disablesSummaries, estimateProgressSummaries, PROGRESS_ROWS } from "./progresssummaries.js";
73
+ import { firstQuestion, renderFirstScreen, splitFirstFixes } from "./firstfix.js";
72
74
  import { claudeMcpConfigs, MCP_ROWS } from "./mcpschema.js";
73
75
  import { effectiveEnv, settingsSources, shellSet, underClaudeCode } from "./effective.js";
74
76
  import { SettingsError } from "./settingsedit.js";
@@ -116,15 +118,16 @@ Start here:
116
118
  What your recent Claude Code sessions cost, and what
117
119
  /compact at cold resumes, autopilot and an earlier
118
120
  auto-compact window would save, replayed and priced
119
- as billed. --share: totals only, to paste. Also
120
- what a bare \`context-doctor\` shows
121
+ as billed. --share: totals only, to paste
121
122
  context-doctor fix [--apply ids|all] [--share] What to change, ranked by dollars on your own
122
123
  sessions (compact earlier, the cache lifetime,
123
124
  autopilot, MCP tool search, unused servers, the
124
125
  subagents' model): each applied only on a yes
125
126
  (the subagents' model only by name, never by
126
127
  "all"), \`fix undo\` reverts them, later runs show
127
- what each saved since
128
+ what each saved since. A bare \`context-doctor\`
129
+ in a terminal shows the same plan on one screen
130
+ and asks once about the fixes with no quality cost
128
131
  context-doctor doctor Self-check the installation (configs, hook, skill,
129
132
  MCP handshake) with one pasteable diagnosis
130
133
  context-doctor uninstall Undo install
@@ -277,11 +280,13 @@ Input: a conversation JSON file (OpenAI or Anthropic message format, or a bare
277
280
  message array). Use "-" to read from stdin.
278
281
 
279
282
  Options:
280
- --model <name> Model name for window-size math (e.g. claude-sonnet-5, gpt-4o)
283
+ --model <name> (analyze, session, cursor, diff, watch, pack, cache-plan, ci, ab,
284
+ experiment) Model to count and price for (e.g. claude-sonnet-5, gpt-4o)
281
285
  --exact (analyze) Add an exact token count: Anthropic count-tokens API for
282
286
  Claude models (needs ANTHROPIC_API_KEY), tiktoken for GPT (if installed)
283
- --redact Mask message previews and file paths in the report, so it can be
284
- shared in a bug report without leaking conversation content
287
+ --redact (analyze, session, cursor) Mask message previews and file paths in
288
+ the report, so it can be shared in a bug report without leaking
289
+ conversation content
285
290
  --json ${optionText(`(${JSON_COMMANDS.join(", ")}) Machine-readable output on stdout`)}
286
291
  --fail-over-budget (analyze/session) Exit 1 when the .contextdoctorrc budget is
287
292
  exceeded — lets CI gate a pull request on context size
@@ -382,7 +387,7 @@ async function measureFixInputs(days) {
382
387
  // Each transcript read once for every replay below; what an earlier run kept is not read again (scan.ts).
383
388
  prescan([
384
389
  { paths: claudeTranscripts(days), extractors: [savingsRows(!autopilotOnNow), REQUEST_ROWS, TOOL_OUTPUT_ROWS] },
385
- { paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS, SUBAGENT_ROWS, TOOL_OUTPUT_ROWS] },
390
+ { paths: subagentTranscripts(Date.now() - days * 86_400_000), extractors: [REQUEST_ROWS, SUBAGENT_ROWS, TOOL_OUTPUT_ROWS, PROGRESS_ROWS] },
386
391
  ...(setWindow === undefined ? [{ paths: claudeTranscripts(60), extractors: [QUALITY_ROWS] }] : []),
387
392
  { paths: codexRollouts(Date.now() - days * 86_400_000), extractors: [CODEX_COMPACT_ROWS] },
388
393
  ], replaying.tick);
@@ -432,6 +437,10 @@ async function measureFixInputs(days) {
432
437
  : shellSet(BASH_OUTPUT_ENV, sources, process.env)
433
438
  ? { name: BASH_OUTPUT_ENV, value: process.env[BASH_OUTPUT_ENV], where: underClaudeCode() ? "this Claude Code session's environment" : "the environment" }
434
439
  : undefined;
440
+ // The subagents' progress summaries: estimated from their transcripts; a value of the variable the user set is theirs.
441
+ const psState = progressSummariesState({ cwd });
442
+ const psSince = Date.now() - days * 86_400_000;
443
+ const progressSummaries = estimateProgressSummaries(subagentTranscripts(psSince), { since: psSince, forkGateOff: psState.forkGateOff, offSince: psState.offSince });
435
444
  // Codex's auto-compact limit: its rollouts replayed at earlier limits; a limit the user set is theirs.
436
445
  const codexCompact = replayCodexCompact({ days });
437
446
  const cxSet = currentCodexCompact();
@@ -459,7 +468,7 @@ async function measureFixInputs(days) {
459
468
  recordProblem = e.message;
460
469
  }
461
470
  const sessions = report.sessions.length;
462
- const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search", "subagent-model", "tool-output", "codex-compact"];
471
+ const ids = ["compact-window", "cache-ttl", "cache-ttl-subagents", "tool-search", "subagent-model", "tool-output", "codex-compact", "progress-summaries"];
463
472
  return {
464
473
  prunePlan,
465
474
  inputs: {
@@ -476,6 +485,8 @@ async function measureFixInputs(days) {
476
485
  subagentModelSet,
477
486
  toolOutput,
478
487
  toolOutputSet,
488
+ progressSummaries,
489
+ ...(psState.set ? { progressSummariesSet: psState.set } : {}),
479
490
  ...(codexCompact.requests > 0 ? { codexCompact } : {}),
480
491
  ...(cxSet ? { codexCompactSet: { raw: cxSet.raw, where: cxSet.where } } : {}),
481
492
  overrides: Object.fromEntries(ids.map((id) => [id, fixOverrides(id, { cwd })])),
@@ -662,6 +673,18 @@ function applyBudgetGate(overBudget, failOverBudget) {
662
673
  function readInput(file) {
663
674
  return stripBom(readFileSync(file === "-" ? 0 : file, "utf8"));
664
675
  }
676
+ /** Write --out's file, or say why not and exit 1 (a folder that does not exist ended in a stack trace). */
677
+ function writeOut(path, text) {
678
+ try {
679
+ writeFileSync(path, text);
680
+ }
681
+ catch (e) {
682
+ const code = e.code;
683
+ const why = code === "ENOENT" ? "its folder does not exist" : code === "EACCES" || code === "EPERM" ? "permission denied" : code === "EISDIR" ? "it is a folder" : e.message;
684
+ console.error(`context-doctor: could not write ${path}: ${why}`);
685
+ process.exit(1);
686
+ }
687
+ }
665
688
  /**
666
689
  * A UTF-8 byte-order mark (Windows editors, PowerShell's Out-File) is not
667
690
  * part of the text: left in, JSON.parse rejects the file and a valid
@@ -724,6 +747,35 @@ function hasClaudeSessions() {
724
747
  return false;
725
748
  }
726
749
  }
750
+ /**
751
+ * Apply the chosen fixes through applyFix, in the order given: `fix`'s
752
+ * answers and `--apply`, and a bare `context-doctor`'s one question, write
753
+ * the same settings and the same records.
754
+ */
755
+ async function applyChosenFixes(chosen, fixes, inputs, prunePlan, port) {
756
+ const results = [];
757
+ for (const id of chosen) {
758
+ const f = fixes.find((x) => x.id === id);
759
+ if (!f || f.state !== "available") {
760
+ results.push({ id, ok: false, lines: [`${id}: ${f?.note ?? "not available here"}; skipped.`] });
761
+ continue;
762
+ }
763
+ const kind = id === "cache-ttl" ? "main" : id === "cache-ttl-subagents" ? "subagents" : undefined;
764
+ const r = await applyFix(f, { autopilotOn: () => autopilotOn(port ?? DEFAULT_AUTOPILOT_PORT) }, { oneHourShare: kind ? inputs.ttl?.[kind].oneHourShare : undefined, prune: prunePlan, modelsBefore: inputs.subagentModel ? shares(inputs.subagentModel.before) : undefined });
765
+ results.push({ id, ...r });
766
+ }
767
+ return results;
768
+ }
769
+ /** What each applied fix wrote, and where to undo it. */
770
+ function printApplied(results) {
771
+ if (!results.length)
772
+ return;
773
+ console.log("");
774
+ for (const r of results)
775
+ console.log(r.lines.join("\n"));
776
+ if (results.some((r) => r.ok))
777
+ console.log(`\nNew ${results.every((r) => !r.ok || r.id === "codex-compact") ? "Codex" : results.some((r) => r.ok && r.id === "codex-compact") ? "Claude Code and Codex" : "Claude Code"} sessions pick these up. Undo: ${selfCommand("fix undo")}; ${selfCommand("fix")} later shows what each saved since.`);
778
+ }
727
779
  async function main() {
728
780
  const args = parseArgs(process.argv.slice(2));
729
781
  if (args.command && !COMMANDS.includes(args.command)) {
@@ -1005,10 +1057,46 @@ async function main() {
1005
1057
  process.exitCode = 1;
1006
1058
  return;
1007
1059
  }
1008
- if (args.command === "savings" || (!args.command && process.stdout.isTTY && hasClaudeSessions())) {
1060
+ if (!args.command && !args.json && !args.share && process.stdout.isTTY && hasClaudeSessions()) {
1009
1061
  // A bare `context-doctor` in a terminal, with Claude Code history on the
1010
- // machine, answers the question people install this for: what would it
1011
- // save me? Scripts and pipes still get the help text.
1062
+ // machine: fix's plan (one scan), the quality-free fixes under one y/N
1063
+ // question, the others with their dollars and the command for each.
1064
+ // Asked only when stdin is a terminal too; scripts and pipes still get
1065
+ // the Start here screen, and `--json`/`--share` the savings report.
1066
+ const { inputs, prunePlan } = await measureFixInputs(args.days ?? 30);
1067
+ const fixes = planFixes(inputs);
1068
+ const { free } = splitFirstFixes(fixes);
1069
+ const ask = !!process.stdin.isTTY && free.length > 0 && !inputs.recordProblem;
1070
+ console.log(renderFirstScreen({ days: inputs.days, billedUsd: inputs.billedUsd, codexBilledUsd: inputs.codexCompact?.billedUsd, fixes, command: selfCommand, recordProblem: inputs.recordProblem, ask }));
1071
+ if (!ask)
1072
+ return;
1073
+ const rl = (await import("node:readline/promises")).createInterface({ input: process.stdin, output: process.stdout });
1074
+ // Ctrl-D or a closed terminal is a no, never a wait. A Ctrl-D typed during
1075
+ // the scan, while the terminal was still line-buffered, reaches readline's
1076
+ // raw mode as \x04 on macOS but as a NUL on Linux (the tty keeps a pending
1077
+ // end-of-file as \0), which readline ignores: on an empty line it is a no too.
1078
+ const typedAheadEof = (s) => { if (s === "\0" && rl.line === "")
1079
+ rl.close(); };
1080
+ process.stdin.on("keypress", typedAheadEof);
1081
+ const answer = await new Promise((resolve) => {
1082
+ rl.once("close", () => resolve(""));
1083
+ rl.question(firstQuestion(free.length, selfCommand)).then(resolve, () => resolve(""));
1084
+ });
1085
+ process.stdin.off("keypress", typedAheadEof);
1086
+ rl.close();
1087
+ if (!/^(y|yes)$/i.test(answer.trim())) {
1088
+ console.log(`Nothing changed. ${selfCommand("fix")} asks about each lever, the ones above included.`);
1089
+ return;
1090
+ }
1091
+ const results = await applyChosenFixes(free.map((f) => f.id), fixes, inputs, prunePlan, args.port);
1092
+ if (results.some((r) => !r.ok))
1093
+ process.exitCode = 1;
1094
+ printApplied(results);
1095
+ return;
1096
+ }
1097
+ if (args.command === "savings" || (!args.command && process.stdout.isTTY && hasClaudeSessions())) {
1098
+ // `savings`, and a bare `context-doctor --json` or `--share` in a terminal
1099
+ // with Claude Code history (what a bare run printed before the one-question screen).
1012
1100
  const replaying = progressLine("Replaying your Claude Code sessions through autopilot");
1013
1101
  // Each transcript read once for every report below; what an earlier run kept is not read again (scan.ts).
1014
1102
  prescan([
@@ -1055,8 +1143,6 @@ async function main() {
1055
1143
  else {
1056
1144
  console.log(renderSavings(report, on, cwLine, cacheMissesSignificant(misses) ? cacheMissesLine(misses) : undefined, limitLines, renderLens(lens)));
1057
1145
  console.log(`\nNext: ${selfCommand("fix")} ranks every fix by what it saves you and applies only the ones you say yes to (${selfCommand("fix undo")} reverts them).`);
1058
- if (!args.command)
1059
- console.log(`All commands: ${selfCommand("--help")}`);
1060
1146
  }
1061
1147
  return;
1062
1148
  }
@@ -1304,35 +1390,20 @@ async function main() {
1304
1390
  }
1305
1391
  rl.close();
1306
1392
  }
1307
- const results = [];
1308
- for (const id of chosen) {
1309
- const f = fixes.find((x) => x.id === id);
1310
- if (!f || f.state !== "available") {
1311
- results.push({ id, ok: false, lines: [`${id}: ${f?.note ?? "not available here"}; skipped.`] });
1312
- continue;
1313
- }
1314
- const kind = id === "cache-ttl" ? "main" : id === "cache-ttl-subagents" ? "subagents" : undefined;
1315
- 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 });
1316
- results.push({ id, ...r });
1317
- }
1393
+ const results = await applyChosenFixes(chosen, fixes, inputs, prunePlan, args.port);
1318
1394
  // Naming fixes that are not there (or nothing at all, with "all") is not a silent success.
1319
1395
  if (args.apply !== undefined && (chosen.length === 0 || results.some((r) => !r.ok)))
1320
1396
  process.exitCode = 1;
1321
1397
  if (args.json) {
1322
- console.log(JSON.stringify({ days: inputs.days, billedUsd: inputs.billedUsd, ...(inputs.codexCompact ? { codexBilledUsd: inputs.codexCompact.billedUsd } : {}), fixes, since, ...(args.apply !== undefined ? { applied: results } : {}), ...(inputs.recordProblem ? { recordProblem: inputs.recordProblem } : {}) }, null, 2));
1398
+ // qualityFree is the bare screen's grouping, not part of fix's JSON.
1399
+ console.log(JSON.stringify({ days: inputs.days, billedUsd: inputs.billedUsd, ...(inputs.codexCompact ? { codexBilledUsd: inputs.codexCompact.billedUsd } : {}), fixes: fixes.map(({ qualityFree: _q, ...f }) => f), since, ...(args.apply !== undefined ? { applied: results } : {}), ...(inputs.recordProblem ? { recordProblem: inputs.recordProblem } : {}) }, null, 2));
1323
1400
  if (args.apply !== undefined && chosen.length === 0)
1324
1401
  console.error("--apply: no fix available to apply.");
1325
1402
  return;
1326
1403
  }
1327
1404
  if (args.apply !== undefined && chosen.length === 0)
1328
1405
  console.error("\n--apply: no fix available to apply.");
1329
- if (!results.length)
1330
- return;
1331
- console.log("");
1332
- for (const r of results)
1333
- console.log(r.lines.join("\n"));
1334
- if (results.some((r) => r.ok))
1335
- console.log(`\nNew ${results.every((r) => !r.ok || r.id === "codex-compact") ? "Codex" : results.some((r) => r.ok && r.id === "codex-compact") ? "Claude Code and Codex" : "Claude Code"} sessions pick these up. Undo: ${selfCommand("fix undo")}; ${selfCommand("fix")} later shows what each saved since.`);
1406
+ printApplied(results);
1336
1407
  return;
1337
1408
  }
1338
1409
  if (args.command === "cache-ttl") {
@@ -1419,7 +1490,9 @@ async function main() {
1419
1490
  if (args.share && args.json)
1420
1491
  usageError("--share and --json do not go together: --share prints a few lines to paste.");
1421
1492
  const reading = progressLine("Reading your usage across tools");
1422
- const report = spendReport(args.days ?? 30, { onProgress: reading.tick });
1493
+ // The progress summaries' estimate: none after the variable turned them off (fix's record), none at all when set with no record.
1494
+ const ps = progressSummariesState({ cwd: process.cwd() });
1495
+ const report = spendReport(args.days ?? 30, { onProgress: reading.tick, progress: { forkGateOff: ps.forkGateOff, offSince: ps.offSince, ...(ps.set && disablesSummaries(ps.set.value) ? { set: ps.set.where } : {}) } });
1423
1496
  reading.clear();
1424
1497
  if (args.json)
1425
1498
  console.log(JSON.stringify(report, null, 2));
@@ -1499,7 +1572,7 @@ async function main() {
1499
1572
  }
1500
1573
  console.log(args.json ? JSON.stringify(result.plan, null, 2) : renderCachePlan(result.plan));
1501
1574
  if (args.out) {
1502
- writeFileSync(args.out, JSON.stringify(result.apply(), null, 2));
1575
+ writeOut(args.out, JSON.stringify(result.apply(), null, 2));
1503
1576
  console.error(result.plan.plan.length
1504
1577
  ? `context-doctor: request with the planned breakpoints written to ${args.out}`
1505
1578
  : `context-doctor: nothing to place; the request was written unchanged to ${args.out}`);
@@ -1713,7 +1786,7 @@ async function main() {
1713
1786
  }
1714
1787
  const output = JSON.stringify(result.conversation, null, 2);
1715
1788
  if (args.out) {
1716
- writeFileSync(args.out, output);
1789
+ writeOut(args.out, output);
1717
1790
  }
1718
1791
  else if (args.json) {
1719
1792
  console.log(JSON.stringify(result, null, 2));
@@ -0,0 +1,74 @@
1
+ /**
2
+ * A compaction's own request, estimated: the one request of a session that no
3
+ * transcript row carries usage for.
4
+ *
5
+ * Compacting sends the whole conversation once more with an instruction to
6
+ * summarize it, and the answer is the summary the session restarts from.
7
+ * Claude Code bills it and counts it in its own cost (the mods API says the
8
+ * session's cost ledger holds it), but writes only a `compact_boundary` row
9
+ * (`compactMetadata.preTokens`: the context it read) and the summary as a user
10
+ * row (`isCompactSummary`): no usage (2.1.321). So `spend`, the budget and a
11
+ * session's price left every compaction out, and the mod's comparison with
12
+ * Claude Code's own cost showed the gap.
13
+ *
14
+ * Estimated from what the transcript does record, at the model of the reply
15
+ * before it (rateCard, as every request: the organization's rates, the day's
16
+ * price, its fast mode and US-only):
17
+ * - the context it read, `preTokens`: at the cache-read rate when the cache
18
+ * the last reply left was still alive (an automatic compaction mid-turn,
19
+ * Claude Code's idle compaction before expiry), else written again at the
20
+ * session's lifetime (a /compact after the cache went cold);
21
+ * - its output, the summary: the summary row's text, in tokens.
22
+ * Not counted: the request's own instruction (a few hundred tokens) and any
23
+ * thinking it did. The next request's re-write of the new context is in that
24
+ * request's own usage, as before.
25
+ */
26
+ import { type RecordedUsage, type RequestCost } from "./pricing.js";
27
+ /** The summary's output when no summary row follows the boundary: compactwindow.ts's measured figure. */
28
+ export declare const SUMMARY_TOKENS_UNSEEN = 20000;
29
+ /** Per thread ("0" the main conversation, "1" a sidechain): the last reply's model, time, cache lifetime and billing. */
30
+ interface Thread {
31
+ m?: string;
32
+ at?: number;
33
+ ttl?: number;
34
+ b?: Pick<RecordedUsage, "speed" | "inference_geo">;
35
+ }
36
+ /** What a reader keeps between rows (and, in the budget's ledger, between reads). */
37
+ export interface CompactTrack {
38
+ t: Record<string, Thread>;
39
+ /** A boundary met whose summary row has not been: its uuid, time, context, thread, session. */
40
+ p?: {
41
+ u?: string;
42
+ at: number;
43
+ pre: number;
44
+ th: string;
45
+ s?: string;
46
+ };
47
+ }
48
+ export declare const newTrack: () => CompactTrack;
49
+ /** A ledger's kept state, when it is one this version wrote. */
50
+ export declare function isTrack(v: unknown): v is CompactTrack;
51
+ /** One compaction's request, priced. */
52
+ export interface CompactionRequest {
53
+ uuid?: string;
54
+ sessionId?: string;
55
+ sidechain: boolean;
56
+ ts: number;
57
+ model: string;
58
+ usage: RecordedUsage;
59
+ cost: RequestCost;
60
+ /** The context it read from a live cache (false: written again). */
61
+ warm: boolean;
62
+ }
63
+ /** The rows a reader must hand on: replies with usage, compaction boundaries, summary rows. */
64
+ export declare function isCompactionRow(line: string): boolean;
65
+ /**
66
+ * Feed one parsed row; a compaction's request when this row completes one
67
+ * (its summary row, or a reply that came with no summary row between). A
68
+ * boundary still waiting for its summary at the end of what was read is kept
69
+ * in `st` and priced when the summary is read.
70
+ */
71
+ export declare function trackCompaction(st: CompactTrack, e: any): CompactionRequest | undefined;
72
+ /** A summary row as an extractor keeps it: its length, not its text. */
73
+ export declare function slimSummary(e: any): Record<string, unknown>;
74
+ export {};
@@ -0,0 +1,115 @@
1
+ /**
2
+ * A compaction's own request, estimated: the one request of a session that no
3
+ * transcript row carries usage for.
4
+ *
5
+ * Compacting sends the whole conversation once more with an instruction to
6
+ * summarize it, and the answer is the summary the session restarts from.
7
+ * Claude Code bills it and counts it in its own cost (the mods API says the
8
+ * session's cost ledger holds it), but writes only a `compact_boundary` row
9
+ * (`compactMetadata.preTokens`: the context it read) and the summary as a user
10
+ * row (`isCompactSummary`): no usage (2.1.321). So `spend`, the budget and a
11
+ * session's price left every compaction out, and the mod's comparison with
12
+ * Claude Code's own cost showed the gap.
13
+ *
14
+ * Estimated from what the transcript does record, at the model of the reply
15
+ * before it (rateCard, as every request: the organization's rates, the day's
16
+ * price, its fast mode and US-only):
17
+ * - the context it read, `preTokens`: at the cache-read rate when the cache
18
+ * the last reply left was still alive (an automatic compaction mid-turn,
19
+ * Claude Code's idle compaction before expiry), else written again at the
20
+ * session's lifetime (a /compact after the cache went cold);
21
+ * - its output, the summary: the summary row's text, in tokens.
22
+ * Not counted: the request's own instruction (a few hundred tokens) and any
23
+ * thinking it did. The next request's re-write of the new context is in that
24
+ * request's own usage, as before.
25
+ */
26
+ import { requestCost } from "./pricing.js";
27
+ import { textOf } from "./session.js";
28
+ import { realModel, tokensForLength } from "./tokens.js";
29
+ const HOUR_MS = 3_600_000;
30
+ const FIVE_MIN_MS = 300_000;
31
+ /** The summary's output when no summary row follows the boundary: compactwindow.ts's measured figure. */
32
+ export const SUMMARY_TOKENS_UNSEEN = 20_000;
33
+ export const newTrack = () => ({ t: {} });
34
+ /** A ledger's kept state, when it is one this version wrote. */
35
+ export function isTrack(v) {
36
+ return Boolean(v) && typeof v === "object" && Boolean(v.t) && typeof v.t === "object";
37
+ }
38
+ /** The rows a reader must hand on: replies with usage, compaction boundaries, summary rows. */
39
+ export function isCompactionRow(line) {
40
+ return line.includes('"compact_boundary"') || line.includes('"isCompactSummary"');
41
+ }
42
+ const thread = (e) => (e?.isSidechain === true ? "1" : "0");
43
+ function priced(st, summaryTokens) {
44
+ const p = st.p;
45
+ st.p = undefined;
46
+ if (!p)
47
+ return undefined;
48
+ const th = st.t[p.th];
49
+ if (!th?.m || !(p.pre > 0))
50
+ return undefined;
51
+ const ttl = th.ttl ?? HOUR_MS;
52
+ const warm = th.at !== undefined && p.at - th.at <= ttl;
53
+ const usage = warm
54
+ ? { input_tokens: 0, cache_read_input_tokens: p.pre, cache_creation_input_tokens: 0, output_tokens: summaryTokens, ...th.b }
55
+ : { input_tokens: 0, cache_read_input_tokens: 0, cache_creation_input_tokens: p.pre, cache_creation: ttl >= HOUR_MS ? { ephemeral_5m_input_tokens: 0, ephemeral_1h_input_tokens: p.pre } : { ephemeral_5m_input_tokens: p.pre, ephemeral_1h_input_tokens: 0 }, output_tokens: summaryTokens, ...th.b };
56
+ const cost = requestCost(th.m, usage, p.at);
57
+ if (!cost)
58
+ return undefined;
59
+ return { ...(p.u ? { uuid: p.u } : {}), ...(p.s ? { sessionId: p.s } : {}), sidechain: p.th === "1", ts: p.at, model: th.m, usage, cost, warm };
60
+ }
61
+ /**
62
+ * Feed one parsed row; a compaction's request when this row completes one
63
+ * (its summary row, or a reply that came with no summary row between). A
64
+ * boundary still waiting for its summary at the end of what was read is kept
65
+ * in `st` and priced when the summary is read.
66
+ */
67
+ export function trackCompaction(st, e) {
68
+ if (!e || typeof e !== "object")
69
+ return undefined;
70
+ if (e.type === "system" && e.subtype === "compact_boundary") {
71
+ // A boundary right after another (no summary between): the first is priced as unseen.
72
+ const before = st.p ? priced(st, SUMMARY_TOKENS_UNSEEN) : undefined;
73
+ const at = Date.parse(String(e.timestamp ?? ""));
74
+ const pre = Number(e.compactMetadata?.preTokens);
75
+ if (Number.isFinite(at) && Number.isFinite(pre) && pre > 0) {
76
+ st.p = { at, pre, th: thread(e), ...(typeof e.uuid === "string" ? { u: e.uuid } : {}), ...(typeof e.sessionId === "string" ? { s: e.sessionId } : {}) };
77
+ }
78
+ return before;
79
+ }
80
+ if (e.type === "user" && e.isCompactSummary === true) {
81
+ if (!st.p)
82
+ return undefined;
83
+ const length = typeof e.n === "number" ? e.n : textOf(e.message?.content).length;
84
+ const model = st.t[st.p.th]?.m;
85
+ return priced(st, Math.max(1, tokensForLength(length, false, model)));
86
+ }
87
+ if (e.type === "assistant" && e.message?.usage) {
88
+ const done = st.p && st.p.th === thread(e) ? priced(st, SUMMARY_TOKENS_UNSEEN) : undefined;
89
+ const model = realModel(e.message.model);
90
+ if (!model)
91
+ return done;
92
+ const u = e.message.usage;
93
+ const th = (st.t[thread(e)] ??= {});
94
+ th.m = model;
95
+ const at = Date.parse(String(e.timestamp ?? ""));
96
+ if (Number.isFinite(at))
97
+ th.at = at;
98
+ const split = u.cache_creation;
99
+ if (split && (split.ephemeral_1h_input_tokens ?? 0) > 0)
100
+ th.ttl = HOUR_MS;
101
+ else if (split && (split.ephemeral_5m_input_tokens ?? 0) > 0)
102
+ th.ttl = FIVE_MIN_MS;
103
+ const b = { ...(u.speed === "fast" ? { speed: "fast" } : {}), ...(u.inference_geo === "us" ? { inference_geo: "us" } : {}) };
104
+ if (Object.keys(b).length)
105
+ th.b = b;
106
+ else
107
+ delete th.b;
108
+ return done;
109
+ }
110
+ return undefined;
111
+ }
112
+ /** A summary row as an extractor keeps it: its length, not its text. */
113
+ export function slimSummary(e) {
114
+ return { type: "user", isCompactSummary: true, n: textOf(e?.message?.content).length, ...(e?.isSidechain === true ? { isSidechain: true } : {}) };
115
+ }
package/dist/cursor.js CHANGED
@@ -12,6 +12,7 @@
12
12
  * say so plainly instead of failing obscurely.
13
13
  */
14
14
  import { execFileSync } from "node:child_process";
15
+ import { toolCwd } from "./toolcwd.js";
15
16
  import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
16
17
  import { createRequire } from "node:module";
17
18
  import { homedir, platform } from "node:os";
@@ -127,6 +128,7 @@ export function queryRows(dbPath, sql) {
127
128
  }
128
129
  // Fallback: the sqlite3 CLI, if the user has it.
129
130
  const cli = (target) => execFileSync("sqlite3", ["-readonly", "-json", target, sql], {
131
+ cwd: toolCwd(),
130
132
  encoding: "utf8",
131
133
  maxBuffer: 512 * 1024 * 1024,
132
134
  stdio: ["ignore", "pipe", "ignore"], // a missing table is expected on some DBs